diff --git a/.ci/README.md b/.ci/README.md index 1f146894095c..e39b09c4bbe0 100644 --- a/.ci/README.md +++ b/.ci/README.md @@ -1,7 +1,8 @@ +# Continuous integration + ATTENTION: All scripts in this folder expect to be launched from root folder of repository Example of usage: - ./.ci/travis/travis.sh all-sevntu-checks - - export TRAVIS_PULL_REQUEST="" && ./.ci/travis/travis.sh releasenotes-gen + ./.ci/validation.sh all-sevntu-checks + ./.ci/validation.sh releasenotes-gen diff --git a/.ci/append-to-github-output.sh b/.ci/append-to-github-output.sh new file mode 100755 index 000000000000..29cf76ada7dc --- /dev/null +++ b/.ci/append-to-github-output.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +set -e + +NAME=$1 +VALUE=$2 + +if [[ "$#" != "2" ]]; then + echo "not all parameters are set" + echo "Usage: $BASH_SCRIPT " + exit 1 +fi + +# Select random value for EOF as a delimiter. +EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64) +{ + echo "$NAME<<$EOF" + echo "$VALUE" + echo "$EOF" +} >> "$GITHUB_OUTPUT" diff --git a/.ci/appveyor.bat b/.ci/appveyor.bat deleted file mode 100644 index b99a70111054..000000000000 --- a/.ci/appveyor.bat +++ /dev/null @@ -1,52 +0,0 @@ -@echo off - -::---------------------------------------------------------------------- -:: Appveyor bat file to run on local for windows users. -:: Example of usage -:: ./.ci/appveyor.bat verify_without_checkstyle -::---------------------------------------------------------------------- - -SET OPTION=%1 - -if "%OPTION%" == "sevntu" ( - call mvn -e verify -DskipTests -DskipITs -Dpmd.skip=true^ - -Dspotbugs.skip=true -Djacoco.skip=true -Dxml.skip=true^ - || goto :ERROR - goto :END_CASE -) - -if "%OPTION%" == "verify_without_checkstyle" ( - call mvn -e verify -Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true^ - || goto :ERROR - goto :END_CASE -) - -if "%OPTION%" == "verify_without_checkstyle_JDK11" ( - call mvn -e verify -Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true^ - || goto :ERROR - goto :END_CASE -) - -if "%OPTION%" == "verify_without_checkstyle_JDK13" ( - call mvn -e verify -Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true^ - || goto :ERROR - goto :END_CASE -) - -if "%OPTION%" == "site_without_verify" ( - call mvn -e -Pno-validations site^ - || goto :ERROR - goto :END_CASE -) - -echo Unexpected argument %OPTION% -SET ERRORLEVEL=-1 -goto :END_CASE - -:END_CASE - VER > NUL - EXIT /b %ERRORLEVEL% - -:ERROR -echo appveyor.bat failed with error code #%ERRORLEVEL%. -exit /b %ERRORLEVEL% diff --git a/.ci/bump-license-year-in-all-projects.sh b/.ci/bump-license-year-in-all-projects.sh deleted file mode 100755 index 09ebf8d16860..000000000000 --- a/.ci/bump-license-year-in-all-projects.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env bash - -set -e - -CURR_YEAR=$(date +"%Y") -JAVA_FILE=$(find ./src/main -type f -name *.java -print -quit) -echo "Current year will be taken from $JAVA_FILE" -PREV_YEAR=$(grep "Copyright" $JAVA_FILE | cut -d " " -f 4 | cut -d '-' -f 2) -echo "CURR_YEAR=$CURR_YEAR" -echo "PREV_YEAR=$PREV_YEAR" - -./.ci/bump-license-year.sh $PREV_YEAR $CURR_YEAR . -git add . && git commit -m "minor: bump year to $CURR_YEAR" && git push origin master - -mkdir -p .ci-temp/bump-year -cd .ci-temp/bump-year - -git clone git@github.com:checkstyle/contribution.git -git clone git@github.com:checkstyle/sonar-checkstyle.git -git clone git@github.com:checkstyle/regression-tool.git -git clone git@github.com:sevntu-checkstyle/sevntu.checkstyle.git -git clone git@github.com:sevntu-checkstyle/methods-distance.git - -./../../.ci/bump-license-year.sh $PREV_YEAR $CURR_YEAR contribution -./../../.ci/bump-license-year.sh $PREV_YEAR $CURR_YEAR sonar-checkstyle -./../../.ci/bump-license-year.sh $PREV_YEAR $CURR_YEAR regression-tool -./../../.ci/bump-license-year.sh $PREV_YEAR $CURR_YEAR sevntu.checkstyle -./../../.ci/bump-license-year.sh $PREV_YEAR $CURR_YEAR methods-distance - -cd contribution -git add . && git commit -m "minor: bump year to $CURR_YEAR" && git push origin master -cd ../ -cd sonar-checkstyle -git add . && git commit -m "minor: bump year to $CURR_YEAR" && git push origin master -cd ../ -cd regression-tool -git add . && git commit -m "minor: bump year to $CURR_YEAR" && git push origin master -cd ../ -cd sevntu.checkstyle -git add . && git commit -m "minor: bump year to $CURR_YEAR" && git push origin master -cd ../ -cd methods-distance -git add . && git commit -m "minor: bump year to $CURR_YEAR" && git push origin master -cd ../ diff --git a/.ci/bump-license-year.sh b/.ci/bump-license-year.sh index b9bfa80fb2c9..672c154d3a98 100755 --- a/.ci/bump-license-year.sh +++ b/.ci/bump-license-year.sh @@ -9,11 +9,11 @@ DIR=$3 OLD_VALUE="// Copyright (C) 2001-$PREV_YEAR the original author or authors." NEW_VALUE="// Copyright (C) 2001-$CURR_YEAR the original author or authors." -find $DIR -type f \( -name *.java -o -name *.header -o -name *.g \) \ +find "$DIR" -type f \( -name '*.java' -o -name '*.header' -o -name '*.g4' \) \ -exec sed -i "s|$OLD_VALUE|$NEW_VALUE|g" {} + BASEDIR=$(pwd) echo "Distinct Diff in $DIR is:" -cd $DIR +cd "$DIR" git diff | grep -Eh "^\+" | grep -v "+++ b" | sort | uniq -cd $BASEDIR +cd "$BASEDIR" diff --git a/.ci/bump-version.sh b/.ci/bump-version.sh new file mode 100755 index 000000000000..4d3870909790 --- /dev/null +++ b/.ci/bump-version.sh @@ -0,0 +1,69 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +NEW_VERSION=$1 +echo NEW_VERSION="$NEW_VERSION" + +if ! [[ "$NEW_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "[ERROR] New version($NEW_VERSION) is not in the format of .." + exit 1; +fi + +CURRENT_VERSION=$(getCheckstylePomVersionWithoutSnapshot) +echo CURRENT_VERSION="$CURRENT_VERSION" + +if [ "$NEW_VERSION" == "$CURRENT_VERSION" ]; then + echo "[ERROR] New Version and Current Version are the same." + exit 1; +fi + +CURRENT_VERSION_FIRST_NUMBER=$(echo "$CURRENT_VERSION" | cut -d "." -f 1) +CURRENT_VERSION_SECOND_NUMBER=$(echo "$CURRENT_VERSION" | cut -d "." -f 2) +CURRENT_VERSION_THIRD_NUMBER=$(echo "$CURRENT_VERSION" | cut -d "." -f 3) + +NEW_VERSION_FIRST_NUMBER=$(echo "$NEW_VERSION" | cut -d "." -f 1) +NEW_VERSION_SECOND_NUMBER=$(echo "$NEW_VERSION" | cut -d "." -f 2) +NEW_VERSION_THIRD_NUMBER=$(echo "$NEW_VERSION" | cut -d "." -f 3) + +function assertNumberIsIncrementedByOne { + NEW_NUMBER=$1 + CURRENT_NUMBER=$2 + NUMBER_TYPE=$3 + DIFFERENCE="$(($NEW_NUMBER-$CURRENT_NUMBER))" + if [ "$DIFFERENCE" -ne 1 ]; then + echo "[ERROR] $NUMBER_TYPE number($CURRENT_NUMBER) has changed to" \ + "$NEW_NUMBER but it should be incremented by max 1." + exit 1; + fi +} + +if [ "$CURRENT_VERSION_FIRST_NUMBER" != "$NEW_VERSION_FIRST_NUMBER" ]; then + assertNumberIsIncrementedByOne "$NEW_VERSION_FIRST_NUMBER" "$CURRENT_VERSION_FIRST_NUMBER" "Major" + + if [ "$NEW_VERSION_SECOND_NUMBER" -ne 0 ] || [ "$NEW_VERSION_THIRD_NUMBER" -ne 0 ]; then + echo "[ERROR] Minor and patch number should be 0 when major number is bumped." + exit 1; + fi +elif [ "$CURRENT_VERSION_SECOND_NUMBER" != "$NEW_VERSION_SECOND_NUMBER" ]; then + assertNumberIsIncrementedByOne "$NEW_VERSION_SECOND_NUMBER" \ + "$CURRENT_VERSION_SECOND_NUMBER" "Minor" + + if [ "$NEW_VERSION_THIRD_NUMBER" -ne 0 ]; then + echo "[ERROR] Patch number should be 0 when minor number is bumped." + exit 1; + fi +elif [ "$CURRENT_VERSION_THIRD_NUMBER" != "$NEW_VERSION_THIRD_NUMBER" ]; then + assertNumberIsIncrementedByOne "$NEW_VERSION_THIRD_NUMBER" "$CURRENT_VERSION_THIRD_NUMBER" "Patch" +fi + +echo "bump version in pom.xml" +./mvnw -e --no-transfer-progress versions:set -DnewVersion="$NEW_VERSION-SNAPSHOT" +./mvnw -e --no-transfer-progress versions:commit diff --git a/.ci/check-performance-regression.sh b/.ci/check-performance-regression.sh new file mode 100755 index 000000000000..30b207497450 --- /dev/null +++ b/.ci/check-performance-regression.sh @@ -0,0 +1,111 @@ +#!/bin/bash + +set -e + +# Get the baseline seconds and config file from arguments +if [ "$#" -ne 2 ]; then + echo "Missing arguments!" + echo "Usage: $0 BASELINE_SECONDS CONFIG_FILE" + exit 1 +fi + +BASELINE_SECONDS=$1 +CONFIG_FILE=$2 + +# max difference tolerance in % +THRESHOLD_PERCENTAGE=10 +# JDK version +JDK_VERSION=25 +# sample project path +SAMPLE_PROJECT="./.ci-temp/jdk$JDK_VERSION" +# suppression file +SUPPRESSION_FILE="./config/projects-to-test/openjdk$JDK_VERSION-excluded.files" + +# execute a command and time it +# $TEST_COMMAND: command being timed +time_command() { + # execute the command and time it + /usr/bin/time -o time.temp -q -f "%e" "$@" &>result.tmp + + cat time.temp +} + +# execute the benchmark a few times to calculate the average metrics +# $JAR_PATH: path of the jar file being benchmarked +execute_benchmark() { + local JAR_PATH=$1 + if [ -z "$JAR_PATH" ]; then + echo "Missing JAR_PATH as an argument." + exit 1 + fi + + local TOTAL_SECONDS=0 + local NUM_EXECUTIONS=3 + + [ ! -d "$SAMPLE_PROJECT" ] && + echo "Directory $SAMPLE_PROJECT DOES NOT exist." | exit 1 + + # add suppressions to config file + sed -i "/ /r $SUPPRESSION_FILE" \ + "$CONFIG_FILE" + + for ((i = 0; i < NUM_EXECUTIONS; i++)); do + local CMD=(java -jar "$JAR_PATH" -c "$CONFIG_FILE" \ + -x .git -x module-info.java "$SAMPLE_PROJECT") + local BENCHMARK=($(time_command "${CMD[@]}")) + TOTAL_SECONDS=$(echo "$TOTAL_SECONDS + $BENCHMARK" | bc) + done + + # average execution time in patch + local AVERAGE_IN_SECONDS=$(echo "scale=2; $TOTAL_SECONDS / $NUM_EXECUTIONS" | bc) + echo "$AVERAGE_IN_SECONDS" +} + +# compare baseline and patch benchmarks +# $EXECUTION_TIME_SECONDS execution time of the patch +compare_results() { + local EXECUTION_TIME_SECONDS=$1 + if [ -z "$EXECUTION_TIME_SECONDS" ]; then + echo "Missing EXECUTION_TIME_SECONDS as an argument." + return 1 + fi + # Calculate absolute percentage difference for execution time + local DEVIATION_IN_SECONDS=$(echo "scale=4; \ + ((${EXECUTION_TIME_SECONDS} - ${BASELINE_SECONDS}) / ${BASELINE_SECONDS}) * 100" | bc) + DEVIATION_IN_SECONDS=$(echo "scale=4; \ + if ($DEVIATION_IN_SECONDS < 0) -($DEVIATION_IN_SECONDS) else $DEVIATION_IN_SECONDS" | bc) + + echo "Execution Time Difference: $DEVIATION_IN_SECONDS%" + + # Check if differences exceed the maximum allowed difference + if (( $(echo "$DEVIATION_IN_SECONDS > $THRESHOLD_PERCENTAGE" | bc -l) )); then + echo "Difference exceeds the maximum allowed difference (${DEVIATION_IN_SECONDS}% \ + > ${THRESHOLD_PERCENTAGE}%)!" + return 1 + else + echo "Difference is within the maximum allowed difference (${DEVIATION_IN_SECONDS}% \ + <= ${THRESHOLD_PERCENTAGE}%)." + return 0 + fi +} + +# package patch +./mvnw -e --no-transfer-progress -Passembly,no-validations package + +# start benchmark +echo "Benchmark launching..." +AVERAGE_IN_SECONDS="$(execute_benchmark "$(find "./target/" -type f -name "checkstyle-*-all.jar")")" + +# print the command execution result +echo "================ MOST RECENT COMMAND RESULT =================" +cat result.tmp + +echo "===================== BENCHMARK SUMMARY ====================" +echo "Execution Time Baseline: ${BASELINE_SECONDS} s" +echo "Average Execution Time: ${AVERAGE_IN_SECONDS} s" +echo "============================================================" + +# compare result with baseline +compare_results "$AVERAGE_IN_SECONDS" + +exit $? diff --git a/.ci/checkchmod.sh b/.ci/checkchmod.sh new file mode 100755 index 000000000000..3a8e926b3132 --- /dev/null +++ b/.ci/checkchmod.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +set -e + +# CI environments may change file permissions; only executable bits are checked. +CHMOD=$(find -type f \ + -not -path '*/.git/*' \ + -not -path './mvnw' \ + -not -path './.ci-temp/*' \ + -a -type f -not -name '*.sh' \ + -a -type f -not -name '*.pl' \ + -a \( -type d -not -perm 775 -o -type f -executable \)) +if [[ -n $CHMOD ]]; then + echo "Expected mode for non '.sh' files is 664."; + echo "Files that violates this rule:" + for NAMEFILE in $CHMOD + do + echo "$NAMEFILE"; + done + exit 1; +fi + +# Check all '.sh' files for missing executable permission +CHMOD=$(find -type f \ + -not -path '*/.git/*' \ + -not -path './mvnw' \ + -name '*.sh' \ + -not -executable) + +if [[ -n $CHMOD ]]; then + echo "Expected mode for '.sh' files is 755."; + echo "Files that violates this rule:" + for NAMEFILE in $CHMOD + do + echo "$NAMEFILE"; + done + exit 1; +fi diff --git a/.ci/checker-framework.groovy b/.ci/checker-framework.groovy new file mode 100644 index 000000000000..21b4fcbee9e4 --- /dev/null +++ b/.ci/checker-framework.groovy @@ -0,0 +1,497 @@ +import groovy.transform.EqualsAndHashCode +import groovy.transform.Field +import groovy.transform.Immutable +import groovy.util.slurpersupport.GPathResult +import groovy.util.slurpersupport.NodeChildren +import groovy.xml.XmlUtil + +import java.util.regex.Matcher +import java.util.regex.Pattern + +@Field static final String USAGE_STRING = 'Usage groovy ' + + ".${File.separator}.ci${File.separator}checker-framework.groovy" + + ' [profile] [--list]\n' + +int exitCode = 1 +if (args.length == 1) { + exitCode = parseArgumentAndExecute(args[0]) +} +else { + throw new IllegalArgumentException(USAGE_STRING) +} +System.exit(exitCode) + +/** + * Parse the command line arguments passed in and execute the branch based on the arguments. + * + * @param argument command line argument + * @return {@code 0} if command executes successfully, {@code 1} otherwise + */ +private int parseArgumentAndExecute(final String argument) { + final int exitCode + final Set profiles = getCheckerFrameworkProfiles() + if (profiles.contains(argument)) { + exitCode = checkCheckerFrameworkReport(argument) + } + else if (argument == '--list') { + println 'Supported profiles:' + profiles.each { println it } + exitCode = 0 + } + else { + final String exceptionMessage = "Unexpected argument: '${argument}'\n" + USAGE_STRING + throw new IllegalArgumentException(exceptionMessage) + } + return exitCode +} + +/** + * Parse the pom.xml file to get all the available checker framework profiles. + * + * @return A set of all available checker framework profiles + */ +private static Set getCheckerFrameworkProfiles() { + final GPathResult mainNode = new XmlSlurper().parse(".${File.separator}pom.xml") + final NodeChildren ids = mainNode.profiles.profile.id as NodeChildren + final Set profiles = new HashSet<>() + ids.each { final node -> + final GPathResult id = node as GPathResult + final String idText = id.text() + if (idText.startsWith('checker-')) { + profiles.add(idText) + } + } + return profiles +} + +/** + * Check the generated checker framework report. Parse the errors and compare them with + * the suppressed errors. + * + * @param profile the checker framework profile to execute + * @return {@code 0} if checker framework report is as expected, {@code 1} otherwise + */ +private static int checkCheckerFrameworkReport(final String profile) { + final XmlParser xmlParser = new XmlParser() + final String suppressedErrorsFileUri = + ".${File.separator}config${File.separator}" + + "checker-framework-suppressions${File.separator}${profile}-suppressions.xml" + final List> checkerFrameworkErrors = getCheckerFrameworkErrors(profile) + List errors = Collections.emptyList() + if (!checkerFrameworkErrors.isEmpty()) { + errors = getErrorFromText(checkerFrameworkErrors) + } + final File suppressionFile = new File(suppressedErrorsFileUri) + List suppressedErrors = Collections.emptyList() + if (suppressionFile.exists()) { + final Node suppressedErrorsNode = xmlParser.parse(suppressedErrorsFileUri) + suppressedErrors = getSuppressedErrors(suppressedErrorsNode) + } + + String newSuppression = '\n' + errors.each { + newSuppression += it.toXmlString() + '\n' + } + if (errors.isEmpty()) { + newSuppression += '\n' + } + newSuppression += '\n' + final FileWriter writer = new FileWriter(suppressionFile) + writer.write(newSuppression) + writer.flush() + writer.close() + + return compareErrors(errors, suppressedErrors) +} + +/** + * Generates the checker framework report and filters out the errors. + * + * @param profile the checker framework profile to execute + * @return A set of errors + */ +private static List> getCheckerFrameworkErrors(final String profile) { + final List checkerFrameworkLines = new ArrayList<>() + final String command = "mvn -e --no-transfer-progress clean compile" + + " -P${profile},no-validations" + println("Execution of Checker by command:") + println(command) + final ProcessBuilder processBuilder = new ProcessBuilder(getOsSpecificCmd(command).split(' ')) + processBuilder.redirectErrorStream(true) + final Process process = processBuilder.start() + + BufferedReader reader = null + try { + reader = new BufferedReader(new InputStreamReader(process.inputStream)) + String lineFromReader = reader.readLine() + while (lineFromReader != null) { + println(lineFromReader) + checkerFrameworkLines.add(lineFromReader) + lineFromReader = reader.readLine() + } + int exitCode = process.waitFor() + if (exitCode != 0) { + throw new IllegalStateException("Maven process exited with error code: " + exitCode) + } + } finally { + reader.close() + } + + final List> checkerFrameworkErrors = new ArrayList<>() + for (int index = 0; index < checkerFrameworkLines.size(); index++) { + final String line = checkerFrameworkLines.get(index) + if (line.startsWith('[WARNING]')) { + final List error = new ArrayList<>() + error.add(line) + int currentErrorIndex = index + 1 + while (currentErrorIndex < checkerFrameworkLines.size()) { + final String currentLine = checkerFrameworkLines.get(currentErrorIndex) + if (currentLine.startsWith('[ERROR]') + || currentLine.startsWith('[INFO]') + || currentLine.startsWith('[WARNING]')) { + break + } + error.add(currentLine) + currentErrorIndex++ + } + checkerFrameworkErrors.add(error) + } + } + return checkerFrameworkErrors +} + +/** + * Get OS specific command. + * + * @param cmd input command + * @return OS specific command + */ +private static String getOsSpecificCmd(final String cmd) { + final String osSpecificCmd + if (System.getProperty('os.name').toLowerCase().contains('windows')) { + osSpecificCmd = "cmd /c ${cmd}" + } + else { + osSpecificCmd = cmd + } + return osSpecificCmd +} + +/** + * Get a set of {@link CheckerFrameworkError} from text. + * + * @param errorsText errors in text format + * @return A set of errors + */ +private static List getErrorFromText(final List> errorsList) { + final List errors = new ArrayList<>() + final Pattern errorExtractingPattern = Pattern + .compile('.*[\\\\/](src[\\\\/].*\\.java):\\[(\\d+)[^]]*][^\\[]*\\[([^]]*)](.*)') + final Pattern filePathExtractingPattern = Pattern.compile('\\[WARNING] (.*\\.java)') + final int fileNameGroup = 1 + final int lineNumberGroup = 2 + final int specifierGroup = 3 + final int messageGroup = 4 + errorsList.each { final errorList -> + final String error = errorList.get(0) + final Matcher matcher = errorExtractingPattern.matcher(error) + final List details = new ArrayList<>() + String fileName = null + String specifier = null + String message = null + String lineContent = null + int lineNumber = 0 + if (matcher.matches()) { + fileName = matcher.group(fileNameGroup).replace('\\', '/') + lineNumber = Integer.parseInt(matcher.group(lineNumberGroup)) + specifier = XmlUtil.escapeXml(matcher.group(specifierGroup).trim()) + message = XmlUtil.escapeXml(matcher.group(messageGroup).trim()) + .replaceAll('temp-var-\\d+', 'temp-var') + + final Matcher filePathMatcher = filePathExtractingPattern.matcher(error) + if (filePathMatcher.find()) { + final String absoluteFilePath = filePathMatcher.group(1) + final File file = new File(absoluteFilePath) + lineContent = XmlUtil.escapeXml(file.readLines().get(lineNumber - 1).trim()) + } + + if (errorList.size() > 1) { + for (int index = 1; index < errorList.size(); index++) { + final String errorDetail = XmlUtil.escapeXml(errorList.get(index).trim()) + if (!errorDetail.isEmpty()) { + details.add(errorDetail.replaceAll('capture#\\d+', 'capture')) + } + } + } + + // Errors extracted from Checker Framework Report are by default considered stable. + final boolean isUnstable = false + final CheckerFrameworkError checkerFrameworkError = new CheckerFrameworkError( + fileName, specifier, message, details, lineContent, lineNumber, isUnstable) + errors.add(checkerFrameworkError) + } + } + return errors.sort() +} + +/** + * Get the suppressed error. All child nodes of the main {@code suppressedErrors} node + * are parsed. + * + * @param mainNode the main {@code suppressedErrors} node + * @return A set of suppressed errors + */ +private static List getSuppressedErrors(final Node mainNode) { + final List children = mainNode.children() + final List suppressedErrors = new ArrayList<>(children.size()) + + children.each { final node -> + final Node errorNode = node as Node + suppressedErrors.add(getError(errorNode)) + } + return suppressedErrors +} + +/** + * Construct the {@link CheckerFrameworkError} object from the {@code checkerFrameworkError} + * XML node. The suppression file is parsed to get the {@code checkerFrameworkError} node. + * + * @param errorNode the {@code error} XML node + * @return {@link CheckerFrameworkError} object represented by the {@code error} XML node + */ +private static CheckerFrameworkError getError(final Node errorNode) { + final List childNodes = errorNode.children() + + final List details = new ArrayList<>() + String fileName = null + String specifier = null + String message = null + String lineContent = null + final int lineNumber = -1 + childNodes.each { + final Node childNode = it as Node + final String text = childNode.name() + + final String childNodeText = XmlUtil.escapeXml(childNode.text()) + switch (text) { + case 'fileName': + fileName = childNodeText + break + case 'specifier': + specifier = childNodeText + break + case 'message': + message = childNodeText + break + case 'lineContent': + lineContent = childNodeText + break + case 'details': + final String[] detailsArray = childNodeText.split('\\n') + detailsArray.each { final detail -> + final String detailString = detail.trim() + if (!detailString.isEmpty()) { + details.add(detailString) + } + } + } + } + + final String unstableAttributeValue = errorNode.attribute('unstable') + final boolean isUnstable = Boolean.parseBoolean(unstableAttributeValue) + + return new CheckerFrameworkError(fileName, specifier, message, details, lineContent, + lineNumber, isUnstable) +} + +/** + * Compare the actual and the suppressed errors. The comparison passes successfully + * (i.e. returns 0) when: + *
    + *
  1. Surviving and suppressed errors are equal.
  2. + *
  3. There are extra suppressed errors but they are unstable + * i.e. {@code unstable="true"}.
  4. + *
+ * The comparison fails when (i.e. returns 1) when: + *
    + *
  1. Surviving errors are not present in the suppressed list.
  2. + *
  3. There are errors in the suppression list that are not there is surviving list.
  4. + *
+ * + * @param actualErrors A set of actual errors reported by error prone + * @param suppressedErrors A set of suppressed errors from suppression file + * @return {@code 0} if comparison passes successfully + */ +private static int compareErrors(final List actualErrors, + final List suppressedErrors) { + final List unsuppressedErrors = + setDifference(actualErrors, suppressedErrors) + final List extraSuppressions = + setDifference(suppressedErrors, actualErrors) + + final int exitCode + if (actualErrors == suppressedErrors) { + exitCode = 0 + } + else if (unsuppressedErrors.isEmpty() + && !hasOnlyStableErrors(extraSuppressions)) { + exitCode = 0 + } + else { + if (!unsuppressedErrors.isEmpty()) { + println 'New surviving error(s) found:' + unsuppressedErrors.each { + printError(it) + } + } + if (!extraSuppressions.isEmpty() + && extraSuppressions.any { !it.isUnstable() }) { + println '\nUnnecessary suppressed error(s) found and should be removed:' + extraSuppressions.each { + if (!it.isUnstable()) { + printError(it) + } + } + } + exitCode = 1 + } + + if (exitCode == 0) { + println 'Build successful with no errors.' + } + + return exitCode +} + +/** + * Whether a set has only stable errors. + * + * @param errors A set of errors + * @return {@code true} if a set has only stable errors + */ +private static boolean hasOnlyStableErrors(final List errors) { + return errors.every { !it.isUnstable() } +} + +/** + * Prints the error. + * + * @param error error to print + */ +private static void printError(final CheckerFrameworkError error) { + println error.toXmlString() +} + +/** + * Determine the difference between 2 sets. The result is {@code setOne - setTwo}. + * + * @param setOne The first set in the difference + * @param setTwo The second set in the difference + * @return {@code setOne - setTwo} + */ +private static List setDifference(final List setOne, + final List setTwo) { + final List result = new ArrayList<>(setOne) + result.removeIf { final error -> setTwo.contains(error) } + return result +} + +/** + * A class to represent the XML {@code checkerFrameworkError} node. + */ +@EqualsAndHashCode(excludes = ['lineNumber', 'unstable']) +@Immutable +class CheckerFrameworkError implements Comparable { + + /** + * Error nodes present in suppressions file do not have a {@code lineNumber}. + * The {@code lineNumber} is set to {@code -1} for such errors. + */ + private static final int LINE_NUMBER_NOT_PRESENT_VALUE = -1 + + String fileName + String specifier + String message + List details + String lineContent + int lineNumber + + /** + * Whether the error is unstable. Unstable errors in suppression list are not flagged as + * unnecessary suppressions. + */ + boolean unstable + + @Override + String toString() { + String toString = """ + File Name: "${fileName}" + Specifier: "${specifier}" + Message: "${message}" + Line Contents: "${lineContent}\"""".stripIndent() + if (lineNumber != LINE_NUMBER_NOT_PRESENT_VALUE) { + toString += '\nLine Number: ' + lineNumber + } + + if (!details.isEmpty()) { + toString += '\nDetails: ' + details.get(0) + if (details.size() > 1) { + for (int index = 1; index < details.size(); index++) { + toString += '\n' + ' ' * 9 + details.get(index) + } + } + } + return toString + } + + @Override + int compareTo(CheckerFrameworkError other) { + int i = fileName <=> other.fileName + if (i != 0) { + return i + } + + i = specifier <=> other.specifier + if (i != 0) { + return i + } + + i = message <=> other.message + if (i != 0) { + return i + } + + i = details.join('') <=> other.details.join('') + if (i != 0) { + return i + + } + + return lineContent <=> other.lineContent + } + + /** + * XML format of the checker framework error. + * + * @return XML format of the checker framework error + */ + String toXmlString() { + String toXmlString = """ + + ${fileName} + ${specifier} + ${message} + ${lineContent} + """.stripIndent(10) + if (!details.isEmpty()) { + toXmlString += '
' + details.each { + toXmlString += '\n' + ' ' * 6 + it + } + toXmlString += '\n
\n' + } + toXmlString += '
' + return toXmlString + } + +} diff --git a/.ci/codenarc.groovy b/.ci/codenarc.groovy new file mode 100644 index 000000000000..5ecd8db68d7b --- /dev/null +++ b/.ci/codenarc.groovy @@ -0,0 +1,12 @@ +@Grapes( + @Grab(group='org.codenarc', module='CodeNarc', version='2.2.0') +) +@GrabExclude('org.codehaus.groovy:groovy-xml') +import java.lang.Object + +org.codenarc.CodeNarc.main([ + "-basedir=${args[0]}", + "-includes=**/${args[1]}", + '-rulesetfiles=./config/codenarc-rules.groovy.txt', + '-report=console', +] as String[]) diff --git a/.ci/codenarc.sh b/.ci/codenarc.sh new file mode 100755 index 000000000000..119b01d6990f --- /dev/null +++ b/.ci/codenarc.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +set -e + +CODENARC_REPORT=$(groovy ./.ci/codenarc.groovy ./.ci/ *.groovy) +CLEAN_CODENARC_REPORT="(p1=0; p2=0; p3=0)" +echo "$CODENARC_REPORT" +if [[ "$CODENARC_REPORT" != *"$CLEAN_CODENARC_REPORT"* ]]; then + exit 1 +fi diff --git a/.ci/common.sh b/.ci/common.sh index 0e5024f527d7..3ac2f97c139d 100755 --- a/.ci/common.sh +++ b/.ci/common.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Attention, there is no "-x" to avoid problems on Travis + set -e DEBUG=true @@ -10,8 +10,8 @@ DEBUG=true function should_run_job { local SKIP_JOB_BY_FILES=$1 local SKIP_FILES=$2 - ## OUT is needed to display the result of the commands for debugging - ## because some CIs don't like them being executed directly + # OUT is needed to display the result of the commands for debugging + # because some CIs don't like them being executed directly local OUT="" echo "Initial value of SKIP_JOB_BY_FILES: $SKIP_JOB_BY_FILES" @@ -19,40 +19,39 @@ function should_run_job { if [[ $SKIP_JOB_BY_FILES != 'false' ]]; then if [[ $DEBUG == "true" ]]; then - OUT=`git branch -r` + OUT=$(git branch -r) echo "List of branches: $OUT" - OUT=`git log -10 --format="%h %B"` + OUT=$(git log -10 --format="%h %B") echo "Current Branch log: $OUT" - OUT=`git log origin/master -10 --format="%h %B"` + OUT=$(git log origin/master -10 --format="%h %B") echo "origin/master log: $OUT" fi - ## Travis merges the PR commit into origin/master - ## This identifies the PR's original commit - ## if it notices a merge commit - local HEAD=`git rev-parse HEAD` + # This identifies the PR's original commit + # if it notices a merge commit + local HEAD=$(git rev-parse HEAD) if git show --summary HEAD | grep ^Merge: ; then - HEAD=`git log -n 1 --no-merges --pretty=format:"%H"` + HEAD=$(git log -n 1 --no-merges --pretty=format:"%H") fi - ## Identify previous commit to know how much to examine - ## Script assumes we are only working with 1 commit if we are in master - ## Otherwise, it looks for the common ancestor with master - local PREVIOUS_COMMIT=`git rev-parse HEAD~1` + # Identify previous commit to know how much to examine + # Script assumes we are only working with 1 commit if we are in master + # Otherwise, it looks for the common ancestor with master + local PREVIOUS_COMMIT=$(git rev-parse HEAD~1) if [[ $DEBUG == "true" ]]; then echo "Head commit: $HEAD" - OUT=$(git branch -a --contains $HEAD) + OUT=$(git branch -a --contains "$HEAD") echo "Master contains head commit: $OUT" - OUT=$(git branch -a --contains $HEAD | grep " origin/master$" || true) + OUT=$(git branch -a --contains "$HEAD" | grep " origin/master$" || true) echo "Master contains head commit (filtered): $OUT" fi # We are not in master if master does not contain the head commit - if [[ $(git branch -a --contains $HEAD | grep " origin/master$" \ + if [[ $(git branch -a --contains "$HEAD" | grep " origin/master$" \ | wc -c ) == 0 ]]; then - PREVIOUS_COMMIT=`git merge-base origin/master $HEAD` + PREVIOUS_COMMIT=$(git merge-base origin/master "$HEAD") fi echo "Previous Commit to start with: $PREVIOUS_COMMIT" @@ -66,16 +65,16 @@ function should_run_job { fi if [[ $DEBUG == "true" ]]; then - OUT=`git diff --name-only $HEAD $PREVIOUS_COMMIT` + OUT=$(git diff --name-only "$HEAD" "$PREVIOUS_COMMIT") echo "Files between top commit and previous: $OUT" - OUT=`git diff --name-only $HEAD $PREVIOUS_COMMIT | grep -vE "$SKIP_FILES" | cat` + OUT=$(git diff --name-only "$HEAD" "$PREVIOUS_COMMIT" | grep -vE "$SKIP_FILES" | cat) echo "Files should not skip: $OUT" fi # Identifies if the files involved in the commits between head and previous # is more than the list of skippable files - if [[ $(git diff --name-only $HEAD $PREVIOUS_COMMIT \ - | grep -vE "$SKIP_FILES" | cat | wc -c | sed 's/^ *//' ) > 0 ]]; then + if [[ $(git diff --name-only "$HEAD" "$PREVIOUS_COMMIT" \ + | grep -vE "$SKIP_FILES" | cat | wc -c | sed 's/^ *//' ) -gt 0 ]]; then SKIP_JOB_BY_FILES="false" else SKIP_JOB_BY_FILES="true" @@ -89,13 +88,13 @@ function should_run_job { local SKIP_JOB_BY_COMMIT="false" if [[ $DEBUG == "true" ]]; then - OUT=`git log -1 --format=%B` + OUT=$(git log -1 --format=%B) echo "Top commit message: $OUT" fi # Note: this command only works in master branch - if [ $(git log -1 --format=%B | grep -E "\[maven-release-plugin\] prepare release" \ - | cat | wc -l) -lt 1 ]; + if [ "$(git log -1 --format=%B | grep -E "\[maven-release-plugin\] prepare release" \ + | cat | wc -l)" -lt 1 ]; then SKIP_JOB_BY_COMMIT="false" else diff --git a/.ci/copy-site-to-sourceforge.sh b/.ci/copy-site-to-sourceforge.sh deleted file mode 100755 index 94e3bb4f2068..000000000000 --- a/.ci/copy-site-to-sourceforge.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env bash - -set -e - -PREV_RELEASE=$1 -RELEASE=$2 - -echo "PREVIOUS RELEASE version:"$PREV_RELEASE -echo "RELEASE version:"$RELEASE - -if [[ -z $RELEASE ]]; then - echo "Problem to calculate release version." - exit 1 -fi -if [[ -z $PREV_RELEASE ]]; then - echo "Problem to calculate previous release version." - exit 1 -fi - -SF_USER=romanivanov -############################# -echo "Please provide password for $SF_USER,checkstyle@shell.sourceforge.net" -echo "exit" | ssh -t $SF_USER,checkstyle@shell.sourceforge.net create - -##### - -mkdir -p .ci-temp -cd .ci-temp -rm -fr checkstyle.github.io -echo "Clone by ssh only to avoid passwords on push" -git clone git@github.com:checkstyle/checkstyle.github.io.git -echo "clean up git files" -rm -rf checkstyle.github.io/.git -rm -rf checkstyle.github.io/CNAME -echo "Archiving ..." -tar cfz checkstyle.github.io.tar.gz checkstyle.github.io -echo "Uploading to sourceforge ..." -scp checkstyle.github.io.tar.gz \ - $SF_USER,checkstyle@shell.sourceforge.net:/home/project-web/checkstyle/ - -############################# - -ssh $SF_USER,checkstyle@shell.sourceforge.net << EOF - -echo "Swap html content" -cd /home/project-web/checkstyle -tar -xzvf checkstyle.github.io.tar.gz -mv htdocs htdocs-$PREV_RELEASE -mv checkstyle.github.io htdocs - -echo "create .htaccess for dtds redirection" -cat <> htdocs/.htaccess -Redirect 301 "/dtds" "https://checkstyle.org/dtds" -RedirectMatch 301 "/version/.*/dtds/(.*)" "https://checkstyle.org/dtds/\$1" -HTACCESS -chmod o+r htdocs/.htaccess - -ln -s /home/project-web/checkstyle/reports htdocs/reports -echo "remove dtds folder from unsecure web site" -rm -r htdocs/dtds -echo "restore folder with links to old releases" -mv htdocs-$PREV_RELEASE/version htdocs - -echo "Archiving" -tar cfz htdocs-$PREV_RELEASE.tar.gz htdocs-$PREV_RELEASE/ -mv htdocs-$PREV_RELEASE.tar.gz htdocs-archive/ -rm -rf htdocs-$PREV_RELEASE/ - -echo "Extracting archive to previous releases documentation" -tar -xzvf htdocs-archive/htdocs-$PREV_RELEASE.tar.gz -C htdocs-version/ --same-owner \ ---exclude="*/apidocs" \ ---exclude="*/xref" --exclude="*/xref-test" --exclude="*/cobertura" --exclude="*/dsm" \ ---exclude="*/api" --exclude="reports" --exclude="jacoco" --exclude="dtds" \ ---exclude="dependency-updates-report.html" --exclude="plugin-updates-report.html" \ ---exclude="jdepend-report.html" --exclude="failsafe-report.html" \ ---exclude="surefire-report.html" \ ---exclude="linkcheck.html" --exclude="findbugs.html" --exclude="taglist.html" \ ---exclude="releasenotes_old.html" --exclude="dependencies.html" - -echo "Make a link to make it accessible from web" -ln -f -s \$(pwd)/htdocs-version/htdocs-$PREV_RELEASE \$(pwd)/htdocs/version/$PREV_RELEASE - -EOF diff --git a/.ci/diff-report.sh b/.ci/diff-report.sh new file mode 100755 index 000000000000..da816aaae018 --- /dev/null +++ b/.ci/diff-report.sh @@ -0,0 +1,140 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh + +# Validates the URL, checks if it is a raw link, and exits if it is not. We +# expect users to provide a raw gist or GitHub link. +validate_url () { + URL=$1 + + VALID_URL_REGEX='^(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]' + VALID_URL_REGEX+='\.[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]$' + + if [[ -z "$URL" ]]; then + # It is ok for a URL to be empty, we use this later in the workflow + # to determine what "mode" we should generate report with. + echo "URL is empty." + elif [[ "$URL" == *: ]]; then + echo "Parameter '${URL}' is incorrectly formatted, please use the following format:" + echo "'Parameter name: https://gist.githubusercontent.com/username/gist_id/raw/file'" + echo "Parameter name and URL must be separated by a colon and single space only." + exit 1 + elif [[ "$URL" != *"raw"* ]]; then + echo "URL '${URL}' must be a direct raw link to a gist or GitHub file." + exit 1 + elif ! [[ "$URL" =~ $VALID_URL_REGEX ]]; then + echo "URL '${URL}' does not match regexp '${VALID_URL_REGEX}'." + exit 1 + else + echo "URL '${URL}' is valid." + fi +} + +case $1 in + +# Downloads all files necessary to generate regression report to the parent directory. +download-files) + checkForVariable "GITHUB_TOKEN" + mkdir -p .ci-temp + echo "Downloading files..." + + # Check for projects link from PR, if not found use default from contribution repo + LINK="${DIFF_PROJECTS_LINK:-$DEFAULT_PROJECTS_LINK}" + + # Determine the extension of the projects file + PROJECTS_FILENAME=$(basename "$LINK") + EXTENSION="${PROJECTS_FILENAME##*.}" + + echo "Downloading project list ${LINK}" + curl --fail-with-body -X GET "${LINK}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o ".ci-temp/projects.${EXTENSION}" + + if [ -n "$NEW_MODULE_CONFIG_LINK" ]; then + echo "Downloading new module config ${NEW_MODULE_CONFIG_LINK}" + curl --fail-with-body -X GET "${NEW_MODULE_CONFIG_LINK}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o .ci-temp/new_module_config.xml + fi + + if [ -n "$DIFF_CONFIG_LINK" ]; then + echo "Downloading diff config ${DIFF_CONFIG_LINK}" + curl --fail-with-body -X GET "${DIFF_CONFIG_LINK}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o .ci-temp/diff_config.xml + fi + + if [ -n "$PATCH_CONFIG_LINK" ]; then + echo "Downloading patch config ${PATCH_CONFIG_LINK}" + curl --fail-with-body -X GET "${PATCH_CONFIG_LINK}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o .ci-temp/patch_config.xml + fi + ;; + +# Parses the text of the PR description, validates the URLs, and +# sets the environment variables. +# Expects PR description to be in a file called 'text'. +parse-pr-description-text) + + # parse parameters from PR description text + PROJECTS_FILE_PARAMETER=$(grep "^Diff Regression projects:" .ci-temp/text || true) + CONFIG_PARAMETER=$(grep "^Diff Regression config:" .ci-temp/text || true) + NEW_MODULE_CONFIG_PARAMETER=$(grep "^New module config:" .ci-temp/text || true) + PATCH_CONFIG_PARAMETER=$(grep "^Diff Regression patch config:" .ci-temp/text || true) + REPORT_LABEL_PARAMETER=$(grep "^Report label:" .ci-temp/text || true) + + echo "Parameters parsed from PR description:" + echo "PROJECTS_FILE_PARAMETER: '$PROJECTS_FILE_PARAMETER'" + echo "CONFIG_PARAMETER: '$CONFIG_PARAMETER'" + echo "NEW_MODULE_CONFIG_PARAMETER: '$NEW_MODULE_CONFIG_PARAMETER'" + echo "PATCH_CONFIG_PARAMETER: '$PATCH_CONFIG_PARAMETER'" + echo "REPORT_LABEL_PARAMETER: '$REPORT_LABEL_PARAMETER'" + + # extract URLs from text + PROJECTS_LINK=$(echo "$PROJECTS_FILE_PARAMETER" | sed -E 's/Diff Regression projects: //') + CONFIG_LINK=$(echo "$CONFIG_PARAMETER" | sed -E 's/Diff Regression config: //') + NEW_MODULE_CONFIG_LINK=$(echo "$NEW_MODULE_CONFIG_PARAMETER" | sed -E 's/New module config: //') + PATCH_CONFIG_LINK=$(echo "$PATCH_CONFIG_PARAMETER" | sed -E 's/Diff Regression patch config: //') + REPORT_LABEL=$(echo "$REPORT_LABEL_PARAMETER" | sed -E 's/Report label: //') + # trim + PROJECTS_LINK=$(echo "$PROJECTS_LINK" | tr -d '[:space:]') + CONFIG_LINK=$(echo "$CONFIG_LINK" | tr -d '[:space:]') + NEW_MODULE_CONFIG_LINK=$(echo "$NEW_MODULE_CONFIG_LINK" | tr -d '[:space:]') + PATCH_CONFIG_LINK=$(echo "$PATCH_CONFIG_LINK" | tr -d '[:space:]') + + echo "URLs extracted from parameters:" + echo "PROJECTS_LINK: '$PROJECTS_LINK'" + echo "CONFIG_LINK: '$CONFIG_LINK'" + echo "NEW_MODULE_CONFIG_LINK: '$NEW_MODULE_CONFIG_LINK'" + echo "PATCH_CONFIG_LINK: '$PATCH_CONFIG_LINK'" + echo "REPORT_LABEL: '$REPORT_LABEL'" + + echo "Validating PROJECTS_LINK..." + validate_url "$PROJECTS_LINK" + echo "Validating CONFIG_LINK..." + validate_url "$CONFIG_LINK" + echo "Validating NEW_MODULE_CONFIG_LINK..." + validate_url "$NEW_MODULE_CONFIG_LINK" + echo "Validating PATCH_CONFIG_LINK..." + validate_url "$PATCH_CONFIG_LINK" + + ./.ci/append-to-github-output.sh "projects_link" "$PROJECTS_LINK" + ./.ci/append-to-github-output.sh "config_link" "$CONFIG_LINK" + ./.ci/append-to-github-output.sh "new_module_config_link" "$NEW_MODULE_CONFIG_LINK" + ./.ci/append-to-github-output.sh "patch_config_link" "$PATCH_CONFIG_LINK" + ./.ci/append-to-github-output.sh "report_label" "$REPORT_LABEL" + ;; + +*) + echo "Unexpected argument: $1" + sleep 5s + false + ;; + +esac diff --git a/.ci/drone-io.sh b/.ci/drone-io.sh new file mode 100755 index 000000000000..e16c5ef72cd9 --- /dev/null +++ b/.ci/drone-io.sh @@ -0,0 +1,24 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh + +case $1 in + +restore-maven-cache) + mkdir -p .ci-temp + # public backup: + # https://sourceforge.net/projects/checkstyle/files/drone-io/drone-io-m2-repository.tar/download + curl --fail-with-body -o .ci-temp/cache.tar -SsL \ + https://www.dropbox.com/s/"sh1g8o4h16p4n""x6"/cache.tar?dl=0 + tar -xf .ci-temp/cache.tar -C / + rm .ci-temp/cache.tar + ;; + +*) + echo "Unexpected argument: $1" + sleep 5s + false + ;; + +esac diff --git a/.ci/eclipse-compiler-javac.sh b/.ci/eclipse-compiler-javac.sh index 6c7dab2aa30e..afae66807eb4 100755 --- a/.ci/eclipse-compiler-javac.sh +++ b/.ci/eclipse-compiler-javac.sh @@ -1,21 +1,46 @@ #!/bin/bash set -e +DEFAULT_JAVA_RELEASE=21 if [ -z "$1" ]; then echo "No parameters supplied!" - echo " The classpath of the project and it's libraries to compile must be supplied." + echo "Usage %0 [RELEASE]" + echo " CLASSPATH: The classpath of the project and it's libraries to compile (required)." + echo " RELEASE: The optional Java release. Default is ${DEFAULT_JAVA_RELEASE}." exit 1 fi +JAVA_RELEASE=${2:-$DEFAULT_JAVA_RELEASE} -ECJ_JAR="ecj-4.11.jar" -ECJ_MAVEN_VERSION="R-4.11-201903070500" +ECLIPSE_URL="http://ftp-stud.fht-esslingen.de/pub/Mirrors/eclipse/eclipse/downloads/drops4" +ECJ_MAVEN_VERSION=$(wget --quiet -O- "$ECLIPSE_URL/?C=M;O=D" | grep -o "R-[^/]*" | head -n1) +echo "Latest eclipse release is $ECJ_MAVEN_VERSION" + +ECJ_MAVEN_VERSION=$(wget --quiet -O- "$ECLIPSE_URL/?C=M;O=D" | grep -o "R-[^/]*" | head -n1) +ECJ_JAR=$(wget --quiet -O- "$ECLIPSE_URL/$ECJ_MAVEN_VERSION/" | grep -o "ecj-[^\"]*" | head -n1) ECJ_PATH=~/.m2/repository/$ECJ_MAVEN_VERSION/$ECJ_JAR -if [ ! -f $ECJ_PATH ]; then +if [ ! -f "$ECJ_PATH" ]; then echo "$ECJ_PATH is not found, downloading ..." - mkdir -p $(dirname "$ECJ_PATH") - ECLIPSE_URL="http://ftp-stud.fht-esslingen.de/pub/Mirrors/eclipse/eclipse/downloads/drops4" - wget $ECLIPSE_URL/$ECJ_MAVEN_VERSION/$ECJ_JAR -O $ECJ_PATH + cd target + wget $ECLIPSE_URL/"$ECJ_MAVEN_VERSION"/"$ECJ_JAR" + echo "test jar after download:" + jar -tvf "$ECJ_JAR" > /dev/null + echo "check compiler options" + ECJ_OPTIONS=org/eclipse/jdt/internal/compiler/impl/CompilerOptions.class + ECJ_OPTIONS_PATTERN='org.eclipse.jdt.core.compiler.problem.[^"]*' + jar -xf "$ECJ_JAR" $ECJ_OPTIONS + javap -constants $ECJ_OPTIONS | grep -o "$ECJ_OPTIONS_PATTERN" | sort > ecj.opt + grep -o "^[^=#]*" ../config/org.eclipse.jdt.core.prefs | sort > cs.opt + OPTIONS_DIFF=$(diff --unified cs.opt ecj.opt | cat) + if [ "${OPTIONS_DIFF}" != "" ] ; then + echo "JDT compiler options diff:" + echo "${OPTIONS_DIFF}" + echo please update "config/org.eclipse.jdt.core.prefs" file + exit 1 + fi + mkdir -p "$(dirname "$ECJ_PATH")" + cp "$ECJ_JAR" "$ECJ_PATH" + cd .. fi mkdir -p target/classes target/test-classes target/eclipse @@ -23,14 +48,18 @@ mkdir -p target/classes target/test-classes target/eclipse RESULT_FILE=target/eclipse/report.txt echo "Executing eclipse compiler, output is redirected to $RESULT_FILE..." -echo "java -jar $ECJ_PATH -target 1.8 -source 1.8 -cp $1 ..." +echo "java -jar $ECJ_PATH -target ${JAVA_RELEASE} -source ${JAVA_RELEASE} -cp $1 ..." set +e -java -jar $ECJ_PATH -target 1.8 -source 1.8 -encoding UTF-8 -cp $1 \ +java -jar "$ECJ_PATH" -target "${JAVA_RELEASE}" -source "${JAVA_RELEASE}" -encoding UTF-8 -cp "$1" \ -d target/eclipse-compile \ -properties config/org.eclipse.jdt.core.prefs \ -enableJavadoc \ -nowarn:[target/generated-sources/antlr] \ + -nowarn:[src/test/resources/] \ + -nowarn:[src/test/resources-noncompilable/] \ + -nowarn:[src/it/resources/] \ + -nowarn:[src/it/resources-noncompilable/] \ src/main/java \ target/generated-sources/antlr \ src/test/java \ @@ -44,13 +73,19 @@ if [[ $EXIT_CODE != 0 ]]; then cat $RESULT_FILE false else - # check compilation of resources, all WARN and INFO are ignored + JAVA_RELEASE=24 + echo "In eclipse, Preview of features is supported only at the latest source level" + echo "JAVA_RELEASE isset to ${JAVA_RELEASE}" + echo "Executing eclipse compiler on generated resources with all warnings suppressed..." set +e - java -jar $ECJ_PATH -target 1.8 -source 1.8 -cp $1 \ + # Compile test resources with all warnings suppressed + java -jar "$ECJ_PATH" -target "${JAVA_RELEASE}" -source "${JAVA_RELEASE}" -cp "$1" \ -d target/eclipse-compile \ + --enable-preview \ -nowarn \ src/main/java \ src/test/java \ + src/it/java \ target/generated-sources/antlr \ src/test/resources \ src/it/resources \ diff --git a/.ci/error-prone-check.groovy b/.ci/error-prone-check.groovy new file mode 100644 index 000000000000..f67e725ad717 --- /dev/null +++ b/.ci/error-prone-check.groovy @@ -0,0 +1,363 @@ +import groovy.transform.EqualsAndHashCode +import groovy.transform.Field +import groovy.transform.Immutable +import groovy.xml.XmlUtil +import groovy.xml.XmlParser + +import java.util.regex.Matcher +import java.util.regex.Pattern + +@Field static final String USAGE_STRING = "Usage groovy " + + ".${File.separator}.ci${File.separator}error-prone-check.groovy" + + " (compile | test-compile) [-g | --generate-suppression]\n" + +int exitCode = 1 +if (args.length == 2) { + exitCode = parseArgumentAndExecute(args[0], args[1]) +} +else if (args.length == 1) { + exitCode = parseArgumentAndExecute(args[0], null) +} +else { + throw new IllegalArgumentException(USAGE_STRING) +} +System.exit(exitCode) + +/** + * Parse the command line arguments passed in and execute the branch based on the arguments. + * compile - compile the source code of the project. + * test-compile - compile the test source code into the test destination directory. + * + * @param argument command line argument + * @return {@code 0} if command executes successfully, {@code 1} otherwise + */ +private int parseArgumentAndExecute(String argument, String flag) { + final int exitCode + if (argument in ["compile", "test-compile"]) { + if (flag != null && flag != "-g" && flag != "--generate-suppression") { + final String exceptionMessage = "Unexpected flag: '${flag}'\n" + USAGE_STRING + throw new IllegalArgumentException(exceptionMessage) + } + exitCode = checkErrorProneReport(argument, flag) + } + else { + final String exceptionMessage = "Unexpected argument: '${argument}'\n" + USAGE_STRING + throw new IllegalArgumentException(exceptionMessage) + } + return exitCode +} + +/** + * Check the generated error prone report. Parse the errors and compare them with the suppressed + * errors. + * + * @param profile the error prone profile to execute + * @param flag command line argument flag to determine output format + * @return {@code 0} if error prone report is as expected, {@code 1} otherwise + */ +private static int checkErrorProneReport(String profile, String flag) { + final XmlParser xmlParser = new XmlParser() + final String suppressedErrorsFileUri = + ".${File.separator}config${File.separator}" + + "error-prone-suppressions${File.separator}${profile}-phase-suppressions.xml" + final List errorProneErrors = getErrorProneErrors(profile) + Set errors = Collections.emptySet() + if (!errorProneErrors.isEmpty()) { + errors = getErrorFromText(errorProneErrors) + } + final File suppressionFile = new File(suppressedErrorsFileUri) + Set suppressedErrors = Collections.emptySet() + if (suppressionFile.exists()) { + final Node suppressedErrorsNode = xmlParser.parse(suppressedErrorsFileUri) + suppressedErrors = getSuppressedErrors(suppressedErrorsNode) + } + return compareErrors(errors, suppressedErrors, flag) +} + +/** + * Generates the error prone report and filters out the errors. + * + * @param profile the error prone profile to execute + * @return A set of errors + */ +private static List getErrorProneErrors(String profile) { + final List errorProneErrors = [] as ArrayList + final String command = "mvn -e --no-transfer-progress clean" + + " ${profile} -Perror-prone-${profile}" + println "Execution of error-prone by command:" + println command + final Process process = getOsSpecificCmd(command).execute() + process.in.eachLine { line -> + if (line.startsWith("[ERROR]")) { + errorProneErrors.add(line) + } + println(line) + } + process.waitFor() + return errorProneErrors +} + +/** + * Get OS specific command. + * + * @param cmd input command + * @return OS specific command + */ +private static String getOsSpecificCmd(String cmd) { + final String osSpecificCmd + if (System.getProperty("os.name").toLowerCase().contains('windows')) { + osSpecificCmd = "cmd /c ${cmd}" + } + else { + osSpecificCmd = cmd + } + return osSpecificCmd +} + +/** + * Get a set of {@link ErrorProneError} from text. + * + * @param errorsText errors in text format + * @return A set of errors + */ +private static Set getErrorFromText(List errorsText) { + final Set errors = new HashSet<>() + final Pattern errorExtractingPattern = Pattern + .compile(".*[\\\\/](.*\\.java):\\[(\\d+).*\\[(\\w+)](.*)") + final Pattern filePathExtractingPattern = Pattern.compile("\\[ERROR] (.*\\.java)") + final int sourceFileGroup = 1 + final int lineNumberGroup = 2 + final int bugPatternGroup = 3 + final int descriptionGroup = 4 + errorsText.each { error -> + final Matcher matcher = errorExtractingPattern.matcher(error) + String sourceFile = null + String bugPattern = null + String description = null + String lineContent = null + int lineNumber = 0 + if (matcher.matches()) { + sourceFile = matcher.group(sourceFileGroup) + lineNumber = Integer.parseInt(matcher.group(lineNumberGroup)) + bugPattern = matcher.group(bugPatternGroup).trim() + description = XmlUtil.escapeXml(matcher.group(descriptionGroup).trim()) + + final Matcher filePathMatcher = filePathExtractingPattern.matcher(error) + if (filePathMatcher.find()) { + final String absoluteFilePath = filePathMatcher.group(1) + final File file = new File(absoluteFilePath) + lineContent = XmlUtil.escapeXml(file.readLines().get(lineNumber - 1).trim()) + } + + final ErrorProneError errorProneError = new ErrorProneError( + sourceFile, bugPattern, description, lineContent, lineNumber) + errors.add(errorProneError) + } + } + return errors +} + +/** + * Get the suppressed error. All child nodes of the main {@code suppressedErrors} node + * are parsed. + * + * @param mainNode the main {@code suppressedErrors} node + * @return A set of suppressed errors + */ +private static Set getSuppressedErrors(Node mainNode) { + final List children = mainNode.children() + final Set suppressedErrors = new HashSet<>() + + children.each { node -> + final Node errorNode = node as Node + suppressedErrors.add(getError(errorNode)) + } + return suppressedErrors +} + +/** + * Construct the {@link ErrorProneError} object from the {@code error} XML node. + * The suppression file is parsed to get the {@code errorNode}. + * + * @param errorNode the {@code error} XML node + * @return {@link ErrorProneError} object represented by the {@code error} XML node + */ +private static ErrorProneError getError(Node errorNode) { + final List childNodes = errorNode.children() + + String sourceFile = null + String bugPattern = null + String description = null + String lineContent = null + final int lineNumber = -1 + childNodes.each { + final Node childNode = it as Node + final String text = childNode.name() + + final String childNodeText = XmlUtil.escapeXml(childNode.text()) + switch (text) { + case "sourceFile": + sourceFile = childNodeText + break + case "bugPattern": + bugPattern = childNodeText + break + case "description": + description = childNodeText + break + case "lineContent": + lineContent = childNodeText + break + } + } + + return new ErrorProneError(sourceFile, bugPattern, description, lineContent, lineNumber) +} + +/** + * Compare the actual and the suppressed errors. The comparison passes successfully + * (i.e. returns 0) when: + *
    + *
  1. Surviving and suppressed errors are equal.
  2. + *
+ * The comparison fails when (i.e. returns 1) when: + *
    + *
  1. Surviving errors are not present in the suppressed list.
  2. + *
  3. There are errors in the suppression list that are not there is surviving list.
  4. + *
+ * + * @param actualErrors A set of actual errors reported by error prone + * @param suppressedErrors A set of suppressed errors from suppression file + * @param flag command line argument flag to determine output format + * @return {@code 0} if comparison passes successfully + */ +private static int compareErrors(Set actualErrors, + Set suppressedErrors, + String flag) { + final Set unsuppressedErrors = + setDifference(actualErrors, suppressedErrors) + final Set extraSuppressions = + setDifference(suppressedErrors, actualErrors) + + final int exitCode + if (actualErrors == suppressedErrors) { + exitCode = 0 + } + else { + if (!unsuppressedErrors.isEmpty()) { + println "New surviving error(s) found:" + unsuppressedErrors.each { + printError(flag, it) + } + } + if (!extraSuppressions.isEmpty()) { + println "\nUnnecessary suppressed error(s) found and should be removed:" + extraSuppressions.each { + printError(flag, it) + } + } + exitCode = 1 + } + return exitCode +} + +/** + * Prints the error according to the nature of the flag. + * + * @param flag command line argument flag to determine output format + * @param error error to print + */ +private static void printError(String flag, ErrorProneError error) { + if (flag != null) { + println error.toXmlString() + } + else { + println error + } +} + +/** + * Determine the difference between 2 sets. The result is {@code setOne - setTwo}. + * + * @param setOne The first set in the difference + * @param setTwo The second set in the difference + * @return {@code setOne - setTwo} + */ +private static Set setDifference(final Set setOne, + final Set setTwo) { + final Set result = new TreeSet<>(setOne) + result.removeIf { error -> setTwo.contains(error) } + return result +} + +/** + * A class to represent the XML {@code error} node. + */ +@EqualsAndHashCode(excludes = "lineNumber") +@Immutable +class ErrorProneError implements Comparable { + + /** + * Error nodes present in suppressions file do not have a {@code lineNumber}. + * The {@code lineNumber} is set to {@code -1} for such errors. + */ + private static final int LINE_NUMBER_NOT_PRESENT_VALUE = -1 + + String sourceFile + String bugPattern + String description + String lineContent + int lineNumber + + @Override + String toString() { + String toString = """ + Source File: "${getSourceFile()}" + Bug Pattern: "${getBugPattern()}" + Description: "${getDescription()}" + Line Contents: "${getLineContent()}" + """.stripIndent() + if (getLineNumber() != LINE_NUMBER_NOT_PRESENT_VALUE) { + toString += 'Line Number: ' + getLineNumber() + } + return toString + } + + @Override + int compareTo(ErrorProneError other) { + int i = getSourceFile() <=> other.getSourceFile() + if (i != 0) { + return i + } + + i = getBugPattern() <=> other.getBugPattern() + if (i != 0) { + return i + } + + i = getLineContent() <=> other.getLineContent() + if (i != 0) { + return i + } + + return getDescription() <=> other.getDescription() + } + + /** + * XML format of the error. + * + * @return XML format of the error + */ + String toXmlString() { + return """ + + ${getSourceFile()} + ${getBugPattern()} + ${getDescription()} + ${getLineContent()} + + """.stripIndent(10) + } + +} + diff --git a/.ci/fast-forward-merge.sh b/.ci/fast-forward-merge.sh index bf118bc75d3e..c89bfda4b0bd 100755 --- a/.ci/fast-forward-merge.sh +++ b/.ci/fast-forward-merge.sh @@ -23,27 +23,27 @@ REPO=${FORK_USER_NAME}-fork LOCAL_USER_BRANCH=${FORK_USER_NAME}-${USER_BRANCH} echo "removing remote ${REPO} if present ..." -git remote rm ${REPO} | true +git remote rm "${REPO}" | true echo "adding remote ..." -git remote add ${REPO} https://github.com/${FORK_USER_NAME}/${GIT_REPO}.git -git fetch ${REPO} +git remote add "${REPO}" https://github.com/"${FORK_USER_NAME}"/${GIT_REPO}.git +git fetch "${REPO}" echo "removing remote ${LOCAL_USER_BRANCH} if present ..." -git branch -D ${LOCAL_USER_BRANCH} | true +git branch -D "${LOCAL_USER_BRANCH}" | true echo "creating local branch ..." -git checkout -b ${LOCAL_USER_BRANCH} ${REPO}/${USER_BRANCH} +git checkout -b "${LOCAL_USER_BRANCH}" "${REPO}"/"${USER_BRANCH}" echo "rebasing over master ..." git rebase master echo "merge to master ..." git checkout master -git merge ${LOCAL_USER_BRANCH} --ff-only +git merge "${LOCAL_USER_BRANCH}" --ff-only echo "removing local branch ..." -git branch -D ${LOCAL_USER_BRANCH} +git branch -D "${LOCAL_USER_BRANCH}" echo "removing remote ..." -git remote rm ${REPO} +git remote rm "${REPO}" diff --git a/.ci/generate-extra-site-links.sh b/.ci/generate-extra-site-links.sh new file mode 100755 index 000000000000..696b6b4a0484 --- /dev/null +++ b/.ci/generate-extra-site-links.sh @@ -0,0 +1,111 @@ +#!/bin/bash + +set -e + +source ./.ci/util.sh + +PR_NUMBER=$1 +AWS_FOLDER_LINK=$2 + +if [[ -z $PR_NUMBER || -z $AWS_FOLDER_LINK ]]; then + echo "not all parameters are set" + echo "Usage: $BASH_SCRIPT " + exit 1 +fi + +checkForVariable "GITHUB_TOKEN" +checkForVariable "GITHUB_REPOSITORY_OWNER" +echo "PR_NUMBER=$PR_NUMBER" +echo "AWS_FOLDER_LINK=$AWS_FOLDER_LINK" + +GITHUB_API_RESPONSE=$(curl --fail-with-body -Ls \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer $GITHUB_TOKEN" \ + "https://api.github.com/repos/$GITHUB_REPOSITORY_OWNER/checkstyle/pulls/$PR_NUMBER/files?per_page=100") +echo "GITHUB_API_RESPONSE=$GITHUB_API_RESPONSE" + +# Extract a list of the changed xdocs in the pull request. For example 'xdoc/config_misc.xml'. +# We ignore template files and deleted files. +CHANGED_XDOCS_PATHS=$(echo "$GITHUB_API_RESPONSE" \ + | jq -r '.[] | select(.status != "removed") | .filename' \ + | grep src/site/xdoc/ \ + | grep -v '.*xml.template$' \ + || true) +echo "CHANGED_XDOCS_PATHS=$CHANGED_XDOCS_PATHS" + +if [[ -z "$CHANGED_XDOCS_PATHS" ]]; then + echo "[WARN] No xdocs were changed in the pull request." + exit 0 +fi + +# Fetch the diff of the pull request. +PR_DIFF=$(curl --fail-with-body -s \ + "https://patch-diff.githubusercontent.com/raw/$GITHUB_REPOSITORY_OWNER/checkstyle/pull/$PR_NUMBER.diff") + +# Iterate through all changed xdocs files. +while IFS= read -r CURRENT_XDOC_PATH; do + echo "Processing file: $CURRENT_XDOC_PATH" + + EARLIEST_CHANGE_LINE_NUMBER=$( + echo "$PR_DIFF" | grep -A 5 "diff.*$CURRENT_XDOC_PATH" | grep @@ | \ + head -1 | grep -oEi "[0-9]+" | head -1 + ) + if [[ -n "$EARLIEST_CHANGE_LINE_NUMBER" ]]; then + EARLIEST_CHANGE_LINE_NUMBER=$((EARLIEST_CHANGE_LINE_NUMBER + 3)) + echo "EARLIEST_CHANGE_LINE_NUMBER=$EARLIEST_CHANGE_LINE_NUMBER" + else + echo "No diff change for $CURRENT_XDOC_PATH; using diff context only." + fi + + SUBSECTION_ID="" + + DIFF_CONTEXT=$( + head -n "$EARLIEST_CHANGE_LINE_NUMBER" "$CURRENT_XDOC_PATH" | tac + ) + echo "DIFF_CONTEXT:" + echo "$DIFF_CONTEXT" + + # Extract name attribute only from section or subsection tags. + SECTION_NAME=$(echo "$DIFF_CONTEXT" | \ + grep -oP '<(?:section|subsection)[^>]*name="\K[^"]+' | head -1) + SECTION_NAME=$(echo "$SECTION_NAME" | tr -d '\n\r' | \ + sed 's/^[[:space:]]*//;s/[[:space:]]*$//') + + # Decode all HTML entities using Perl. + SECTION_NAME=$(echo "$SECTION_NAME" | \ + perl -MHTML::Entities -pe '$_ = decode_entities($_)') + + echo "SECTION_NAME found: '$SECTION_NAME'" + + if [[ -n "$SECTION_NAME" ]]; then + if echo "$SECTION_NAME" | grep -q '[^A-Za-z0-9 _-]'; then + echo "Section name has special characters; encoding..." + SUBSECTION_ID=$(echo "$SECTION_NAME" | tr -d '\n\r' | jq -sRr @uri | \ + sed 's/%/./g' | sed 's/\.20/_/g') + else + echo "Section name contains only allowed characters; replacing spaces..." + SUBSECTION_ID=${SECTION_NAME// /_} + fi + + # If the anchor starts with a digit, prefix it with an "a". + if [[ "$SUBSECTION_ID" =~ ^[0-9] ]]; then + SUBSECTION_ID="a$SUBSECTION_ID" + fi + echo "Derived SUBSECTION_ID: $SUBSECTION_ID" + else + echo "Warning: No section or subsection name found in $CURRENT_XDOC_PATH" + fi + + CURRENT_XDOC_NAME=$( + echo "$CURRENT_XDOC_PATH" | sed 's/src\/site\/xdoc\/\(.*\)\.xml/\1/' | \ + sed 's/.vm//' + ) + echo "CURRENT_XDOC_NAME=$CURRENT_XDOC_NAME" + + echo "" >> .ci-temp/message + echo "$AWS_FOLDER_LINK/$CURRENT_XDOC_NAME.html#$SUBSECTION_ID" \ + >> .ci-temp/message + echo "Added link: $AWS_FOLDER_LINK/$CURRENT_XDOC_NAME.html#$SUBSECTION_ID" + + SUBSECTION_ID="" +done <<< "$CHANGED_XDOCS_PATHS" diff --git a/.ci/generate-website.sh b/.ci/generate-website.sh new file mode 100755 index 000000000000..6f0e3d646436 --- /dev/null +++ b/.ci/generate-website.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +git checkout "checkstyle-$TARGET_VERSION" + +echo "Generating web site" +./mvnw -e --no-transfer-progress site -Pno-validations \ + -Dmaven.javadoc.skip=false -Djdepend.skip=false + +git checkout origin/master diff --git a/.ci/google-java-format.sh b/.ci/google-java-format.sh new file mode 100755 index 000000000000..d4a406d6c173 --- /dev/null +++ b/.ci/google-java-format.sh @@ -0,0 +1,88 @@ +#!/bin/bash + +set -e + +JAR_PATH="$1" + +NONFORMATTED_LIST=( + config/google-java-format/excluded/compilable-input-paths.txt + config/google-java-format/excluded/noncompilable-input-paths.txt +) + +SUPPRESS_LTE_100="config/google-java-format/suppressions/suppress-diff-lte-100.txt" +SUPPRESS_GT_100_LTE_500="config/google-java-format/suppressions/suppress-diff-gt-100-lte-500.txt" +SUPPRESS_GT_500="config/google-java-format/suppressions/suppress-diff-gt-500.txt" + +is_suppressed() { + local suppress_file="$1" + local name="$2" + if grep -Fxq "$name" "$suppress_file"; then + return 0 + fi + return 1 +} + +echo "Checking that all excluded java files in this script have matching InputFormatted* file:" +NOT_FOUND_CONTENT=$(cat "${NONFORMATTED_LIST[@]}" \ + | sed -E 's/.*Input([^\.]+)\.java.*/\1/' \ + | while read -r name; do \ + [[ $(find ./src -type f -name "InputFormatted${name}.java") ]] \ + || echo "Create InputFormatted${name}.java for Input${name}.java";\ + done) + +if [[ $(echo -n "$NOT_FOUND_CONTENT" | wc --chars) -eq 0 ]]; then + echo "Excluded Input files matches to InputFormatted files." +else + echo "not found matches: $NOT_FOUND_CONTENT" + exit 1 +fi + +echo "Checking that all excluded java files have same size as matching InputFormatted* file:" +for list_file_path in "${NONFORMATTED_LIST[@]}"; do + while IFS= read -r path; do + size=$(sed -E 's|^[[:space:]]+||; s|//.*||' "$path" | wc -c) + name=$(basename "$path" | sed -E 's/Input([^\.]+)\.java/\1/') + formatted_path=$(find ./src -type f -name "InputFormatted${name}.java") + size_formatted=$(sed -E 's|^[[:space:]]+||; s|//.*||' "$formatted_path" | wc -c) + diff=$(( size - size_formatted )) + if (( diff < 0 )); then + diff=$(( -diff )) + fi + if (( diff > 500 )); then + if ! is_suppressed "$SUPPRESS_GT_500" "Input${name}.java"; then + echo -e "\033[1;31mError: Difference for Input${name}.java is more than 50 bytes (${diff})" + exit 1 + fi + elif (( diff > 100 )); then + if ! is_suppressed "$SUPPRESS_GT_100_LTE_500" "Input${name}.java"; then + echo -e "\033[1;31mError: Difference for Input${name}.java is more than 50 bytes (${diff})" + exit 1 + fi + elif (( diff > 50 )); then + if ! is_suppressed "$SUPPRESS_LTE_100" "Input${name}.java"; then + echo -e "\033[1;31mError: Difference for Input${name}.java is more than 50 bytes (${diff})" + exit 1 + fi + fi + done < "$list_file_path" +done + +echo "All excluded java files have same size as matching InputFormatted* file" + +echo "Formatting all Input files file at src/it/resources/com/google/checkstyle/test :" +COMPILABLE_INPUT_PATHS=($(find src/it/resources/com/google/checkstyle/test/ -name "Input*.java" \ + | grep -v -x -f config/google-java-format/excluded/compilable-input-paths.txt + )) + +for INPUT_PATH in "${COMPILABLE_INPUT_PATHS[@]}"; do + java -jar "$JAR_PATH" --replace "$INPUT_PATH" +done + +echo "Formatting all Non-compilable Input files file at src/it/resources-noncompilable/com/google/checkstyle/test :" +NON_COMPILABLE_INPUT_PATHS=($(find src/it/resources-noncompilable/com/google/checkstyle/test/ -name "Input*.java" \ + | grep -v -x -f config/google-java-format/excluded/noncompilable-input-paths.txt + )) + +for INPUT_PATH in "${NON_COMPILABLE_INPUT_PATHS[@]}"; do + java -jar "$JAR_PATH" --replace "$INPUT_PATH" +done diff --git a/.ci/idea-inspection.bat b/.ci/idea-inspection.bat new file mode 100644 index 000000000000..70bfcb7b86ad --- /dev/null +++ b/.ci/idea-inspection.bat @@ -0,0 +1,46 @@ +@echo off + +::---------------------------------------------------------------------- +:: IntelliJ IDEA inspections for checkstyle. +:: +:: Example: +:: SET IDEA_PATH=C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2017.2.1\bin\idea.bat +:: .ci\idea-inspection.bat +::---------------------------------------------------------------------- + +SET PROJECT_DIR=%CD%\ +SET INSPECTIONS_PATH=%CD%\config\intellij-idea-inspections.xml +SET RESULTS_DIR=%CD%\target\inspection-results +SET NOISE_LVL=v1 +SET IDEA_LOCATION= +SET IDEA_PROPERTIES=%CD%\config\intellij-idea-inspections.properties + +::Check IDEA_PATH env variable +IF EXIST %IDEA_PATH% SET ( + SET IDEA_LOCATION=%IDEA_PATH% + goto run +) ELSE ( + echo IDEA_PATH variable not found. +) + +::Try to search in path +FOR /f "delims=" %%i IN ('"where idea.bat"') DO SET IDEA_LOCATION="%%i" +if [%IDEA_LOCATION%] NEQ [] ( + goto run +) ELSE ( + echo IntelliJ IDEA was not found in path. + exit /b +) + +:run +mkdir %RESULTS_DIR% +del %RESULTS_DIR%\*.* /s /q + +mkdir .idea\scopes +copy config\intellij-idea-inspection-scope.xml .idea\scopes + +::Execute compilation of Checkstyle to generate all source files +call mvnw.cmd -e compile + +::Launch inspections +call "%IDEA_LOCATION%" inspect %PROJECT_DIR% %INSPECTIONS_PATH% %RESULTS_DIR% -%NOISE_LVL% diff --git a/.ci/idea-inspection.sh b/.ci/idea-inspection.sh new file mode 100755 index 000000000000..e457e25b05d1 --- /dev/null +++ b/.ci/idea-inspection.sh @@ -0,0 +1,75 @@ +#!/bin/bash -e + +################################################# +# IntelliJ IDEA inspections for checkstyle. +# +# Example Mac OS: +# IDEA_PATH="/Applications/IntelliJ IDEA.app/Contents/MacOS/idea" ./.ci/idea-inspection.sh +# +# Example Linux: +# export IDEA_PATH=$HOME/java/idea-IU-172.4574.11 && ./.ci/idea-inspection.sh +################################################# + +PROJECT_DIR=$PWD/ +INSPECTIONS_PATH=$PWD/config/intellij-idea-inspections.xml +RESULTS_DIR=$PWD/target/inspection-results +NOISE_LVL=v1 +# we need to export this variable as it is required for idea.sh script +export IDEA_PROPERTIES=$PWD/config/intellij-idea-inspections.properties + +# Check IDEA_PATH env variable +if [[ -z $IDEA_PATH ]]; then + echo "IDEA_PATH variable not found." + # Try to search in path + IDEA_PATH="$(which idea)" + if [ -z "$IDEA_PATH" ]; then + echo "IntelliJ IDEA was not found in path." + exit -1 + fi +fi + +# Execute compilation of Checkstyle to generate all source files +# YOU MUST BUILD PROJECT BEFORE INSPECTION EXECUTION!!! +./mvnw -e --no-transfer-progress clean compile + +echo "" +for i in {1..100}; do echo -n "#"; done +echo "" + +mkdir -p "$RESULTS_DIR" +rm -rf "$RESULTS_DIR"/* + +echo "Intellij Idea validation is about to start" +echo "Progress output will be flushed at end. Validation is in progress ..." + +# we pipe standard error to /dev/null to avoid messy IDEA output in console +IDEA_OUTPUT=$("$IDEA_PATH"/bin/inspect.sh "$PROJECT_DIR" "$INSPECTIONS_PATH" "$RESULTS_DIR" \ + -$NOISE_LVL 2>/dev/null) + +if [[ $IDEA_OUTPUT == "Already running" ]]; then + echo "It might be that Intellij Idea is running, please close it." + exit 1; +fi + +echo "Checking results ..." +PROBLEM_COUNT=$(grep -R " 0 ]]; then - echo "There are inspection problems. Review results at $RESULTS_DIR folder. Files:" - grep -Rl ") { - chomp; - next if m{$exclude}; - print "$_$/"; -} diff --git a/.ci/jsoref-spellchecker/whitelist.words b/.ci/jsoref-spellchecker/whitelist.words deleted file mode 100644 index 1287d1daea24..000000000000 --- a/.ci/jsoref-spellchecker/whitelist.words +++ /dev/null @@ -1,1471 +0,0 @@ -aaaa -aaaaaa -Aapt -aar -aarch -abbreviationaswordinname -abcun -abego -abstractcheck -abstractclassname -abstractfileset -abstractjavadoc -abstracttypeaware -ABx -Acceptabletokens -Acheckstyle -acm -Aconfig -adb -addons -adf -adr -AFDF -AFilter -aggregators -Agoogle -Aleksey -allchecks -allclasses -alot -ambig -Amessages -androidx -annotationlocation -annotationonsameline -annotationusestyle -anoninner -anoninnerlength -antfile -antlib -antlr -ANTLRv -Antrl -antrun -anttask -Aop -api -apidocs -apirefs -apogeum -apos -applet -appveyor -APRV -areaoftest -arget -argn -arity -Arquillian -arraycopy -arraylist -arraytrailingcomma -arraytypestyle -asda -ASF -ASingle -Aspectj -Asrc -assertj -ASTNo -asttreestringprinter -Asun -atclause -atclauseorder -ATest -AThis -atid -ation -atlassian -attlist -attr -autoboxing -autocomplete -autocrlf -Autoproxy -Autowire -Autowired -Autowiring -avax -avgt -avoiddoublebraceinitialization -avoidescapedunicodecharacters -avoidinlineconditionals -avoidnestedblocks -avoidnoargumentsuperconstructorcall -avoidstarimport -avoidstaticimport -awt -backend -backport -Backquote -Backticks -BADN -badpackage -baeldung -baratali -Barowski -basedir -basefont -basetag -baz -bbb -BBBB -bc -BCA -bcff -BClass -bdc -bdo -beanutils -Bechter -beforeexecutionexclusionfilefilter -bestpractices -bew -bfd -bintray -bitbucket -bitset -bjrke -blablabla -bleh -Blic -blockandinlinetags -blockcomment -blockcommentposition -blockcommentstyle -blockquote -blog -blogspot -Bludov -bluej -bluejcheckstyle -BNOT -Bolkensteyn -booleanexpressioncomplexity -bothfiles -bountysource -Bpmn -bracesareused -breadcrumbs -bsr -Bsubscribe -BTest -buf -bugdatabase -bugfixes -Bunsubscribe -bunzip -bw -BXOR -bykey -Bytecode -bzip -Cacheable -cachefile -callstack -camelcase -casegroup -catchparametername -cba -cbc -cbeaff -ccc -CCCC -CClass -ccomment -CDATA -cde -cdfd -Cdi -Cfg -Cfml -Cfoo -cfz -cgi -charset -CHDBACBF -CHDBEFIF -CHDCBAHA -CHDCDBGG -CHDCEAHH -CHDCFJDG -CHDCHAHD -CHDCHBAE -CHDDCDHH -CHDDIECH -CHDDIEDI -CHDFHHBB -CHDGBICD -CHDGHIDG -CHDGJCHC -CHDHDECF -CHDHGJGD -CHDHJECF -CHDJBFDB -checkchmod -checkconfig -checkouting -checkstyle -checkstyleanttask -checkstylecompilation -checkutil -chmod -chr -ci -cidfile -circleci -Claira -classdataabstractioncoupling -classfanoutcomplexity -classloader -classmemberimpliedmodifier -classname -classpath -classpathref -classtypeparametername -clazz -clemens -Clickable -Clientjunk -clirr -Cloneable -clp -clss -cmdline -CMP -cmt -CNAME -Cnt -cobertura -codacy -codeanalyzers -codeclimate -codeconv -codeconventions -codeconvtoc -codecov -codehaus -codeselectorpresentation -codeship -codestyle -colgroup -columnlimit -Combobox -commentsindentation -commerical -commitish -commonutil -Compat -Compiletime -Comspace -concat -config -configurationloader -Connell's -constantname -Contextualizable -contextualization -contextualized -Contextualizing -courtlink -courtlinkkk -covariantequals -COVEREDRATIO -cpio -cpp -crlf -cron -crossplatform -CSOFF -CSON -css -CStyle -csv -ctor -ctx -customimportorder -cvs -cyclomatic -cyclomaticcomplexity -cz -daaf -dalvik -Daniil -daniilyar -Darguments -Datasource -DATETIME -daveho -davidwalsh -Dcheckstyle -dcm -DDDD -Ddry -declarationorder -DECOMPRESSOR -ded -defau -defaultcasepresent -defaultcomeslast -delims -DENORMALIZER -Depedency -dependabot -Deque -DEREF -descendanttoken -descr -Deserializable -designforextension -DEST -destfile -Destructuring -detailast -detailastimpl -detailnodetreestringprinter -Dexec -dfn -Dfoo -Dforbiddenapis -dghj -Dgpg -Dgui -dhj -Diachenko -dirname -distelli -Djacoco -Dlinkcheck -DMail -Dmaven -doccheck -Dockter -doclet -DOCTYPE -documentationcomments -Don''t -donotignoreexceptions -Dorekit -DOTALL -doubletag -Dpi -Dpmd -Dpuppycrawl -dropdown -drydock -Dskip -dsm -Dsonar -Dspotbugs -Dstrict -Dtest -Dubinin -Duser -Dxml -Dxwiki -eb -ecj -eclemma -eclipsecommunityawards -ected -edb -edef -edf -edu -Eghj -ej -ejb -elasticsearch -elementdef -elif -elist -Ellipsize -elsif -emacs -emptyblock -emptycatchblock -emptyforinitializerpad -emptyforiteratorpad -emptylineseparator -emptystatement -emptytag -Emtpy -endeavours -endline -ent -enum -enumer -envvar -eol -eot -equalsavoidnull -equalshashcode -equalsverifier -erial -ERRORLEVEL -errorprone -esac -Eslint -esslingen -etsy -ev -Evt -Exceptiontest -executablestatementcount -executon -Exif -explicitinitialization -expr -Externalizable -faa -fallsthrough -fallthrough -fallthru -Fannotation -favicon -Fblocks -Fchecks -Fcheckstyle -fchurn -Fcoding -Fcom -fd -FDCB -FDCF -Fdesign -FDF -featuretested -FEF -ffd -fff -FFFD -FFFE -FFFF -Fheader -fht -fieldset -filebasic -filechooser -filefilters -filelength -filepath -fileset -filesetcheck -filestructure -filesystem -filetab -filetabcharacter -filetext -Fimports -finalclass -finalizer -finallocalvariable -finalparameters -findbugs -Findentation -firefox -firstsentence -FIXME -Fjava -Fjavadoc -Flas -flattr -flowtested -Flushables -Fmain -Fmetrics -Fmodifier -Fnaming -forbiddenapis -foreach -Fpuppycrawl -fq -fqn -freedomsponsors -Fregexp -Fresources -Frob -fsc -Fsizes -Ftl -Ftools -ftp -ftpclient -fullident -fullname -func -Fwhitespace -Fx -gav -generalform -genericwhitespace -Getenv -gg -gh -ghprb -gitattributes -github -githubusercontent -gitignore -Gjs -google -googleapis -googleblog -googleecommon -googlegroups -googlesource -govstrangefolder -gplus -gradle -gradlew -Grenner -grep -grepped -grp -Gsp -GString -Gtk -gui -gunzip -gwt -gx -gz -gzip -hadoop -hamcrest -Haml -hardcoded -hashcode -hashset -hashtable -hbase -hcoles -hdr -hdrsize -Headerjava -Hejl -herokuapp -HEXDIGIT -hh -hiddenfield -hideutilityclassconstructor -hipparchus -hne -Homepage -horizontalwhitespace -Hostname -href -htaccess -htag -htdocs -html -HTMLJS -htmlunit -http -hurz -iae -ibs -ico -icu -identifiernames -Idref -idx -Igno -IGNORETHIS -igorminar -IInterfacable -Ilja -illegalcatch -illegalimport -illegalinstantiation -illegalthrows -illegaltoken -illegaltokentext -illegaltype -Imag -Ime -img -iml -impl -importcontrol -importcontrolloader -importcontroltest -importorder -importrule -imprt -Incompatabilities -Inet -infinispan -initialiser -Inlined -inlining -innerassignment -Innerclass -INNERR -innertypelast -inplace -instanceof -Intelli -intellij -intercell -interfaceistype -interfacememberimpliedmodifier -interfacetypeparametername -invalidformat -invalidinherit -invalidjavadocposition -ioe -ioffset -IPv -isindex -isrutf -isset -issuecomment -issuehunt -itemvalue -ith -itr -itsallcode -ivanov -ivanovjr -IVersion -iws -Izmailov -jacoco -Jakub -jarchitect -javac -javadoc -javadocblocktaglocation -javadoccontentlocation -javadocdetailnodeparser -javadocmethod -javadocpackage -javadocparagraph -javadocpropertiesgenerator -javadocstyle -javadoctagcontinuationindentation -javadoctags -javadoctype -javadocvariable -Javaee -javaformat -javaguide -javall -javamail -javancss -javaparser -javarevisited -javascript -javase -javastrangefolder -javax -Jax -jayway -JB -JBoss -JButton -JCheck -JCombo -JComponent -jcp -jdbc -JDE -jdee -jdepend -jdk -jdt -jedit -jenkins -Jenkinsfile -jep -jetbrains -JFile -JFrame -jgit -jgrasp -jguru -jhu -jira -jitpack -jjva -jkl -JLabel -Jlo -jls -JNDI -jooq -JOption -jp -Jpa -JPanel -Jpdl -jpeg -jpf -jpg -jprofiler -jq -jqno -jquery -jre -JScroll -Jscs -jsecurity -Jsf -jshiell -JSJ -jslint -jsni -json -jsoref -jsp -JSplit -jsr -JTable -JText -JToggle -JTool -jtree -junit -junitpioneer -jvm -jxr -kailasam -kazgroup -kbd -kclee -KDoc -keygen -konstantinos -Kordas -Kotlin -kused -lambdaparametername -lbc -LBRACK -lbt -lcurly -leadsize -Leanback -leftcurly -len -lexer -lgpl -lharris -LHSOf -libcore -liberapay -libexec -lifecycle -linebreak -linecolumn -linelength -linkcheck -linkplain -linksource -linux -Lisetskii -lkuehne -llll -lmessage -LNOT -localctx -localfinalvariablename -localhost -localvariablename -Loggable -lombok -Loughran -lparen -lpb -lpl -lucene -lui -luiframework -LVL -LZMA -lzmash -madbean -magicnumber -mailhost -mailto -mainframemodel -marazmatic -Massol -mavenbadge -maxmethods -MCHECKSTYLE -mct -membername -MENFORCER -metadata -Metaspace -methodcount -methodlength -methodname -methodparampad -methodtypeparametername -MEZk -Micha -Microsoft -minimalistic -Mipmap -misconfigured -Misordered -missingctor -missingdeprecated -missingjavadocmethod -missingjavadocpackage -missingjavadoctype -missingoverride -missingswitchdefault -missingtag -mixin -mkdir -mkordas -MLINKCHECK -mockfile -mockito -modifiedcontrolvariable -modifierorder -Mohnen -mojohaus -moks -moradan -moz -MRELEASE -MSITE -MSONAR -mstudman -MTAGLIST -multicharacter -multiline -Multimap -multiplestringliterals -multiplevariabledeclarations -Multiset -multithreading -mutableexception -MVC -mvn -Mycheckstyle -mycompany -mycompanychecks -mycustom -myfile -myfolder -myformat -MYN -myname -mypackage -myproject -Mysql -mytag -n'th -NAMEFILE -nameofcompany -nameofdivision -nameofproject -namespace -Nanos -nbactions -nbia -nbsp -ncss -ndex -needbraces -NEGS -Nejmeh -NEQ -nestedfordepth -nestedifdepth -nestedtrydepth -netbeans -newdomain -newlineatendoffile -Nfc -Nfo -Niederhauser -nio -nlow -NMTOKEN -noarch -noarg -noarraytrailingcomma -noauto -nobr -noclone -nocstylearray -nodeps -NODESET -noembed -noenumtrailingcomma -noerr -nofinalizer -NOI -noinfo -noinspection -nojavadoc -nolinewrap -nonascii -noncompilable -nonconstantfieldnames -nondex -nonemptyatclausedescription -nonemptyblocks -NONGROUP -NONJAVA -nonjavadoc -nonnull -nonrequiredjavadoc -nonvalidating -noparentfile -noscript -nospace -Nothin -notjava -NOTNULL -nowarn -nowhitespaceafter -nowhitespacebefore -nowildcard -nowrap -npath -npathcomplexity -npe -npm -nts -nullanalysis -NULLCHECK -nullness -numberperline -numericliterals -nutsandbolts -nyu -objblock -oburn -ogg -olddomain -ololo -olympe -onestatement -onestatementperline -onetoplevel -onetoplevelclass -onevariableperline -oo -OOL -oopsla -opencollective -openjdk -operatorwrap -optgroup -optimisation -Optimizable -oraclejdk -orderedproperties -orderingandspacing -orekit -Orgorgan -orm -Osgi -oss -osx -otechie -outertypefilename -outertypenumber -outter -ove -overloadmethodsdeclarationorder -overloadsplit -overridable -Overriden -OVERRIDERS -packageannotation -packagecomment -packagedeclaration -packagediffdirectory -packageinfo -packagename -packagenamesloader -packageobjectfactory -packagestate -packge -packifc -packpub -Pageflow -pageview -Papaioannou -paraception -parameterassignment -parametername -parameternumber -paramnum -Parcelable -parenpad -parrt -parsetreetablepresentation -Passembly -pathcomplexity -pathelement -patreon -Paulicke -paypal -pbludov -pdf -Peclipse -perl -pex -pgjdbc -Pgpg -pguyot -php -picocli -pid -PIPESTATUS -pitest -pitesttyle -pkga -pkghtml -pkginfo -pkx -plugin -pmd -pmdruleset -PModel -png -Pno -Pointcut -pojo -Popup -Postgresql -powermock -Ppitest -prameterless -prebuilts -preformatted -printf -println -priva -programpractice -Proguard -propertycachefile -propertyfile -prot -PROTECTE -protonpack -pubconstr -pubifc -PUBLI -pubpub -pullrequest -puppycrawl -pw -pwd -px -py -qa -qalab -qaplug -Qube -qux -qw -qwe -qwerty -rawtypes -rb -RBRACK -rcurly -rdiachenko -RDz -reactivex -README -Readonly -rebased -rebasing -redundantimport -redundantmodifier -refactor -refactoring -refid -regex -regexp -regexpheader -regexpmultiline -regexponfilename -regexpsingleline -regexpsinglelinejava -relativized -releasenotes -remkop -requirethis -Rethrown -returncount -revwalk -rfe -rga -Rgb -rhs -RHSOf -rickgiles -rightcurly -rl -rnveach -romani -romanivanov -Rootsmorejunk -rp -rparen -rpmfind -rq -Rrridden -RRRR -RSPEC -rss -rtc -Rtl -ru -ruleset -Ruslan -rw -rx -sabaka -Sameline -saxonica -sbe -sbt -scache -Schneeberger -scm -scp -screenshot -Scss -sdk -selfexplanatory -Selkin -separatorwrap -servlet -SETPOINT -sevntu -sflogo -shengchen -Shiell -Shipil -shipilev -sickboy -sigsize -Simplifiable -simplifybooleanexpression -simplifybooleanreturn -singleline -singlelined -singlelinejavadoc -singlespaceseparator -sivakumar -Slawinski -slf -slist -Sms -smth -snyk -solr -som -someinner -somename -someoneelse -sonarcloud -sonarjava -sonarqube -sonarsource -sonatype -Sopov -sourcefile -sourceforce -sourceforge -sourcepath -sourcesets -spacebar -specialescape -spellchecker -spliterator -spotbugs -spotbugsreports -spotify -springframework -sqale -sqe -sql -src -ssh -ssl -stackexchange -stackoverflow -stackoverflowerror -stacktrace -standalone -staticvariablename -Stdlib -stdout -stedolan -stefanbirkner -stemp -stevewall -sthref -stmt -streamapi -strictfp -stringliteralequality -Studman -Styleable -styleguide -stylesheets -subdir -subelements -subext -subscope -sudo -suitebuilder -sukhodolsky -summaryjavadoc -superclasses -superclone -superfinalize -Superinterface -supertype -suppressioncommentfilter -suppressionfilter -suppressionsinglefilter -suppressionsloader -suppressionsstringprinter -suppressionxpathfilter -suppressionxpathsinglefilter -suppresswarnings -suppresswarningsfilter -suppresswarningsholder -suppresswithnearbycommentfilter -suppresswithplaintextcommentfilter -svg -svn -sxpath -sys -sysextensions -sysprop -systemout -systemtests -Taglib -taglist -taskdef -tbody -tcr -td -teamcity -technetwork -technotes -tected -Testik -testmodules -textlevel -Tfo -tfoot -thead -thejavageek -thesummaryfragment -thetaphi -thr -throwable -throwscount -Thymeleaf -tidelift -TKN -tmp -toc -todo -todocomment -tok -tokenizer -tokenks -tokennizer -tokentype -tolist -Toolbar -Touchscreen -trailingcomment -treelayout -treewalker -TRequest -tschneeberger -tstamp -tt -ttf -ttype -tw -typecastparenpad -typename -typeof -typevariablenames -uber -Ubuntu -ucc -UElement -ufeff -ul -UMD -UML -uname -uncomment -uncommentedmain -Unconstructable -unicode -Uninstantiable -uniq -uniqueproperties -Unitless -unlzma -unnecessaryparentheses -unnecessarysemicolonaftertypememberdeclaration -unnecessarysemicoloninenumeration -unnecessarysemicolonintrywithresources -Unproxyable -unregister -unsubscribe -unusedimports -unxz -uppercased -upperell -upsss -uri -url -userguide -username -usr -UTests -utf -UUID -UWF -uxxxx -Validator -VALUEEEE -vararg -variabledeclarationusagedistance -variabledistance -Veach -versioning -verticalwhitespace -Vetrenko -Veyor -Vfs -viesure -viewcvs -visibilitymodifier -visualstudio -VK -Vladislav -Vladlis -vm -vscode -Vtl -Wadl -Wakelock -Warni -wbr -Weakento -Webflow -Weblogic -Webp -website -webtoolkit -Wellformedness -wercker -wget -wheretobreak -whi -Whitebox -whitelist -whitespaceafter -whitespacearound -wholename -Wifi -wiki -wikipedia -wiktionary -woff -wontfix -wordpress -workaround -workflows -writetag -writingchecks -writingdoccomments -writingfilefilters -writingfilters -writingjavadocchecks -writinglisteners -Wsdl -www -xa -Xandy -xargs -xcode -xcommons -xdoc -xdocspagetitle -xerces -xf -xfeff -xfff -xfffa -xfffb -xffff -xffffffff -xffffffffffffffff -xg -Xhenseval -XHTML -xml -xmlcatalog -XMLHTTP -xmllogger -xmlns -xmlp -xmlstarlet -xmlvalidate -Xms -Xmx -xpath -xpathfilegeneratorastfilter -xpathfilegeneratorauditlistener -xpathfilter -xpathfilterelement -xpathmapper -xpathquerygenerator -xsd -Xshow -xsi -xsl -Xslt -xsltproc -XSO -Xss -xterm -xtr -xwiki -XXXX -xxxxxx -xxxxxxxxxx -XXXXXXXXXXXXXXXXXXXXXXXXXXXX -xy -XYzz -xz -xzvf -Yaml -Yaroslavtsev -yml -youtrack -Youtube -Yoyodyne -yyyy -Yzz -zf -zh -ZSH diff --git a/.ci/no-exception-test.sh b/.ci/no-exception-test.sh new file mode 100755 index 000000000000..dd0096ee3992 --- /dev/null +++ b/.ci/no-exception-test.sh @@ -0,0 +1,288 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh + +case $1 in + +guava-with-google-checks) + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "$CS_POM_VERSION" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#guava|/guava|/' projects-to-test-on.properties + cd ../../../ + cp src/main/resources/google_checks.xml .ci-temp/google_checks.xml + sed -i.'' 's/warning/ignore/' .ci-temp/google_checks.xml + cd .ci-temp/contribution/checkstyle-tester + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig ../../google_checks.xml \ + --mode single --allowExcludes -xm "-Dcheckstyle.failsOnError=false" \ + -p "$BRANCH" -r ../../.. + cd ../.. + removeFolderWithProtectedFiles contribution + rm google_checks.* + ;; + +guava-with-sun-checks) + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "$CS_POM_VERSION" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#guava|/guava|/' projects-to-test-on.properties + cd ../../../ + cp src/main/resources/sun_checks.xml .ci-temp/sun_checks.xml + sed -i.'' 's/value=\"error\"/value=\"ignore\"/' .ci-temp/sun_checks.xml + cd .ci-temp/contribution/checkstyle-tester + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig ../../sun_checks.xml \ + --mode single --allowExcludes -xm "-Dcheckstyle.failsOnError=false" \ + -p "$BRANCH" -r ../../.. + cd ../.. + removeFolderWithProtectedFiles contribution + rm sun_checks.* + ;; + +openjdk17-with-checks-nonjavadoc-error) + LOCAL_GIT_REPO=$(pwd) + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + sed -i.'' 's/value=\"error\"/value=\"ignore\"/' \ + .ci-temp/contribution/checkstyle-tester/checks-nonjavadoc-error.xml + cd .ci-temp/contribution/checkstyle-tester + cp ../../../config/projects-to-test/openjdk-17-projects-to-test-on.config \ + openjdk-17-projects-to-test-on.config + sed -i '/ /r ../../../config/projects-to-test/openjdk17-excluded.files' \ + checks-nonjavadoc-error.xml + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects openjdk-17-projects-to-test-on.config \ + --mode single --allowExcludes \ + --patchConfig checks-nonjavadoc-error.xml \ + --localGitRepo "$LOCAL_GIT_REPO" \ + --patchBranch "$BRANCH" -xm "-Dcheckstyle.failsOnError=false" + + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +openjdk19-with-checks-nonjavadoc-error) + LOCAL_GIT_REPO=$(pwd) + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + sed -i.'' 's/value=\"error\"/value=\"ignore\"/' \ + .ci-temp/contribution/checkstyle-tester/checks-nonjavadoc-error.xml + cd .ci-temp/contribution/checkstyle-tester + cp ../../../config/projects-to-test/openjdk-19-projects-to-test-on.config \ + openjdk-19-projects-to-test-on.config + sed -i '/ /r ../../../config/projects-to-test/openjdk19-excluded.files' \ + checks-nonjavadoc-error.xml + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects openjdk-19-projects-to-test-on.config \ + --mode single --allowExcludes \ + --patchConfig checks-nonjavadoc-error.xml \ + --localGitRepo "$LOCAL_GIT_REPO" \ + --patchBranch "$BRANCH" -xm "-Dcheckstyle.failsOnError=false" + + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +openjdk20-with-checks-nonjavadoc-error) + LOCAL_GIT_REPO=$(pwd) + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + sed -i.'' 's/value=\"error\"/value=\"ignore\"/' \ + .ci-temp/contribution/checkstyle-tester/checks-nonjavadoc-error.xml + cd .ci-temp/contribution/checkstyle-tester + cp ../../../config/projects-to-test/openjdk-20-projects-to-test-on.config \ + openjdk-20-projects-to-test-on.config + sed -i '/ /r ../../../config/projects-to-test/openjdk20-excluded.files' \ + checks-nonjavadoc-error.xml + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects openjdk-20-projects-to-test-on.config \ + --mode single --allowExcludes \ + --patchConfig checks-nonjavadoc-error.xml \ + --localGitRepo "$LOCAL_GIT_REPO" \ + --patchBranch "$BRANCH" -xm "-Dcheckstyle.failsOnError=false" + + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +openjdk25-with-checks-nonjavadoc-error) + LOCAL_GIT_REPO=$(pwd) + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + sed -i.'' 's/value=\"error\"/value=\"ignore\"/' \ + .ci-temp/contribution/checkstyle-tester/checks-nonjavadoc-error.xml + cd .ci-temp/contribution/checkstyle-tester + cp ../../../config/projects-to-test/openjdk-25-projects-to-test-on.config \ + openjdk-25-projects-to-test-on.config + sed -i '/ /r ../../../config/projects-to-test/openjdk25-excluded.files' \ + checks-nonjavadoc-error.xml + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects openjdk-25-projects-to-test-on.config \ + --mode single --allowExcludes \ + --patchConfig checks-nonjavadoc-error.xml \ + --localGitRepo "$LOCAL_GIT_REPO" \ + --patchBranch "$BRANCH" -xm "-Dcheckstyle.failsOnError=false" + + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-lucene-and-others-javadoc) + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo 'CS_POM_VERSION='"${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cp config/projects-to-test/projects-for-no-exception-javadoc.config \ + .ci-temp/contribution/checkstyle-tester + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-for-no-exception-javadoc.config + sed -i'' 's/#infinispan/infinispan/' projects-for-no-exception-javadoc.config + sed -i'' 's/#protonpack/protonpack/' projects-for-no-exception-javadoc.config + sed -i'' 's/#jOOL/jOOL/' projects-for-no-exception-javadoc.config + sed -i'' 's/#lucene-solr/lucene-solr/' projects-for-no-exception-javadoc.config + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects projects-for-no-exception-javadoc.config \ + --patchConfig checks-only-javadoc-error.xml \ + --mode single --allowExcludes -xm "-Dcheckstyle.failsOnError=false" \ + -p "$BRANCH" -r ../../.. + cd ../.. + removeFolderWithProtectedFiles contribution + ;; + +no-exception-cassandra-storm-tapestry-javadoc) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo 'CS_POM_VERSION='"${CS_POM_VERSION}" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + cp config/projects-to-test/projects-for-no-exception-javadoc.config \ + .ci-temp/contribution/checkstyle-tester + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-for-no-exception-javadoc.config + sed -i'' 's/#tapestry-5/tapestry-5/' projects-for-no-exception-javadoc.config + sed -i'' 's/#storm/storm/' projects-for-no-exception-javadoc.config + sed -i'' 's/#cassandra/cassandra/' projects-for-no-exception-javadoc.config + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects projects-for-no-exception-javadoc.config \ + --patchConfig checks-only-javadoc-error.xml \ + --mode single --allowExcludes -xm "-Dcheckstyle.failsOnError=false" \ + -p "$BRANCH" -r ../../.. + cd ../.. + removeFolderWithProtectedFiles contribution + ;; + +no-exception-hadoop-apache-groovy-scouter-javadoc) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo 'CS_POM_VERSION='"${CS_POM_VERSION}" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + cp config/projects-to-test/projects-for-no-exception-javadoc.config \ + .ci-temp/contribution/checkstyle-tester + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-for-no-exception-javadoc.config + sed -i'' 's/#apache-commons/apache-commons/' projects-for-no-exception-javadoc.config + sed -i'' 's/#hadoop/hadoop/' projects-for-no-exception-javadoc.config + sed -i'' 's/#groovy/groovy/' projects-for-no-exception-javadoc.config + sed -i'' 's/#scouter/scouter/' projects-for-no-exception-javadoc.config + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects projects-for-no-exception-javadoc.config \ + --patchConfig checks-only-javadoc-error.xml \ + --mode single --allowExcludes -xm "-Dcheckstyle.failsOnError=false" \ + -p "$BRANCH" -r ../../.. + cd ../.. + removeFolderWithProtectedFiles contribution + ;; + +no-exception-only-javadoc) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo 'CS_POM_VERSION='"${CS_POM_VERSION}" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties + sed -i.'' 's/#nbia-dcm4che-tools/nbia-dcm4che-tools/' projects-to-test-on.properties + sed -i.'' 's/#spotbugs/spotbugs/' projects-to-test-on.properties + sed -i.'' 's/#pmd/pmd/' projects-to-test-on.properties + sed -i.'' 's/#apache-ant/apache-ant/' projects-to-test-on.properties + export MAVEN_OPTS="-Xmx2g" + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-only-javadoc-error.xml --allowExcludes \ + --mode single -xm "-Dcheckstyle.failsOnError=false" \ + -p "$BRANCH" -r ../../.. + cd ../.. + removeFolderWithProtectedFiles contribution + ;; + +no-exception-samples-ant) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo 'CS_POM_VERSION='"${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress -B install -Pno-validations + checkout_from https://github.com/sevntu-checkstyle/checkstyle-samples + cd .ci-temp/checkstyle-samples/ant-project + + sed -i -e "//,/<\/dependencies>/ "` + `"s|name=\"checkstyle\" rev=\".*\""` + `"|name=\"checkstyle\" rev=\"$CS_POM_VERSION\"|g" ivy.xml + + ant checkstyle + + cd ../.. + removeFolderWithProtectedFiles checkstyle-samples + ;; + +no-exception-samples-gradle) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo 'CS_POM_VERSION='"${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress -B install -Pno-validations + checkout_from https://github.com/sevntu-checkstyle/checkstyle-samples + cd .ci-temp/checkstyle-samples/gradle-project + + sed -i "s/\(project\.ext\.checkstyleVersion = \)'[0-9.]\+'/\\1'${CS_POM_VERSION}'/" \ + build.gradle + sed -i "s/JavaLanguageVersion.of(21)/JavaLanguageVersion.of(17)/" \ + build.gradle + + echo "Checking gradle properties..." + ./gradlew properties + ./gradlew check + + cd ../.. + removeFolderWithProtectedFiles checkstyle-samples + ;; + +no-exception-samples-maven) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo 'CS_POM_VERSION='"${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress -B install -Pno-validations + + checkout_from https://github.com/sevntu-checkstyle/checkstyle-samples + cd .ci-temp/checkstyle-samples/maven-project + + sed -i "s|\(\)[0-9.]\+\(\)"` + `"|\1${CS_POM_VERSION}\2|" pom.xml + + + echo "Building Maven project..." + mvn -e --no-transfer-progress -B verify + + cd ../.. + removeFolderWithProtectedFiles checkstyle-samples + ;; + + *) + echo "Unexpected argument: $1" + sleep 5s + false + ;; + +esac diff --git a/.ci/no-old-refs.sh b/.ci/no-old-refs.sh new file mode 100755 index 000000000000..cd075a945961 --- /dev/null +++ b/.ci/no-old-refs.sh @@ -0,0 +1,76 @@ +#!/bin/bash + +set -e + +# Script requires GITHUB_TOKEN env variable +MENTIONED_ISSUES_GREP_OUTPUT=/tmp/mentioned_issues_grep_output +CLOSED_ISSUES=/tmp/failed_issues + +# Linked issues that are mentioned in the code +LINKED_ISSUES_MENTIONED=/tmp/linked_issues_mentioned +API_GITHUB_PREFIX="https://api.github.com/repos" +GITHUB_HOST="https://github.com" +MAIN_REPO="checkstyle/checkstyle" +DEFAULT_BRANCH="master" + +# These are modified when event is of type pull_request +if [ -n "$PR_HEAD_REPO_NAME" ]; then + MAIN_REPO=$PR_HEAD_REPO_NAME + DEFAULT_BRANCH=$GITHUB_HEAD_REF +fi + +# collect issues where full link is used +grep -IPonr "(after|[Tt]il[l]?) (> $MENTIONED_ISSUES_GREP_OUTPUT + +# collect checkstyle issues where only hash sign is used +grep -IPonr "[Tt]il[l]? #\d{1,5}" . \ + | sed -e 's/:[a-zA-Z].*#/:checkstyle\/checkstyle\/issues\//' >> $MENTIONED_ISSUES_GREP_OUTPUT + +for MENTIONED_ISSUES_GREP_OUTPUT_LINE in $(cat $MENTIONED_ISSUES_GREP_OUTPUT); do + ISSUE=${MENTIONED_ISSUES_GREP_OUTPUT_LINE#*[0-9]:} + + FILE_PATH=${MENTIONED_ISSUES_GREP_OUTPUT_LINE%:[0-9]*} + FILE_PATH=${FILE_PATH:2} + + LINE_NUMBER=${MENTIONED_ISSUES_GREP_OUTPUT_LINE#*:} + LINE_NUMBER=${LINE_NUMBER%:*} + + LINK="$GITHUB_HOST/$MAIN_REPO/blob/$DEFAULT_BRANCH/$FILE_PATH#L$LINE_NUMBER" + + STATE=$(curl --fail-with-body -s -H \ + "Authorization: token $GITHUB_TOKEN" "$API_GITHUB_PREFIX/$ISSUE" \ + | jq '.state' | xargs) + if [ "$STATE" = "closed" ]; then + echo "$LINK" >> $CLOSED_ISSUES + fi + if [ -n "$LINKED_ISSUES" ]; then + for LINKED_ISSUE in $(cat "$LINKED_ISSUES"); do + if [ "$LINKED_ISSUE" = "$GITHUB_HOST/$ISSUE" ]; then + echo "$LINK" >> $LINKED_ISSUES_MENTIONED + fi + done + fi +done + +EXIT_CODE=0 + +if [ -f "$CLOSED_ISSUES" ]; then + echo + echo "Following lines are referencing closed issues." + echo "Such lines should be removed or the issue should be examined:" + echo + cat $CLOSED_ISSUES + EXIT_CODE=1 +fi + +if [ -f "$LINKED_ISSUES_MENTIONED" ]; then + echo + echo "Following lines are referencing to issues linked to this PR." + echo "Such lines should be removed or the issue should be examined:" + echo + cat $LINKED_ISSUES_MENTIONED + EXIT_CODE=1 +fi + +exit $EXIT_CODE diff --git a/.ci/pitest-survival-check-xml.groovy b/.ci/pitest-survival-check-xml.groovy new file mode 100644 index 000000000000..d015cd9bb373 --- /dev/null +++ b/.ci/pitest-survival-check-xml.groovy @@ -0,0 +1,405 @@ +import groovy.io.FileType +import groovy.transform.EqualsAndHashCode +import groovy.transform.Field +import groovy.transform.Immutable +import groovy.util.slurpersupport.GPathResult +import groovy.util.slurpersupport.NodeChildren +import groovy.xml.XmlUtil + +@Field static final String USAGE_STRING = "Usage groovy .${File.separator}.ci${File.separator}" + + "pitest-survival-check-xml.groovy [profile]\n" + + "To see the full list of supported profiles run\ngroovy .${File.separator}" + + ".ci${File.separator} pitest-survival-check-xml.groovy --list\n" + +int exitCode = 1 +if (args.length == 1) { + exitCode = parseArgumentAndExecute(args[0]) +} +else { + throw new IllegalArgumentException(USAGE_STRING) +} +System.exit(exitCode) + +/** + * Parse the command line arguments passed in and execute the branch based on the arguments. + * + * @param argument command line argument + * @return {@code 0} if command executes successfully, {@code 1} otherwise + */ +private int parseArgumentAndExecute(String argument) { + final Set profiles = getPitestProfiles() + final int exitCode + if (profiles.contains(argument)) { + exitCode = checkPitestReport(argument) + } + else if (argument == "--list") { + println "Supported profiles:" + profiles.each { println it } + exitCode = 0 + } + else { + final String exceptionMessage = "\nUnexpected argument: '${argument}' " + USAGE_STRING + throw new IllegalArgumentException(exceptionMessage) + } + return exitCode +} + +/** + * Parse the pom.xml file to get all the available pitest profiles. + * + * @return A set of all available pitest profiles + */ +private static Set getPitestProfiles() { + final GPathResult mainNode = new XmlSlurper().parse(".${File.separator}pom.xml") + final NodeChildren ids = mainNode.profiles.profile.id as NodeChildren + final Set profiles = new HashSet<>() + ids.each { node -> + final GPathResult id = node as GPathResult + final String idText = id.text() + if (idText.startsWith("pitest-")) { + profiles.add(idText) + } + } + return profiles +} + +/** + * Check the generated pitest report. Parse the surviving and suppressed mutations and compare + * them. + * + * @param profile the pitest profile to execute + * @return {@code 0} if pitest report is as expected, {@code 1} otherwise + */ +private static int checkPitestReport(String profile) { + final XmlParser xmlParser = new XmlParser() + File mutationReportFile = null + final String suppressedMutationFileUri = ".${File.separator}config${File.separator}" + + "pitest-suppressions${File.separator}${profile}-suppressions.xml" + + final File pitReports = + new File(".${File.separator}target${File.separator}pit-reports") + + if (!pitReports.exists()) { + throw new IllegalStateException( + "Pitest report directory does not exist, generate pitest report first") + } + + pitReports.eachFileRecurse(FileType.FILES) { + if (it.name == 'mutations.xml') { + mutationReportFile = it + } + } + final Node mutationReportNode = xmlParser.parse(mutationReportFile) + final Set survivingMutations = getSurvivingMutations(mutationReportNode) + + final File suppressionFile = new File(suppressedMutationFileUri) + Set suppressedMutations = new TreeSet<>() + if (suppressionFile.exists()) { + final Node suppressedMutationNode = xmlParser.parse(suppressedMutationFileUri) + suppressedMutations = getSuppressedMutations(suppressedMutationNode) + } + + if (survivingMutations.isEmpty()) { + if (suppressionFile.exists()) { + suppressionFile.delete() + } + } + else { + final StringBuilder suppressionFileContent = new StringBuilder(1024) + suppressionFileContent.append( + '\n') + + survivingMutations.each { + suppressionFileContent.append(it.toXmlString()) + } + suppressionFileContent.append('\n') + + if (!suppressionFile.exists()) { + suppressionFile.createNewFile() + } + suppressionFile.write(suppressionFileContent.toString()) + } + + return printComparisonToConsole(survivingMutations, suppressedMutations) +} + +/** + * Get the surviving mutations. All child nodes of the main {@code mutations} node + * are parsed. + * + * @param mainNode the main {@code mutations} node + * @return A set of surviving mutations + */ +private static Set getSurvivingMutations(Node mainNode) { + + final List children = mainNode.children() + final Set survivingMutations = new TreeSet<>() + + children.each { node -> + final Node mutationNode = node as Node + + final String mutationStatus = mutationNode.attribute("status") + + if (mutationStatus == "SURVIVED" || mutationStatus == "NO_COVERAGE") { + survivingMutations.add(getMutation(mutationNode)) + } + } + return survivingMutations +} + +/** + * Get the suppressed mutations. All child nodes of the main {@code suppressedMutations} node + * are parsed. + * + * @param mainNode the main {@code suppressedMutations} node + * @return A set of suppressed mutations + */ +private static Set getSuppressedMutations(Node mainNode) { + final List children = mainNode.children() + final Set suppressedMutations = new TreeSet<>() + + children.each { node -> + final Node mutationNode = node as Node + suppressedMutations.add(getMutation(mutationNode)) + } + return suppressedMutations +} + +/** + * Construct the {@link Mutation} object from the {@code mutation} XML node. + * The {@code mutations.xml} file is parsed to get the {@code mutationNode}. + * + * @param mutationNode the {@code mutation} XML node + * @return {@link Mutation} object represented by the {@code mutation} XML node + */ +private static Mutation getMutation(Node mutationNode) { + final List childNodes = mutationNode.children() + + String sourceFile = null + String mutatedClass = null + String mutatedMethod = null + String mutator = null + String lineContent = null + String description = null + String mutationClassPackage = null + int lineNumber = 0 + childNodes.each { + final Node childNode = it as Node + final String text = childNode.name() + + final String childNodeText = XmlUtil.escapeXml(childNode.text()) + switch (text) { + case "sourceFile": + sourceFile = childNodeText + break + case "mutatedClass": + mutatedClass = childNodeText + mutationClassPackage = mutatedClass.split("[A-Z]")[0] + break + case "mutatedMethod": + mutatedMethod = childNodeText + break + case "mutator": + mutator = childNodeText + break + case "description": + description = childNodeText + break + case "lineNumber": + lineNumber = Integer.parseInt(childNodeText) + break + case "lineContent": + lineContent = childNodeText + break + } + } + if (lineContent == null) { + final String mutationFileName = mutationClassPackage + sourceFile + final String startingPath = + ".${File.separator}src${File.separator}main${File.separator}java${File.separator}" + final String javaExtension = ".java" + final String mutationFilePath = startingPath + mutationFileName + .substring(0, mutationFileName.length() - javaExtension.length()) + .replace(".", File.separator) + javaExtension + + final File file = new File(mutationFilePath) + lineContent = XmlUtil.escapeXml(file.readLines().get(lineNumber - 1).trim()) + } + if (lineNumber == 0) { + lineNumber = -1 + } + + final String unstableAttributeValue = mutationNode.attribute("unstable") + final boolean isUnstable = Boolean.parseBoolean(unstableAttributeValue) + + return new Mutation(sourceFile, mutatedClass, mutatedMethod, mutator, description, + lineContent, lineNumber, isUnstable) +} + +/** + * Compare surviving and suppressed mutations. The comparison passes successfully (i.e. returns 0) + * when: + *
    + *
  1. Surviving and suppressed mutations are equal.
  2. + *
  3. There are extra suppressed mutations but they are unstable + * i.e. {@code unstable="true"}.
  4. + *
+ * The comparison fails (i.e. returns 1) when: + *
    + *
  1. Surviving mutations are not present in the suppressed list.
  2. + *
  3. There are mutations in the suppression list that are not there is surviving list.
  4. + *
+ * + * @param survivingMutations A set of surviving mutations + * @param suppressedMutations A set of suppressed mutations + * @return {@code 0} if comparison passes successfully + */ +private static int printComparisonToConsole(Set survivingMutations, + Set suppressedMutations) { + final Set survivingUnsuppressedMutations = + setDifference(survivingMutations, suppressedMutations) + final Set extraSuppressions = + setDifference(suppressedMutations, survivingMutations) + + final int exitCode + if (survivingMutations == suppressedMutations) { + exitCode = 0 + println 'No new surviving mutation(s) found.' + } + else if (survivingUnsuppressedMutations.isEmpty() + && hasOnlyUnstableMutations(extraSuppressions)) { + exitCode = 0 + println 'No new surviving mutation(s) found.' + } + else { + if (!survivingUnsuppressedMutations.isEmpty()) { + println "New surviving mutation(s) found:" + survivingUnsuppressedMutations.each { + println it + } + } + if (!extraSuppressions.isEmpty() + && extraSuppressions.any { !it.isUnstable() }) { + println "\nUnnecessary suppressed mutation(s) found and should be removed:" + extraSuppressions.each { + if (!it.isUnstable()) { + println it + } + } + } + exitCode = 1 + } + return exitCode +} + +/** + * Whether a set has only unstable mutations. + * + * @param mutations A set of mutations + * @return {@code true} if a set has only unstable mutations + */ +private static boolean hasOnlyUnstableMutations(Set mutations) { + return mutations.every { it.isUnstable() } +} + +/** + * Determine the difference between 2 sets. The result is {@code setOne - setTwo}. + * + * @param setOne The first set in the difference + * @param setTwo The second set in the difference + * @return {@code setOne - setTwo} + */ +private static Set setDifference(final Set setOne, + final Set setTwo) { + final Set result = new TreeSet<>(setOne) + result.removeIf { mutation -> setTwo.contains(mutation) } + return result +} + +/** + * A class to represent the XML {@code mutation} node. + */ +@EqualsAndHashCode(excludes = ["lineNumber", "unstable"]) +@Immutable +class Mutation implements Comparable { + + /** + * Mutation nodes present in suppressions file do not have a {@code lineNumber}. + * The {@code lineNumber} is set to {@code -1} for such mutations. + */ + private static final int LINE_NUMBER_NOT_PRESENT_VALUE = -1 + + String sourceFile + String mutatedClass + String mutatedMethod + String mutator + String description + String lineContent + int lineNumber + boolean unstable + + @Override + String toString() { + String toString = """ + Source File: "${getSourceFile()}" + Class: "${getMutatedClass()}" + Method: "${getMutatedMethod()}" + Line Contents: "${getLineContent()}" + Mutator: "${getMutator()}" + Description: "${getDescription()}" + """.stripIndent() + if (getLineNumber() != LINE_NUMBER_NOT_PRESENT_VALUE) { + toString += 'Line Number: ' + getLineNumber() + } + return toString + } + + @Override + int compareTo(Mutation other) { + int i = getSourceFile() <=> other.getSourceFile() + if (i != 0) { + return i + } + + i = getMutatedClass() <=> other.getMutatedClass() + if (i != 0) { + return i + } + + i = getMutatedMethod() <=> other.getMutatedMethod() + if (i != 0) { + return i + } + + i = getLineContent() <=> other.getLineContent() + if (i != 0) { + return i + } + + i = getMutator() <=> other.getMutator() + if (i != 0) { + return i + } + + return getDescription() <=> other.getDescription() + } + + /** + * XML format of the mutation. + * + * @return XML format of the mutation + */ + String toXmlString() { + return """ + + ${getSourceFile()} + ${getMutatedClass()} + ${getMutatedMethod()} + ${getMutator()} + ${getDescription()} + ${getLineContent()} + + """.stripIndent(10) + } + +} diff --git a/.ci/pitest.sh b/.ci/pitest.sh index ee8368ffd0c5..90fe3b5d64f9 100755 --- a/.ci/pitest.sh +++ b/.ci/pitest.sh @@ -1,237 +1,41 @@ #!/bin/bash -# Attention, there is no "-x" to avoid problems on Wercker +# Attention, there is no "-x" to avoid problems on CircleCI set -e -############################### -function checkPitestReport() { - ignored=("$@") - fail=0 - SEARCH_REGEXP="(span class='survived'|class='uncovered'>
)"
-  grep -irE "$SEARCH_REGEXP" target/pit-reports \
-     | sed -E 's/.*\/([A-Za-z]+.java.html)/\1/' | LC_ALL=C sort > target/actual.txt
-  printf "%s\n" "${ignored[@]}" | sed '/^$/d' | LC_ALL=C sort > target/ignored.txt
-  if [ "$(diff --unified -w target/ignored.txt target/actual.txt)" != "" ] ; then
-      fail=1
-      echo "Actual:" ;
-      grep -irE "$SEARCH_REGEXP" target/pit-reports \
-         | sed -E 's/.*\/([A-Za-z]+.java.html)/\1/' | sort
-      echo "Ignore:" ;
-      printf '%s\n' "${ignored[@]}"
-      echo "Diff:"
-      diff --unified -w target/ignored.txt target/actual.txt | cat
-  fi;
-  if [ "$fail" -ne "0" ]; then
-    echo "Difference between 'Actual' and 'Ignore' lists is detected, lists should be equal."
-    echo "build will be failed."
-  fi
-  sleep 5s
-  exit $fail
+function list_profiles() {
+  POM_PATH="$(dirname "${0}")/../pom.xml"
+  cat "$POM_PATH" | sed -E -n 's/^.*(pitest-[^<]+)<\/id>.*$/\1/p' | sort
 }
-###############################
 
 case $1 in
 
-pitest-annotation|pitest-design \
-|pitest-metrics|pitest-modifier|pitest-naming \
-|pitest-sizes|pitest-whitespace \
-|pitest-api|pitest-blocks \
-|pitest-packagenamesloader \
-|pitest-common-2|pitest-misc|pitest-xpath \
-|pitest-filters \
-|pitest-main \
-|pitest-coding)
-  mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
-  declare -a ignoredItems=();
-  checkPitestReport "${ignoredItems[@]}"
-  ;;
-
-pitest-regexp)
-  mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage;
-  declare -a ignoredItems=(
-  "DetectorOptions.java.html:
        if (pattern == null) {
" - "RegexpCheck.java.html:
        if (message == null) {
" - "RegexpCheck.java.html:
        return errorCount <= errorLimit - 1
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - -pitest-header) - mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "AbstractHeaderCheck.java.html:
            catch (final IOException ex) {
" - "AbstractHeaderCheck.java.html:
                throw new IllegalArgumentException("unable to load header", ex);
" - "HeaderCheck.java.html:
        if (list.length == 0) {
" - "RegexpHeaderCheck.java.html:
        if (list.length == 0) {
" - "RegexpHeaderCheck.java.html:
                    isMatch = headerLineNo == headerSize
" - "RegexpHeaderCheck.java.html:
                            || isMatch(line, headerLineNo);
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - -pitest-imports) - mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "AvoidStarImportCheck.java.html:
            && ast.getType() == TokenTypes.STATIC_IMPORT) {
" - "AvoidStarImportCheck.java.html:
            if (exclude.endsWith(STAR_IMPORT_SUFFIX)) {
" - "AvoidStaticImportCheck.java.html:
        if (exclude.endsWith(".*")) {
" - "CustomImportOrderCheck.java.html:
                        && matcher.start() < betterMatchCandidate.matchPosition) {
" - "CustomImportOrderCheck.java.html:
        else if (customImportOrderRules.contains(SAME_PACKAGE_RULE_GROUP)) {
" - "CustomImportOrderCheck.java.html:
        if (bestMatch.group.equals(NON_GROUP_RULE_GROUP)) {
" - "CustomImportOrderCheck.java.html:
            if (customImportOrderRules.contains(SAME_PACKAGE_RULE_GROUP)) {
" - "CustomImportOrderCheck.java.html:
                    || length == betterMatchCandidate.matchLength
" - "IllegalImportCheck.java.html:
        if (regexp) {
" - "IllegalImportCheck.java.html:
        if (!result && illegalClasses != null) {
" - "IllegalImportCheck.java.html:
        if (!result) {
" - "ImportControlLoader.java.html:
        else if (ALLOW_ELEMENT_NAME.equals(qName) || "disallow".equals(qName)) {
" - "ImportOrderCheck.java.html:
                else if (matcher.start() == bestPos && matcher.end() > bestEnd) {
" - "ImportOrderCheck.java.html:
        final boolean separatorBetween = isStatic != lastImportStatic
" - "ImportOrderCheck.java.html:
        if (caseSensitive) {
" - "ImportOrderCheck.java.html:
                if (!CommonUtil.endsWithChar(pkg, '.')) {
" - "ImportOrderCheck.java.html:
        if (isStatic) {
" - "ImportOrderCheck.java.html:
        return !beforeFirstImport && line - lastImportLine > 1;
" - "ImportOrderCheck.java.html:
            staticImportSeparator = isStatic && separated;
" - "PkgImportControl.java.html:
        if (alreadyRegex) {
" - "PkgImportControl.java.html:
        if (regex || parent.regex) {
" - "PkgImportControl.java.html:
        if (regex) {
" - "PkgImportRule.java.html:
        if (isRegExp()) {
" - "RedundantImportCheck.java.html:
            else if (pkgName != null && isFromPackage(imp.getText(), pkgName)) {
" - "UnusedImportsCheck.java.html:
            if (collect) {
" - ); - checkPitestReport "${ignoredItems[@]}" +--list) + echo "Supported profiles:" + list_profiles "${0}" ;; -pitest-common) - mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "AuditEventDefaultFormatter.java.html:
        if (lastDotIndex == -1) {
" - "AuditEventDefaultFormatter.java.html:
                checkShortName = checkFullName.substring(0, checkFullName.lastIndexOf(SUFFIX));
" - "AuditEventDefaultFormatter.java.html:
                checkShortName = checkFullName;
" - "AuditEventDefaultFormatter.java.html:
            if (checkFullName.endsWith(SUFFIX)) {
" - "Checker.java.html:
                if (cacheFile != null && cacheFile.isInCache(fileName, timestamp)
" - "DefaultLogger.java.html:
        closeError = errorStreamOptions == OutputStreamOptions.CLOSE;
" - "DefaultLogger.java.html:
        closeInfo = infoStreamOptions == OutputStreamOptions.CLOSE;
" - "DefaultLogger.java.html:
        if (closeError) {
" - "DefaultLogger.java.html:
        if (closeInfo) {
" - "DefaultLogger.java.html:
        if (severityLevel != SeverityLevel.IGNORE) {
" - "ConfigurationLoader.java.html:
                    catch (final CheckstyleException ex) {
" - "ConfigurationLoader.java.html:
                                        + recentModule.getName(), ex);
" - "ConfigurationLoader.java.html:
                        throw new SAXException(
" - "PackageObjectFactory.java.html:
        if (instance == null
" - "PackageObjectFactory.java.html:
        if (!name.contains(PACKAGE_SEPARATOR)) {
" - "PackageObjectFactory.java.html:
                if (thirdPartyNameToFullModuleNames == null) {
" - "PackageObjectFactory.java.html:
            returnValue = Collections.emptyMap();
" - "PackageObjectFactory.java.html:
        catch (IOException ignore) {
" - "PropertyCacheFile.java.html:
                if (!cachedHashSum.equals(contentHashSum)) {
" - "PropertyCacheFile.java.html:
                    changed = true;
" - "PropertyCacheFile.java.html:
        catch (final IOException | NoSuchAlgorithmException ex) {
" - "PropertyCacheFile.java.html:
            throw new IllegalStateException("Unable to calculate hashcode.", ex);
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - - -pitest-ant) - mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "CheckstyleAntTask.java.html:
            if (toFile == null || !useFile) {
" - "CheckstyleAntTask.java.html:
            if (toFile == null || !useFile) {
" - "CheckstyleAntTask.java.html:
            log("Adding standalone file for audit", Project.MSG_VERBOSE);
" - "CheckstyleAntTask.java.html:
            log("To process the files took " + (processingEndTime - processingStartTime)
" - "CheckstyleAntTask.java.html:
            log("Total execution took " + (endTime - startTime) + TIME_SUFFIX,
" - "CheckstyleAntTask.java.html:
        log("To locate the files took " + (endTime - startTime) + TIME_SUFFIX,
" - "CheckstyleAntTask.java.html:
        catch (CheckstyleException ex) {
" - "CheckstyleAntTask.java.html:
            throw new BuildException("Unable to process files: " + files, ex);
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - -pitest-indentation) - mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "AbstractExpressionHandler.java.html:
            if (colNum == null || thisLineColumn < colNum) {
" - "AbstractExpressionHandler.java.html:
        if (currLine < realStart) {
" - "AbstractExpressionHandler.java.html:
            if (toTest.getColumnNo() < first.getColumnNo()) {
" - "ArrayInitHandler.java.html:
        if (firstChildPos >= 0) {
" - "BlockParentHandler.java.html:
        return getIndentCheck().getLineWrappingIndentation();
" - "CommentsIndentationCheck.java.html:
            && root.getFirstChild().getFirstChild().getFirstChild().getNextSibling() != null;
" - "CommentsIndentationCheck.java.html:
                if (isUsingOfObjectReferenceToInvokeMethod(blockBody)) {
" - "CommentsIndentationCheck.java.html:
        if (isUsingOfObjectReferenceToInvokeMethod(root)) {
" - "CommentsIndentationCheck.java.html:
            if (root.getFirstChild().getType() == TokenTypes.LITERAL_NEW) {
" - "CommentsIndentationCheck.java.html:
        if (root.getLineNo() >= comment.getLineNo()) {
" - "CommentsIndentationCheck.java.html:
        return root.getFirstChild().getFirstChild().getFirstChild() != null
" - "HandlerFactory.java.html:
        createdHandlers.clear();
" - "HandlerFactory.java.html:
        register(TokenTypes.INDEX_OP, IndexHandler.class);
" - "IndentationCheck.java.html:
        handlerFactory.clearCreatedHandlers();
" - "IndentationCheck.java.html:
        handlers.clear();
" - "IndentationCheck.java.html:
        primordialHandler.checkIndentation();
" - "IndentLevel.java.html:
            for (int i = levels.nextSetBit(0); i >= 0;
" - "MethodDefHandler.java.html:
            if (node.getLineNo() < lineStart) {
" - "MethodDefHandler.java.html:
            if (node.getType() == TokenTypes.ANNOTATION) {
" - "NewHandler.java.html:
        return false;
" - "SwitchHandler.java.html:
        checkExpressionSubtree(
" - "SwitchHandler.java.html:
        checkSwitchExpr();
" - "SynchronizedHandler.java.html:
        checkExpressionSubtree(syncAst, expected, false, false);
" - "SynchronizedHandler.java.html:
            checkSynchronizedExpr();
" - "SynchronizedHandler.java.html:
            checkWrappingIndentation(getMainAst(),
" - "TryHandler.java.html:
            checkTryResParen(getTryResLparen(), "lparen");
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - -pitest-javadoc) - mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "AbstractJavadocCheck.java.html:
            Arrays.sort(acceptableJavadocTokens);
" - "AbstractJavadocCheck.java.html:
            Arrays.sort(defaultJavadocTokens);
" - "AbstractJavadocCheck.java.html:
        beginJavadocTree(root);
" - "AbstractJavadocCheck.java.html:
        finishJavadocTree(root);
" - "AbstractJavadocCheck.java.html:
        javadocTokens.clear();
" - "JavadocMethodCheck.java.html:
        if (!currentClassName.isEmpty()) {
" - "JavadocMethodCheck.java.html:
        if (classInfo == null) {
" - "JavadocMethodCheck.java.html:
                 child != null;
" - "JavadocMethodCheck.java.html:
                if (child.getType() == TokenTypes.TYPE_PARAMETER) {
" - "JavadocMethodCheck.java.html:
            if (classInfo != null) {
" - "JavadocMethodCheck.java.html:
            if (dotIdx == -1) {
" - "JavadocMethodCheck.java.html:
        currentTypeParams.clear();
" - "JavadocMethodCheck.java.html:
        while (iterator.hasNext()) {
" - "JavadocTagInfo.java.html:
            .collect(Collectors.toMap(JavadocTagInfo::getName, tagName -> tagName)));
" - "JavadocTagInfo.java.html:
            .collect(Collectors.toMap(JavadocTagInfo::getText, tagText -> tagText)));
" - "TagParser.java.html:
                while (column < currentLine.length()
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - -pitest-tree-walker) - mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "TreeWalker.java.html:
            if (!commentChecks.isEmpty()) {
" - "TreeWalker.java.html:
            if (!ordinaryChecks.isEmpty()) {
" - "TreeWalker.java.html:
            if (filters.isEmpty()) {
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - -pitest-utils) - mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; - declare -a ignoredItems=( - "CommonUtil.java.html:
                catch (final URISyntaxException ex) {
" - "CommonUtil.java.html:
                    throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename, ex);
" - ); - checkPitestReport "${ignoredItems[@]}" - ;; - -# pitesttyle-gui) -# mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; -# # post validation is skipped, we do not test gui throughly -# ;; - *) - echo "Unexpected argument: $1" - sleep 5s - false + PROFILES=$(list_profiles "${0}"); + + if [[ $(echo "$PROFILES" | grep -w -- "${1}" | cat) != "" ]]; then + echo "Generation of pitest report:" + echo "./mvnw -e --no-transfer-progress -P$1 clean test-compile \ + org.pitest:pitest-maven:mutationCoverage" + set +e + ./mvnw -e --no-transfer-progress -P"$1" clean test-compile \ + org.pitest:pitest-maven:mutationCoverage + EXIT_CODE=$? + set -e + echo "Execution of comparison of suppressed mutations survivals and current survivals:" + echo "groovy ./.ci/pitest-survival-check-xml.groovy $1" + groovy ./.ci/pitest-survival-check-xml.groovy "$1" + exit $EXIT_CODE + else + echo "Unexpected argument: $*" + echo "Usage $0 " + echo "To see the full list of supported profiles run '$0 --list'" + false + fi ;; esac - - - diff --git a/.ci/pr-description.sh b/.ci/pr-description.sh new file mode 100755 index 000000000000..143c4e524058 --- /dev/null +++ b/.ci/pr-description.sh @@ -0,0 +1,36 @@ +#!/bin/bash + +set -e + +if [[ ! $PULL_REQUEST =~ ^([0-9]*)$ ]]; then exit 0; fi +LINK_COMMITS=https://api.github.com/repos/checkstyle/checkstyle/pulls/$PULL_REQUEST/commits +COMMITS=$(curl --fail-with-body -s -H "Authorization: token $READ_ONLY_TOKEN" "$LINK_COMMITS" \ + | jq '.[0] | .commit.message') +echo 'Commit messages from github: '"${COMMITS:0:60}"... +ISSUE_NUMBER=$(echo "$COMMITS" | sed -e 's/^.*Issue //' | sed -e 's/:.*//') +echo 'Issue number: '"$ISSUE_NUMBER" && RESULT=0 +if [[ $ISSUE_NUMBER =~ ^#[0-9]+$ ]]; then + LINK_PR=https://api.github.com/repos/checkstyle/checkstyle/pulls/$PULL_REQUEST + LINK_ISSUE=https://api.github.com/repos/checkstyle/checkstyle/issues/${ISSUE_NUMBER:1} + REGEXP=($ISSUE_NUMBER\|https://github.com/checkstyle/checkstyle/issues/${ISSUE_NUMBER:1}) + PR_DESC=$(curl --fail-with-body -s -H "Authorization: token $READ_ONLY_TOKEN" "$LINK_PR" \ + | jq '.body' | grep -E "$REGEXP" | cat ) + echo 'PR Description grepped:'"${PR_DESC:0:80}" + if [[ -z $PR_DESC ]]; then + echo 'Please put a reference to an Issue in the PR description,' + echo 'this will bind the Issue to your PR in Github' + RESULT=1; + fi + LABEL_APRV=$(curl --fail-with-body -s -H "Authorization: token $READ_ONLY_TOKEN" "$LINK_ISSUE" \ + | jq '.labels [] | .name' | grep approved | cat | wc -l ) + if [[ $LABEL_APRV == 0 ]]; then + echo 'You are providing a PR for an Issue that is not approved yet,' + echo 'please ask admins to approve your Issue first' + RESULT=1; + fi + fi +if [[ $RESULT == 0 ]]; then + echo 'PR validation succeeded.'; +else + echo 'PR validation failed.' && false; +fi diff --git a/.ci/print-diff-as-patch.sh b/.ci/print-diff-as-patch.sh new file mode 100755 index 000000000000..402abdc0bf80 --- /dev/null +++ b/.ci/print-diff-as-patch.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -e + +if [ -z "$1" ]; then + echo "patch file-path not provided" + echo "Usage: $0 " + exit 1 +fi + +patch_file="$1" +echo "git diff > $patch_file" +git diff > "$patch_file" + +if [ ! -s "$patch_file" ]; then + echo "The file '$patch_file' is empty or does not exist." + exit 0 +else + echo 'There are some diff in repository after execution.' + echo 'If you are ok with diff of this run,' + echo 'you will need to run the following entire multiline command:' + echo "patch -p1 <<'EOF'" + cat "$patch_file" + echo "EOF" + exit 1 +fi + diff --git a/.ci/release-close-create-milestone.sh b/.ci/release-close-create-milestone.sh new file mode 100755 index 000000000000..f99b29396512 --- /dev/null +++ b/.ci/release-close-create-milestone.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash + +set -e + +source ./.ci/util.sh + +checkForVariable "GITHUB_TOKEN" +checkForVariable "GITHUB_REPOSITORY_OWNER" + +echo "Close previous milestone at github" +MILESTONE_NUMBER=$(curl --fail-with-body -s \ + -H "Authorization: token $GITHUB_TOKEN" \ + -X GET https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/checkstyle/milestones?state=open \ + | jq ".[0] | .number") +curl --fail-with-body -i -H "Authorization: token $GITHUB_TOKEN" \ + -d "{ \"state\": \"closed\" }" \ + -X PATCH https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/checkstyle/milestones/"$MILESTONE_NUMBER" + + +echo "Creation of new milestone ..." + +CURRENT_VERSION=$(getCheckstylePomVersionWithoutSnapshot) +echo CURRENT_VERSION="$CURRENT_VERSION" + +LAST_SUNDAY_DAY=$(cal -d "$(date -d "next month" +"%Y-%m")" \ + | awk '/^ *[0-9]/ { d=$1 } END { print d }') +LAST_SUNDAY_DATETIME=$(date -d "next month" +"%Y-%m")"-$LAST_SUNDAY_DAY""T08:00:00Z" +echo "$LAST_SUNDAY_DATETIME" + +curl --fail-with-body -i -H "Authorization: token $GITHUB_TOKEN" \ + -d "{ \"title\": \"$CURRENT_VERSION\", \ + \"state\": \"open\", \ + \"description\": \"\", \ + \"due_on\": \"$LAST_SUNDAY_DATETIME\" \ + }" \ + -X POST https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/checkstyle/milestones diff --git a/.ci/release-copy-github-io-to-sourceforge.sh b/.ci/release-copy-github-io-to-sourceforge.sh new file mode 100755 index 000000000000..0689983833cc --- /dev/null +++ b/.ci/release-copy-github-io-to-sourceforge.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash + +set -e + +source ./.ci/util.sh + +RELEASE=$1 + +echo "RELEASE version:""$RELEASE" + +if [[ -z $RELEASE ]]; then + echo "Problem to calculate release version." + exit 1 +fi + +checkForVariable "SF_USER" + +echo "Creating shell for $SF_USER@shell.sourceforge.net" +ssh -i ~/.ssh/private_sourceforge_key "$SF_USER"@shell.sourceforge.net create + +echo "Creating .ci-temp if it does not exist" +mkdir -p .ci-temp +cd .ci-temp +rm -fr checkstyle.github.io + +echo "Cloning checkstyle.github.io repo" +git clone https://github.com/checkstyle/checkstyle.github.io.git + +echo "Cleaning up git files" +rm -rf checkstyle.github.io/.git +rm -rf checkstyle.github.io/CNAME + +echo "Archiving" +tar cfz checkstyle.github.io.tar.gz checkstyle.github.io + +echo "Uploading to sourceforge" +scp -i ~/.ssh/private_sourceforge_key checkstyle.github.io.tar.gz \ + "$SF_USER"@web.sourceforge.net:/home/project-web/checkstyle + +echo "Using shell for $SF_USER@shell.sourceforge.net" +ssh -i ~/.ssh/private_sourceforge_key "$SF_USER"@shell.sourceforge.net << 'EOF' + +cd /home/project-web/checkstyle + +echo "Extracting previous release version" +PREVIOUS_RELEASE_VERSION_SPAN=$(grep "projectVersion" htdocs/index.html) +REGEX="Version: (.*)<" +[[ $PREVIOUS_RELEASE_VERSION_SPAN =~ $REGEX ]] +PREV_RELEASE="${BASH_REMATCH[1]}" +echo "PREVIOUS RELEASE version:""$PREV_RELEASE" +if [[ -z "$PREV_RELEASE" ]] +then + echo "Problem to calculate previous release version." + exit 1 +fi + +echo "Swapping html content" +tar -xzvf checkstyle.github.io.tar.gz +mv htdocs htdocs-$PREV_RELEASE +mv checkstyle.github.io htdocs + +echo "Creating .htaccess for dtds redirection" +cat <> htdocs/.htaccess +Redirect 301 "/dtds" "https://checkstyle.org/dtds" +RedirectMatch 301 "/version/.*/dtds/(.*)" "https://checkstyle.org/dtds/\$1" +HTACCESS +chmod o+r htdocs/.htaccess + +ln -s /home/project-web/checkstyle/reports htdocs/reports +echo "Removing dtds folder from unsecure web site" +rm -r htdocs/dtds + +echo "Restoring folder with links to old releases" +mv htdocs-$PREV_RELEASE/version htdocs + +echo "Archiving" +tar cfz htdocs-$PREV_RELEASE.tar.gz htdocs-$PREV_RELEASE/ +mv htdocs-$PREV_RELEASE.tar.gz htdocs-archive/ +rm -rf htdocs-$PREV_RELEASE/ + +echo "Extracting archive to previous releases documentation" +tar -xzvf htdocs-archive/htdocs-$PREV_RELEASE.tar.gz -C htdocs-version/ --same-owner \ +--exclude="*/apidocs" \ +--exclude="*/xref" --exclude="*/xref-test" --exclude="*/cobertura" --exclude="*/dsm" \ +--exclude="*/api" --exclude="reports" --exclude="jacoco" --exclude="dtds" \ +--exclude="dependency-updates-report.html" --exclude="plugin-updates-report.html" \ +--exclude="jdepend-report.html" --exclude="failsafe-report.html" \ +--exclude="surefire-report.html" \ +--exclude="linkcheck.html" --exclude="findbugs.html" --exclude="taglist.html" \ +--exclude="releasenotes_old_6-0_7-8.html" --exclude="releasenotes_old_1-0_5-9.html" \ +--exclude="dependencies.html" + +echo "Making a link to make it accessible from web" +ln -f -s $(pwd)/htdocs-version/htdocs-"$PREV_RELEASE" $(pwd)/htdocs/version/"$PREV_RELEASE" + +EOF diff --git a/.ci/release-create-issues-in-other-repos.sh b/.ci/release-create-issues-in-other-repos.sh new file mode 100755 index 000000000000..92693e42f79d --- /dev/null +++ b/.ci/release-create-issues-in-other-repos.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash + +set -e + +source ./.ci/util.sh + +checkForVariable "GITHUB_TOKEN" +checkForVariable "GITHUB_REPOSITORY_OWNER" + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +echo "Creation of issue in eclipse-cs repo ..." +curl --fail-with-body -i -H "Authorization: token $GITHUB_TOKEN" \ + -d "{ \"title\": \"upgrade to checkstyle $TARGET_VERSION\", \ + \"body\": \"https://checkstyle.org/releasenotes.html#Release_$TARGET_VERSION\" \ + }" \ + -X POST https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/eclipse-cs/issues + +echo "Creation of issue in sonar-checkstyle repo ..." +curl --fail-with-body -i -H "Authorization: token $GITHUB_TOKEN" \ + -d "{ \"title\": \"upgrade to checkstyle $TARGET_VERSION\", \ + \"body\": \"https://checkstyle.org/releasenotes.html#Release_$TARGET_VERSION\" \ + }" \ + -X POST https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/sonar-checkstyle/issues diff --git a/.ci/release-create-maven-settings-xml.sh b/.ci/release-create-maven-settings-xml.sh new file mode 100755 index 000000000000..97ec07dd4783 --- /dev/null +++ b/.ci/release-create-maven-settings-xml.sh @@ -0,0 +1,38 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh + +mkdir -p .ci-temp +cp config/release-settings.xml .ci-temp/ + +checkForVariable "SONATYPE_USER" +checkForVariable "SONATYPE_PWD" +checkForVariable "GPG_PASSPHRASE" +checkForVariable "GPG_KEYNAME" + +replace() { + sed -i "s/$1/$2/g" .ci-temp/release-settings.xml +} + +replace SONATYPE_USER "$SONATYPE_USER" +replace SONATYPE_PWD "$SONATYPE_PWD" +replace GPG_PASSPHRASE "$GPG_PASSPHRASE" +replace GPG_KEYNAME "$GPG_KEYNAME" + +mkdir -p ~/.m2 +TEMP_SETTING=./.ci-temp/release-settings.xml +SETTING=~/.m2/settings.xml + +if [ -f "$SETTING" ]; then + echo "file $SETTING already exists" + if ! cmp -s "$TEMP_SETTING" "$SETTING"; then + NOW=$( date '+%Y%m%d%H%M%S' ) + echo "backup $SETTING to $SETTING.backup.${NOW}" + mv "$SETTING" "$SETTING.backup.${NOW}" + else + echo "no backup is required as content is same" + fi +fi + +cp "$TEMP_SETTING" "$SETTING" diff --git a/.ci/release-maven-perform.sh b/.ci/release-maven-perform.sh new file mode 100755 index 000000000000..08ca39e210c8 --- /dev/null +++ b/.ci/release-maven-perform.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SCRIPT " + exit 1 +fi + +checkForVariable "GITHUB_REPOSITORY_OWNER" + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +SKIP_TEST="-DskipTests -DskipITs" +SKIP_CHECKSTYLE="-Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true" +SKIP_OTHERS="-Dpmd.skip=true -Dspotbugs.skip=true -Djacoco.skip=true -Dxml.skip=true \ + --no-transfer-progress" + +git checkout "checkstyle-$TARGET_VERSION" +echo "Deploying jars to maven central (release:perform) ..." +./mvnw -e --no-transfer-progress -Pgpg -Pgpgv2 release:perform \ + -DconnectionUrl=scm:git:https://github.com/"$GITHUB_REPOSITORY_OWNER"/checkstyle.git \ + -Dtag=checkstyle-"$TARGET_VERSION" \ + -Darguments="$SKIP_TEST $SKIP_CHECKSTYLE $SKIP_OTHERS" diff --git a/.ci/release-maven-prepare.sh b/.ci/release-maven-prepare.sh new file mode 100755 index 000000000000..0c36a54d260c --- /dev/null +++ b/.ci/release-maven-prepare.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash + +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +CURRENT_VERSION=$(getCheckstylePomVersionWithoutSnapshot) +echo CURRENT_VERSION="$CURRENT_VERSION" + +if [ "$TARGET_VERSION" != "$CURRENT_VERSION" ]; then + echo "[ERROR] Target Version and Current Version doesn't match." + exit 1; +fi + +if [[ $(grep "
" src/site/xdoc/releasenotes.xml \ + | cat | wc -l) -eq 0 ]]; then + echo "src/site/xdoc/releasenotes.xml do not have section for $TARGET_VERSION" + exit 1 +fi + +SKIP_TEST="-DskipTests -DskipITs" +SKIP_CHECKSTYLE="-Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true" +SKIP_OTHERS="-Dpmd.skip=true -Dspotbugs.skip=true -Djacoco.skip=true -Dxml.skip=true -Dgpg.skip" + +echo "Version bump in pom.xml (release:prepare) ..." +./mvnw -e --no-transfer-progress release:prepare -B -DpushChanges=false \ + -Darguments="$SKIP_TEST $SKIP_CHECKSTYLE $SKIP_OTHERS" diff --git a/.ci/release-publish-releasenotes-twitter.sh b/.ci/release-publish-releasenotes-twitter.sh new file mode 100755 index 000000000000..23ccf9055d88 --- /dev/null +++ b/.ci/release-publish-releasenotes-twitter.sh @@ -0,0 +1,68 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh + +checkForVariable "TWITTER_CONSUMER_KEY" +checkForVariable "TWITTER_CONSUMER_SECRET" +checkForVariable "TWITTER_ACCESS_TOKEN" +checkForVariable "TWITTER_ACCESS_TOKEN_SECRET" +checkForVariable "GITHUB_READ_ONLY_TOKEN" +checkForVariable "GITHUB_REPOSITORY_OWNER" + +checkout_from https://github.com/checkstyle/contribution + +cd .ci-temp/contribution/releasenotes-builder +./mvnw -e --no-transfer-progress clean compile package +cd ../../../ + +if [ -d .ci-temp/checkstyle ]; then + cd .ci-temp/checkstyle/ + git reset --hard origin/master + git pull origin master + git fetch --tags + cd ../../ +else + cd .ci-temp/ + git clone https://github.com/"$GITHUB_REPOSITORY_OWNER"/checkstyle + cd ../ +fi + +cd .ci-temp/checkstyle + +curl --fail-with-body https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/checkstyle/releases \ + -H "Authorization: token $GITHUB_READ_ONLY_TOKEN" \ + -o /var/tmp/cs-releases.json + +TARGET_RELEASE_NUM=$1 +TARGET_RELEASE_INDEX=$(cat /var/tmp/cs-releases.json | \ + jq "[.[].tag_name] | to_entries | .[] | \ + select(.value==\"checkstyle-$TARGET_RELEASE_NUM\") | .key") +echo TARGET_RELEASE_INDEX="$TARGET_RELEASE_INDEX" + +PREVIOUS_RELEASE_INDEX=$(($TARGET_RELEASE_INDEX+1)) +echo PREVIOUS_RELEASE_INDEX="$PREVIOUS_RELEASE_INDEX" + +END_REF=$(cat /var/tmp/cs-releases.json | jq -r ".[$TARGET_RELEASE_INDEX].tag_name") +START_REF=$(cat /var/tmp/cs-releases.json | jq -r ".[$PREVIOUS_RELEASE_INDEX].tag_name") + +echo START_REF="$START_REF" +echo END_REF="$END_REF" + +cd ../ +BUILDER_RESOURCE_DIR="contribution/releasenotes-builder/src/main/resources/com/github/checkstyle" + +java -jar contribution/releasenotes-builder/target/releasenotes-builder-1.0-all.jar \ + -remoteRepoPath "$GITHUB_REPOSITORY_OWNER"/checkstyle \ + -localRepoPath checkstyle \ + -startRef "$START_REF" \ + -endRef "$END_REF" \ + -releaseNumber "$TARGET_RELEASE_NUM" \ + -githubAuthToken "$GITHUB_READ_ONLY_TOKEN" \ + -twitterTemplate $BUILDER_RESOURCE_DIR/templates/twitter.template \ + -generateTwit \ + -twitterConsumerKey "$TWITTER_CONSUMER_KEY" \ + -twitterConsumerSecret "$TWITTER_CONSUMER_SECRET" \ + -twitterAccessToken "$TWITTER_ACCESS_TOKEN" \ + -twitterAccessTokenSecret "$TWITTER_ACCESS_TOKEN_SECRET" \ + -publishTwit diff --git a/.ci/release-update-github-io.sh b/.ci/release-update-github-io.sh new file mode 100755 index 000000000000..4ba83a7dc410 --- /dev/null +++ b/.ci/release-update-github-io.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +cd .ci-temp/checkstyle.github.io/ +git config user.name 'github-actions[bot]' +git config user.email 'github-actions[bot]@users.noreply.github.com' +git rm -rf * +git checkout HEAD -- CNAME +cp -R ../../target/site/* . +git add . +git commit -m "release $TARGET_VERSION" +echo "Push site content to remote ..." +echo "We do force to avoid history changes, we do not need history as github.io shows only HEAD." +git push origin --force diff --git a/.ci/release-update-github-page.sh b/.ci/release-update-github-page.sh new file mode 100755 index 000000000000..c5002df74143 --- /dev/null +++ b/.ci/release-update-github-page.sh @@ -0,0 +1,90 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "release number is not set" + echo "usage: $BASH_SOURCE {release number}" + exit 1 +fi +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +checkForVariable "GITHUB_TOKEN" +checkForVariable "GITHUB_REPOSITORY_OWNER" + +checkout_from https://github.com/checkstyle/contribution + +cd .ci-temp/contribution/releasenotes-builder +mvn -e --no-transfer-progress clean compile package +cd ../../../ + +if [ -d .ci-temp/checkstyle ]; then + cd .ci-temp/checkstyle/ + git reset --hard origin/master + git pull origin master + git fetch --tags + cd ../../ +else + cd .ci-temp/ + git clone https://github.com/"$GITHUB_REPOSITORY_OWNER"/checkstyle + cd ../ +fi + +cd .ci-temp/checkstyle + +curl --fail-with-body https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/checkstyle/releases \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o /var/tmp/cs-releases.json + +# Last release is at index 0. +START_REF=$(cat /var/tmp/cs-releases.json | jq -r ".[0].tag_name") +END_REF="checkstyle-$TARGET_VERSION" + +echo START_REF="$START_REF" +echo END_REF="$END_REF" + +cd ../ + +BUILDER_RESOURCE_DIR="contribution/releasenotes-builder/src/main/resources/com/github/checkstyle" + +java -jar contribution/releasenotes-builder/target/releasenotes-builder-1.0-all.jar \ + -localRepoPath checkstyle \ + -remoteRepoPath "$GITHUB_REPOSITORY_OWNER"/checkstyle \ + -startRef "$START_REF" \ + -endRef "$END_REF" \ + -releaseNumber "$TARGET_VERSION" \ + -githubAuthToken "$GITHUB_TOKEN" \ + -generateGitHub \ + -gitHubTemplate $BUILDER_RESOURCE_DIR/templates/github_post.template + +echo ============================================== +echo "GITHUB PAGE:" +echo ============================================== +CONTENT=$(cat github_post.txt) +echo "$CONTENT" + +echo 'Updating content to be be json value friendly' +UPDATED_CONTENT=$(awk '{printf "%s\n", $0}' github_post.txt | jq -Rsa .) +echo "$UPDATED_CONTENT" + +cat < body.json +{ + "tag_name": "checkstyle-$TARGET_VERSION", + "body": ${UPDATED_CONTENT}, + "target_commitish": "master", + "name": "", + "draft": false, + "prerelease": false +} +EOF +echo "JSON Body" +cat body.json + +echo "Creating Github release" +curl --fail-with-body \ + -X POST https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/checkstyle/releases \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + --data @body.json diff --git a/.ci/release-update-xdoc-with-releasenotes.sh b/.ci/release-update-xdoc-with-releasenotes.sh new file mode 100755 index 000000000000..3c72d7656cdb --- /dev/null +++ b/.ci/release-update-xdoc-with-releasenotes.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +CURRENT_VERSION=$(getCheckstylePomVersionWithoutSnapshot) +echo CURRENT_VERSION="$CURRENT_VERSION" + +if [ "$TARGET_VERSION" != "$CURRENT_VERSION" ]; then + echo "[ERROR] Target Version and Current Version doesn't match." + exit 1; +fi + +./.ci/releasenotes-gen-xdoc-push.sh "$TARGET_VERSION" diff --git a/.ci/release-upload-all-jar.sh b/.ci/release-upload-all-jar.sh new file mode 100755 index 000000000000..93dddc1f0e87 --- /dev/null +++ b/.ci/release-upload-all-jar.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash + +set -e + +source ./.ci/util.sh + +checkForVariable "GITHUB_TOKEN" +checkForVariable "GITHUB_REPOSITORY_OWNER" + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +git checkout checkstyle-"$TARGET_VERSION" + +echo "Generating uber jar ...(no clean to keep site resources just in case)" +./mvnw -e --no-transfer-progress -Passembly,no-validations package + +echo "Publishing 'all' jar to Github" +UPLOAD_LINK=https://uploads.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/checkstyle/releases +RELEASE_ID=$(curl --fail-with-body -s -X GET \ + -H "Authorization: token $GITHUB_TOKEN" \ + https://api.github.com/repos/"$GITHUB_REPOSITORY_OWNER"/checkstyle/releases/tags/checkstyle-"$TARGET_VERSION" \ + | jq ".id") + + +curl --fail-with-body -i -H "Authorization: token $GITHUB_TOKEN" \ + -H "Content-Type: application/java-archive" \ + --data-binary @"target/checkstyle-$TARGET_VERSION-all.jar" \ + -X POST "$UPLOAD_LINK"/"$RELEASE_ID"/assets?name=checkstyle-"$TARGET_VERSION"-all.jar + +echo "Jar Published for $TARGET_VERSION" diff --git a/.ci/releasenotes-gen-xdoc-push.sh b/.ci/releasenotes-gen-xdoc-push.sh new file mode 100755 index 000000000000..7ca894fc0e16 --- /dev/null +++ b/.ci/releasenotes-gen-xdoc-push.sh @@ -0,0 +1,57 @@ +#!/bin/bash +set -e + +source ./.ci/util.sh +checkForVariable "READ_ONLY_TOKEN" + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +checkout_from https://github.com/checkstyle/contribution + +cd .ci-temp/contribution/releasenotes-builder +mvn -e --no-transfer-progress clean compile package +cd ../../../ + +if [ -d .ci-temp/checkstyle ]; then + cd .ci-temp/checkstyle/ + git reset --hard origin/master + git pull origin master + git fetch --tags + cd ../../ +else + cd .ci-temp/ + git clone https://github.com/checkstyle/checkstyle + cd ../ +fi + +cd .ci-temp/checkstyle +LATEST_RELEASE_TAG=$(curl --fail-with-body -s -H "Authorization: token $READ_ONLY_TOKEN" \ + https://api.github.com/repos/checkstyle/checkstyle/releases/latest \ + | jq ".tag_name") +echo LATEST_RELEASE_TAG="$LATEST_RELEASE_TAG" + +cd ../ + +BUILDER_RESOURCE_DIR="contribution/releasenotes-builder/src/main/resources/com/github/checkstyle" + +java -jar contribution/releasenotes-builder/target/releasenotes-builder-1.0-all.jar \ + -localRepoPath checkstyle \ + -remoteRepoPath checkstyle/checkstyle \ + -startRef "$LATEST_RELEASE_TAG" \ + -releaseNumber "$TARGET_VERSION" \ + -githubAuthToken "$READ_ONLY_TOKEN" \ + -generateXdoc \ + -xdocTemplate $BUILDER_RESOURCE_DIR/templates/xdoc_freemarker.template + +cd ../ +sed -i '12r .ci-temp/xdoc.xml' src/site/xdoc/releasenotes.xml + +echo "releasenotes.xml:" +head "src/site/xdoc/releasenotes.xml" -n 100 diff --git a/.ci/releasenotes-gen.sh b/.ci/releasenotes-gen.sh new file mode 100755 index 000000000000..48c4d8423184 --- /dev/null +++ b/.ci/releasenotes-gen.sh @@ -0,0 +1,81 @@ +#!/bin/bash +# to run on local: +# export READ_ONLY_TOKEN=9ffd28f +# && export DRONE_PULL_REQUEST="master" && ./.ci/releasenotes-gen.sh + +set -e + +if [ -z "$READ_ONLY_TOKEN" ]; then + echo "'READ_ONLY_TOKEN' not found, exiting..." + sleep 5s; + exit 1; +fi + +echo "PULL_REQUEST:""$PULL_REQUEST" +if [[ $PULL_REQUEST =~ ^([0-9]+)$ ]]; then + echo "Build is not for Pull Request"; + sleep 5s; + exit 0; +fi + +mkdir -p .ci-temp +if [ -d .ci-temp/contribution ]; then + cd .ci-temp/contribution/ + git reset --hard origin/master + git pull origin master + git fetch --tags + cd ../../ +else + cd .ci-temp/ + git clone https://github.com/checkstyle/contribution + cd ../ +fi +cd .ci-temp/contribution/releasenotes-builder +mvn -e --no-transfer-progress clean compile package +cd ../../../ + +if [ -d .ci-temp/checkstyle ]; then + cd .ci-temp/checkstyle/ + git reset --hard origin/master + git pull origin master + git fetch --tags + cd ../../ +else + cd .ci-temp/ + git clone https://github.com/checkstyle/checkstyle + cd ../ +fi +cd .ci-temp/checkstyle +LATEST_RELEASE_TAG=$(git describe "$(git rev-list --tags --max-count=1)") +cd ../../ + +# shellcheck disable=2016 # we do not want to expand properties in this command +CS_RELEASE_VERSION=$(mvn -e --no-transfer-progress -q -Dexec.executable='echo' \ + -Dexec.args='${project.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | sed 's/-SNAPSHOT//') +echo LATEST_RELEASE_TAG="$LATEST_RELEASE_TAG" +echo CS_RELEASE_VERSION="$CS_RELEASE_VERSION" +cd .ci-temp +java -jar contribution/releasenotes-builder/target/releasenotes-builder-1.0-all.jar \ + -localRepoPath checkstyle -remoteRepoPath checkstyle/checkstyle \ + -startRef "$LATEST_RELEASE_TAG" -releaseNumber "$CS_RELEASE_VERSION" \ + -githubAuthToken "$READ_ONLY_TOKEN" -generateAll -validateVersion + +echo ============================================== +echo +echo "xdoc segment:" +echo ============================================== +cat xdoc.xml +echo ============================================== +echo +echo "twitter post:" +echo ============================================== +cat twitter.txt +echo ============================================== +echo +echo "GitHub post:" +echo ============================================== +cat github_post.txt +echo ============================================== + +find . -delete diff --git a/.ci/run-link-check-plugin.sh b/.ci/run-link-check-plugin.sh index 128be52ca1a5..79222a6503ca 100755 --- a/.ci/run-link-check-plugin.sh +++ b/.ci/run-link-check-plugin.sh @@ -1,21 +1,43 @@ #!/bin/bash -#This script is used at https://app.codeship.com/projects/124310 -#Run "firefox target/site/linkcheck.html" after completion to review html report +# Run "firefox target/site/linkcheck.html" after completion to review html report set -e pwd uname -a -mvn --version -curl -I https://sourceforge.net/projects/checkstyle/ -mvn -e clean site -Dcheckstyle.ant.skip=true -DskipTests -DskipITs \ +./mvnw --version +curl --fail-with-body -I https://sourceforge.net/projects/checkstyle/ +./mvnw -e --no-transfer-progress clean site -Dcheckstyle.ant.skip=true -DskipTests -DskipITs \ -Dpmd.skip=true -Dspotbugs.skip=true -Djacoco.skip=true -Dcheckstyle.skip=true +mkdir -p .ci-temp + +OPTION=$1 + echo "------------ grep of linkcheck.html--BEGIN" -# "grep ... | cat" is required command is running in "set -e" mode and -# grep could return exit code 1 if nothing is matching -grep externalLink target/site/linkcheck.html | cat +LINKCHECK_ERRORS=$(grep -E "doesn't exist|externalLink" target/site/linkcheck.html \ + | grep -v 'Read timed out' | sed 's/<\/table><\/td><\/tr>//g' \ + | sed 's///g' | sed 's/<\/i><\/td><\/tr>//g' | sed 's/<\/table><\/section>//g' \ + | sed 's/ <\/main>//g' || true) + +if [[ $OPTION == "--skip-external" ]]; then + echo "Checking internal (checkstyle website) links only." + echo "$LINKCHECK_ERRORS" | grep -v 'externalLink' | sort > .ci-temp/linkcheck-errors-sorted.txt + sort config/linkcheck-suppressions.txt | grep -v 'apidocs/constant-values.html' \ + > .ci-temp/linkcheck-suppressions-sorted.txt +else + echo "Checking internal (checkstyle website) and external links." + echo "$LINKCHECK_ERRORS" | sort > .ci-temp/linkcheck-errors-sorted.txt + sort config/linkcheck-suppressions.txt > .ci-temp/linkcheck-suppressions-sorted.txt +fi + +# Suppressions exist until https://github.com/checkstyle/checkstyle/issues/11572 +diff -u .ci-temp/linkcheck-suppressions-sorted.txt .ci-temp/linkcheck-errors-sorted.txt || true echo "------------ grep of linkcheck.html--END" -RESULT=$(grep externalLink target/site/linkcheck.html | grep -v 'Read timed out' | wc -l) -echo 'Exit code:'$RESULT -if [[ $RESULT != 0 ]]; then false; fi +RESULT=$(diff -y --suppress-common-lines .ci-temp/linkcheck-suppressions-sorted.txt \ + .ci-temp/linkcheck-errors-sorted.txt | wc -l) +rm .ci-temp/linkcheck-suppressions-sorted.txt +rm .ci-temp/linkcheck-errors-sorted.txt + +echo 'Exit code:'"$RESULT" +if [[ $RESULT != 0 ]]; then false; fi diff --git a/.ci/set-milestone-on-referenced-issue.sh b/.ci/set-milestone-on-referenced-issue.sh new file mode 100755 index 000000000000..5dff00002ffe --- /dev/null +++ b/.ci/set-milestone-on-referenced-issue.sh @@ -0,0 +1,69 @@ +#!/bin/bash + +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "[ERROR] Commits array is not set." + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +checkForVariable "GITHUB_TOKEN" + +COMMITS_ARRAY=$1 +echo "COMMITS_ARRAY=$COMMITS_ARRAY" + +echo "Extracting commit messages from commits array that match '^(Pull|Issue) #[0-9]+'." +COMMIT_MESSAGES=$(echo "$COMMITS_ARRAY" | jq -r .[].message \ + | grep -E "^(Pull|Issue) #[0-9]+" || true) +echo "COMMIT_MESSAGES= +$COMMIT_MESSAGES" + +if [ -z "$COMMIT_MESSAGES" ]; then + echo "[WARN] No issue numbers found in commit messages." + exit 0 +fi + +echo "Extracting issue numbers from commit messages." +ISSUE_NUMBERS=$(echo "$COMMIT_MESSAGES" | grep -oE "#[0-9]+" | cut -c2-) +echo "ISSUE_NUMBERS= +$ISSUE_NUMBERS" + +if [ -z "$ISSUE_NUMBERS" ]; then + echo "[ERROR] No issue numbers found in commit messages but was expecting some." + exit 1 +fi + +echo "Fetching latest milestone." +MILESTONE=$(curl --fail-with-body -s \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer $GITHUB_TOKEN"\ + https://api.github.com/repos/checkstyle/checkstyle/milestones) +MILESTONE_NUMBER=$(echo "$MILESTONE" | jq .[0].number) +MILESTONE_TITLE=$(echo "$MILESTONE" | jq -r .[0].title) + +if [ "$MILESTONE_NUMBER" == "null" ]; then + echo "[ERROR] No milestone is found." + exit 1 +fi + +echo "MILESTONE_NUMBER=$MILESTONE_NUMBER" +echo "MILESTONE_TITLE=$MILESTONE_TITLE" + +function setMilestoneOnIssue { + ISSUE_NUMBER=$1 + echo "Setting milestone $MILESTONE_TITLE to issue #$ISSUE_NUMBER." + BODY="{\"milestone\": $MILESTONE_NUMBER}" + curl --fail-with-body -s \ + -X PATCH \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer $GITHUB_TOKEN"\ + -d "$BODY" \ + https://api.github.com/repos/checkstyle/checkstyle/issues/"$ISSUE_NUMBER" +} + +for ISSUE_NUMBER in $ISSUE_NUMBERS; do + setMilestoneOnIssue "$ISSUE_NUMBER" +done diff --git a/.ci/shippable.sh b/.ci/shippable.sh deleted file mode 100755 index 41330b06709e..000000000000 --- a/.ci/shippable.sh +++ /dev/null @@ -1,116 +0,0 @@ -#!/bin/bash -# Attention, there is no "-x" to avoid problems on Wercker -set -e - -function checkout_from { - CLONE_URL=$1 - PROJECT=$(echo "$CLONE_URL" | sed -nE 's/.*\/(.*).git/\1/p') - mkdir -p .ci-temp - cd .ci-temp - if [ -d "$PROJECT" ]; then - echo "Target project $PROJECT is already cloned, latest changes will be fetched" - cd $PROJECT - git fetch - cd ../ - else - for i in 1 2 3 4 5; do git clone $CLONE_URL && break || sleep 15; done - fi - cd ../ -} - -function build_checkstyle { - if [[ "$SHIPPABLE" == "true" ]]; then - echo "Build checkstyle ..." - mvn clean install -Pno-validations - fi -} - -case $1 in - -no-exception-openjdk7-openjdk8) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo 'CS_POM_VERSION='${CS_POM_VERSION} - build_checkstyle - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i'' 's/^guava/#guava/' projects-for-circle.properties - sed -i'' 's/#openjdk7/openjdk7/' projects-for-circle.properties - sed -i'' 's/#openjdk8/openjdk8/' projects-for-circle.properties - groovy launch.groovy --listOfProjects projects-for-circle.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - ;; - -no-exception-openjdk9-lucene-and-others) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo 'CS_POM_VERSION='${CS_POM_VERSION} - build_checkstyle - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i'' 's/^guava/#guava/' projects-for-circle.properties - # till hg is installed - #sed -i'' 's/#openjdk9/openjdk9/' projects-for-circle.properties - sed -i'' 's/#infinispan/infinispan/' projects-for-circle.properties - sed -i'' 's/#protonpack/protonpack/' projects-for-circle.properties - sed -i'' 's/#jOOL/jOOL/' projects-for-circle.properties - sed -i'' 's/#lucene-solr/lucene-solr/' projects-for-circle.properties - groovy launch.groovy --listOfProjects projects-for-circle.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - ;; - -no-exception-cassandra-storm-tapestry) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo 'CS_POM_VERSION='${CS_POM_VERSION} - build_checkstyle - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i'' 's/^guava/#guava/' projects-for-circle.properties - sed -i'' 's/#tapestry-5/tapestry-5/' projects-for-circle.properties - sed -i'' 's/#storm/storm/' projects-for-circle.properties - sed -i'' 's/#cassandra/cassandra/' projects-for-circle.properties - groovy launch.groovy --listOfProjects projects-for-circle.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - ;; - -no-exception-hadoop-apache-groovy-scouter) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo 'CS_POM_VERSION='${CS_POM_VERSION} - build_checkstyle - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i'' 's/^guava/#guava/' projects-for-circle.properties - sed -i'' 's/#apache-commons/apache-commons/' projects-for-circle.properties - sed -i'' 's/#hadoop/hadoop/' projects-for-circle.properties - sed -i'' 's/#groovy/groovy/' projects-for-circle.properties - sed -i'' 's/#scouter/scouter/' projects-for-circle.properties - groovy launch.groovy --listOfProjects projects-for-circle.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - ;; - -no-exception-only-javadoc) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo 'CS_POM_VERSION='${CS_POM_VERSION} - build_checkstyle - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties - sed -i.'' 's/#nbia-dcm4che-tools/nbia-dcm4che-tools/' projects-to-test-on.properties - sed -i.'' 's/#spotbugs/spotbugs/' projects-to-test-on.properties - sed -i.'' 's/#pmd/pmd/' projects-to-test-on.properties - sed -i.'' 's/#apache-ant/apache-ant/' projects-to-test-on.properties - groovy launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-only-javadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - ;; - -*) - echo "Unexpected argument: $1" - sleep 5s - false - ;; - -esac diff --git a/.ci/sonar-break-build.sh b/.ci/sonar-break-build.sh new file mode 100755 index 000000000000..5dc51f77bb84 --- /dev/null +++ b/.ci/sonar-break-build.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env sh +set -e +# inspired by https://github.com/viesure/blog-sonar-build-breaker + +SONAR_RESULT="target/sonar/report-task.txt" +SONAR_SERVER="https://sonarcloud.io" + +if [ -z "$SONAR_API_TOKEN" ]; then + echo "Sonar API Token not set" + exit 1 +fi + +if [ ! -f $SONAR_RESULT ]; then + echo "Sonar result does not exist" + exit 1 +fi + +CE_TASK_ID=$(cat $SONAR_RESULT | sed -n 's/ceTaskId=\(.*\)/\1/p') + +if [ -z "$CE_TASK_ID" ]; then + echo "ceTaskId is not set from sonar build" + exit 1 +fi + +TASK_URL="$SONAR_SERVER/api/ce/task?id=$CE_TASK_ID" +HTTP_STATUS=$(curl -s -o /dev/null -w '%{http_code}' \ + -u "$SONAR_API_TOKEN": "$TASK_URL") + +if [ "$HTTP_STATUS" -ne 200 ]; then + echo "Sonar API Token has no access rights" + exit 1 +fi + +# While report is processed ANALYSIS_ID is not available and jq returns null +ANALYSIS_ID=$(curl -X GET -s -u "$SONAR_API_TOKEN": "$TASK_URL" \ + | jq -r .task.analysisId) +I=1 +TIMEOUT=0 +while [ "$ANALYSIS_ID" = "null" ]; do + if [ "$TIMEOUT" -gt 30 ]; then + echo "Timeout of " + $TIMEOUT + " seconds exceeded for getting ANALYSIS_ID" + exit 1 + fi + sleep $I + TIMEOUT=$((TIMEOUT+I)) + I=$((I+1)) + ANALYSIS_ID=$(curl -X GET -s -u "$SONAR_API_TOKEN": "$TASK_URL" \ + | jq -r .task.analysisId) +done + +ANALYSIS_URL="$SONAR_SERVER/api/qualitygates/project_status?analysisId=$ANALYSIS_ID" +STATUS=$(curl -X GET -s -u "$SONAR_API_TOKEN": "$ANALYSIS_URL" \ + | jq -r .projectStatus.status) + +DASHBOARD_URL=$(cat $SONAR_RESULT | sed -n 's/dashboardUrl=\(.*\)/\1/p') + +if [ "$STATUS" = "ERROR" ]; then + echo "Quality gate failed." + echo "See sonar dashboard at '${DASHBOARD_URL}' for failures." + exit 1 +fi + +echo "Sonar Quality gate is OK" +exit 0 diff --git a/.ci/sonar-wrapper.sh b/.ci/sonar-wrapper.sh index 05b7716b8361..1f9bad214a16 100755 --- a/.ci/sonar-wrapper.sh +++ b/.ci/sonar-wrapper.sh @@ -1,6 +1,6 @@ #!/bin/sh -#This file is for manual execution only +# This file is for manual execution only set -e @@ -8,11 +8,12 @@ echo "Building docker image" docker pull sonarqube echo "Running docker container" docker run -dit -p 9000:9000 --name sonar sonarqube:latest + echo "sleeping 60 sec to let sonar start up" -sleep "60" +sleep 60s ./.ci/sonar.sh -#kill container +# kill container docker stop sonar docker rm sonar diff --git a/.ci/sonar.sh b/.ci/sonar.sh index 4cd0c3b8f785..899ddae17074 100755 --- a/.ci/sonar.sh +++ b/.ci/sonar.sh @@ -1,27 +1,28 @@ #!/bin/sh -#set checkstyle sonar profile -curl -X POST -u admin:admin \ +# set checkstyle sonar profile +curl --fail-with-body -X POST -u admin:admin \ -F 'backup=@config/default_sonar_profile.xml' -v http://localhost:9000/api/profiles/restore -#execute inspection -mvn -e sonar:sonar -P sonar -Dsonar.language=java -Dsonar.profile=checkstyle-profile +# execute inspection +./mvnw -e --no-transfer-progress sonar:sonar -P sonar -Dsonar.language=java \ + -Dsonar.profile=checkstyle-profile # Uncomment following to get HTML report. -# mvn sonar:sonar -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true \ +# ./mvnw -e sonar:sonar -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true \ # -Dsonar.language=java -Dsonar.profile=checkstyle-profile -#get and parse response from sonar -#give some time to sonar for report processing -sleep "60" -curl -u admin:admin \ +# get and parse response from sonar +# give some time to sonar for report processing +sleep 60s +curl --fail-with-body -u admin:admin \ -v http://localhost:9000/api/issues/search?componentRoots=com.puppycrawl.tools:checkstyle \ > response.json OUTPUT="$(cat response.json | jq '.total')" -#print number of found issues +# print number of found issues if [ ! "$OUTPUT" -eq "0" ]; then jq '.' response.json echo "Found issues - $OUTPUT" diff --git a/.ci/test-spelling-unknown-words.sh b/.ci/test-spelling-unknown-words.sh index 111c2d8a8a91..aa5f4be8375d 100755 --- a/.ci/test-spelling-unknown-words.sh +++ b/.ci/test-spelling-unknown-words.sh @@ -5,26 +5,27 @@ # plus `fchurn` which uses `dn` mostly rolled together. set -e -spellchecker='.ci/jsoref-spellchecker' +spellchecker='config/jsoref-spellchecker' temp='.ci-temp' whitelist_path="$spellchecker/whitelist.words" dict="$temp/english.words" -word_splitter="$spellchecker/spelling-unknown-word-splitter.pl" -run_output="$spellchecker/unknown.words" +word_splitter="$temp/spelling-unknown-word-splitter.pl" +run_output="$temp/unknown.words" + +mkdir -p $temp if [ ! -e "$dict" ]; then - mkdir -p $temp echo "Retrieve cached english.words from checkstyle.sourceforge.io" # english.words is taken from rpm: # https://rpmfind.net/linux/fedora/linux/development/rawhide/Everything/aarch64/os/Packages/w/" # "words-.*.noarch.rpm" - curl https://checkstyle.sourceforge.io/reports/english.words -o $dict + curl --fail-with-body -k https://checkstyle.sourceforge.io/reports/english.words -o $dict fi if [ ! -e "$word_splitter" ]; then echo "Retrieve w" w_location='https://raw.githubusercontent.com/jsoref/spelling/master/w' - curl -s "$w_location" |\ + curl --fail-with-body -s "$w_location" |\ perl -p -n -e "s<$dict>" > "$word_splitter" get_word_splitter_status="${PIPESTATUS[0]} ${PIPESTATUS[1]}" if [ "$get_word_splitter_status" != '0 0' ]; then @@ -54,7 +55,8 @@ echo "Run w" printDetails() { echo '' - echo 'If you are ok with the output of this run, you will need to' + echo 'If you are ok with the output of this run,' + echo 'you will need to run the following entire multiline command:' } echo "Review results" @@ -71,6 +73,9 @@ diff_output=$(diff -U1 "$whitelist_path" "$run_output" |grep -v "$spellchecker" if [ -z "$diff_output" ]; then echo "No new words and misspellings found." + rm $dict + rm $word_splitter + rm $run_output exit 0 fi @@ -83,7 +88,8 @@ if [ -z "$new_output" ]; then echo "patch '$whitelist_path' < - - - - - 1.0.0 - - The <code>&lt;project&gt;</code> element - is the root of the site decoration descriptor. - The following table lists all of the possible child elements. - - - - - - 1.0.0 - - The <code>&lt;project&gt;</code> element - is the root of the site decoration descriptor. - The following table lists all of the possible child elements. - - - - - - 1.0.0 - - Banner logo on the masthead of the site to the left. - - - - - - 1.0.0 - - Banner logo on the masthead of the site to the right. - - - - - - 1.0.0 - - Modify the date published display properties. - - - - - - 1.0.0 - - Modify the version published display properties. - - - - - - 1.0.0 - - Powered by logos list. - - - - - - - - - - - 1.0.0 - - The artifact containing the skin for the site. - - - - - - 1.0.0 - - The main site content decoration. - - - - - - 1.0.0 - - Custom configuration for use with customized Velocity templates. - - - - - - - - - - - - 1.0.0 - - The full name of the project. - - - - - - - 1.0.0 - - Banner logo on the masthead of the site. - - - - - - 1.0.0 - - The name of the banner. - - - - - - 1.0.0 - - The location of an image for the banner. - - - - - - 1.0.0 - - The alt description for the banner image. - - - - - - 1.0.0 - - The href of a link to be used for the banner image. - - - - - - - - 1.0.0 - - The main content decoration. - - - - - - 1.0.0 - - Additional content (like Javascript) to include in the HEAD - block of the generated pages. - - - - - - - - - - - 1.0.0 - - A list of links to display in the navigation. - - - - - - - - - - - 1.0.0 - - A list of breadcrumbs to display in the navigation. - - - - - - - - - - - 1.0.0 - - A list of menus to include in the navigation. - - - - - - - - 1.0.0 - - A link in the navigation. - - - - - 1.0.0 - - The name to display for the link. - - - - - - 1.0.0 - - The href to use for the link. - - - - - - - 1.0.0 - - A menu in the navigation. - - - - - - 1.0.0 - - A list of menu item. - - - - - - - 1.0.0 - - The name to display for the menu. - - - - - - 1.0.0 - - The way in which the menu is inherited. Can be one of - : <code>top</code>, <code>bottom</code>. - - - - - - 1.0.0 - - If this is a reference, setting <inheritAsRef>true</inheritAsRef> - means that it will be populated - in the project, whereas if it is false, - it is populated in the parent and then inherited. - - - - - - 1.0.0 - - A reference to a pre-defined menu, such as a - <code>reports</code>, <code>modules</code> - or <code>parentProject</code>. - - - - - - 1.0.0 - - The location of an image. - - - - - - - 1.0.0 - - A menu item. - - - - - - 1.0.0 - - A description of the menu item. This is used on any summary pages for a menu. - - - - - - 1.0.0 - Menu item. - - - - - - 1.0.0 - - Whether to collapse children elements of an item menu (by default). - - - - - - 1.0.0 - - A reference to a pre-defined menu item, such as a report (specified by the report goal - name). Any elements explicitly given override those from the pre-defined reference. - - - - - - 1.0.0 - - The name to display for the link. - - - - - - 1.0.0 - - The href to use for the link. - - - - - - - 1.0.0 - - An skin artifact declaration. - - - - - - 1.0.0 - - The skin group ID. - - - - - - 1.0.0 - - The skin artifact ID. - - - - - - 1.0.0 - - The skin version. - - - - - - - - 1.0.0 - - Modify display properties for version published. - - - - - 1.0.0 - - Where to place the version published - (left, right, navigation-top, navigation-bottom, bottom). - - - - - - - 1.0.0 - - Modify display properties for date published. - - - - - 1.0.0 - - Where to place the date published - (left, right, navigation-top, navigation-bottom, bottom). - - - - - - 1.0.0 - - Date format to use. The default is MM/dd/yyyy. - - - - - - - 1.0.0 - - Power by logo on the navigation. - - - - - 1.0.0 - - The href of a link to be used for the power by image. - - - - - - 1.0.0 - - The name to display for the link. - - - - - - 1.0.0 - - The href to use for the link. - - - - - diff --git a/.ci/travis/travis.sh b/.ci/travis/travis.sh deleted file mode 100755 index 06692741cd5c..000000000000 --- a/.ci/travis/travis.sh +++ /dev/null @@ -1,589 +0,0 @@ -#!/bin/bash -# Attention, there is no "-x" to avoid problems on Travis -set -e - -case $1 in - -checkstyle-and-sevntu) - export MAVEN_OPTS='-Xmx2000m' - mvn -e clean verify -DskipTests -DskipITs -Dpmd.skip=true -Dspotbugs.skip=true -Djacoco.skip=true - ;; - -jacoco) - export MAVEN_OPTS='-Xmx2000m' - mvn -e clean test \ - jacoco:restore-instrumented-classes \ - jacoco:report@default-report \ - jacoco:check@default-check - ;; - -test-de) - mvn -e clean integration-test failsafe:verify \ - -DargLine='-Duser.language=de -Duser.country=DE -Xms1024m -Xmx2048m' - ;; - -test-es) - mvn -e clean integration-test failsafe:verify \ - -DargLine='-Duser.language=es -Duser.country=ES -Xms1024m -Xmx2048m' - ;; - -test-fi) - mvn -e clean integration-test failsafe:verify \ - -DargLine='-Duser.language=fi -Duser.country=FI -Xms1024m -Xmx2048m' - ;; - -test-fr) - mvn -e clean integration-test failsafe:verify \ - -DargLine='-Duser.language=fr -Duser.country=FR -Xms1024m -Xmx2048m' - ;; - -test-zh) - mvn -e clean integration-test failsafe:verify \ - -DargLine='-Duser.language=zh -Duser.country=CN -Xms1024m -Xmx2048m' - ;; - -test-ja) - mvn -e clean integration-test failsafe:verify \ - -DargLine='-Duser.language=ja -Duser.country=JP -Xms1024m -Xmx2048m' - ;; - -test-pt) - mvn -e clean integration-test failsafe:verify \ - -DargLine='-Duser.language=pt -Duser.country=PT -Xms1024m -Xmx2048m' - ;; - -test-tr) - mvn -e clean integration-test failsafe:verify \ - -DargLine='-Duser.language=tr -Duser.country=TR -Xms1024m -Xmx2048m' - ;; - -osx-assembly) - export JAVA_HOME=$(/usr/libexec/java_home) - mvn -e package -Passembly - ;; - -osx-package) - export JAVA_HOME=$(/usr/libexec/java_home) - mvn -e package - ;; - -osx-jdk13-package) - export JAVA_HOME=$(/usr/libexec/java_home) - mvn -e package - ;; - -osx-jdk13-assembly) - mvn -e package -Passembly - ;; - -site) - mvn -e clean site -Pno-validations - ;; - -javac8) - # InputCustomImportOrderNoPackage2 - nothing is required in front of first import - # InputIllegalTypePackageClassName - bad import for testing - # InputVisibilityModifierPackageClassName - bad import for testing - files=($(grep -REL --include='*.java' \ - --exclude='InputCustomImportOrderNoPackage2.java' \ - --exclude='InputIllegalTypePackageClassName.java' \ - --exclude='InputVisibilityModifierPackageClassName.java' \ - '//non-compiled (syntax|with javac)?\:' \ - src/test/resources-noncompilable)) - mkdir -p target - for file in "${files[@]}" - do - javac -d target "${file}" - done - ;; - -javac9) - files=($(grep -Rl --include='*.java' ': Compilable with Java9' \ - src/test/resources-noncompilable || true)) - if [[ ${#files[@]} -eq 0 ]]; then - echo "No Java9 files to process" - else - mkdir -p target - for file in "${files[@]}" - do - javac --release 9 -d target "${file}" - done - fi - ;; - -javac13) - files=($(grep -Rl --include='*.java' ': Compilable with Java13' \ - src/test/resources-noncompilable || true)) - if [[ ${#files[@]} -eq 0 ]]; then - echo "No Java13 files to process" - else - mkdir -p target - for file in "${files[@]}" - do - javac --release 13 --enable-preview -d target "${file}" - done - fi - ;; - -jdk13-assembly-site) - mvn -e package -Passembly - mvn -e site -Pno-validations - ;; - -jdk13-verify-limited) - # we skip pmd and spotbugs as they executed in special Travis build - mvn -e verify -Dpmd.skip=true -Dspotbugs.skip=true - ;; - -nondex) - mvn -e --fail-never clean nondex:nondex -DargLine='-Xms1024m -Xmx2048m' - cat `grep -RlE 'td class=.x' .nondex/ | cat` < /dev/null > output.txt - RESULT=$(cat output.txt | wc -c) - cat output.txt - echo 'Size of output:'$RESULT - if [[ $RESULT != 0 ]]; then sleep 5s; false; fi - ;; - -versions) - if [ -v TRAVIS_EVENT_TYPE ] && [ $TRAVIS_EVENT_TYPE != "cron" ] ; then exit 0; fi - mvn -e clean versions:dependency-updates-report versions:plugin-updates-report - if [ $(grep "" target/*-updates-report.xml | cat | wc -l) -gt 0 ]; then - echo "Version reports (dependency-updates-report.xml):" - cat target/dependency-updates-report.xml - echo "Version reports (plugin-updates-report.xml):" - cat target/plugin-updates-report.xml - echo "New dependency versions:" - grep -B 7 -A 7 "" target/dependency-updates-report.xml | cat - echo "New plugin versions:" - grep -B 4 -A 7 "" target/plugin-updates-report.xml | cat - echo "Verification is failed." - sleep 5s - false - else - echo "No new versions found" - fi - ;; - -assembly-run-all-jar) - mvn -e clean package -Passembly - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo version:$CS_POM_VERSION - mkdir -p .ci-temp - FOLDER=src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks - FILE=InputRightCurlyAloneOrEmptyNoViolations.java - java -jar target/checkstyle-$CS_POM_VERSION-all.jar -c /google_checks.xml \ - $FOLDER/$FILE > .ci-temp/output.log - if grep -vE '(Starting audit)|(warning)|(Audit done.)' .ci-temp/output.log ; then exit 1; fi - if grep 'warning' .ci-temp/output.log ; then exit 1; fi - ;; - -release-dry-run) - if [ $(git log -1 | grep -E "\[maven-release-plugin\] prepare release" | cat | wc -l) -lt 1 ];then - mvn -e release:prepare -DdryRun=true --batch-mode -Darguments='-DskipTests -DskipITs \ - -Djacoco.skip=true -Dpmd.skip=true -Dspotbugs.skip=true -Dxml.skip=true \ - -Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true -Dgpg.skip=true' - fi - ;; - -releasenotes-gen) - .ci/travis/xtr_releasenotes-gen.sh - ;; - -pr-description) - .ci/travis/xtr_pr-description.sh - ;; - -pr-age) - ## Travis merges the PR commit into origin/master - ## This command undoes that to work with the original branch - ## if it notices a merge commit - if git show --summary HEAD | grep ^Merge: ; - then - git reset --hard `git log -n 1 --no-merges --pretty=format:"%h"` - fi - - PR_MASTER=`git merge-base origin/master HEAD` - COMMITS_SINCE_MASTER=`git rev-list --count $PR_MASTER..origin/master` - MAX_ALLOWED=10 - - echo "The PR is based on a master that is $COMMITS_SINCE_MASTER commit(s) old." - echo "The max allowed is $MAX_ALLOWED." - - if (( $COMMITS_SINCE_MASTER > $MAX_ALLOWED )); - then - echo "This PR is too old and should be rebased on origin/master." - sleep 5s - false - fi - ;; - -check-chmod) - .ci/travis/checkchmod.sh - ;; - -all-sevntu-checks) - xmlstarlet sel --net --template -m .//module -v "@name" -n config/checkstyle_sevntu_checks.xml \ - | grep -vE "Checker|TreeWalker|Filter|Holder" | grep -v "^$" \ - | sed "s/com\.github\.sevntu\.checkstyle\.checks\..*\.//" \ - | sort | uniq | sed "s/Check$//" > file.txt - wget -q http://sevntu-checkstyle.github.io/sevntu.checkstyle/apidocs/allclasses-frame.html -O - \ - | grep "
  • " | cut -d '>' -f 3 | sed "s/<\/a//" \ - | grep -E "Check$" \ - | sort | uniq | sed "s/Check$//" > web.txt - # temporal ignore list - # sed -i.backup '/Jsr305Annotations/d' web.txt - diff -u web.txt file.txt - ;; - -no-error-test-sbe) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo version:$CS_POM_VERSION - mvn -e clean install -Pno-validations - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/real-logic/simple-binary-encoding.git - cd simple-binary-encoding - sed -i'' \ - "s/'com.puppycrawl.tools:checkstyle:.*'/'com.puppycrawl.tools:checkstyle:$CS_POM_VERSION'/" \ - build.gradle - ./gradlew build --stacktrace - ;; - -no-exception-test-checkstyle-sevntu-checkstyle) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#checkstyle/checkstyle/' projects-to-test-on.properties - sed -i.'' 's/#sevntu-checkstyle/sevntu-checkstyle/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-guava) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#guava|/guava|/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties - --config checks-nonjavadoc-error.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-guava-with-google-checks) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#guava|/guava|/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cp src/main/resources/google_checks.xml .ci-temp/google_checks.xml - sed -i.'' 's/warning/ignore/' .ci-temp/google_checks.xml - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config ../../google_checks.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-guava-with-sun-checks) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#guava|/guava|/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cp src/main/resources/sun_checks.xml .ci-temp/sun_checks.xml - sed -i.'' 's/value=\"error\"/value=\"ignore\"/' .ci-temp/sun_checks.xml - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config ../../sun_checks.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-hibernate) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#hibernate-orm/hibernate-orm/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-spotbugs) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#spotbugs/spotbugs/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-spring-framework) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-hbase) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#Hbase/Hbase/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-Pmd-elasticsearch-lombok-ast) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#pmd/pmd/' projects-to-test-on.properties - sed -i.'' 's/#elasticsearch/elasticsearch/' projects-to-test-on.properties - sed -i.'' 's/#lombok-ast/lombok-ast/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion $CS_POM_VERSION - ;; - -no-exception-test-alot-of-project1) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: $CS_POM_VERSION - mkdir -p .ci-temp/ - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#RxJava/RxJava/' projects-to-test-on.properties - sed -i.'' 's/#java-design-patterns/java-design-patterns/' projects-to-test-on.properties - sed -i.'' 's/#MaterialDesignLibrary/MaterialDesignLibrary/' projects-to-test-on.properties - sed -i.'' 's/#apache-ant/apache-ant/' projects-to-test-on.properties - sed -i.'' 's/#apache-jsecurity/apache-jsecurity/' projects-to-test-on.properties - sed -i.'' 's/#android-launcher/android-launcher/' projects-to-test-on.properties - cd ../../../ - mvn -e clean install -Pno-validations - cd .ci-temp/contribution/checkstyle-tester - export MAVEN_OPTS="-Xmx2048m" - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion $CS_POM_VERSION - ;; - -check-missing-pitests) - fail=0 - mkdir -p target - - list=($(cat pom.xml | \ - xmlstarlet sel --ps -N pom="http://maven.apache.org/POM/4.0.0" \ - -t -v '//pom:profile[./pom:id[contains(text(),'pitest')]]//pom:targetClasses/pom:param')) - - CMD="find src/main/java -type f ! -name 'package-info.java'" - - for item in ${list[@]} - do - item=${item//\./\/} - if [[ $item == */\* ]] ; then - item=$item - else - if [[ $item != *\* ]] ; then - item="$item.java" - else - item="${item::-1}.java" - fi - fi - - CMD="$CMD -and ! -wholename '*/$item'" - done - - CMD="$CMD | sort > target/result.txt" - eval $CMD - - results=`cat target/result.txt` - - echo "List of missing files in pitest profiles: $results" - - if [[ -n $results ]] ; then - fail=1 - fi - - sleep 5s - exit $fail - ;; - -verify-no-exception-configs) - mkdir -p .ci-temp - wget -q \ - --directory-prefix .ci-temp \ - --no-clobber \ - https://raw.githubusercontent.com/checkstyle/contribution/master/checkstyle-tester/checks-nonjavadoc-error.xml - wget -q \ - --directory-prefix .ci-temp \ - --no-clobber \ - https://raw.githubusercontent.com/checkstyle/contribution/master/checkstyle-tester/checks-only-javadoc-error.xml - MODULES_WITH_EXTERNAL_FILES="Filter|ImportControl" - xmlstarlet sel --net --template -m .//module -v "@name" \ - -n .ci-temp/checks-nonjavadoc-error.xml -n .ci-temp/checks-only-javadoc-error.xml \ - | grep -vE $MODULES_WITH_EXTERNAL_FILES | grep -v "^$" \ - | sort | uniq | sed "s/Check$//" > .ci-temp/web.txt - xmlstarlet sel --net --template -m .//module -v "@name" -n config/checkstyle_checks.xml \ - | grep -vE $MODULES_WITH_EXTERNAL_FILES | grep -v "^$" \ - | sort | uniq | sed "s/Check$//" > .ci-temp/file.txt - DIFF_TEXT=$(diff -u .ci-temp/web.txt .ci-temp/file.txt | cat) - if [[ $DIFF_TEXT != "" ]]; then - echo "Diff is detected." - if [[ $TRAVIS_PULL_REQUEST =~ ^([0-9]+)$ ]]; then - LINK_PR=https://api.github.com/repos/checkstyle/checkstyle/pulls/$TRAVIS_PULL_REQUEST - REGEXP="https://github.com/checkstyle/contribution/pull/" - PR_DESC=$(curl -s -H "Authorization: token $READ_ONLY_TOKEN" $LINK_PR \ - | jq '.body' | grep $REGEXP | cat ) - echo 'PR Description grepped:'${PR_DESC:0:180} - if [[ -z $PR_DESC ]]; then - echo 'You introduce new Check' - diff -u .ci-temp/web.txt .ci-temp/file.txt | cat - echo 'Please create PR to repository https://github.com/checkstyle/contribution' - echo 'and add your new Check ' - echo ' to file checkstyle-tester/checks-nonjavadoc-error.xml' - echo 'or to file checkstyle-tester/checks-only-javadoc-error.xml' - echo 'PR for contribution repository will be merged right after this PR.' - sleep 5s - false; - fi - else - diff -u .ci-temp/web.txt .ci-temp/file.txt | cat - echo 'file config/checkstyle_checks.xml contains Check that is not present at:' - echo 'https://github.com/checkstyle/contribution/checkstyle-tester/checks-nonjavadoc-error.xml' - echo 'https://github.com/checkstyle/contribution/checkstyle-tester/checks-nonjavadoc-error.xml' - echo 'Please add new Check to one of such files to let Check participate in auto testing' - sleep 5s - false; - fi - fi - ;; - -git-status) - if [ $(git status | grep "Changes not staged for commit" | wc -l) -gt 0 ]; then - echo "There are changes in files after clone, recheck .gitattributes file" - sleep 5s - false - fi - ;; - -check-since-version) - ## Travis merges the PR commit into origin/master - ## This identifies the PR's original commit - ## if it notices a merge commit - HEAD=`git rev-parse HEAD` - if git show --summary HEAD | grep ^Merge: ; then - echo "Merge detected." - HEAD=`git log -n 1 --no-merges --pretty=format:"%H"` - fi - ## Identify previous commit to know how much to examine - ## Script assumes we are only working with 1 commit if we are in master - ## Otherwise, it looks for the common ancestor with master - COMMIT=`git rev-parse $HEAD` - echo "PR commit: $COMMIT" - - HEAD_NEW_FILES=$(git show $COMMIT | cat | grep -A 1 "\-\-\- /dev/null" | cat) - echo "New files in commit: $HEAD_NEW_FILES" - MODULE_REG=".*(Check|Filter).java" - REGEXP="b/src/main/java/com/puppycrawl/tools/checkstyle/(checks|filters|filefilters)/$MODULE_REG" - NEW_CHECK_FILE=$(git show $COMMIT | cat | grep -A 1 "\-\-\- /dev/null" | cat | \ - grep -E "$REGEXP" | \ - cat | sed "s/+++ b\///") - echo "New Check file: $NEW_CHECK_FILE" - - if [ -f "$NEW_CHECK_FILE" ]; then - echo "New Check detected: $NEW_CHECK_FILE" - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - CS_RELEASE_VERSION=$(echo $CS_POM_VERSION | cut -d '-' -f 1) - echo "CS Release version: $CS_RELEASE_VERSION" - echo "Grep for @since $CS_RELEASE_VERSION" - sleep 5s - grep "* @since $CS_RELEASE_VERSION" $NEW_CHECK_FILE - else - echo "No new Check, all is good." - fi - ;; - -*) - echo "Unexpected argument: $1" - sleep 5s - false - ;; - -esac diff --git a/.ci/travis/xtr_pr-description.sh b/.ci/travis/xtr_pr-description.sh deleted file mode 100755 index 9a0982f4eb5c..000000000000 --- a/.ci/travis/xtr_pr-description.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash -# Attention, there is no "-x" to avoid problems on Travis -set -e - -if [[ ! $TRAVIS_PULL_REQUEST =~ ^([0-9]*)$ ]]; then exit 0; fi -LINK_COMMITS=https://api.github.com/repos/checkstyle/checkstyle/pulls/$TRAVIS_PULL_REQUEST/commits -COMMITS=$(curl -s -H "Authorization: token $READ_ONLY_TOKEN" $LINK_COMMITS \ - | jq '.[0] | .commit.message') -echo 'Commit messages from github: '${COMMITS:0:60}... -ISSUE_NUMBER=$(echo $COMMITS | sed -e 's/^.*Issue //' | sed -e 's/:.*//') -echo 'Issue number: '$ISSUE_NUMBER && RESULT=0 -if [[ $ISSUE_NUMBER =~ ^#[0-9]+$ ]]; then - LINK_PR=https://api.github.com/repos/checkstyle/checkstyle/pulls/$TRAVIS_PULL_REQUEST - LINK_ISSUE=https://api.github.com/repos/checkstyle/checkstyle/issues/${ISSUE_NUMBER:1} - REGEXP=($ISSUE_NUMBER\|https://github.com/checkstyle/checkstyle/issues/${ISSUE_NUMBER:1}) - PR_DESC=$(curl -s -H "Authorization: token $READ_ONLY_TOKEN" $LINK_PR \ - | jq '.body' | grep -E $REGEXP | cat ) - echo 'PR Description grepped:'${PR_DESC:0:80} - if [[ -z $PR_DESC ]]; then - echo 'Please put a reference to an Issue in the PR description,' - echo 'this will bind the Issue to your PR in Github' - RESULT=1; - fi - LABEL_APRV=$(curl -s -H "Authorization: token $READ_ONLY_TOKEN" $LINK_ISSUE \ - | jq '.labels [] | .name' | grep approved | cat | wc -l ) - if [[ $LABEL_APRV == 0 ]]; then - echo 'You are providing a PR for an Issue that is not approved yet,' - echo 'please ask admins to approve your Issue first' - RESULT=1; - fi - fi -if [[ $RESULT == 0 ]]; then - echo 'PR validation succeeded.'; -else - echo 'PR validation failed.' && false; -fi diff --git a/.ci/travis/xtr_releasenotes-gen.sh b/.ci/travis/xtr_releasenotes-gen.sh deleted file mode 100755 index 629e6be83013..000000000000 --- a/.ci/travis/xtr_releasenotes-gen.sh +++ /dev/null @@ -1,82 +0,0 @@ -#!/bin/bash -# Attention, there is no "-x" to avoid problem on Travis -# to run on local: -# export READ_ONLY_TOKEN=9ffd28f -# && export TRAVIS_PULL_REQUEST="master" && ./.ci/travis/travis.sh releasenotes-gen - -set -e - -echo "TRAVIS_PULL_REQUEST:"$TRAVIS_PULL_REQUEST -if [[ $TRAVIS_PULL_REQUEST =~ ^([0-9]*)$ ]]; then - echo "Build is not for Pull Request"; - sleep 5; - exit 0; -fi - -mkdir -p .ci-temp -if [ -d .ci-temp/contribution ]; then - cd .ci-temp/contribution/ - git reset --hard origin/master - git pull origin master - git fetch --tags - cd ../../ -else - cd .ci-temp/ - git clone https://github.com/checkstyle/contribution - cd ../ -fi -cd .ci-temp/contribution/releasenotes-builder -mvn -e clean compile package -cd ../../../ - -# we need to do full clone as Travis do "git clone --depth=50" -if [ -d .ci-temp/checkstyle ]; then - cd .ci-temp/checkstyle/ - git reset --hard origin/master - git pull origin master - git fetch --tags - cd ../../ -else - cd .ci-temp/ - git clone https://github.com/checkstyle/checkstyle - cd ../ -fi -cd .ci-temp/checkstyle -LATEST_RELEASE_TAG=$(git describe $(git rev-list --tags --max-count=1)) -cd ../../ - -CS_RELEASE_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | sed 's/-SNAPSHOT//' ) -echo LATEST_RELEASE_TAG=$LATEST_RELEASE_TAG -echo CS_RELEASE_VERSION=$CS_RELEASE_VERSION -cd .ci-temp -java -jar contribution/releasenotes-builder/target/releasenotes-builder-1.0-all.jar \ - -localRepoPath checkstyle -remoteRepoPath checkstyle/checkstyle \ - -startRef $LATEST_RELEASE_TAG -releaseNumber $CS_RELEASE_VERSION \ - -githubAuthToken $READ_ONLY_TOKEN -generateAll -publishXdoc - -echo ============================================== -echo -echo "xdoc segment:" -echo ============================================== -cat xdoc.xml -echo ============================================== -echo -echo "twitter post:" -echo ============================================== -cat twitter.txt -echo ============================================== -echo -echo "RSS post:" -echo ============================================== -cat rss.txt -echo ============================================== -echo -echo "mailing list post:" -echo ============================================== -cat mailing_list.txt -echo ============================================== -cd checkstyle/src/xdocs -echo -echo "releasenotes.xml after commit:" -head -n 100 releasenotes.xml diff --git a/.ci/update-github-milestone.sh b/.ci/update-github-milestone.sh new file mode 100755 index 000000000000..0b2707fa05b7 --- /dev/null +++ b/.ci/update-github-milestone.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +set -e + +source ./.ci/util.sh + +if [[ -z $1 ]]; then + echo "version is not set" + echo "Usage: $BASH_SOURCE " + exit 1 +fi + +checkForVariable "GITHUB_TOKEN" + +TARGET_VERSION=$1 +echo TARGET_VERSION="$TARGET_VERSION" + +echo "Updating milestone at github" +MILESTONE_ID=$(curl --fail-with-body -s \ + -H "Authorization: token $GITHUB_TOKEN" \ + -X GET https://api.github.com/repos/checkstyle/checkstyle/milestones?state=open \ + | jq ".[0] | .number") + +echo TARGET_VERSION="$TARGET_VERSION" +echo MILESTONE_ID="$MILESTONE_ID" + +curl --fail-with-body \ + -X PATCH https://api.github.com/repos/checkstyle/checkstyle/milestones/"$MILESTONE_ID" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -d "{ \"title\": \"$TARGET_VERSION\" }" diff --git a/.ci/util.sh b/.ci/util.sh new file mode 100755 index 000000000000..21e1fb4aa731 --- /dev/null +++ b/.ci/util.sh @@ -0,0 +1,59 @@ +#!/bin/bash +# This script contains common bash CI functions +set -e + +removeFolderWithProtectedFiles() { + find "$1" -delete +} + +function checkForVariable() { + VAR_NAME=$1 + if [ ! -v "$VAR_NAME" ]; then + echo "Error: Define $1 environment variable" + exit 1 + fi + + VAR_VALUE="${!VAR_NAME}" + if [ -z "$VAR_VALUE" ]; then + echo "Error: Set not empty value to $1 environment variable" + exit 1 + fi +} + +function getMavenProperty { + property="\${$1}" + ./mvnw -e --no-transfer-progress -q -Dexec.executable='echo' \ + -Dexec.args="${property}" \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec +} + +function getCheckstylePomVersion { + getMavenProperty project.version +} + +function getCheckstylePomVersionWithoutSnapshot { + getCheckstylePomVersion | sed "s/-SNAPSHOT//" +} + +function getCheckstylePomVersionWithoutSnapshotWithXmlstarlet { + xmlstarlet sel -N pom=http://maven.apache.org/POM/4.0.0 \ + -t -m pom:project -v pom:version pom.xml | sed "s/-SNAPSHOT//" +} + +function checkout_from { + CLONE_URL=$1 + PROJECT=$(echo "$CLONE_URL" | sed -nE 's/.*\/(.*).git/\1/p') + mkdir -p .ci-temp + cd .ci-temp + if [ -d "$PROJECT" ]; then + echo "Target project $PROJECT is already cloned, latest changes will be fetched and reset" + cd "$PROJECT" + git fetch + git reset --hard HEAD + git clean -f -d + cd ../ + else + for i in 1 2 3 4 5; do git clone "$CLONE_URL" && break || sleep 15s; done + fi + cd ../ +} diff --git a/.ci/validation.cmd b/.ci/validation.cmd new file mode 100644 index 000000000000..97b78d9eb4db --- /dev/null +++ b/.ci/validation.cmd @@ -0,0 +1,58 @@ +@echo off + +::---------------------------------------------------------------------- +:: Validation script to run on local for windows users. +:: Example of usage +:: ./.ci/validation.cmd verify_without_checkstyle +::---------------------------------------------------------------------- + +SET OPTION=%1 + +if "%OPTION%" == "sevntu" ( + call mvnw.cmd -e --no-transfer-progress verify -Pno-validations,sevntu^ + || goto :ERROR + goto :END_CASE +) + +if "%OPTION%" == "run_checkstyle" ( + call mvnw.cmd -e --no-transfer-progress clean compile antrun:run@ant-phase-verify^ + || goto :ERROR + goto :END_CASE +) + +if "%OPTION%" == "verify_without_checkstyle" ( + call mvnw.cmd -e --no-transfer-progress verify -Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true^ + || goto :ERROR + goto :END_CASE +) + +if "%OPTION%" == "site_without_verify" ( + call mvnw.cmd -e --no-transfer-progress -Pno-validations site^ + || goto :ERROR + goto :END_CASE +) + +if "%OPTION%" == "git_diff" ( + for /f "delims=" %%a in ('git status ^| findstr /c:"Changes not staged"') do set output=%%a + if defined output ( + echo Please clean up or update .gitattributes file. + echo Git status output: + echo Top 300 lines of diff: + call git diff | find /v /n "" | findstr /R "^\[[1-2]*[1-9]*[0-9]\]" + echo There should be no changes in git repository after any CI job/task + goto :ERROR + ) + goto :END_CASE +) + +echo Unexpected argument %OPTION% +SET ERRORLEVEL=-1 +goto :END_CASE + +:END_CASE + VER > NUL + EXIT /b %ERRORLEVEL% + +:ERROR +echo validation failed with error code #%ERRORLEVEL%. +exit /b %ERRORLEVEL% diff --git a/.ci/validation.sh b/.ci/validation.sh new file mode 100755 index 000000000000..06cc51056b76 --- /dev/null +++ b/.ci/validation.sh @@ -0,0 +1,1341 @@ +#!/bin/bash + +set -e + +source ./.ci/util.sh + +addCheckstyleBundleToAntResolvers() { + # shellcheck disable=2016 # we do not want to expand properties in this command + xmlstarlet ed --inplace \ + -s '/ivysettings/resolvers' -t elem -n filesystem \ + -i '/ivysettings/resolvers/filesystem[last()]' -t attr -n name -v local-checkstyle \ + -s '/ivysettings/resolvers/filesystem[last()]' -t elem -n artifact \ + -i '/ivysettings/resolvers/filesystem[last()]/artifact' -t attr -n pattern -v \ + '${base.dir}/../../target/[artifact]-[revision]-all.[ext]' \ + -s '/ivysettings/modules' -t elem -n module \ + -i '/ivysettings/modules/module[last()]' -t attr -n organisation -v com.puppycrawl.tools \ + -i '/ivysettings/modules/module[last()]' -t attr -n name -v checkstyle \ + -i '/ivysettings/modules/module[last()]' -t attr -n resolver -v local-checkstyle \ + ivysettings.xml +} + +function list_tasks() { + cat "${0}" | sed -E -n 's/^([a-zA-Z0-9\-]*)\)$/\1/p' | sort +} + +case $1 in + +all-sevntu-checks) + working_dir=.ci-temp/all-sevntu-checks + mkdir -p $working_dir + xmlstarlet sel --net --template -m .//module -v "@name" -n config/checkstyle-sevntu-checks.xml \ + | grep -vE "Checker|TreeWalker|Filter|Holder" | grep -v "^$" \ + | sed "s/com\.github\.sevntu\.checkstyle\.checks\..*\.//" \ + | sort | uniq | sed "s/Check$//" > $working_dir/file.txt + wget -q http://sevntu-checkstyle.github.io/sevntu.checkstyle/apidocs/allclasses-frame.html -O - \ + | grep "
  • " | cut -d '>' -f 3 | sed "s/<\/a//" \ + | grep -E "Check$" \ + | sort | uniq | sed "s/Check$//" > $working_dir/web.txt + # temporal ignore list + # sed -i.backup '/Jsr305Annotations/d' web.txt + diff -u $working_dir/web.txt $working_dir/file.txt + removeFolderWithProtectedFiles $working_dir + ;; + +check-missing-pitests) + fail=0 + mkdir -p target + + list=($(cat pom.xml | \ + xmlstarlet sel --ps -N pom="http://maven.apache.org/POM/4.0.0" \ + -t -v "//pom:profile[./pom:id[contains(text(),'pitest')]]//pom:targetClasses/pom:param")) + + # Temporary skip for Metadata generator related files for + # https://github.com/checkstyle/checkstyle/issues/8761 + # Coverage for site package is skipped + # until https://github.com/checkstyle/checkstyle/issues/13393 + list=("com.puppycrawl.tools.checkstyle.meta.*" + "com.puppycrawl.tools.checkstyle.site.*" "${list[@]}") + + CMD="find src/main/java -type f ! -name 'package-info.java'" + + for item in "${list[@]}" + do + item=${item//\./\/} + if [[ $item != */\* ]] ; then + if [[ $item != *\* ]] ; then + item="$item.java" + else + item="${item::-1}.java" + fi + fi + + CMD="$CMD -and ! -wholename '*/$item'" + done + + CMD="$CMD | sort > target/result.txt" + eval "$CMD" + + results=$(cat target/result.txt) + + echo "List of missing files in pitest profiles: $results" + + if [[ -n $results ]] ; then + fail=1 + fi + + sleep 5s + exit $fail + ;; + +eclipse-static-analysis) + ./mvnw -e --no-transfer-progress clean compile exec:exec -Peclipse-compiler + ;; + +nondex) + # Exclude test that fails due to picocli library usage + SKIPPED_TESTS='!JavadocPropertiesGeneratorTest#testNonExistentArgument,' + # Exclude test that fails due to stackoverflow error + SKIPPED_TESTS+='!SingleSpaceSeparatorCheckTest#testNoStackoverflowError' + ./mvnw -e --no-transfer-progress \ + --fail-never clean nondex:nondex -DargLine='-Xms1g -Xmx2g' \ + -Dtest="$SKIPPED_TESTS" + + mkdir -p .ci-temp + grep -RlE 'td class=.x' .nondex/ | cat > .ci-temp/output.txt + RESULT=$(cat .ci-temp/output.txt | wc -c) + cat .ci-temp/output.txt + echo 'Size of output:'"$RESULT" + if [[ $RESULT != 0 ]]; then false; fi + rm .ci-temp/output.txt + ;; + +pr-age) + # This command undoes that to work with the original branch + # if it notices a merge commit + if git show --summary HEAD | grep ^Merge: ; + then + git reset --hard "$(git log -n 1 --no-merges --pretty=format:"%h")" + fi + + PR_MASTER=$(git merge-base origin/master HEAD) + COMMITS_SINCE_MASTER=$(git rev-list --count "$PR_MASTER"..origin/master) + MAX_ALLOWED=10 + + echo "The PR is based on a master that is $COMMITS_SINCE_MASTER commit(s) old." + echo "The max allowed is $MAX_ALLOWED." + + if (( $COMMITS_SINCE_MASTER > $MAX_ALLOWED )); + then + echo "This PR is too old and should be rebased on origin/master." + false + fi + ;; + +test) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -DargLine='-Xms1g -Xmx2g' + ;; + +test-de) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=de -Duser.country=DE -Xms1g -Xmx2g' + ;; + +test-es) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=es -Duser.country=ES -Xms1g -Xmx2g' + ;; + +test-fi) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=fi -Duser.country=FI -Xms1g -Xmx2g' + ;; + +test-fr) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=fr -Duser.country=FR -Xms1g -Xmx2g' + ;; + +test-zh) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=zh -Duser.country=CN -Xms1g -Xmx2g' + ;; + +test-ja) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=ja -Duser.country=JP -Xms1g -Xmx2g' + ;; + +test-pt) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=pt -Duser.country=PT -Xms1g -Xmx2g' + ;; + +test-tr) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=tr -Duser.country=TR -Xms1g -Xmx2g' + ;; + +test-ru) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=ru -Duser.country=RU -Xms1g -Xmx2g' + ;; + +test-al) + ./mvnw -e --no-transfer-progress clean integration-test failsafe:verify \ + -Dsurefire.options='-Duser.language=sq -Duser.country=AL -Xms1g -Xmx2g' + ;; + +versions) + ./mvnw -e --no-transfer-progress clean versions:dependency-updates-report \ + versions:plugin-updates-report + if [ "$(grep "" target/*-updates-report.xml | cat | wc -l)" -gt 0 ]; then + echo "Version reports (dependency-updates-report.xml):" + cat target/dependency-updates-report.xml + echo "Version reports (plugin-updates-report.xml):" + cat target/plugin-updates-report.xml + echo "New dependency versions:" + grep -B 7 -A 7 "" target/dependency-updates-report.xml | cat + echo "New plugin versions:" + grep -B 4 -A 7 "" target/plugin-updates-report.xml | cat + echo "Verification is failed." + false + else + echo "No new versions found" + fi + ;; + +markdownlint) + mdl -g . && echo "All .md files verified" + ;; + +no-error-pmd) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo "CS_version: ${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from "https://github.com/pmd/build-tools.git" + cd .ci-temp/build-tools/ + mvn -e --no-transfer-progress install + cd .. + git clone https://github.com/pmd/pmd.git + cd pmd + mvn -e --no-transfer-progress verify --show-version --errors --batch-mode \ + -DskipTests \ + -Dmaven.javadoc.skip=true \ + -Dmaven.source.skip=true \ + -Dpmd.skip=true \ + -Dcheckstyle.skip=false \ + -Dcheckstyle.version="${CS_POM_VERSION}" + cd .. + removeFolderWithProtectedFiles build-tools + removeFolderWithProtectedFiles pmd + ;; + +no-error-hazelcast) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo "CS_version: ${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout Hazelcast sources..." + checkout_from "https://github.com/hazelcast/hazelcast.git" + cd .ci-temp/hazelcast + mvn -e --no-transfer-progress checkstyle:check \ + -Dcheckstyle.version="${CS_POM_VERSION}" + cd .. + removeFolderWithProtectedFiles hazelcast + ;; + +no-violation-test-configurate) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo "CS_version: ${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + mkdir -p .ci-temp + cd .ci-temp + git clone https://github.com/SpongePowered/Configurate.git + cd Configurate + ./gradlew -PcheckstyleVersion="${CS_POM_VERSION}" -x test check + cd .. + removeFolderWithProtectedFiles Configurate + ;; + +no-error-xwiki) + CS_POM_VERSION="$(getCheckstylePomVersion)" + ANTLR4_VERSION="$(getMavenProperty 'antlr4.version')" + echo "version:${CS_POM_VERSION} antlr4:${ANTLR4_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from "https://github.com/xwiki/xwiki-commons.git" + cd .ci-temp/xwiki-commons + # Build custom Checkstyle rules + mvn -e --no-transfer-progress -f \ + xwiki-commons-tools/xwiki-commons-tool-verification-resources/pom.xml \ + install -DskipTests -Dcheckstyle.version="${CS_POM_VERSION}" \ + -Dantlr4.version="${ANTLR4_VERSION}" + # Validate xwiki-commons + mvn -e --no-transfer-progress checkstyle:check@default -Dcheckstyle.version="${CS_POM_VERSION}" + # Install various required poms and extensions + mvn -e --no-transfer-progress install:install-file -Dfile=pom.xml -DpomFile=pom.xml + mvn -e --no-transfer-progress install:install-file -Dfile=xwiki-commons-tools/pom.xml \ + -DpomFile=xwiki-commons-tools/pom.xml + mvn -e --no-transfer-progress install:install-file \ + -Dfile=xwiki-commons-tools/xwiki-commons-tool-pom/pom.xml \ + -DpomFile=xwiki-commons-tools/xwiki-commons-tool-pom/pom.xml + mvn -e --no-transfer-progress install:install-file -Dfile=xwiki-commons-pom/pom.xml \ + -DpomFile=xwiki-commons-pom/pom.xml + mvn -e --no-transfer-progress -f xwiki-commons-tools/xwiki-commons-tool-webjar-handlers/pom.xml \ + install -Dmaven.test.skip -Dcheckstyle.version="${CS_POM_VERSION}" + mvn -e --no-transfer-progress \ + -f xwiki-commons-tools/xwiki-commons-tool-webjar-node-handlers/pom.xml \ + install -Dmaven.test.skip -Dcheckstyle.version="${CS_POM_VERSION}" + mvn -e --no-transfer-progress -f xwiki-commons-tools/xwiki-commons-tool-xar/pom.xml \ + install -Dmaven.test.skip -Dcheckstyle.version="${CS_POM_VERSION}" + cd .. + removeFolderWithProtectedFiles xwiki-commons + cd .. + checkout_from https://github.com/xwiki/xwiki-rendering.git + cd .ci-temp/xwiki-rendering + # Validate xwiki-rendering + mvn -e --no-transfer-progress checkstyle:check@default -Dcheckstyle.version="${CS_POM_VERSION}" + cd .. + removeFolderWithProtectedFiles xwiki-rendering + cd .. + checkout_from https://github.com/xwiki/xwiki-platform.git + cd .ci-temp/xwiki-platform + # Validate xwiki-platform + mvn -e --no-transfer-progress checkstyle:check@default -Dcheckstyle.version="${CS_POM_VERSION}" + cd .. + removeFolderWithProtectedFiles xwiki-platform + ;; + +no-error-test-sbe) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo version:"$CS_POM_VERSION" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/real-logic/simple-binary-encoding.git + cd .ci-temp/simple-binary-encoding + sed -i'' \ + "s/'com.puppycrawl.tools:checkstyle:.*'/'com.puppycrawl.tools:checkstyle:$CS_POM_VERSION'/" \ + build.gradle + ./gradlew build --stacktrace + cd .. + removeFolderWithProtectedFiles simple-binary-encoding + ;; + +verify-no-exception-configs) + mkdir -p .ci-temp/verify-no-exception-configs + working_dir=.ci-temp/verify-no-exception-configs + wget -q \ + --directory-prefix $working_dir \ + --no-clobber \ + https://raw.githubusercontent.com/checkstyle/contribution/master/checkstyle-tester/checks-nonjavadoc-error.xml + wget -q \ + --directory-prefix $working_dir \ + --no-clobber \ + https://raw.githubusercontent.com/checkstyle/contribution/master/checkstyle-tester/checks-only-javadoc-error.xml + MODULES_WITH_EXTERNAL_FILES="Filter|ImportControl" + xmlstarlet fo -D \ + -n $working_dir/checks-nonjavadoc-error.xml \ + | xmlstarlet sel --net --template -m .//module -n -v "@name" \ + | grep -vE $MODULES_WITH_EXTERNAL_FILES | grep -v "^$" > $working_dir/temp.txt + xmlstarlet fo -D \ + -n $working_dir/checks-only-javadoc-error.xml \ + | xmlstarlet sel --net --template -m .//module -n -v "@name" \ + | grep -vE $MODULES_WITH_EXTERNAL_FILES | grep -v "^$" >> $working_dir/temp.txt + sort $working_dir/temp.txt | uniq | sed "s/Check$//" > $working_dir/web.txt + + xmlstarlet fo -D -n config/checkstyle-checks.xml \ + | xmlstarlet sel --net --template -m .//module -n -v "@name" \ + | grep -vE $MODULES_WITH_EXTERNAL_FILES | grep -v "^$" \ + | sort | uniq | sed "s/Check$//" > $working_dir/file.txt + + DIFF_TEXT=$(diff -u $working_dir/web.txt $working_dir/file.txt | cat) + fail=0 + + if [[ $DIFF_TEXT != "" ]]; then + echo "Diff is detected." + if [[ $PULL_REQUEST =~ ^([0-9]+)$ ]]; then + LINK_PR=https://api.github.com/repos/checkstyle/checkstyle/pulls/$PULL_REQUEST + REGEXP="https://github.com/checkstyle/contribution/pull/" + PR_DESC=$(curl -s -H "Authorization: token $READ_ONLY_TOKEN" "$LINK_PR" \ + | jq '.body' | grep $REGEXP | cat ) + echo 'PR Description grepped:'"${PR_DESC:0:180}" + if [[ -z $PR_DESC ]]; then + echo 'You introduce new Check' + diff -u $working_dir/web.txt $working_dir/file.txt | cat + echo 'Please create PR to repository https://github.com/checkstyle/contribution' + echo 'and add your new Check ' + echo ' to file checkstyle-tester/checks-nonjavadoc-error.xml' + echo 'or to file checkstyle-tester/checks-only-javadoc-error.xml' + echo 'Place the contribution repository PR link in the description of this PR.' + echo 'PR for contribution repository will be merged right after this PR.' + fail=1; + fi + else + diff -u $working_dir/web.txt $working_dir/file.txt | cat + echo 'file config/checkstyle-checks.xml contains Check that is not present at:' + echo 'https://github.com/checkstyle/contribution/blob/master/checkstyle-tester/checks-nonjavadoc-error.xml' + echo 'https://github.com/checkstyle/contribution/blob/master/checkstyle-tester/checks-only-javadoc-error.xml' + echo 'Please add new Check to one of such files to let Check participate in auto testing' + fail=1; + fi + else + echo "No Diff detected." + fi + removeFolderWithProtectedFiles .ci-temp/verify-no-exception-configs + sleep 5 + exit $fail + ;; + +verify-regexp-id) + fail=0 + for FILE in config/*_checks.xml + do + a=$(grep -c " errors.log + RESULT=$(cat errors.log | wc -l) + if [[ $RESULT != 0 ]]; then + echo "Errors are detected in target/site/pmd.html." + sleep 5s + fi + cd .. + removeFolderWithProtectedFiles spotbugs-and-pmd + exit "$RESULT" +;; + +site) + ./mvnw -e --no-transfer-progress clean site -Pno-validations + ;; + +release-dry-run) + if [ "$(git log -1 | grep -E "\[maven-release-plugin\] prepare release" | cat | wc -l)" -lt 1 ] + then + ./mvnw -e --no-transfer-progress release:prepare -DdryRun=true --batch-mode \ + -Darguments='-DskipTests -DskipITs -Djacoco.skip=true -Dpmd.skip=true \ + -Dspotbugs.skip=true -Dxml.skip=true -Dcheckstyle.ant.skip=true \ + -Dcheckstyle.skip=true -Dgpg.skip=true --no-transfer-progress' + ./mvnw -e --no-transfer-progress release:clean + fi + ;; + +assembly-run-all-jar) + ./mvnw -e --no-transfer-progress clean package -Passembly,no-validations + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo version:"$CS_POM_VERSION" + mkdir -p .ci-temp + FOLDER=src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule73wherejavadocrequired + FILE=InputMissingJavadocTypeCorrect.java + echo "Execution with plain text report" + java -jar target/checkstyle-"$CS_POM_VERSION"-all.jar -c /google_checks.xml \ + $FOLDER/$FILE > .ci-temp/output.log + fail=0 + if grep -vE '(Starting audit)|(warning)|(Audit done.)' .ci-temp/output.log ; then + fail=1; + exit $fail; + elif grep 'warning' .ci-temp/output.log ; then + fail=1; + exit $fail; + fi + rm .ci-temp/output.log + echo "Execution with xml report" + java -jar target/checkstyle-"$CS_POM_VERSION"-all.jar -f xml -c /google_checks.xml \ + $FOLDER/$FILE -o .ci-temp/output.xml + fail=0 + echo "Content of report:" + cat .ci-temp/output.xml + echo "Validation of report" + if ! grep '' .ci-temp/output.xml ; then + fail=1; + echo "no closed tag" + exit $fail; + elif ! grep 'file name' .ci-temp/output.xml ; then + fail=1; + echo "no file tag" + exit $fail; + fi + rm .ci-temp/output.xml + echo "Execution with sarif report" + java -jar target/checkstyle-"$CS_POM_VERSION"-all.jar -f sarif -c /google_checks.xml \ + $FOLDER/$FILE -o .ci-temp/output.json + fail=0 + echo "Content of report:" + cat .ci-temp/output.json + echo "Validation of report" + if ! grep 'downloadUri' .ci-temp/output.json ; then + fail=1; + exit $fail; + elif ! grep 'results' .ci-temp/output.json ; then + fail=1; + exit $fail; + fi + rm .ci-temp/output.json + + ;; + +check-since-version) + # This identifies the PR's original commit + # if it notices a merge commit + HEAD=$(git rev-parse HEAD) + if git show --summary HEAD | grep ^Merge: ; then + echo "Merge detected." + HEAD=$(git log -n 1 --no-merges --pretty=format:"%H") + fi + # Identify previous commit to know how much to examine + # Script assumes we are only working with 1 commit if we are in master + # Otherwise, it looks for the common ancestor with master + COMMIT=$(git rev-parse "$HEAD") + echo "PR commit: $COMMIT" + + HEAD_NEW_FILES=$(git show "$COMMIT" | cat | grep -A 1 "\-\-\- /dev/null" | cat) + echo "New files in commit: $HEAD_NEW_FILES" + MODULE_REG=".*(Check|Filter).java" + REGEXP="b/src/main/java/com/puppycrawl/tools/checkstyle/(checks|filters|filefilters)/$MODULE_REG" + NEW_CHECK_FILE=$(git show "$COMMIT" | cat | grep -A 1 "\-\-\- /dev/null" | cat | \ + grep -E "$REGEXP" | \ + cat | sed "s/+++ b\///") + echo "New Check file: $NEW_CHECK_FILE" + + if [ -f "$NEW_CHECK_FILE" ]; then + echo "New Check detected: $NEW_CHECK_FILE" + CS_RELEASE_VERSION="$(getCheckstylePomVersionWithoutSnapshot)" + echo "CS Release version: $CS_RELEASE_VERSION" + + if [[ $CS_RELEASE_VERSION != *.0 ]]; then + echo "Next release version is bug fix '$CS_RELEASE_VERSION', we will bump second digit in it"; + MAJOR=$(echo "$CS_RELEASE_VERSION" | cut -d. -f1) + MINOR=$(echo "$CS_RELEASE_VERSION" | cut -d. -f2) + PATCH=$(echo "$CS_RELEASE_VERSION" | cut -d. -f3) + CS_RELEASE_VERSION="$MAJOR""."$((MINOR+1))".0" + echo "Expected CS Release version after merge of target commit: $CS_RELEASE_VERSION" + fi + + echo "Grep for @since $CS_RELEASE_VERSION" + grep "* @since $CS_RELEASE_VERSION" "$NEW_CHECK_FILE" + else + echo "No new Check, all is good." + fi + ;; + +compile-test-resources) + # this task is useful during migration to new JDK to let compile resources on new jdk only + ./mvnw -e --no-transfer-progress clean test-compile \ + -Dcheckstyle.skipCompileInputResources=false \ + -Dmaven.compiler.release=21 \ + -Dmaven.compiler.enablePreview=true + ;; + +javac17_standard) + # InputCustomImportOrderNoPackage2 - nothing is required in front of first import + # InputIllegalTypePackageClassName - bad import for testing + # InputVisibilityModifierPackageClassName - bad import for testing + files=($(grep -RELi --include='*.java' \ + --exclude='InputCustomImportOrderNoPackage2.java' \ + --exclude='InputIllegalTypePackageClassName.java' \ + --exclude='InputVisibilityModifierPackageClassName.java' \ + '// non-compiled (syntax|with javac|with eclipse)?\:' \ + src/test/resources-noncompilable \ + src/it/resources-noncompilable \ + src/xdocs-examples/resources-noncompilable)) + mkdir -p target + for file in "${files[@]}" + do + echo "Compiling ${file} with standard JDK17" + javac -d target "${file}" + done + ;; + +javac17) + files=($(grep -Rli --include='*.java' ': Compilable with Java17' \ + src/test/resources-noncompilable \ + src/it/resources-noncompilable \ + src/xdocs-examples/resources-noncompilable \ + | grep -v 'importorder/' || true)) + if [[ ${#files[@]} -eq 0 ]]; then + echo "No Java17 files to process" + else + mkdir -p target + for file in "${files[@]}" + do + javac --release 17 --enable-preview -d target "${file}" + done + fi + ;; + +javac19) + files=($(grep -Rli --include='*.java' ': Compilable with Java19' \ + src/test/resources-noncompilable \ + src/it/resources-noncompilable \ + src/xdocs-examples/resources-noncompilable || true)) + if [[ ${#files[@]} -eq 0 ]]; then + echo "No Java19 files to process" + else + mkdir -p target + for file in "${files[@]}" + do + javac --release 19 --enable-preview -d target "${file}" + done + fi + ;; + +javac20) + files=($(grep -Rli --include='*.java' ': Compilable with Java20' \ + src/test/resources-noncompilable \ + src/it/resources-noncompilable \ + src/xdocs-examples/resources-noncompilable || true)) + if [[ ${#files[@]} -eq 0 ]]; then + echo "No Java20 files to process" + else + mkdir -p target + for file in "${files[@]}" + do + javac --release 20 --enable-preview -d target "${file}" + done + fi + ;; + +javac21) + files=($(grep -Rli --include='*.java' ': Compilable with Java21' \ + src/test/resources-noncompilable \ + src/it/resources-noncompilable \ + src/xdocs-examples/resources-noncompilable || true)) + if [[ ${#files[@]} -eq 0 ]]; then + echo "No Java21 files to process" + else + mkdir -p target + for file in "${files[@]}" + do + javac --release 21 --enable-preview -d target "${file}" + done + fi + ;; + +javac22) + files=($(grep -Rli --include='*.java' ': Compilable with Java22' \ + src/test/resources-noncompilable \ + src/it/resources-noncompilable \ + src/xdocs-examples/resources-noncompilable || true)) + if [[ ${#files[@]} -eq 0 ]]; then + echo "No Java22 files to process" + else + mkdir -p target + for file in "${files[@]}" + do + javac --release 22 --enable-preview -d target "${file}" + done + fi + ;; + +javac25) + files=($(grep -Rli --include='*.java' ': Compilable with Java25' \ + src/test/resources-noncompilable \ + src/it/resources-noncompilable \ + src/xdocs-examples/resources-noncompilable || true)) + if [[ ${#files[@]} -eq 0 ]]; then + echo "No Java25 files to process" + else + mkdir -p target + for file in "${files[@]}" + do + javac --release 25 --enable-preview -d target "${file}" + done + fi + ;; + +package-site) + ./mvnw -e --no-transfer-progress package -Passembly,no-validations + ./mvnw -e --no-transfer-progress site -Dlinkcheck.skip=true + ;; + +sonarqube) + # token could be generated at https://sonarcloud.io/account/security/ + # execution on local for master: + # SONAR_TOKEN=xxxxxx ./.ci/validation.sh sonarqube + # execution on local for non-master: + # SONAR_TOKEN=xxxxxx PR_NUMBER=xxxxxx PR_BRANCH_NAME=xxxxxx ./.ci/validation.sh sonarqube + checkForVariable "SONAR_TOKEN" + + if [[ $PR_NUMBER =~ ^([0-9]+)$ ]]; then + SONAR_PR_VARIABLES="-Dsonar.pullrequest.key=$PR_NUMBER" + SONAR_PR_VARIABLES+=" -Dsonar.pullrequest.branch=$PR_BRANCH_NAME" + SONAR_PR_VARIABLES+=" -Dsonar.pullrequest.base=master" + echo "SONAR_PR_VARIABLES: ""$SONAR_PR_VARIABLES" + fi + + export MAVEN_OPTS='-Xmx2g' + # until https://github.com/checkstyle/checkstyle/issues/11637 + # shellcheck disable=SC2086 + ./mvnw -e --no-transfer-progress -Pno-validations clean package sonar:sonar \ + $SONAR_PR_VARIABLES \ + -Dsonar.host.url=https://sonarcloud.io \ + -Dsonar.login="$SONAR_TOKEN" \ + -Dsonar.projectKey=org.checkstyle:checkstyle \ + -Dsonar.organization=checkstyle + echo "report-task.txt:" + cat target/sonar/report-task.txt + echo "Verification of sonar gate status" + export SONAR_API_TOKEN=$SONAR_TOKEN + .ci/sonar-break-build.sh + ;; + +no-error-pgjdbc) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/pgjdbc/pgjdbc.git + cd .ci-temp/pgjdbc + ./gradlew --no-parallel --no-daemon checkstyleAll \ + -PenableMavenLocal -Pcheckstyle.version="${CS_POM_VERSION}" + cd ../ + removeFolderWithProtectedFiles pgjdbc + ;; + +no-error-orekit) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/Hipparchus-Math/hipparchus.git + cd .ci-temp/hipparchus + # checkout to version that Orekit expects + SHA_HIPPARCHUS="1492f06848f57e46bef911a""ad16203a242080028" + git checkout $SHA_HIPPARCHUS + mvn -e --no-transfer-progress install -DskipTests + cd - + checkout_from https://github.com/CS-SI/Orekit.git + cd .ci-temp/Orekit + # no CI is enforced in project, so to make our build stable we should + # checkout to latest release/development (annotated tag or hash) or sha that have fix we need + # git checkout $(git describe --abbrev=0 --tags) + git checkout "9b121e504771f3ddd303ab""cc""c74ac9db64541ea1" + mvn -e --no-transfer-progress compile checkstyle:check \ + -Dorekit.checkstyle.version="${CS_POM_VERSION}" + cd .. + removeFolderWithProtectedFiles Orekit + removeFolderWithProtectedFiles hipparchus + ;; + +no-error-hibernate-search) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/hibernate/hibernate-search.git + cd .ci-temp/hibernate-search + mvn -e --no-transfer-progress clean install -pl build/config -am \ + -DskipTests=true -Dmaven.compiler.failOnWarning=false \ + -Dcheckstyle.skip=true -Dforbiddenapis.skip=true \ + -Dversion.com.puppycrawl.tools.checkstyle="${CS_POM_VERSION}" + mvn -e --no-transfer-progress checkstyle:check \ + -Dversion.com.puppycrawl.tools.checkstyle="${CS_POM_VERSION}" + cd ../ + removeFolderWithProtectedFiles hibernate-search + ;; + +no-error-checkstyles-sevntu) + set -e + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + ./mvnw -e --no-transfer-progress compile verify -Psevntu \ + -Dmaven.sevntu-checkstyle-check.checkstyle.version="${CS_POM_VERSION}" \ + -Dmaven.test.skip=true -Dpmd.skip=true -Dspotbugs.skip=true \ + -Djacoco.skip=true -Dforbiddenapis.skip=true -Dxml.skip=true + ;; + +no-error-sevntu-checks) + set -e + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/sevntu-checkstyle/sevntu.checkstyle.git + cd .ci-temp/sevntu.checkstyle/sevntu-checks + mvn -e --no-transfer-progress -Pno-validations verify -Dcheckstyle.ant.skip=false \ + -Dcheckstyle.version="${CS_POM_VERSION}" \ + -Dcheckstyle.configLocation=../../../config/checkstyle-checks.xml \ + -Dcheckstyle.nonMain.configLocation=../../../config/checkstyle-non-main-files-checks.xml \ + -Dcheckstyle.non-main-files-suppressions.file=config/checkstyle-non-main-files-suppressions.xml + cd ../../ + removeFolderWithProtectedFiles sevntu.checkstyle + ;; + +no-error-contribution) + set -e + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/checkstyle/contribution.git + cd .ci-temp/contribution + cd patch-diff-report-tool + mvn -e --no-transfer-progress verify -DskipTests -Dcheckstyle.version="${CS_POM_VERSION}" \ + -Dcheckstyle.configLocation=../../../config/checkstyle-checks.xml + cd ../ + cd releasenotes-builder + mvn -e --no-transfer-progress verify -DskipTests -Dcheckstyle.version="${CS_POM_VERSION}" \ + -Dcheckstyle.configLocation=../../../config/checkstyle-checks.xml + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-error-methods-distance) + set -e + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/sevntu-checkstyle/methods-distance.git + cd .ci-temp/methods-distance + mvn -e --no-transfer-progress verify -DskipTests -Dcheckstyle-version="${CS_POM_VERSION}" \ + -Dcheckstyle.configLocation=../../config/checkstyle-checks.xml + cd .. + removeFolderWithProtectedFiles methods-distance + ;; + +no-error-equalsverifier) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/jqno/equalsverifier.git + cd .ci-temp/equalsverifier + mvn -e --no-transfer-progress -Pstatic-analysis-checkstyle compile \ + checkstyle:check -Dversion.checkstyle="${CS_POM_VERSION}" + cd ../ + removeFolderWithProtectedFiles equalsverifier + ;; + +no-error-strata) + set -e + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/OpenGamma/Strata.git + cd .ci-temp/Strata + # shellcheck disable=2016 # we do not want to expand properties in this command + STRATA_CS_POM_VERSION=$(mvn -e --no-transfer-progress -q -Dexec.executable='echo' \ + -Dexec.args='${checkstyle.version}' \ + --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) + mvn -e --no-transfer-progress install -B -Dstrict -DskipTests \ + -Dforbiddenapis.skip=true -Dcheckstyle.version="${CS_POM_VERSION}" \ + -Dcheckstyle.config.suffix="-v$STRATA_CS_POM_VERSION" + cd ../ + removeFolderWithProtectedFiles Strata + ;; + +no-error-spring-integration) + set -e + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/spring-projects/spring-integration.git + cd .ci-temp/spring-integration + PROP_MAVEN_LOCAL="mavenLocal" + PROP_CS_VERSION="checkstyleVersion" + ./gradlew clean check --parallel -x test -P$PROP_MAVEN_LOCAL \ + -P$PROP_CS_VERSION="${CS_POM_VERSION}" + cd ../ + removeFolderWithProtectedFiles spring-integration + ;; + +no-error-htmlunit) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/HtmlUnit/htmlunit + cd .ci-temp/htmlunit + mvn -e --no-transfer-progress compile checkstyle:check -Dcheckstyle.version="${CS_POM_VERSION}" + cd ../ + removeFolderWithProtectedFiles htmlunit + ;; + +no-error-spotbugs) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + ./mvnw -e --no-transfer-progress clean install -Pno-validations + echo "Checkout target sources ..." + checkout_from https://github.com/spotbugs/spotbugs + cd .ci-temp/spotbugs + sed -i'' "s/mavenCentral()/mavenLocal(); mavenCentral()/" build.gradle + sed -i'' "s/toolVersion.*$/toolVersion '${CS_POM_VERSION}'/" gradle/checkstyle.gradle + ./gradlew :eclipsePlugin-junit:checkstyleTest -Dcheckstyle.version="${CS_POM_VERSION}" + cd ../ + removeFolderWithProtectedFiles spotbugs + ;; + +no-error-trino) + echo "Building checkstyle..." + ./mvnw -e --no-transfer-progress clean install -Pno-validations -DskipTests + echo "Resolving Checkstyle version from pom.xml..." + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo "CS_version: ${CS_POM_VERSION}" + echo "Cloning Trino sources..." + checkout_from https://github.com/trinodb/trino.git + cd .ci-temp/trino + echo "Running Checkstyle ${CS_POM_VERSION} on Trino..." + ./mvnw -e --no-transfer-progress checkstyle:check -Dcheckstyle.version="${CS_POM_VERSION}" + cd ../ + echo "Cleaning up cloned Trino repo..." + removeFolderWithProtectedFiles trino + ;; + +no-exception-struts) + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i'' 's/#apache-struts/apache-struts/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + + +no-exception-checkstyle-sevntu) + set -e + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i'' 's/#local-checkstyle/local-checkstyle/' projects-to-test-on.properties + sed -i'' 's/#sevntu-checkstyle/sevntu-checkstyle/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-checkstyle-sevntu-javadoc) + set -e + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i'' 's/#local-checkstyle/local-checkstyle/' projects-to-test-on.properties + sed -i'' 's/#sevntu-checkstyle/sevntu-checkstyle/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-only-javadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + + +no-exception-guava) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i'' 's/#guava/guava/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-hibernate-orm) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#hibernate-orm/hibernate-orm/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-spotbugs) + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#spotbugs/spotbugs/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-spoon) + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#spoon/spoon/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-spring-framework) + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-hbase) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#Hbase/Hbase/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-Pmd-elasticsearch-lombok-ast) + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#pmd/pmd/' projects-to-test-on.properties + sed -i.'' 's/#elasticsearch/elasticsearch/' projects-to-test-on.properties + sed -i.'' 's/#lombok-ast/lombok-ast/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-exception-alot-of-projects) + CS_POM_VERSION="$(getCheckstylePomVersion)" + echo CS_version: "${CS_POM_VERSION}" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties + sed -i.'' 's/#RxJava/RxJava/' projects-to-test-on.properties + sed -i.'' 's/#java-design-patterns/java-design-patterns/' projects-to-test-on.properties + sed -i.'' 's/#MaterialDesignLibrary/MaterialDesignLibrary/' projects-to-test-on.properties + sed -i.'' 's/#apache-ant/apache-ant/' projects-to-test-on.properties + sed -i.'' 's/#apache-jsecurity/apache-jsecurity/' projects-to-test-on.properties + sed -i.'' 's/#android-launcher/android-launcher/' projects-to-test-on.properties + groovy ./diff.groovy --listOfProjects projects-to-test-on.properties \ + --patchConfig checks-nonjavadoc-error.xml -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --allowExcludes --mode single -xm "-Dcheckstyle.failsOnError=false" + cd ../../ + removeFolderWithProtectedFiles contribution + ;; + +no-warning-imports-guava) + PROJECTS=checks-import-order/projects-to-test-imports-guava.properties + CONFIG=checks-import-order/checks-imports-error-guava.xml + REPORT=reports/guava/site/index.html + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + groovy ./diff.groovy --listOfProjects $PROJECTS --patchConfig $CONFIG \ + --allowExcludes -p "$BRANCH" -r ../../.. \ + --useShallowClone \ + --mode single -xm "-Dcheckstyle.failsOnError=false" + RESULT=$(grep -A 5 " Warning" $REPORT | cat) + cd ../../ + removeFolderWithProtectedFiles contribution + if [ -z "$RESULT" ]; then + echo "Inspection did not find any warnings" + else + echo "$RESULT" + echo "Some warnings have been found. Verification failed." + sleep 5s + exit 1 + fi + ;; + +no-warning-imports-java-design-patterns) + PROJECTS=checks-import-order/projects-to-test-imports-java-design-patterns.properties + CONFIG=checks-import-order/checks-imports-error-java-design-patterns.xml + REPORT=reports/java-design-patterns/site/index.html + CS_POM_VERSION="$(getCheckstylePomVersion)" + BRANCH=$(git rev-parse --abbrev-ref HEAD) + echo CS_version: "${CS_POM_VERSION}" + checkout_from https://github.com/checkstyle/contribution + cd .ci-temp/contribution/checkstyle-tester + groovy ./diff.groovy --listOfProjects $PROJECTS --patchConfig $CONFIG \ + --allowExcludes -p "$BRANCH" -r ../../..\ + --useShallowClone \ + --mode single + RESULT=$(grep -A 5 " Warning" $REPORT | cat) + cd ../../ + removeFolderWithProtectedFiles contribution + if [ -z "$RESULT" ]; then + echo "Inspection did not find any warnings" + else + echo "$RESULT" + echo "Some warnings have been found. Verification failed." + sleep 5s + exit 1 + fi + ;; + +git-diff) + if [ "$(git status | grep 'Changes not staged\|Untracked files')" ]; then + printf "Please clean up or update .gitattributes file.\nGit status output:\n" + printf "Top 300 lines of diff:\n" + git status + git diff | head -n 300 + false + fi + ;; + +git-no-merge-commits) + MERGE_COMMITS=$(git rev-list --merges master.."$PR_HEAD_SHA") + + if [ -n "$MERGE_COMMITS" ]; then + for MERGE_COMMIT in $MERGE_COMMITS; do + echo "Merge commit found in PR: $MERGE_COMMIT" + done + echo "To learn how to clean up your commit history, visit:" + echo "https://checkstyle.org/beginning_development.html#Starting_Development" + exit 1 + fi + ;; + +git-check-pull-number) + PR_NUMBER=${CIRCLE_PULL_REQUEST##*/} + echo "PR_NUMBER=${PR_NUMBER}" + COMMITS="$(git log --format=format:%B master.."$PR_HEAD_SHA")" + + echo "$COMMITS" | while read -r COMMIT ; do + if [[ $COMMIT =~ 'Pull #' ]]; then + echo "COMMIT=${COMMIT}" + PULL_MESSAGE_NUMBER=$(echo "$COMMIT" | cut -d'#' -f 2 | cut -d':' -f 1) + echo "PULL_MESSAGE_NUMBER=${PULL_MESSAGE_NUMBER}" + if [[ $PULL_MESSAGE_NUMBER != "$PR_NUMBER" ]]; then + echo "Referenced PR and this PR number do not match." + echo "Commit message should reference '$PR_NUMBER'" + exit 1 + fi + fi + done + ;; + +jacoco) + export MAVEN_OPTS='-Xmx2g' + ./mvnw -e --no-transfer-progress clean test \ + jacoco:restore-instrumented-classes \ + jacoco:report@default-report \ + jacoco:check@default-check + # if launch is not from CI, we skip this step + if [[ $CI == 'true' ]]; then + echo "Reporting to codecov" + bash <(curl --fail-with-body -s https://codecov.io/bash) + else + echo "Result is at target/site/jacoco/index.html" + fi + ;; + +ci-temp-check) + fail=0 + mkdir -p .ci-temp + if [ -z "$(ls -A .ci-temp)" ]; then + echo "Folder .ci-temp/ is empty." + else + echo "Folder .ci-temp/ is not empty. Verification failed." + echo "Contents of .ci-temp/:" + fail=1 + fi + ls -A .ci-temp + exit $fail + ;; + + check-github-workflows-concurrency) + GITHUB_WORKFLOW_FILES=$(find .github/workflows -maxdepth 1 -not -type d -name "*.y*ml") + + FILES_NO_CONCURRENCY=() + for f in $GITHUB_WORKFLOW_FILES; do + if ! grep -wq "concurrency:" "$f"; then + FILES_NO_CONCURRENCY+=( $f ) + fi + done + + if [[ ${#FILES_NO_CONCURRENCY[@]} -gt 0 ]]; then + echo "The following Github workflows are missing a concurrency block:" + fi + + for value in "${FILES_NO_CONCURRENCY[@]}"; do + echo "$value" + done + + exit ${#FILES_NO_CONCURRENCY[@]} + ;; + +check-wildcards-on-pitest-target-classes) + ALL_CLASSES=$(xmlstarlet sel \ + -N x=http://maven.apache.org/POM/4.0.0 \ + -t -v "/x:project/x:profiles/x:profile//x:targetClasses/x:param" \ + -n pom.xml) + + CLASSES_NO_WILDCARD=$(echo "$ALL_CLASSES" | grep -v ".*\*\$" | grep -v -e '^\s*$' || echo) + CLASSES_NO_WILDCARD_COUNT=$(echo "$CLASSES_NO_WILDCARD" | grep -v -e '^\s*$' | wc -l) + + if [[ "$CLASSES_NO_WILDCARD_COUNT" -gt 0 ]]; then + echo "Append asterisks to the following pitest target classes in pom.xml:" + echo "$CLASSES_NO_WILDCARD" + fi + exit "$CLASSES_NO_WILDCARD_COUNT" + ;; + +verify) + ./mvnw -e --no-transfer-progress clean verify + ;; + +package-all-jar) + ./mvnw -e --no-transfer-progress clean package -Passembly + ;; + +website-only) + ./mvnw -e --no-transfer-progress clean site -Pno-validations + ;; + +pmd) + ./mvnw -e --no-transfer-progress clean test-compile pmd:check + ;; + +spotbugs) + ./mvnw -e --no-transfer-progress clean test-compile spotbugs:check + ;; + +checkstyle) + ./mvnw -e --no-transfer-progress clean compile antrun:run@ant-phase-verify + ;; + +forbiddenapis) + ./mvnw -e --no-transfer-progress \ + clean compile test-compile forbiddenapis:testCheck@forbiddenapis-test + ;; + +run-test) + if [[ -z "$2" ]] ; then + echo "Error: test class is not defined." + echo "Example: ./mvnw -e --no-transfer-progress clean test" \ + "-Dtest=XdocsPagesTest,XdocsJavaDocsTest" + echo "Example: ./mvnw -e --no-transfer-progress clean test -Dtest=CheckerTest#testDestroy" + exit 1 + fi + ./mvnw -e --no-transfer-progress clean test -Dtest="$2" + ;; + +sevntu) + ./mvnw -e --no-transfer-progress clean compile checkstyle:check@sevntu-checkstyle-check + ;; + +spotless) + ./mvnw -e --no-transfer-progress clean spotless:check -P spotless-autofix + ;; + +openrewrite-recipes) + echo "Cloning and building OpenRewrite recipes..." + PROJECT_ROOT="$(pwd)" + export MAVEN_OPTS="-Xmx4g -Xms2g" + + cd /tmp + git clone https://github.com/checkstyle/checkstyle-openrewrite-recipes.git + cd checkstyle-openrewrite-recipes + mvn -e --no-transfer-progress clean install -DskipTests + + cd "$PROJECT_ROOT" + + echo "Running Checkstyle validation to get report for openrewrite..." + set +e + ./mvnw -e --no-transfer-progress clean compile antrun:run@ant-phase-verify + set -e + echo "Running OpenRewrite recipes..." + ./mvnw -e --no-transfer-progress -Drewrite.recipeChangeLogLevel=INFO \ + rewrite:run -P checkstyle-autofix + + echo "Checking for uncommitted changes..." + ./.ci/print-diff-as-patch.sh target/rewrite.patch + + rm -rf /tmp/checkstyle-openrewrite-recipes + ;; + +*) + echo "Unexpected argument: $1" + echo "Supported tasks:" + list_tasks "${0}" + false + ;; + +esac diff --git a/.ci/wercker.sh b/.ci/wercker.sh deleted file mode 100755 index 51df7e400490..000000000000 --- a/.ci/wercker.sh +++ /dev/null @@ -1,426 +0,0 @@ -#!/bin/bash -# Attention, there is no "-x" to avoid problems on Wercker -set -e - -function checkout_from { - CLONE_URL=$1 - PROJECT=$(echo "$CLONE_URL" | sed -nE 's/.*\/(.*).git/\1/p') - mkdir -p .ci-temp - cd .ci-temp - if [ -d "$PROJECT" ]; then - echo "Target project $PROJECT is already cloned, latest changes will be fetched" - cd $PROJECT - git fetch - cd ../ - else - for i in 1 2 3 4 5; do git clone $CLONE_URL && break || sleep 15; done - fi - cd ../ -} - -case $1 in - -sonarqube) - # token could be generated at https://sonarcloud.io/account/security/ - # executon on local: - # SONAR_TOKEN=xxxxxx PR=xxxxxx WERCKER_GIT_BRANCH=xxxxxx ./.ci/travis/travis.sh sonarqube - if [[ $PR && $PR =~ ^([0-9]*)$ ]]; then - SONAR_PR_VARIABLES="-Dsonar.pullrequest.key=$PR" - SONAR_PR_VARIABLES+=" -Dsonar.pullrequest.branch=$WERCKER_GIT_BRANCH" - SONAR_PR_VARIABLES+=" -Dsonar.pullrequest.base=master" - echo "SONAR_PR_VARIABLES: "$SONAR_PR_VARIABLES - fi - if [[ -z $SONAR_TOKEN ]]; then echo "SONAR_TOKEN is not set"; sleep 5s; exit 1; fi - export MAVEN_OPTS='-Xmx2000m' - mvn -e -Pno-validations clean package sonar:sonar $SONAR_PR_VARIABLES \ - -Dsonar.host.url=https://sonarcloud.io \ - -Dsonar.login=$SONAR_TOKEN \ - -Dsonar.projectKey=org.checkstyle:checkstyle \ - -Dsonar.organization=checkstyle - echo "report-task.txt:" - cat target/sonar/report-task.txt - echo "Verification of sonar gate status" - checkout_from https://github.com/viesure/blog-sonar-build-breaker.git - sed -i'' "s|our.sonar.server|sonarcloud.io|" \ - .ci-temp/blog-sonar-build-breaker/sonar_break_build.sh - export SONAR_API_TOKEN=$SONAR_TOKEN - .ci-temp/blog-sonar-build-breaker/sonar_break_build.sh - ;; - - -no-error-pgjdbc) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/pgjdbc/pgjdbc.git - cd .ci-temp/pgjdbc/pgjdbc - mvn -e checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION} - cd ../../ - rm -rf pgjdbc - ;; - -no-error-orekit) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/Hipparchus-Math/hipparchus.git - cd .ci-temp/hipparchus - # checkout to version that Orekit expects - SHA_HIPPARCHUS="4c6c6fc45e859e""ae2d4eb091a3a3c0a7a458b8d9" - git checkout $SHA_HIPPARCHUS - mvn install -DskipTests - cd - - checkout_from https://github.com/CS-SI/Orekit.git - cd .ci-temp/Orekit - # no CI is enforced in project, so to make our build stable we should - # checkout to latest release/development (annotated tag or hash) or sha that have fix we need - # git checkout $(git describe --abbrev=0 --tags) - git checkout "a7e67ce73803c67a""ad90e0b28ed77a7781dc28a9" - mvn -e compile checkstyle:check -Dorekit.checkstyle.version=${CS_POM_VERSION} - cd ../ - rm -rf Orekit - ;; - -no-error-xwiki) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/xwiki/xwiki-commons.git - cd .ci-temp/xwiki-commons - SHA_XWIKI="8a2e04689fb8e707a3457833d""d44c909a""cc43e5b" - git checkout $SHA_XWIKI - mvn -f xwiki-commons-tools/xwiki-commons-tool-verification-resources/pom.xml \ - install -DskipTests -Dcheckstyle.version=${CS_POM_VERSION} - mvn -e test-compile checkstyle:check@default -Dcheckstyle.version=${CS_POM_VERSION} - cd ../../ - rm -rf xwiki-commons - ;; - -no-error-apex-core) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/apache/incubator-apex-core.git - cd .ci-temp/incubator-apex-core - mvn -e compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION} - cd ../ - rm -rf incubator-apex-core - ;; - -no-error-equalsverifier) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/jqno/equalsverifier.git - cd .ci-temp/equalsverifier - mvn -e compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION} - cd ../ - rm -rf equalsverifier - ;; - -no-error-hibernate-search) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/hibernate/hibernate-search.git - cd .ci-temp/hibernate-search - mvn -e clean install -DskipTests=true -Dtest.elasticsearch.run.skip=true \ - -Dcheckstyle.skip=true -Dforbiddenapis.skip=true \ - -Dpuppycrawl.checkstyle.version=${CS_POM_VERSION} - mvn -e checkstyle:check -Dpuppycrawl.checkstyle.version=${CS_POM_VERSION} - cd ../ - rm -rf hibernate-search - ;; - -no-error-htmlunit) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - echo "checkouting project sources ..." - svn -q export https://svn.code.sf.net/p/htmlunit/code/trunk/htmlunit@r14923 htmlunit - cd htmlunit - sed -i "s/ 2.28-SNAPSHOT/ 2.28-20171106.080245-12/" pom.xml - echo "Running checkstyle validation ..." - mvn -e compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION} - cd ../ - rm -rf htmlunit - ;; - -no-error-checkstyles-sevntu) - set -e - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - mvn -e compile verify -Dmaven.sevntu-checkstyle-check.checkstyle.version=${CS_POM_VERSION} \ - -Dmaven.test.skip=true -Dcheckstyle.ant.skip=true -Dpmd.skip=true -Dspotbugs.skip=true \ - -Djacoco.skip=true -Dforbiddenapis.skip=true -Dxml.skip=true - ;; - -no-error-sevntu-checks) - set -e - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/sevntu-checkstyle/sevntu.checkstyle.git - cd .ci-temp/sevntu.checkstyle/sevntu-checks - mvn -e -Pno-validations verify -Dcheckstyle.skip=false -Dcheckstyle.version=${CS_POM_VERSION} \ - -Dcheckstyle.configLocation=../../../config/checkstyle_checks.xml - cd ../../ - rm -rf sevntu.checkstyle - ;; - -no-error-contribution) - set -e - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution - cd patch-diff-report-tool - mvn -e verify -DskipTests -Dcheckstyle.version=${CS_POM_VERSION} \ - -Dcheckstyle.configLocation=../../../config/checkstyle_checks.xml - cd ../ - cd releasenotes-builder - mvn -e verify -DskipTests -Dcheckstyle.version=${CS_POM_VERSION} \ - -Dcheckstyle.configLocation=../../../config/checkstyle_checks.xml - cd ../ - cd ../../ - rm -rf checkstyle - ;; - -no-error-strata) - set -e - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/OpenGamma/Strata.git - cd .ci-temp/Strata - STRATA_CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${checkstyle.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - mvn install -e -B -Dstrict -DskipTests \ - -Dforbiddenapis.skip=true -Dcheckstyle.version=${CS_POM_VERSION} \ - -Dcheckstyle.config.suffix="-v$STRATA_CS_POM_VERSION" - cd ../ - rm -rf Strata - ;; - -no-error-spring-integration) - set -e - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/spring-projects/spring-integration.git - cd .ci-temp/spring-integration - PROP_MAVEN_LOCAL="mavenLocal" - PROP_CS_VERSION="checkstyleVersion" - ./gradlew clean check --parallel -x test -P$PROP_MAVEN_LOCAL -P$PROP_CS_VERSION=${CS_POM_VERSION} - cd ../ - rm -rf spring-integration - ;; - -no-exception-struts) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i'' 's/^guava/#guava/' projects-for-wercker.properties - sed -i'' 's/#apache-struts/apache-struts/' projects-for-wercker.properties - groovy ./launch.groovy --listOfProjects projects-for-wercker.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-checkstyle-sevntu) - set -e - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i'' 's/^guava/#guava/' projects-for-wercker.properties - sed -i'' 's/#local-checkstyle/local-checkstyle/' projects-for-wercker.properties - sed -i'' 's/#sevntu-checkstyle/sevntu-checkstyle/' projects-for-wercker.properties - groovy ./launch.groovy --listOfProjects projects-for-wercker.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-checkstyle-sevntu-javadoc) - set -e - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i'' 's/^guava/#guava/' projects-for-wercker.properties - sed -i'' 's/#local-checkstyle/local-checkstyle/' projects-for-wercker.properties - sed -i'' 's/#sevntu-checkstyle/sevntu-checkstyle/' projects-for-wercker.properties - groovy ./launch.groovy --listOfProjects projects-for-wercker.properties \ - --config checks-only-javadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-guava) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i'' 's/^guava/#guava/' projects-for-wercker.properties - sed -i'' 's/#guava/guava/' projects-for-wercker.properties - groovy ./launch.groovy --listOfProjects projects-for-wercker.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-hibernate-orm) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#hibernate-orm/hibernate-orm/' projects-to-test-on.properties - groovy ./launch.groovy --listOfProjects projects-for-wercker.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-spotbugs) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#spotbugs/spotbugs/' projects-to-test-on.properties - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-spring-framework) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-hbase) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#Hbase/Hbase/' projects-to-test-on.properties - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-Pmd-elasticsearch-lombok-ast) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#pmd/pmd/' projects-to-test-on.properties - sed -i.'' 's/#elasticsearch/elasticsearch/' projects-to-test-on.properties - sed -i.'' 's/#lombok-ast/lombok-ast/' projects-to-test-on.properties - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-exception-alot-of-projects) - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties - sed -i.'' 's/#RxJava/RxJava/' projects-to-test-on.properties - sed -i.'' 's/#java-design-patterns/java-design-patterns/' projects-to-test-on.properties - sed -i.'' 's/#MaterialDesignLibrary/MaterialDesignLibrary/' projects-to-test-on.properties - sed -i.'' 's/#apache-ant/apache-ant/' projects-to-test-on.properties - sed -i.'' 's/#apache-jsecurity/apache-jsecurity/' projects-to-test-on.properties - sed -i.'' 's/#android-launcher/android-launcher/' projects-to-test-on.properties - groovy ./launch.groovy --listOfProjects projects-to-test-on.properties \ - --config checks-nonjavadoc-error.xml --checkstyleVersion ${CS_POM_VERSION} - cd ../../ - rm -rf contribution - ;; - -no-warning-imports-guava) - PROJECTS=checks-import-order/projects-to-test-imports-guava.properties - CONFIG=checks-import-order/checks-imports-error-guava.xml - REPORT=reports/guava/site/index.html - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - groovy ./launch.groovy --listOfProjects $PROJECTS --config $CONFIG \ - --checkstyleVersion ${CS_POM_VERSION} - RESULT=`grep -A 5 " Warning" $REPORT | cat` - cd ../../ - rm -rf contribution - if [ -z "$RESULT" ]; then - echo "Inspection did not find any warnings" - else - echo "$RESULT" - echo "Some warnings have been found. Verification failed." - sleep 5s - exit 1 - fi - ;; - -no-warning-imports-java-design-patterns) - PROJECTS=checks-import-order/projects-to-test-imports-java-design-patterns.properties - CONFIG=checks-import-order/checks-imports-error-java-design-patterns.xml - REPORT=reports/java-design-patterns/site/index.html - CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' \ - --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) - echo CS_version: ${CS_POM_VERSION} - checkout_from https://github.com/checkstyle/contribution.git - cd .ci-temp/contribution/checkstyle-tester - groovy ./launch.groovy --listOfProjects $PROJECTS --config $CONFIG \ - --checkstyleVersion ${CS_POM_VERSION} - RESULT=`grep -A 5 " Warning" $REPORT | cat` - cd ../../ - rm -rf contribution - if [ -z "$RESULT" ]; then - echo "Inspection did not find any warnings" - else - echo "$RESULT" - echo "Some warnings have been found. Verification failed." - sleep 5s - exit 1 - fi - ;; - -*) - echo "Unexpected argument: $1" - sleep 5s - false - ;; - -esac diff --git a/.circleci/config.yml b/.circleci/config.yml index 60d1de95c8a5..598c7da5459d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,251 +1,337 @@ -version: 2 +version: 2.1 + jobs: - build-caches: - machine: true + run-inspections: + docker: + - image: amitkumardeoghoria/idea-image:jdk21-idea2022.3.3-v1 + steps: - # restore_cache.keys does not work, so multiple restore_cache.key is used - - restore_cache: - key: m2-cache - checkout - run: - name: run_job creation + name: Print versions command: | - mkdir -p .ci-temp - SKIP_FILES1=".github|appveyor.yml|.travis.yml|\.ci/" - SKIP_FILES2="|fast-forward-merge.sh" - SKIP_FILES3="|LICENSE|LICENSE.apache20|README.md|release.sh" - SKIP_FILES4="|RIGHTS.antlr|shippable.yml|codeship" - SKIP_FILES5="|shippable.sh|wercker.yml|wercker.sh" - SKIP_FILES6="|intellij-idea-inspections.xml" - SKIP_FILES7="|org.eclipse.jdt.core.prefs" - SKIP_FILES8="|Jenkinsfile" - FULL_SKIP1=$SKIP_FILES1$SKIP_FILES2$SKIP_FILES3$SKIP_FILES4 - FULL_SKIP2=$SKIP_FILES5$SKIP_FILES6$SKIP_FILES7$SKIP_FILES8 - SKIP_FILES=$FULL_SKIP1$FULL_SKIP2 - export RUN_JOB=1 - #source ./.ci/common.sh - # should_run_job will change RUN_JOB variable - #should_run_job "recheck" $SKIP_FILES - echo $RUN_JOB > .ci-temp/run_job + echo "Maven version:" + ./mvnw --version + echo "Java version:" + java --version + echo "IDEA version:" + echo $IDEA_VERSION - run: - name: download all maven dependencies and groovy + name: Run inspections command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - pwd - ls -la - java -version - mvn --version - mvn -Ppitest-metrics dependency:go-offline - else - echo "build is skipped ..." - fi - - persist_to_workspace: - root: /home/circleci/ - paths: - - .m2 - - project - - contribution + mkdir .idea + cp config/intellij-idea-inspections-misc.xml .idea/misc.xml + ./.ci/idea-inspection.sh + no_output_timeout: 25m + working_directory: ~/project + - store_artifacts: + path: /home/circleci/project/target/inspection-results - pitest1: - machine: true - parallelism: 4 - steps: - - attach_workspace: - at: /home/circleci/ - - run: - command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - echo "./.ci/pitest.sh pitest-coding" >> commands.txt - echo "./.ci/pitest.sh pitest-common" >> commands.txt - echo "./.ci/pitest.sh pitest-imports" >> commands.txt - echo "./.ci/pitest.sh pitest-ant" >> commands.txt - CMD="$(circleci tests split commands.txt)" - echo "Command: $CMD" - eval $CMD - else - echo "build is skipped ..." - fi - - pitest2: - machine: true - parallelism: 4 - steps: - - attach_workspace: - at: /home/circleci/ - - run: - command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - echo "./.ci/pitest.sh pitest-main" >> commands.txt - echo "./.ci/pitest.sh pitest-javadoc" >> commands.txt - echo "./.ci/pitest.sh pitest-indentation" >> commands.txt - echo "./.ci/pitest.sh pitest-xpath" >> commands.txt - CMD="$(circleci tests split commands.txt)" - echo "Command: $CMD" - eval $CMD - else - echo "build is skipped ..." - fi - - pitest3: - machine: true - parallelism: 4 + validate-with-maven-script: + description: "Runs a maven script using the job name as the argument." + parameters: &script_parameters + image-name: + type: string + default: "cimg/openjdk:21.0.6" + description: "docker image to use" + command: + description: "command to run" + type: string + default: "" + docker: + - image: << parameters.image-name >> steps: - - attach_workspace: - at: /home/circleci/ + - checkout + - restore_cache: + name: Restore Maven repo and wrapper cache + keys: + - mvn-cache-{{ checksum "pom.xml" }} - run: - command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - echo "./.ci/pitest.sh pitest-misc" >> commands.txt - echo "./.ci/pitest.sh pitest-design" >> commands.txt - echo "./.ci/pitest.sh pitest-api" >> commands.txt - echo "./.ci/pitest.sh pitest-utils" >> commands.txt - CMD="$(circleci tests split commands.txt)" - echo "Command: $CMD" - eval $CMD - else - echo "build is skipped ..." - fi - - pitest4: - machine: true - parallelism: 4 - steps: - - attach_workspace: - at: /home/circleci/ + command: << parameters.command >> - run: command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - echo "./.ci/pitest.sh pitest-whitespace" >> commands.txt - echo "./.ci/pitest.sh pitest-filters" >> commands.txt - echo "./.ci/pitest.sh pitest-header" >> commands.txt - echo "./.ci/pitest.sh pitest-annotation" >> commands.txt - CMD="$(circleci tests split commands.txt)" - echo "Command: $CMD" - eval $CMD - else - echo "build is skipped ..." - fi - - pitest5: - machine: true - parallelism: 4 + ./.ci/validation.sh git-diff + ./.ci/validation.sh ci-temp-check + - save_cache: + name: Save Maven repo and wrapper cache + key: mvn-cache-{{ checksum "pom.xml" }} + paths: + - .m2 + - .mvn/wrapper + + validate-with-script: + description: "Runs a non-maven script using the job name as the argument." + parameters: *script_parameters + docker: + - image: << parameters.image-name >> steps: - - attach_workspace: - at: /home/circleci/ + - checkout - run: + name: run << parameters.command >> command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - echo "./.ci/pitest.sh pitest-packagenamesloader" >> commands.txt - echo "./.ci/pitest.sh pitest-tree-walker" >> commands.txt - echo "./.ci/pitest.sh pitest-naming" >> commands.txt - echo "./.ci/pitest.sh pitest-metrics" >> commands.txt - CMD="$(circleci tests split commands.txt)" - echo "Command: $CMD" - eval $CMD - else - echo "build is skipped ..." - fi - - pitest6: - machine: true - parallelism: 4 + sudo apt update + sudo apt install -y xmlstarlet --no-install-recommends apt-utils + export PULL_REQUEST=$CIRCLE_PR_NUMBER + export PR_HEAD_SHA=$CIRCLE_SHA1 + export PR_NUMBER=$CIRCLE_PR_NUMBER + << parameters.command >> + + sonarqube: + docker: + - image: amitkumardeoghoria/jdk-21-groovy-git-mvn-ant-jq:v1 + steps: - - attach_workspace: - at: /home/circleci/ + - checkout - run: + name: Run sonarqube command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - echo "./.ci/pitest.sh pitest-blocks" >> commands.txt - echo "./.ci/pitest.sh pitest-sizes" >> commands.txt - echo "./.ci/pitest.sh pitest-modifier" >> commands.txt - echo "./.ci/pitest.sh pitest-regexp" >> commands.txt - CMD="$(circleci tests split commands.txt)" - echo "Command: $CMD" - eval $CMD - else - echo "build is skipped ..." - fi - - pitest7: - machine: true - parallelism: 4 + export PR_NUMBER=$CIRCLE_PR_NUMBER + export PR_BRANCH_NAME=$CIRCLE_BRANCH + export SONAR_API_TOKEN=$SONAR_TOKEN + ./.ci/validation.sh sonarqube + + yamllint: + docker: + - image: cimg/base:2022.11 + steps: - - attach_workspace: - at: /home/circleci/ + - checkout - run: + name: Install dependencies command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - echo "./.ci/pitest.sh pitest-gui" >> commands.txt - CMD="$(circleci tests split commands.txt)" - echo "Command: $CMD" - eval $CMD - else - echo "build is skipped ..." - fi - - pitest8: - machine: true - parallelism: 4 - steps: - - attach_workspace: - at: /home/circleci/ + sudo apt update + sudo apt install -y yamllint - run: - command: | - RUN_JOB=`cat .ci-temp/run_job` - echo "RUN_JOB="$RUN_JOB - if [[ $RUN_JOB == 1 ]]; then - echo "./.ci/pitest.sh pitest-common-2" >> commands.txt - CMD="$(circleci tests split commands.txt)" - echo "Command: $CMD" - eval $CMD - else - echo "build is skipped ..." - fi + name: Run yamllint + command: yamllint -f parsable -c config/yamllint.yaml . workflows: - version: 2 - pitest-testing: + # sonarqube: + # jobs: + # - sonarqube: + # context: + # - sonarqube + + test: + jobs: + # no-exception-test script + - validate-with-maven-script: + name: "no-exception-lucene-and-others-javadoc" + image-name: &cs_img "amitkumardeoghoria/jdk-21-groovy-git-mvn-ant-jq:v1" + command: "./.ci/no-exception-test.sh no-exception-lucene-and-others-javadoc" + - validate-with-maven-script: + name: "no-exception-cassandra-storm-tapestry-javadoc" + image-name: *cs_img + command: "./.ci/no-exception-test.sh no-exception-cassandra-storm-tapestry-javadoc" + - validate-with-maven-script: + name: "no-exception-hadoop-apache-groovy-scouter-javadoc" + image-name: *cs_img + command: "./.ci/no-exception-test.sh no-exception-hadoop-apache-groovy-scouter-javadoc" + - validate-with-maven-script: + name: "no-exception-only-javadoc" + image-name: *cs_img + command: "./.ci/no-exception-test.sh no-exception-only-javadoc" + + # validation script + - validate-with-maven-script: + name: "no-error-xwiki" + image-name: "cimg/openjdk:21.0.6" + command: "./.ci/validation.sh no-error-xwiki" + - validate-with-maven-script: + name: "no-error-pmd" + image-name: *cs_img + command: "./.ci/validation.sh no-error-pmd" + - validate-with-maven-script: + name: "no-exception-struts" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-struts" + - validate-with-maven-script: + name: "no-exception-checkstyle-sevntu" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-checkstyle-sevntu" + - validate-with-maven-script: + name: "no-exception-checkstyle-sevntu-javadoc" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-checkstyle-sevntu-javadoc" + - validate-with-maven-script: + name: "no-exception-guava" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-guava" + - validate-with-maven-script: + name: "no-exception-hibernate-orm" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-hibernate-orm" + - validate-with-maven-script: + name: "no-exception-spotbugs" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-spotbugs" + - validate-with-maven-script: + name: "no-exception-spoon" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-spoon" + - validate-with-maven-script: + name: "no-exception-spring-framework" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-spring-framework" + - validate-with-maven-script: + name: "no-exception-hbase" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-hbase" + - validate-with-maven-script: + name: "no-exception-Pmd-elasticsearch-lombok-ast" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-Pmd-elasticsearch-lombok-ast" + - validate-with-maven-script: + name: "no-exception-alot-of-projects" + image-name: *cs_img + command: "./.ci/validation.sh no-exception-alot-of-projects" + - validate-with-maven-script: + name: "no-warning-imports-guava" + image-name: *cs_img + command: "./.ci/validation.sh no-warning-imports-guava" + - validate-with-maven-script: + name: "no-warning-imports-java-design-patterns" + image-name: *cs_img + command: "./.ci/validation.sh no-warning-imports-java-design-patterns" + - validate-with-maven-script: + name: "checkstyle-and-sevntu" + image-name: *cs_img + command: "./.ci/validation.sh checkstyle-and-sevntu" + # https://github.com/spotbugs/spotbugs-maven-plugin/issues/806 explains + # why we need execution of spotbugs without any other maven plugins which can change binaries + - validate-with-maven-script: + name: "spotbugs-and-pmd" + image-name: *cs_img + command: "./.ci/validation.sh spotbugs-and-pmd" + - validate-with-maven-script: + name: "site" + image-name: *cs_img + command: "./.ci/validation.sh site" + - validate-with-maven-script: + name: "release-dry-run" + image-name: *cs_img + command: "./.ci/validation.sh release-dry-run" + - validate-with-maven-script: + name: "assembly-run-all-jar" + image-name: *cs_img + command: "./.ci/validation.sh assembly-run-all-jar" + - validate-with-maven-script: + name: "no-error-test-sbe" + image-name: "cimg/openjdk:21.0.6" + command: "./.ci/validation.sh no-error-test-sbe" + - validate-with-maven-script: + name: "no-error-spotbugs" + image-name: *cs_img + command: "./.ci/validation.sh no-error-spotbugs" + - validate-with-maven-script: + name: "no-error-pgjdbc" + image-name: "cimg/openjdk:21.0" + command: "./.ci/validation.sh no-error-pgjdbc" + - validate-with-maven-script: + name: "linkcheck-plugin" + image-name: "cimg/openjdk:21.0.6" + command: "./.ci/run-link-check-plugin.sh --skip-external" + - validate-with-maven-script: + name: "no-exception-samples-gradle" + image-name: "cimg/openjdk:17.0.7" + command: "./.ci/no-exception-test.sh no-exception-samples-gradle" + - validate-with-maven-script: + name: "no-exception-samples-maven" + image-name: "cimg/openjdk:21.0.6" + command: "./.ci/no-exception-test.sh no-exception-samples-maven" + + - validate-with-maven-script: + name: "no-exception-samples-ant" + image-name: *cs_img + command: "./.ci/no-exception-test.sh no-exception-samples-ant" + - validate-with-maven-script: + name: "no-error-hazelcast" + image-name: *cs_img + command: "./.ci/validation.sh no-error-hazelcast" + + idea: + jobs: + - run-inspections + + git-validation: + jobs: + - validate-with-script: + name: "git-no-merge-commits" + command: "./.ci/validation.sh git-no-merge-commits" + - validate-with-script: + name: "git-check-pull-number" + command: "./.ci/validation.sh git-check-pull-number" + + cli-validation: + jobs: + - yamllint + - validate-with-script: + name: "checkchmod" + command: "./.ci/checkchmod.sh" + - validate-with-script: + name: "check-github-workflows-concurrency" + command: "./.ci/validation.sh check-github-workflows-concurrency" + - validate-with-script: + name: "check-wildcards-on-pitest-target-classes" + image-name: "cimg/base:2022.11" + command: "./.ci/validation.sh check-wildcards-on-pitest-target-classes" + + javac-validation: + jobs: + - validate-with-script: + name: "check-since-version" + command: "./.ci/validation.sh check-since-version" + - validate-with-script: + name: "javac17_standard" + image-name: "cimg/openjdk:17.0.7" + command: "./.ci/validation.sh javac17_standard" + - validate-with-script: + name: "javac17" + image-name: "cimg/openjdk:17.0.7" + command: "./.ci/validation.sh javac17" + - validate-with-script: + name: "java 21 test resources compile" + image-name: "cimg/openjdk:21.0.8" + command: "./.ci/validation.sh compile-test-resources" + - validate-with-script: + name: "javac19" + image-name: "cimg/openjdk:19.0.1" + command: "./.ci/validation.sh javac19" + - validate-with-script: + name: "javac20" + image-name: "cimg/openjdk:20.0.1" + command: "./.ci/validation.sh javac20" + - validate-with-script: + name: "javac21" + image-name: "cimg/openjdk:21.0.6" + command: "./.ci/validation.sh javac21" + - validate-with-script: + name: "javac22" + image-name: "cimg/openjdk:22.0.2" + command: "./.ci/validation.sh javac22" + - validate-with-script: + name: "javac25" + image-name: "cimg/openjdk:25.0" + command: "./.ci/validation.sh javac25" + + site-validation: + jobs: + - validate-with-maven-script: + name: "jdk21-package-site" + image-name: *cs_img + command: "./.ci/validation.sh package-site" + + openrewrite: + jobs: + - validate-with-maven-script: + name: "openrewrite-recipes" + image-name: "cimg/openjdk:21.0" + command: "./.ci/validation.sh openrewrite-recipes" + + spotless: jobs: - - build-caches - - pitest1: - requires: - - build-caches - - pitest2: - requires: - - build-caches - - pitest3: - requires: - - build-caches - - pitest4: - requires: - - build-caches - - pitest5: - requires: - - build-caches - - pitest6: - requires: - - build-caches - # we do not do thorough testing of gui part - # - pitest7: - # requires: - # - build-caches - - pitest8: - requires: - - build-caches + - validate-with-maven-script: + name: spotless + image-name: "cimg/openjdk:21.0" + command: "./.ci/validation.sh spotless" diff --git a/.cirrus.yml b/.cirrus.yml new file mode 100644 index 000000000000..eca3a7f564af --- /dev/null +++ b/.cirrus.yml @@ -0,0 +1,70 @@ +only_if: $CIRRUS_BRANCH == $CIRRUS_DEFAULT_BRANCH || $CIRRUS_BRANCH !=~ 'pull/.*' +task: + name: Windows build + windows_container: + image: cirrusci/windowsservercore:2019 + clone_script: + - git config core.autocrlf + - git clone --recursive + https://x-access-token:%CIRRUS_REPO_CLONE_TOKEN%@github.com/%CIRRUS_REPO_FULL_NAME%.git + %CIRRUS_WORKING_DIR%/ci + - set "JAVA_HOME=%ProgramFiles%\%TEMURIN_PATH%" + - set "PATH=%JAVA_HOME%\bin;%PATH%" + - cd ci + - cmd /c "if defined CIRRUS_PR (git fetch origin pull/%CIRRUS_PR%/head:pull/%CIRRUS_PR%)" + - git reset --hard %CIRRUS_CHANGE_IN_REPO% + choco_cache: + # should be under %CIRRUS_WORKING_DIR% + folder: .chocolatey + maven_cache: + # should be under %CIRRUS_WORKING_DIR% + folder: .m2 + include: + - .mvn/wrapper + matrix: + # add more JDK versions here + - name: Cirrus - JDK21 + env: + TEMURIN_VERSION: "21.0.6.7" + TEMURIN_PATH: 'Eclipse Adoptium\jdk-%TEMURIN_VERSION%-hotspot' + env: + # disable ANSI output for picocli (may affect tests) + NO_COLOR: "1" + # https://stackoverflow.com/questions/42024619/maven-build-gets-connection-reset-when-downloading-artifacts + MAVEN_OPTS: "-Dhttp.keepAlive=false \ + -Dmaven.repo.local=%CIRRUS_WORKING_DIR%/.m2 \ + -Dmaven.wagon.http.retryHandler.count=3" + install_script: + - choco config set cacheLocation %CIRRUS_WORKING_DIR%/.chocolatey + - choco upgrade -y chocolatey + - choco install -y --no-progress ant + - choco install -y --no-progress temurin --version %TEMURIN_VERSION% + - refreshenv + - set "JAVA_HOME=%ProgramFiles%\%TEMURIN_PATH%" + - set "PATH=%JAVA_HOME%\bin;%PATH%" + - java -version + - javac -version + + version_script: + - set "JAVA_HOME=%ProgramFiles%\%TEMURIN_PATH%" + - set "PATH=%JAVA_HOME%\bin;%PATH%" + - set + - ant -version + - java --version + # - xsltproc --version + # - xml --version + sevntu_script: + - set "JAVA_HOME=%ProgramFiles%\%TEMURIN_PATH%" + - set "PATH=%JAVA_HOME%\bin;%PATH%" + - cd ci + - .ci/validation.cmd sevntu + verify_without_checkstyle_script: + - set "JAVA_HOME=%ProgramFiles%\%TEMURIN_PATH%" + - set "PATH=%JAVA_HOME%\bin;%PATH%" + - cd ci + - .ci/validation.cmd verify_without_checkstyle + site_without_verify_script: + - set "JAVA_HOME=%ProgramFiles%\%TEMURIN_PATH%" + - set "PATH=%JAVA_HOME%\bin;%PATH%" + - cd ci + - .ci/validation.cmd site_without_verify diff --git a/.dependabot/config.yml b/.dependabot/config.yml deleted file mode 100644 index a6d247725dd9..000000000000 --- a/.dependabot/config.yml +++ /dev/null @@ -1,7 +0,0 @@ -version: 1 -update_configs: - - package_manager: "java:maven" - directory: "/" - update_schedule: "daily" - commit_message: - prefix: "dependency" diff --git a/.gitattributes b/.gitattributes index 580d0527c051..9fba92f3fec4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -13,4 +13,12 @@ # Test resources that need specific eol /src/test/resources/com/puppycrawl/tools/checkstyle/checks/newlineatendoffile/InputNewlineAtEndOfFileCrlf.java eol=crlf +/src/test/resources/com/puppycrawl/tools/checkstyle/checks/newlineatendoffile/InputNewlineAtEndOfFileCrlf2.java eol=crlf +/src/test/resources/com/puppycrawl/tools/checkstyle/checks/newlineatendoffile/InputNewlineAtEndOfFileCrlf3.java eol=crlf +/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/javadoctype/InputJavadocTypeWithBlockComment.java eol=crlf /src/test/resources/com/puppycrawl/tools/checkstyle/checks/newlineatendoffile/InputNewlineAtEndOfFileCr.java -text +/src/test/resources/com/puppycrawl/tools/checkstyle/checks/newlineatendoffile/InputNewlineAtEndOfFileCr2.java -text +src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/xpath/xpathquerygenerator/InputXpathQueryGeneratorTextBlockCrlf.java eol=crlf +src/test/resources/com/puppycrawl/tools/checkstyle/grammar/javadoc/InputCrAsNewlineMultiline.javadoc -text +src/test/resources/com/puppycrawl/tools/checkstyle/grammar/javadoc/InputDosLineEndingAsNewlineMultiline.javadoc eol=crlf +src/xdocs-examples/resources/com/puppycrawl/tools/checkstyle/checks/newlineatendoffile/Example3.java eol=crlf diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..07064129cad0 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +https://groups.google.com/forum/#!forum/checkstyle-devel. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 1e803c02c807..9d7ce16edc57 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,25 +1,139 @@ -# Contributing +# Contribution Guidelines + ![](https://raw.githubusercontent.com/checkstyle/resources/master/img/checkstyle-logos/checkstyle-logo-260x99.png) -#### [Reporting issues](https://checkstyle.org/report_issue.html) -#### [How to report a bug?](https://checkstyle.org/report_issue.html#How_to_report_a_bug.3F) -#### [Issue Template](https://github.com/checkstyle/checkstyle/blob/master/.github/ISSUE_TEMPLATE.md) +--------------------------------- + +**This guide serves to set clear expectations for everyone involved with the project so that +we can improve it together while also creating a welcoming space for everyone to participate. +Following these guidelines will help ensure a positive experience for contributors and +maintainers alike.** + +:octocat: *Thanks for your interest in contributing to CheckStyle!* :octocat: + +## Contents + +- [Code of Conduct](#code-of-conduct) +- [Getting Started](#getting-started) +- [Opening an Issue](#opening-an-issue) +- [Reporting Security Issues](#reporting-security-issues) +- [Submitting Pull Requests](#submitting-pull-requests) +- [Code Review](#code-review) +- [Google Summer of Code](#google-summer-of-code) +- [Asking Questions](#asking-questions) +- [Credits](#credits) + +## Code of Conduct + +This project and everyone participating in it is governed by the + [CheckStyle Code of Conduct](/.github/CODE_OF_CONDUCT.md). + +## Getting Started + +- Please see the [CheckStyle Documentation](https://checkstyle.org/beginning_development.html) + for information on how to get started with the project. This includes setting up your + development environment, building the project, and running tests. +- Take a look at the [Contribution Guidelines](https://checkstyle.org/contributing.html) for + on how to contribute to the project. +- Select an issue to work on from the + [Issues Page](https://github.com/checkstyle/checkstyle/issues). We + have a few issues labeled as + https://github.com/checkstyle/checkstyle/labels/good%20first%20issue to + help you get started. Please watch [videos](https://www.youtube.com/playlist?list=PLHM9s_lN4X0hzOQ0sUmGdroxW0HfREAqj) + on how to setup local environment and send first fix. +- Once you get your first PR merged, you can move on to + https://github.com/checkstyle/checkstyle/labels/good%20second%20issue, + https://github.com/checkstyle/checkstyle/labels/good%20third%20issue, + and finally https://github.com/checkstyle/checkstyle/labels/good%20fourth%20issue + before taking up some bug fixes or features. Always make sure that the issue you select + has the https://github.com/checkstyle/checkstyle/labels/approved label. +- When you decide which issue you would like to take up, + please comment on the issue to let others know that you are working on it ("I am on it."). + It is completely ok to change a mind, please try to remove comment. + If you see such comment created long time ago but issue is still open and no Pull created, please + feel free to make a comment that you will try to do it. + +## Submitting Pull Requests + +- **Read our pull request rules.** See [PR Rules](https://github.com/checkstyle/checkstyle/wiki/PR-rules). +- **Comment on the issue.** When you decide which issue you would like to take up, + please comment on the issue to let others know that you are working on it ("I am on it."). + Existing "I am on it" comments are a good indication that someone is already working on the + issue, but these comments can be old or outdated; if a comment is a few weeks old with no + activity, feel free to ask if the issue is still being worked on. +- **Read the Github docs.** Visit GitHub's [Pull Request Guide](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests) + for information on how to submit a pull request. +- **Follow the template.** Please follow the [CheckStyle Pull Request Template](https://github.com/checkstyle/checkstyle/blob/master/.github/PULL_REQUEST_TEMPLATE.md) + that is provided in the pull request description when submitting a pull request. +- **Run maven build locally.** `mvn clean verify` should pass on your local before + submitting a pull request. +- **Keep the PR small.** If you are working on a large feature, consider breaking it up into + smaller PRs that can be reviewed and merged independently. This makes it easier for + reviewers to understand the changes and for maintainers to merge the PR. + +## Code Review + +All submissions, including submissions by project members, require review. We use GitHub pull +requests for this purpose. Consult the [GitHub Help](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-request-reviews) +for more information on pull request reviews. + +Here are some general guidelines to follow when submitting a pull request: + +- **Reply to comments.** If a reviewer asks for changes, reply to each + (and every) comment with discussion or follow up questions, or let the reviewer know + that you have addressed their concerns ("done"). +- **Be patient.** Reviewing PRs takes time. If a reviewer hasn't responded in a week or so, + feel free to ping them. If you are a reviewer and you need more time to review a PR, please + let the submitter know. +- **Be kind.** Remember that everyone involved in the project is a human being. Be kind and + respectful in your comments and reviews. +- **Be open to feedback.** If a reviewer asks for changes, be open to their feedback. Remember that + the goal is to improve the project, and feedback is an important part of that process. + +## Opening an Issue + +A great way to contribute to the project is to create a detailed issue when you encounter +a problem or would like to suggest a feature. We always appreciate a well-written, +thorough issue description. :brain: + +Some points to consider when opening an issue: + +- **Make sure you are using the latest Checkstyle version.** + Before [Opening an Issue](https://github.com/checkstyle/checkstyle/issues), + check if you are using the latest version of the project, + [found here](https://github.com/checkstyle/checkstyle/releases). If you are not up-to-date, + check to see if updating to the latest release fixes your issue. +- **Do not open a duplicate feature request.** Search for existing feature requests first. If you + find your feature (or one very similar) previously requested, comment on that issue. +- **Fully complete the provided issue template.** The bug report and feature request templates + specify all the information we need to quickly and efficiently address your issue. Be clear, + concise, and descriptive. + Provide as much information as you can, including steps to reproduce, stack traces, etc. +- **Use [GitHub-flavored Markdown](https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax).** + Especially put code blocks and console outputs in backticks (```). This improves readability. + +## Reporting Security Issues + +**Do not file a public issue for security vulnerabilities.** Please contact the +maintainers directly. +see the [Security Policy](https://github.com/checkstyle/checkstyle/blob/master/SECURITY.md) +for more information. + +## Google Summer of Code -Please provide issue report in the format that we request, EACH DETAIL IS A HUGE HELP. +Please see the [GSoC Participant Guide](https://github.com/checkstyle/checkstyle/blob/master/.github/GSOC.md). -Issues that are not following the guidelines, -will be processed as last priority or never or simply closed as invalid. +## Asking Questions +See our [Discussions Page](https://github.com/checkstyle/checkstyle/discussions). In short, GitHub +issues are not the appropriate place to debug your specific project, but should be reserved +for filing bugs and feature requests. You can also visit our +[Google Groups Forum](https://groups.google.com/g/checkstyle-devel) -# Contributing Guide -Please note that PRs are looked only for approved issues. Follow the PR guide for opening a PR -#### [Pull Request Template](https://github.com/checkstyle/checkstyle/blob/master/.github/PULL_REQUEST_TEMPLATE.md) +## Credits -Please follow the below links in order to start contributing to the checkstyle project -#### [Beginning Development](https://checkstyle.org/beginning_development.html) -#### [Contribution Guidelines](https://checkstyle.org/contributing.html) +*This document was inspired by work from the following communities:* -Find the links below to import the checkstyle project to an IDE -#### [Importing checkstyle project to IntelliJ](https://checkstyle.org/idea.html) -#### [Importing checkstyle project to Eclipse](https://checkstyle.org/eclipse.html) -#### [Importing checkstyle project to Netbeans](https://checkstyle.org/netbeans.html) +- [CocoaPods](https://github.com/CocoaPods/CocoaPods/blob/master/CONTRIBUTING.md) +- [Docker](https://github.com/moby/moby/blob/master/CONTRIBUTING.md) +- [.github](https://github.com/jessesquires/.github) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index c0bb9a4762c8..70c0b1f23766 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,12 +1,11 @@ # These are supported funding model platforms -#github: romani -#patreon: # Replace with a single Patreon username +# github: romani +# patreon: # Replace with a single Patreon username open_collective: checkstyle -#ko_fi: # Replace with a single Ko-fi username -#tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel -#community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +# ko_fi: # Replace with a single Ko-fi username +# tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +# community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: checkstyle -#issuehunt: # Replace with a single IssueHunt username -#otechie: # Replace with a single Otechie username -custom: https://www.bountysource.com/teams/checkstyle/issues +# issuehunt: # Replace with a single IssueHunt username +# otechie: # Replace with a single Otechie username diff --git a/.github/GSOC.md b/.github/GSOC.md new file mode 100644 index 000000000000..e16a98141ce1 --- /dev/null +++ b/.github/GSOC.md @@ -0,0 +1,122 @@ +# GSOC Participant Guide + +![](https://raw.githubusercontent.com/checkstyle/resources/master/img/checkstyle-logos/checkstyle-logo-260x99.png) + +--------------------------------- + +**This guide serves to set clear expectations and provide guidance for Google Summer of Code (GSoC) +participants.** + +:sun_with_face: Thanks for your interest in participating in GSoC with Checkstyle! :sun_with_face: + +## Contents + +- [Getting Started](#getting-started) +- [Additional Tips](#additional-tips) +- [Your Proposal](#your-proposal) + +## Getting Started + +Thanks for your interest in participating in GSoC with Checkstyle! Joining Checkstyle for the summer +is a great way to learn about open source software development and contribute to a widely-used +project. We are excited to work with you and help you grow as a software developer. You don't +need to be an expert in Java or Checkstyle to participate. We are looking for participants who are +eager to learn, work hard, and are excited to contribute to open source software. Additionally, we +want you to stick around after GSoC and become a long-term member of our community :smile:. + +Please take the time to read through this guide and familiarize yourself with the project. If you +have any questions, please don't hesitate to ask. We are here to help you succeed. If you have +not already done so, please read through the following documentation provided by Google: + +- [GSoC Participant Guide](https://summerofcode.withgoogle.com/rules/). +- [GSoC FAQ](https://developers.google.com/open-source/gsoc/faq). + +### Recommended Steps + +- **Get to know the project.** Spend some time reading through the Checkstyle documentation and + familiarizing yourself with the project. You can find the documentation at + [https://checkstyle.org/](https://checkstyle.org/). +- **Join the Checkstyle community.** + Join the Checkstyle community group on [Discord](https://discord.gg/FsUsYC2ura). + This is a great place to ask questions and get to know the community. + Join the Checkstyle group on [Google Groups](https://groups.google.com/forum/#!forum/checkstyle). + This is another place to ask questions and get to know the community. +- **Start contributing.** Please read [CONTRIBUTING doc](CONTRIBUTING.md). +- **Take a Look at Our Project Ideas.** We have a list of project ideas that we think would be + great for GSoC. You can find them in our wiki [Checkstyle Wiki](https://github.com/checkstyle/checkstyle/wiki). + You can also propose your own project idea. We are open to new ideas and would love to hear + what you are interested in working on. +- **Create a Draft Proposal.** Once you have completed a few issues, + you will be ready to start working on some + more challenging issues, like bug fixes and new features. + Once you have a good understanding of the project and have an idea + of what you would like to work on, create a draft proposal. We are happy to help you refine your + proposal and provide feedback. The best way to share your draft proposal is through Google docs. +- **Submit Your Proposal.** Now that you have refined your proposal, submit it through the + GSoC website **before the final submission deadline**. + +## Your Proposal + +Your proposal is your opportunity to show us that you are the right person for the job. To this end, +we have provided a list of things that we would like to see in your proposal. We are not looking for +a long proposal, but we are looking for a well-thought-out proposal that shows us that you have +taken the time to understand the project and have a clear plan for how you will contribute. + +### Proposal Outline + +#### Introduction + +All projects aim to solve a problem or improve something. Start your proposal by introducing the +problem you are trying to solve or the improvement you are trying to make. This is your opportunity +to show us that you understand the problem. +Include any relevant background information that will help us understand the problem, like +statistics, examples, references to existing issues, etc. + +#### Implementation Plan + +Describe your solution to the problem. This should include a high-level overview of the +architecture, a list of tasks, and a list of potential challenges, as well as some technical +details. We want to see that you have thought through the problem and can visualize how you will +solve it. + +#### Timeline + +Demonstrate your ability to break down your project into actionable tasks +and outline a clear timeline for completion. This should be a timeline that shows what you will be +working on each week. It should include milestones and deliverables. An effective way to present +this is in a table. + +#### About You + +Tell us about yourself. what time zone are you located in? +What is your background? +**Share list of links to your Checkstyle contributions +to be considered for GSoC; this is one of the most important selection criteria.** +This is your opportunity to show us that you are a good fit for the project and that +you are excited to work with us. + +### Proposal Tips + +- Be Specific. We want to see that you have thought through the problem and + how you will solve it. +- Be Realistic. We are looking for a proposal that is achievable in the time frame of GSoC. + We want to see that you have a clear plan. +- Be Professional. We are looking for a proposal that is well-written and professional. +- One Proposal <-> One Project. Do not create a proposal that spans multiple projects. +- Proposal Title. Please use the title of the project idea from our page of projects. + +## Additional Tips + +- **Start Early.** The earlier you start, the more time you will have to get to know the project, + accumulate contributions, and refine your proposal. +- **Communicate Effectively.** We are looking for participants who can communicate effectively. This + includes using clear and concise language, being responsive to feedback, and being proactive. +- **Learn About Software Development Beyond Just Code.** To be a great open-source + contributor, it helps to understand more than just writing code. Knowing about + common practices like code reviews, and how developers feel about them, is + valuable. This article on developer feelings about code reviews is a good example: + "[Developer Sentiment in Code Reviews][code-review-feelings-article-link]". +- **Contribute, Contribute, Contribute.** This is the single best way to show us that you are + serious becoming a valuable member of our community. + +[code-review-feelings-article-link]: https://roman-ivanov.blogspot.com/2022/04/comments-on-predicting-developers.html diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index afb910441bd2..000000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,27 +0,0 @@ -Check documentation: https://checkstyle.org/config_xxxxxx.html#NameOfAffectedCheck - -``` -/var/tmp $ javac YOUR_FILE.java -#[[MAKE SURE THERE IS NO OUTPUT]] - -/var/tmp $ cat config.xml -#[[PLACE YOUR OUTPUT HERE]] - -/var/tmp $ cat YOUR_FILE.java -#[[PLACE YOU OUTPUT HERE]] - -/var/tmp $ RUN_LOCALE="-Duser.language=en -Duser.country=US" -/var/tmp $ java $RUN_LOCALE -jar checkstyle-X.XX-all.jar -c config.xml YOUR_FILE.java -#[[PLACE YOUR OUTPUT HERE]] -``` - ---------------- - -Describe what you expect in detail. - --------------- - -Still not clear ??? -see example - https://checkstyle.org/report_issue.html#How_to_report_a_bug.3F - -ATTENTION: FAILURE TO FOLLOW THE ABOVE TEMPLATE WILL RESULT IN THE ISSUE BEING CLOSED. diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 000000000000..add2c1c7f9eb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,47 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +I have read check documentation: https://checkstyle.org/checks/xxxxxx/nameofaffectedcheck.html +I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run +I have executed the cli and showed it below, as cli describes the problem better than 1,000 words + +```bash +/var/tmp $ javac YOUR_FILE.java +#[[MAKE SURE THERE IS SUCCESSFUL COMPILATION]] + +/var/tmp $ cat config.xml +#[[PLACE YOUR OUTPUT HERE]] + +/var/tmp $ cat YOUR_FILE.java +#[[PLACE YOU OUTPUT HERE]] + +/var/tmp $ RUN_LOCALE="-Duser.language=en -Duser.country=US" +/var/tmp $ java $RUN_LOCALE -jar checkstyle-X.XX-all.jar -c config.xml YOUR_FILE.java +#[[PLACE YOUR OUTPUT HERE]] +``` + +For Windows users, please use `type` instead of `cat` and run + +```cmd +set RUN_LOCALE="-Duser.language=en -Duser.country=US" +java %RUN_LOCALE% -jar checkstyle-X.XX-all.jar -c config.xml YOUR_FILE.java +``` + +in place of the last 2 commands above. + +--- + +**Describe what you expect in detail.** + +--- + +Still not clear ??? +see example - https://checkstyle.org/report_issue.html#How_to_report_a_bug.3F + +ATTENTION: FAILURE TO FOLLOW THE ABOVE TEMPLATE WILL RESULT IN THE ISSUE BEING CLOSED. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 000000000000..400f090fa66f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,59 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +I have read check documentation: https://checkstyle.org/checks/xxxxxx/nameofaffectedcheck.html +I have downloaded the latest cli from: https://checkstyle.org/cmdline.html#Download_and_Run +I have executed the cli and showed it below, as cli describes the problem better than 1,000 words + +**How it works Now:** + +```bash +/var/tmp $ javac YOUR_FILE.java +#[[MAKE SURE THERE IS SUCCESSFUL COMPILATION]] + +/var/tmp $ cat config.xml +#[[PLACE YOUR OUTPUT HERE]] + +/var/tmp $ cat YOUR_FILE.java +#[[PLACE YOU OUTPUT HERE]] + +/var/tmp $ RUN_LOCALE="-Duser.language=en -Duser.country=US" +/var/tmp $ java $RUN_LOCALE -jar checkstyle-X.XX-all.jar -c config.xml YOUR_FILE.java +#[[PLACE YOUR OUTPUT HERE]] +``` + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. + +**Describe the solution you'd like** +A clear and detailed description of what you want to happen. +You could provide the expected/suggested cli output for your solution. + +```bash +expected/suggested cli output +``` + +**Additional context** +Add any other context or screenshots about the feature request here. + +Still not clear ??? +see examples: + +- https://checkstyle.org/report_issue.html#How_to_request_new_feature_for_existing_functionality.3F + +- https://checkstyle.org/report_issue.html#How_to_request_new_Check.2FModule.3F + +**Not a feature?** +If (Check, property, new behavior) that you are requesting is already +implemented and you are unsatisfied with their behaviour, report it here +in bug template format: + +- https://checkstyle.org/report_issue.html#How_to_report_a_bug.3F + +ATTENTION: FAILURE TO FOLLOW THE ABOVE TEMPLATE WILL RESULT IN THE ISSUE BEING CLOSED. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 697789417fa9..0a1a6f4357a3 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,22 +1,29 @@ -PLEASE READ before removing!! +# PLEASE READ BEFORE REMOVING -Rules: -1) The issue you are trying to fix/resolve has to have the "approved" label. -2) Put in the description of Pull Request the reference to an issue if it exists. - Example: "Issue: #XXXXXX" -3) Commit message should adhere to the following rules: - a) MUST match one of the following patterns: - ^Issue #\\d+: .*$ - ^Pull #\\d+: .*$ - ^(minor|config|infra|doc|spelling|dependency): .*$ - b) MUST contain only one line of text - c) MUST NOT end with a period, space, or tab - d) MUST be less than or equal to 200 characters +**Rules:** -To avoid multiple iterations of fixes and CIs failures, please read -https://checkstyle.org/contributing.html +- **Issue Requirement** + - The issue you are trying to fix/resolve **must** have the `"approved"` label. + - If an issue exists, reference it in the Pull Request description: + Example: `"Issue: #XXXXXX"` +- **Commit message** should adhere to the following rules: + - MUST match any one of the following patterns: -ATTENTION: We are not merging Pull Requests that are not passing our CIs, + ``` + ^Issue #\d+: .*$ + ^Pull #\d+: .*$ + ^(minor|config|infra|doc|spelling|dependency): .*$ + ``` + + - MUST contain only one line of text + - MUST NOT end with a period, space, or tab + - MUST be less than or equal to 200 characters + +To avoid multiple iterations of fixes and CI failures, please read +[Contribution Guide](https://checkstyle.org/contributing.html). + +**ATTENTION:** Pull Requests that do not pass our CI checks will not be merged, but we will help to resolve issues. -Thanks for reading, remove whole this message and type what you need. +--- +Thanks for reading, feel free to remove this whole message and type what you need. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000000..02a6aa481d4e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,20 @@ +version: 2 +updates: + - package-ecosystem: maven + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 + ignore: + - dependency-name: org.apache.maven.plugins:maven-release-plugin + versions: + - "> 2.1" + commit-message: + prefix: dependency + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 + commit-message: + prefix: dependency diff --git a/.github/workflows/README.md b/.github/workflows/README.md new file mode 100644 index 000000000000..fa4be392418e --- /dev/null +++ b/.github/workflows/README.md @@ -0,0 +1,75 @@ +# Workflows + +[regression-report.yml](#regression-report-workflow---regression-reportyml) + +-------- + +## Regression Report workflow - regression-report.yml + +This workflow allows user/contributor to trigger regression/diff report +for changes that they have in Pull Request(PR). + +Workflow does: + +- takes configurations from user's PR comment or/and PR description, +- builds checkstyle from master branch, +- run checkstyle validation for user defined list of project with user defined configs +- stores results of validation +- builds checkstyle from PR branch, +- run checkstyle validation for user defined list of project with user defined configs +- stores results of validation +- compares results of validation from both execution, generate html report +- share html report link back to PR + +There are few way to trigger diff report. + +### Diff Report by configuration in Input file + +Make a comment in PR: + +```txt +GitHub, generate report by config from InputXxxxxx.java +``` + +or + +```txt +GitHub, generate report by config from some/path/InputXxxxxx.java +``` + +Workflow will find InputXxxxxx.java in repository, take config from it and will use for diff report +generation. Workflow will use default list of projects that is located at +[test-configs repository](https://github.com/checkstyle/test-configs/blob/main/extractor/src/main/resources/list-of-projects.yml). + +### Diff Report by configuration at test-configs repository + +Make a comment in PR: + +```txt +GitHub, generate report for {{folder in https://github.com/checkstyle/test-configs}} +``` + +Workflow will download config.xml and list-of-projects.yml from +[test-configs repository](https://github.com/checkstyle/test-configs), +use then for diff report generation. + +### Diff Report by configuration in Pull Request Description + +Add the links of the config files in the PR description as described at +[checkstyle-tester](https://github.com/checkstyle/contribution/blob/master/checkstyle-tester/README.md#executing-generation-using-github-action) + +Make a comment in PR: + +```txt +Github, generate report for configs in PR description +``` + +### Configure saved-replies to ease typing trigger comment + +If you plan to frequently use regression/diff report, it is recommended to use +["Saved Reply"](https://docs.github.com/en/get-started/writing-on-github/working-with-saved-replies/creating-a-saved-reply) +GitHub feature of your GitHub account. + +Usage: +[by button in web UI](https://docs.github.com/en/get-started/writing-on-github/working-with-saved-replies/using-saved-replies), +[by slash command](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/about-slash-commands) diff --git a/.github/workflows/actionlint.yml b/.github/workflows/actionlint.yml new file mode 100644 index 000000000000..7d99fb8986c8 --- /dev/null +++ b/.github/workflows/actionlint.yml @@ -0,0 +1,26 @@ +name: Lint GitHub Actions workflows +on: + push: + branches: + - master + paths: + - '.github/workflows/**' + pull_request: + branches: + - '*' + paths: + - '.github/workflows/**' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + actionlint: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Check workflow files + uses: docker://rhysd/actionlint:latest diff --git a/.github/workflows/bump-license-year.yml b/.github/workflows/bump-license-year.yml new file mode 100644 index 000000000000..7db8bbe6f5fe --- /dev/null +++ b/.github/workflows/bump-license-year.yml @@ -0,0 +1,42 @@ +############################################################################# +# GitHub Action to bump license year +# +# Workflow starts every new year. +# +############################################################################# +name: "Bump license year" +on: + workflow_dispatch: null + schedule: + - cron: "0 0 1 1 *" +permissions: + contents: write + pull-requests: write + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + bump: + if: github.repository == 'checkstyle/checkstyle' + name: Bump license year + runs-on: ubuntu-latest + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + + - name: Set Current Year + run: | + echo "YEAR=$(date +'%Y')" >> "$GITHUB_ENV" + + - name: Modify Files + run: | + ./.ci/bump-license-year.sh $(("${{ env.YEAR }}" - 1)) ${{ env.YEAR }} . + + - name: Push commit + run: | + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + git commit -am "minor: Bump year to ${{ env.YEAR }}" + git push diff --git a/.github/workflows/bump-version-and-update-milestone.yml b/.github/workflows/bump-version-and-update-milestone.yml new file mode 100644 index 000000000000..4c78a4385e50 --- /dev/null +++ b/.github/workflows/bump-version-and-update-milestone.yml @@ -0,0 +1,55 @@ +############################################################################# +# GitHub Action to bump release version +# +############################################################################# +name: "R: Bump version/Update Milestone" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true +permissions: + contents: write + pull-requests: write + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + printInputs: + name: Print Input + runs-on: ubuntu-latest + steps: + - run: | + echo "Latest Version: ${{ inputs.version }}" + bump: + name: Bump version + runs-on: ubuntu-latest + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Modify File + run: | + ./.ci/bump-version.sh ${{ inputs.version }} + + - name: Push commit + run: | + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + git commit -am "minor: Bump version to ${{ inputs.version }}-SNAPSHOT" + git push + + - name: GitHub Milestone + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + .ci/update-github-milestone.sh ${{ inputs.version }} diff --git a/.github/workflows/check-performance-regression.yml b/.github/workflows/check-performance-regression.yml new file mode 100644 index 000000000000..26e96a991a91 --- /dev/null +++ b/.github/workflows/check-performance-regression.yml @@ -0,0 +1,65 @@ +##################################################################################### +# GitHub Action to test performance regression. +# +# Workflow starts when: +# 1) push to master +# 2) PR created or pushed +# +##################################################################################### +name: Check-Performance-Regression + +on: + push: + branches: + - master + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + test: + if: github.repository == 'checkstyle/checkstyle' + strategy: + matrix: + target: + - java + - javadoc + include: + - target: java + BASELINE_SECONDS: 390.70 + CONFIG_FILE: './config/benchmark-config.xml' + - target: javadoc + BASELINE_SECONDS: 424.59 + CONFIG_FILE: './config/benchmark-javadoc-config.xml' + runs-on: ubuntu-latest + env: + BASELINE_SECONDS: ${{ matrix.BASELINE_SECONDS }} + CONFIG_FILE: ${{ matrix.CONFIG_FILE }} + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Checkout Pull Request Code + uses: actions/checkout@v5 + + - name: Clone JDK 25 Repo + uses: actions/checkout@v5 + with: + repository: openjdk/jdk25u + path: ./.ci-temp/jdk25 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Run performance test + run: | + ./.ci/check-performance-regression.sh "$BASELINE_SECONDS" "$CONFIG_FILE" diff --git a/.github/workflows/check-pr-description.yml b/.github/workflows/check-pr-description.yml new file mode 100644 index 000000000000..84746d0ca9d6 --- /dev/null +++ b/.github/workflows/check-pr-description.yml @@ -0,0 +1,25 @@ +name: "Check PR Description" + +on: + pull_request: + branches: [ master ] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-24.04 + + steps: + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Do action + env: + READ_ONLY_TOKEN: '${{ secrets.GITHUB_TOKEN }}' + PULL_REQUEST: '${{ github.event.number }}' + run: | + ./.ci/pr-description.sh diff --git a/.github/workflows/checker-framework.yml b/.github/workflows/checker-framework.yml new file mode 100644 index 000000000000..7d5c4caf6a57 --- /dev/null +++ b/.github/workflows/checker-framework.yml @@ -0,0 +1,66 @@ +name: Checker + +on: + push: + branches: + - master + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + check: + if: github.repository == 'checkstyle/checkstyle' + strategy: + fail-fast: false + matrix: + profile: [ + nullness-optional-interning, + methods-resource-fenum, + lock-tainting, + index, + formatter, + signature-gui-units-init, + regex-property-key-compiler-message, + purity-value-returns, + ] + + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Install groovy + run: sudo apt install groovy + + - name: Checkout + uses: actions/checkout@v5 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Execute checker framework + env: + MAVEN_OPTS: "-Xmx4g" + run: groovy ./.ci/checker-framework.groovy checker-${{ matrix.profile }} + + - name: Git Diff on fail + if: failure() + run: ./.ci/print-diff-as-patch.sh target/checker-${{ matrix.profile }}.patch + + - name: Share patch as artifact to apply on local + if: failure() + uses: actions/upload-artifact@v5 + with: + name: checker-${{ matrix.profile }}-patch + path: target/checker-${{ matrix.profile }}.patch + retention-days: 7 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000000..ff24bc6d7810 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,77 @@ +name: "CodeQL" + +on: + push: + branches: [ master ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ master ] + schedule: + - cron: '29 2 * * 0' + +permissions: + contents: read + actions: read + security-events: write + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + analyze: + if: github.repository == 'checkstyle/checkstyle' + name: Analyze + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + language: [ 'java' ] + + steps: + - name: Checkout repository + uses: actions/checkout@v5 + + # Setup JDK 21 for the project + - name: Setup JDK 21 + uses: actions/setup-java@v5 + with: + java-version: '21' + distribution: 'temurin' + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + # Configure CodeQL to use Java 21 + config: | + java: + version: 21 + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v4 + + # If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + # - run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 diff --git a/.github/workflows/diff-report.yml b/.github/workflows/diff-report.yml new file mode 100644 index 000000000000..c083a08a8aef --- /dev/null +++ b/.github/workflows/diff-report.yml @@ -0,0 +1,248 @@ +##################################################################################### +# GitHub Action to generate Checkstyle report. +# +# Workflow starts when: +# 1) issue comment - created +# +# Requirements: +# 1) secrets.AWS_ACCESS_KEY_ID - access key for AWS S3 service user +# 2) secrets.AWS_SECRET_ACCESS_KEY - security access key for AWS S3 service user +# +# If you need to change bucket name or region, change AWS_REGION and AWS_BUCKET_NAME variables. +# For another bucket, you will need to change the secrets. +##################################################################################### +name: Diff-Report +env: + AWS_REGION: us-east-2 + AWS_BUCKET_NAME: "checkstyle-diff-reports" + # yamllint disable-line rule:line-length + DEFAULT_PROJECTS_LINK: "https://raw.githubusercontent.com/checkstyle/contribution/master/checkstyle-tester/projects-to-test-on-for-github-action.properties" + USER_LOGIN: ${{ github.event.issue.user.login }} + +on: + issue_comment: + types: [ created, edited ] + +permissions: + contents: read + pull-requests: write + +concurrency: + # run_id is guaranteed to be unique and present + group: ${{ github.run_id }} + cancel-in-progress: false + +jobs: + # Parse PR Body, search for links to .properties and .xml files + parse_body: + if: github.event.comment.body == 'GitHub, generate report' + runs-on: ubuntu-latest + outputs: + projects_link: ${{ steps.parse.outputs.projects_link }} + config_link: ${{ steps.parse.outputs.config_link }} + new_module_config_link: ${{ steps.parse.outputs.new_module_config_link }} + patch_config_link: ${{ steps.parse.outputs.patch_config_link }} + report_label: ${{ steps.parse.outputs.report_label }} + branch: ${{ steps.branch.outputs.ref }} + commit_sha: ${{ steps.branch.outputs.commit_sha }} + + steps: + - uses: shanegenschaw/pull-request-comment-trigger@v3.0.0 + name: React with rocket on run + with: + trigger: ',' + reaction: rocket + env: + GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' + + - run: 'echo We print it here for this action to work' + if: 'true' + + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Getting PR description + env: + ISSUE_BODY: ${{ github.event.issue.body }} + PULL_REQUEST_URL: ${{ github.event.issue.pull_request.url }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mkdir -p .ci-temp + # convert windows line endings to unix in event text + echo "$ISSUE_BODY" > .ci-temp/windows.txt + tr -d '\15\32' < .ci-temp/windows.txt > .ci-temp/text + + curl --fail-with-body -X GET "${PULL_REQUEST_URL}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o .ci-temp/info.json + + jq --raw-output .head.ref .ci-temp/info.json > .ci-temp/branch + jq --raw-output .head.sha .ci-temp/info.json > .ci-temp/commit_sha + + - name: Parsing content of PR description + id: parse + run: | + ./.ci/diff-report.sh parse-pr-description-text + + - name: Set branch + id: branch + run: | + ./.ci/append-to-github-output.sh "ref" "$(cat .ci-temp/branch)" + # shellcheck disable=SC2002 + ./.ci/append-to-github-output.sh "commit_sha" "$(cat .ci-temp/commit_sha | cut -c 1-7)" + + echo "GITHUB_OUTPUT:" + # need to 'echo' to see output in Github CI + # shellcheck disable=SC2005 + echo "$(cat "$GITHUB_OUTPUT")" + + make_report: + runs-on: ubuntu-latest + needs: parse_body + if: needs.parse_body.outputs.config_link != '' + || needs.parse_body.outputs.new_module_config_link != '' + outputs: + message: ${{ steps.out.outputs.message }} + steps: + + - name: Download checkstyle + uses: actions/checkout@v5 + + - name: Download files + env: + NEW_MODULE_CONFIG_LINK: ${{ needs.parse_body.outputs.new_module_config_link }} + DIFF_CONFIG_LINK: ${{ needs.parse_body.outputs.config_link }} + PATCH_CONFIG_LINK: ${{ needs.parse_body.outputs.patch_config_link }} + DIFF_PROJECTS_LINK: ${{ needs.parse_body.outputs.projects_link }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + ./.ci/diff-report.sh download-files + + # set main checkstyle repo as an upstream + # Diff report will be generated taking upstream's master branch as a base branch + - name: set upstream + run: | + bash + MAIN_REPO_GIT_URL="https://github.com/checkstyle/checkstyle.git" + git remote add upstream "$MAIN_REPO_GIT_URL" + git fetch upstream + FORK_REPO_GIT_URL="https://github.com/$USER_LOGIN/checkstyle.git" + git remote add forked "$FORK_REPO_GIT_URL" + git fetch forked + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Download contribution + uses: actions/checkout@v5 + with: + repository: checkstyle/contribution + path: .ci-temp/contribution + + - name: Prepare environment + run: | + mv .ci-temp/projects.properties ./.ci-temp/contribution/checkstyle-tester/ + mv .ci-temp/*.xml ./.ci-temp/contribution/checkstyle-tester/ + sudo apt install groovy + + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@v5 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ env.AWS_REGION }} + + - name: Generate report + env: + BRANCH: ${{ needs.parse_body.outputs.branch }} + run: | + cd .ci-temp/contribution/checkstyle-tester + bash + REF="forked/$BRANCH" + REPO="../../../../checkstyle" + BASE_BRANCH="upstream/master" + export MAVEN_OPTS="-Xmx5g" + if [ -f new_module_config.xml ]; then + groovy diff.groovy -r "$REPO" -p "$REF" -pc new_module_config.xml -m single\ + -l projects.properties -xm "-Dcheckstyle.failsOnError=false"\ + --allowExcludes + elif [ -f patch_config.xml ]; then + groovy diff.groovy -r "$REPO" -b "$BASE_BRANCH" -p "$REF" -bc diff_config.xml\ + -pc patch_config.xml -l projects.properties -xm "-Dcheckstyle.failsOnError=false"\ + --allowExcludes + else + groovy diff.groovy -r "$REPO" -b "$BASE_BRANCH" -p "$REF" -c diff_config.xml\ + -l projects.properties -xm "-Dcheckstyle.failsOnError=false"\ + --allowExcludes + fi + + - name: Copy Report to AWS S3 Bucket + env: + LABEL: ${{ needs.parse_body.outputs.report_label }} + run: | + bash + TIME=$(date +%Y%H%M%S) + FOLDER="${{needs.parse_body.outputs.commit_sha}}_$TIME" + DIFF="./.ci-temp/contribution/checkstyle-tester/reports/diff" + LINK="https://${{env.AWS_BUCKET_NAME}}.s3.${{env.AWS_REGION}}.amazonaws.com" + aws s3 cp $DIFF "s3://${{env.AWS_BUCKET_NAME}}/$FOLDER/reports/diff/" \ + --recursive --storage-class STANDARD_IA + if [ -n "$LABEL" ]; then + echo "$LABEL: " > .ci-temp/message + fi + echo "$LINK/$FOLDER/reports/diff/index.html" >> .ci-temp/message + + - name: Set output + id: out + run: | + ./.ci/append-to-github-output.sh "message" "$(cat .ci-temp/message)" + + # should be always last step + send_message: + runs-on: ubuntu-latest + needs: [ parse_body, make_report ] + if: failure() || success() + steps: + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Get message + env: + MSG: ${{ needs.make_report.outputs.message }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mkdir -p .ci-temp + if [ -z "$MSG" ]; then + JOBS_LINK="https://github.com/checkstyle/checkstyle/actions/runs/${{github.run_id}}" + API_LINK="https://api.github.com/repos/checkstyle/checkstyle/actions/runs/" + API_LINK="${API_LINK}${{github.run_id}}/jobs" + + curl --fail-with-body -X GET "${API_LINK}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o .ci-temp/info.json + + jq '.jobs' .ci-temp/info.json > ".ci-temp/jobs" + jq '.[] | select(.conclusion == "failure") | .name' .ci-temp/jobs > .ci-temp/job_name + jq '.[] | select(.conclusion == "failure") | .steps' .ci-temp/jobs > .ci-temp/steps + jq '.[] | select(.conclusion == "failure") | .name' .ci-temp/steps > .ci-temp/step_name + echo "Report generation failed on phase $(cat .ci-temp/job_name)," > .ci-temp/message + echo "step $(cat .ci-temp/step_name).
    Link: $JOBS_LINK" >> .ci-temp/message + else + echo "$MSG" > .ci-temp/message + fi + + - name: Set message + id: out + run: | + ./.ci/append-to-github-output.sh "message" "$(cat .ci-temp/message)" + + - name: Comment PR + uses: checkstyle/contribution/comment-action@master + with: + message: ${{steps.out.outputs.message}} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/error-prone.yml b/.github/workflows/error-prone.yml new file mode 100644 index 000000000000..dd304a6e2fd3 --- /dev/null +++ b/.github/workflows/error-prone.yml @@ -0,0 +1,52 @@ +name: Error-Prone + +on: + push: + branches: + - master + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + error-prone: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Install Groovy using SDKMAN + run: | + curl --fail-with-body -s "https://get.sdkman.io" | bash + source "$HOME/.sdkman/bin/sdkman-init.sh" + sdk install groovy 5.0.0 + echo "GROOVY_HOME=$HOME/.sdkman/candidates/groovy/current" >> "$GITHUB_ENV" + echo "$HOME/.sdkman/candidates/groovy/current/bin" >> "$GITHUB_PATH" + + - name: Checkout + uses: actions/checkout@v5 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Execute Error-Prone on compile phase + run: groovy ./.ci/error-prone-check.groovy compile + + # Require to compile again in case previous step fails and sources are not compiled + - name: Do a clean compile + if: always() + run: mvn -e --no-transfer-progress clean compile + + - name: Execute Error-Prone on test-compile phase + if: always() + run: groovy ./.ci/error-prone-check.groovy test-compile diff --git a/.github/workflows/google-java-format.yml b/.github/workflows/google-java-format.yml new file mode 100644 index 000000000000..a5fe4195ae4f --- /dev/null +++ b/.github/workflows/google-java-format.yml @@ -0,0 +1,49 @@ +##################################################################################### +# GitHub Action to format specific files by google-java-format. +# +# Workflow starts when: +# 1) push to master +# 2) PR created or pushed +# +##################################################################################### +name: Google-Java-Format + +on: + push: + branches: + - master + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + VERSION: 1.31.0 + +jobs: + test: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Checkout Pull Request Code + uses: actions/checkout@v5 + + - uses: robinraju/release-downloader@v1 + with: + repository: 'google/google-java-format' + tag: "v${{env.VERSION}}" + fileName: "google-java-format-${{env.VERSION}}-all-deps.jar" + out-file-path: '.ci-temp' + + - name: Run Formatting + run: | + ./.ci/google-java-format.sh .ci-temp/google-java-format-${{env.VERSION}}-all-deps.jar + ./.ci/validation.sh git-diff diff --git a/.github/workflows/no-error-trino.yml b/.github/workflows/no-error-trino.yml new file mode 100644 index 000000000000..0e5a81e3a78e --- /dev/null +++ b/.github/workflows/no-error-trino.yml @@ -0,0 +1,27 @@ +name: Trino + +on: + push: + branches: + - master + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + trino-check: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 23 + + - name: Run Checkstyle on Trino + run: ./.ci/validation.sh no-error-trino diff --git a/.github/workflows/no-exception-workflow.yml b/.github/workflows/no-exception-workflow.yml new file mode 100644 index 000000000000..f6d4baebcf46 --- /dev/null +++ b/.github/workflows/no-exception-workflow.yml @@ -0,0 +1,86 @@ +name: "no-exception testing" + +on: + push: + branches: + - master + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + # this execution should stay on GitHub actions due to time/ memory limits in other CI + no-exception-openjdk17: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Install dependencies + run: sudo apt install groovy + + - name: Checkout repository + uses: actions/checkout@v5 + + - run: .ci/no-exception-test.sh openjdk17-with-checks-nonjavadoc-error + # this execution should stay on GitHub actions due to time/ memory limits in other CI + no-exception-openjdk19: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Install dependencies + run: sudo apt install groovy + + - name: Checkout repository + uses: actions/checkout@v5 + + - run: .ci/no-exception-test.sh openjdk19-with-checks-nonjavadoc-error + # this execution should stay on GitHub actions due to time/ memory limits in other CI + no-exception-openjdk20: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Install dependencies + run: sudo apt install groovy + + - name: Checkout repository + uses: actions/checkout@v5 + + - run: .ci/no-exception-test.sh openjdk20-with-checks-nonjavadoc-error + # this execution should stay on GitHub actions due to time/ memory limits in other CI + no-exception-openjdk25: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Install dependencies + run: sudo apt install groovy + + - name: Checkout repository + uses: actions/checkout@v5 + + - run: .ci/no-exception-test.sh openjdk25-with-checks-nonjavadoc-error diff --git a/.github/workflows/no-old-refs.yml b/.github/workflows/no-old-refs.yml new file mode 100644 index 000000000000..4ebc89462bcb --- /dev/null +++ b/.github/workflows/no-old-refs.yml @@ -0,0 +1,64 @@ +##################################################################################### +# GitHub Action to check references to closed issues in code. +# +# Workflow starts when: +# 1) push on master branch +# 2) pull request is opened or synchronized or reopened +# +##################################################################################### +name: "Check no closed issue references" + +on: + push: + branches: [ master ] + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + check_issues: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-24.04 + steps: + - name: Download checkstyle + uses: actions/checkout@v5 + + - name: PR linked issues + id: links + uses: mondeja/pr-linked-issues-action@v2 + if: github.event_name == 'pull_request' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + ####################################################################### + # Linked issues, if present, are received in the following format: + # 37,38 + # We convert it into: + # https://github.com/checkstyle/checkstyle/issues/37 + # https://github.com/checkstyle/checkstyle/issues/38 + ####################################################################### + - name: Format linked issues + id: format-linked-issues + if: github.event_name == 'pull_request' + run: | + LINKED_ISSUES=${{ steps.links.outputs.issues }} + LINKED_ISSUES_FORMATTED=/tmp/linked_issues + CHECKSTYLE_ISSUE_URL="https:\/\/github.com\/checkstyle\/checkstyle\/issues\/" + if [ -n "$LINKED_ISSUES" ]; then + # shellcheck disable=SC2001 + echo $LINKED_ISSUES | sed -e 's/,/\n/g' >> $LINKED_ISSUES_FORMATTED + sed -i "s/^/$CHECKSTYLE_ISSUE_URL/" $LINKED_ISSUES_FORMATTED + fi + echo "linked-issues-formatted=$LINKED_ISSUES_FORMATTED" >> "$GITHUB_OUTPUT" + + - name: Check Issues + env: + GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' + LINKED_ISSUES: '${{ steps.format-linked-issues.outputs.linked-issues-formatted }}' + PR_HEAD_REPO_NAME: "${{ github.event.pull_request.head.repo.full_name }}" + GITHUB_HEAD_REF: "${{ github.head_ref }}" + run: | + ./.ci/no-old-refs.sh diff --git a/.github/workflows/pitest.yml b/.github/workflows/pitest.yml new file mode 100644 index 000000000000..35a9886362d8 --- /dev/null +++ b/.github/workflows/pitest.yml @@ -0,0 +1,95 @@ +name: Pitest + +on: + push: + branches: + - master + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + test: + if: github.repository == 'checkstyle/checkstyle' + strategy: + matrix: + profile: + - annotation + - ant + - api + - blocks + - coding-1 + - coding-2 + - coding-require-this-check + - common + - common-2 + - design + - filters + - header + - imports + - indentation + - javadoc + - main + - metrics + - misc + - modifier + - naming + - packagenamesloader + - regexp + - sizes + - tree-walker + - utils + - whitespace + - xpath + - java-ast-visitor + # GUI package needs better test coverage before adding to execution. + # - gui + runs-on: ubuntu-latest + continue-on-error: true + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - name: Install groovy + run: | + sudo apt update + sudo apt install groovy + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Checkout + uses: actions/checkout@v5 + + - name: Generate pitest-${{ matrix.profile }} report + run: | + ./.ci/pitest.sh "pitest-${{ matrix.profile }}" + + - name: Patch command for pitest-${{ matrix.profile }} + if: failure() + run: | + ./.ci/print-diff-as-patch.sh target/pitest-${{ matrix.profile }}.patch + + - name: Stage results + if: failure() || github.ref == 'refs/heads/master' + run: | + mkdir staging && cp -r target/pit-reports/ staging + + - name: Archive code coverage results + if: failure() || github.ref == 'refs/heads/master' + uses: actions/upload-artifact@v5 + with: + name: pitest-${{ matrix.profile }}-coverage-report + path: | + staging + target/pitest-${{ matrix.profile }}.patch + retention-days: 7 diff --git a/.github/workflows/regression-report.yml b/.github/workflows/regression-report.yml new file mode 100644 index 000000000000..b9f275458f2d --- /dev/null +++ b/.github/workflows/regression-report.yml @@ -0,0 +1,798 @@ +##################################################################################### +# GitHub Action to generate Checkstyle report. +# +# Workflow starts when: +# 1) PR comment - created +# +# Requirements: +# 1) secrets.AWS_ACCESS_KEY_ID - access key for AWS S3 service user +# 2) secrets.AWS_SECRET_ACCESS_KEY - security access key for AWS S3 service user +# +# If you need to change bucket name or region, change AWS_REGION and AWS_BUCKET_NAME variables. +# For another bucket, you will need to change the secrets. +##################################################################################### +name: regression-report +env: + AWS_REGION: us-east-2 + AWS_BUCKET_NAME: "checkstyle-diff-reports" + USER_LOGIN: ${{ github.event.issue.user.login }} + # yamllint disable-line rule:line-length + DEFAULT_PROJECTS_LINK: "https://raw.githubusercontent.com/checkstyle/test-configs/main/extractor/src/main/resources/list-of-projects.yml" + BASE_TEST_CONFIGS_URL: "https://raw.githubusercontent.com/checkstyle/test-configs/main" + EXTRACTOR_VERSION: 2024-10-08 + DIFF_TOOL_VERSION: "1.0-2025-01-30" + PATCH_DIFF_TOOL_VERSION: "0.1-SNAPSHOT" + CACHE_KEY: "regression-report-${{ github.sha }}-${{ github.event.comment.id }}" + GENERATED_CONFIGS_PATH: generated_configs + +on: + issue_comment: + types: [ created ] + +permissions: + contents: read + pull-requests: write + actions: write + +concurrency: + group: ${{ github.run_id }} + cancel-in-progress: true + +jobs: + check_pr_status: + if: | + github.event.issue.pull_request + && (startsWith(github.event.comment.body, 'Github, generate report for ') + || startsWith(github.event.comment.body, 'GitHub, generate report for ') + || startsWith(github.event.comment.body, + 'Github, generate report for configs in PR description') + || startsWith(github.event.comment.body, + 'GitHub, generate report for configs in PR description') + || startsWith(github.event.comment.body, + 'Github, generate report by config from') + || startsWith(github.event.comment.body, + 'GitHub, generate report by config from')) + + runs-on: ubuntu-latest + steps: + - name: Check PR status + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_URL: ${{ github.event.issue.pull_request.url }} + run: | + PR_STATE=$(curl --fail-with-body -s -H "Authorization: token $GITHUB_TOKEN" \ + -H "Accept: application/vnd.github.v3+json" \ + "$PR_URL" | jq -r .state) + if [ "$PR_STATE" != "open" ]; then + echo "PR is not active" + exit 1 + fi + + checkout_and_cache: + runs-on: ubuntu-latest + needs: [ check_pr_status ] + outputs: + pr_branch: ${{ steps.get_pr_details.outputs.branch }} + commit_sha: ${{ steps.get_pr_details.outputs.commit_sha }} + env: + CACHE_KEY: "regression-report-${{ github.sha }}-${{ github.event.comment.id }}" + steps: + - name: Create .ci-temp directory + run: mkdir -p .ci-temp + + - name: Get PR branch and fork details + id: get_pr_details + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_URL: ${{ github.event.issue.pull_request.url }} + run: | + PR_INFO="$(curl --fail-with-body -s -H "Authorization: token $GITHUB_TOKEN" "$PR_URL")" + BRANCH="$(echo "$PR_INFO" | jq -r .head.ref)" + FORK_REPO="$(echo "$PR_INFO" | jq -r .head.repo.full_name)" + COMMIT_SHA="$(echo "$PR_INFO" | jq -r .head.sha)" + { + echo "branch=$BRANCH" + echo "fork_repo=$FORK_REPO" + echo "commit_sha=$COMMIT_SHA" + } >> "$GITHUB_OUTPUT" + + - name: Checkout PR branch + uses: actions/checkout@v5 + with: + repository: ${{ steps.get_pr_details.outputs.fork_repo }} + ref: ${{ steps.get_pr_details.outputs.branch }} + + - name: Checkout master branch + uses: actions/checkout@v5 + with: + repository: checkstyle/checkstyle + path: .ci-temp/checkstyle + + - name: Setup Git remotes + run: | + cd .ci-temp/checkstyle + git remote add upstream https://github.com/checkstyle/checkstyle.git + git remote add forked https://github.com/${{ steps.get_pr_details.outputs.fork_repo }}.git + git fetch upstream + git fetch forked + git checkout -b ${{ steps.get_pr_details.outputs.branch }} \ + forked/${{ steps.get_pr_details.outputs.branch }} + + - name: Save cache + uses: actions/cache/save@v4 + with: + path: . + key: ${{ env.CACHE_KEY }} + + parse_comment: + runs-on: ubuntu-latest + needs: [ check_pr_status, checkout_and_cache ] + outputs: + mode: ${{ steps.parse.outputs.mode }} + config_bundle: ${{ steps.parse.outputs.config_bundle }} + input_file: ${{ steps.parse.outputs.input_file }} + steps: + - name: React to comment + uses: actions/github-script@v8 + with: + github-token: ${{secrets.GITHUB_TOKEN}} + script: | + github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + content: 'rocket' + }) + + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: . + key: ${{ env.CACHE_KEY }} + fail-on-cache-miss: true + + - name: Parse comment + id: parse + env: + COMMENT_BODY: ${{ github.event.comment.body }} + run: | + NAME='^Git[Hh]ub,' + PATTERN_FOR_DESCRIPTION=$NAME' generate report for configs in PR description[[:space:]]*$' + PATTERN_FOR=$NAME' generate report for' + PATTERN_BY_CONFIG_FROM=$NAME' generate report by config from' + + if [[ "$COMMENT_BODY" =~ $PATTERN_FOR_DESCRIPTION ]]; then + ./.ci/append-to-github-output.sh "mode" "configs_in_pr_description" + + elif [[ "$COMMENT_BODY" =~ $PATTERN_FOR ]]; then + ./.ci/append-to-github-output.sh "mode" "existing_config_bundle" + CONFIG_BUNDLE=$(echo "$COMMENT_BODY" | sed -E "s/$PATTERN_FOR //g") + ./.ci/append-to-github-output.sh "config_bundle" "$CONFIG_BUNDLE" + + elif [[ "$COMMENT_BODY" =~ $PATTERN_BY_CONFIG_FROM ]]; then + ./.ci/append-to-github-output.sh "mode" "generated_config_bundle" + INPUT_FILE=$(echo "$COMMENT_BODY" | sed -E "s/$PATTERN_BY_CONFIG_FROM //g") + ./.ci/append-to-github-output.sh "input_file" "$INPUT_FILE" + + else + echo "No recognized pattern found in '$COMMENT_BODY'." + exit 1 + fi + + handle_existing_config_bundle: + needs: [ parse_comment, checkout_and_cache ] + if: needs.parse_comment.outputs.mode == 'existing_config_bundle' + runs-on: ubuntu-latest + outputs: + config_link: ${{ steps.set_links.outputs.config_link }} + projects_link: ${{ steps.set_links.outputs.projects_link }} + label: ${{ steps.create_label.outputs.label }} + steps: + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: . + key: ${{ env.CACHE_KEY }} + fail-on-cache-miss: true + + - name: Set config and projects links + id: set_links + run: | + BASE_URL="${{ env.BASE_TEST_CONFIGS_URL }}" + CONFIG_BUNDLE="${{ needs.parse_comment.outputs.config_bundle }}" + CONFIG_LINK="$BASE_URL/$CONFIG_BUNDLE/config.xml" + PROJECTS_LINK="$BASE_URL/$CONFIG_BUNDLE/list-of-projects.yml" + ./.ci/append-to-github-output.sh "config_link" "$CONFIG_LINK" + ./.ci/append-to-github-output.sh "projects_link" "$PROJECTS_LINK" + + - name: Create label + id: create_label + run: | + CONFIG_BUNDLE="${{ needs.parse_comment.outputs.config_bundle }}" + LABEL="Report for $CONFIG_BUNDLE" + ./.ci/append-to-github-output.sh "label" "$LABEL" + + handle_generated_config_bundle: + needs: [ parse_comment, checkout_and_cache ] + if: needs.parse_comment.outputs.mode == 'generated_config_bundle' + runs-on: ubuntu-latest + outputs: + config_link: ${{ steps.generated_config_bundle.outputs.config_link }} + projects_link: ${{ steps.generated_config_bundle.outputs.projects_link }} + label: ${{ steps.create_label.outputs.label }} + steps: + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: . + key: ${{ env.CACHE_KEY }} + fail-on-cache-miss: true + + - name: Find input file + id: find_input_file + run: | + INPUT_FILE="${{ needs.parse_comment.outputs.input_file }}" + WORKSPACE="${{ github.workspace }}" + + FOUND_FILES=$(find "$WORKSPACE/src" -type f -path "*$INPUT_FILE") + + if [ "$(echo "$FOUND_FILES" | wc -l)" -gt 1 ]; then + echo "Error: Multiple matching files found" + exit 1 + elif [ -z "$FOUND_FILES" ]; then + echo "Error: Could not find input file" + exit 1 + fi + + FOUND_FILE="$FOUND_FILES" + ./.ci/append-to-github-output.sh "input_file" "$FOUND_FILE" + + - name: Download Extractor JAR + uses: robinraju/release-downloader@v1.8 + with: + repository: "checkstyle/test-configs" + tag: "extractor-${{env.EXTRACTOR_VERSION}}" + fileName: "extractor-all-${{env.EXTRACTOR_VERSION}}.jar" + + - name: Set up Java 21 + uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: '21' + + - name: Generate config + id: generated_config_bundle + env: + DEFAULT_PROJECTS_LINK: ${{ env.DEFAULT_PROJECTS_LINK }} + run: | + FOUND_FILE="${{ steps.find_input_file.outputs.input_file }}" + OUTPUT_DIR="${{ env.GENERATED_CONFIGS_PATH }}" + mkdir -p "$OUTPUT_DIR" + + echo "Using input file: $FOUND_FILE" + + # Generate a unique name for the config file + CONFIG_FILE_NAME=$(basename "$FOUND_FILE" .java)_config.xml + CONFIG_FILE_PATH="$OUTPUT_DIR/$CONFIG_FILE_NAME" + + # Generate a name for the projects YAML file + PROJECT_FILE_PATH="$OUTPUT_DIR/projects.yml" + + # Run the extractor + java -jar extractor-all-${{env.EXTRACTOR_VERSION}}.jar \ + "$WORKSPACE" \ + --input-file "$FOUND_FILE" \ + "$CONFIG_FILE_PATH" \ + "$PROJECT_FILE_PATH" + + # Set the config and project file paths + ./.ci/append-to-github-output.sh "config_link" "$CONFIG_FILE_PATH" + ./.ci/append-to-github-output.sh "projects_link" "$PROJECT_FILE_PATH" + + # Print the contents of the files to the logs + echo "Contents of CONFIG_FILE_PATH:" + cat "$CONFIG_FILE_PATH" + + - name: Cache Generated Config and Project Files + uses: actions/cache@v4 + with: + path: ${{ env.GENERATED_CONFIGS_PATH }} + key: ${{ env.CACHE_KEY }}-generated-configs + + - name: Extract filename and create label + id: create_label + run: | + INPUT_FILE="${{ needs.parse_comment.outputs.input_file }}" + FILENAME=$(basename "$INPUT_FILE") + LABEL="Generated config for $FILENAME" + ./.ci/append-to-github-output.sh "label" "$LABEL" + + handle_configs_in_pr_description: + needs: [ parse_comment, checkout_and_cache ] + if: needs.parse_comment.outputs.mode == 'configs_in_pr_description' + runs-on: ubuntu-latest + outputs: + config_link: ${{ steps.parse_description.outputs.config_link }} + projects_link: ${{ steps.parse_description.outputs.projects_link }} + report_label: ${{ steps.parse_description.outputs.report_label }} + patch_config_link: ${{ steps.parse_description.outputs.patch_config_link }} + new_module_config_link: ${{ steps.parse_description.outputs.new_module_config_link }} + steps: + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: . + key: ${{ env.CACHE_KEY }} + fail-on-cache-miss: true + + - name: Getting PR description + env: + ISSUE_BODY: ${{ github.event.issue.body }} + PULL_REQUEST_URL: ${{ github.event.issue.pull_request.url }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mkdir -p .ci-temp + # convert windows line endings to unix in event text + echo "$ISSUE_BODY" > .ci-temp/windows.txt + tr -d '\15\32' < .ci-temp/windows.txt > .ci-temp/text + + - name: Parsing content of PR description + id: parse_description + run: | + ./.ci/diff-report.sh parse-pr-description-text + + download_configs: + needs: [ + parse_comment, + handle_existing_config_bundle, + handle_generated_config_bundle, + handle_configs_in_pr_description + ] + if: | + always() && + (needs.handle_existing_config_bundle.result == 'success' + || needs.handle_generated_config_bundle.result == 'success' + || needs.handle_configs_in_pr_description.result == 'success') + runs-on: ubuntu-latest + outputs: + report_label: >- + ${{ + needs.handle_configs_in_pr_description.outputs.report_label + || needs.handle_generated_config_bundle.outputs.label + || needs.handle_existing_config_bundle.outputs.label + || '' + }} + steps: + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: . + key: ${{ env.CACHE_KEY }} + fail-on-cache-miss: true + + - name: Restore Generated Config and Project Files + if: needs.handle_generated_config_bundle.result == 'success' + uses: actions/cache@v4 + with: + path: ${{ env.GENERATED_CONFIGS_PATH }} + key: ${{ env.CACHE_KEY }}-generated-configs + + - name: Process local-based generated Config and Project File + if: needs.handle_generated_config_bundle.result == 'success' + env: + DIFF_CONFIG_LINK: ${{ needs.handle_generated_config_bundle.outputs.config_link }} + DIFF_PROJECTS_LINK: ${{ needs.handle_generated_config_bundle.outputs.projects_link }} + run: | + mkdir -p .ci-temp + echo "Config link: $DIFF_CONFIG_LINK" + echo "Projects link: $DIFF_PROJECTS_LINK" + cp "$DIFF_CONFIG_LINK" .ci-temp/diff_config.xml + # Determine the projects file extension + if [[ "$DIFF_PROJECTS_LINK" == *.properties ]]; then + cp "$DIFF_PROJECTS_LINK" .ci-temp/projects.properties + else + cp "$DIFF_PROJECTS_LINK" .ci-temp/projects.yml + fi + + - name: Download URL-based Config and Project File + Extra Files + id: download_files + if: needs.handle_existing_config_bundle.result == 'success' + || needs.handle_configs_in_pr_description.result == 'success' + env: + DIFF_CONFIG_LINK: ${{ + needs.handle_existing_config_bundle.outputs.config_link + || needs.handle_configs_in_pr_description.outputs.config_link + }} + PATCH_CONFIG_LINK: ${{ + needs.handle_configs_in_pr_description.outputs.patch_config_link + || '' + }} + NEW_MODULE_CONFIG_LINK: ${{ + needs.handle_configs_in_pr_description.outputs.new_module_config_link + || '' + }} + DIFF_PROJECTS_LINK: ${{ + needs.handle_existing_config_bundle.outputs.projects_link + || needs.handle_configs_in_pr_description.outputs.projects_link + || env.DEFAULT_PROJECTS_LINK + }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mkdir -p .ci-temp + + if ! ./.ci/diff-report.sh download-files; then + ./.ci/append-to-github-output.sh "failed" "true" + exit 1 + fi + + if [ -n "$DIFF_CONFIG_LINK" ]; then + FIXED_LINK="${DIFF_CONFIG_LINK//\/refs\/heads/}" + CONFIG_FOLDER_URL="${FIXED_LINK%/*}" + # Download directly to .ci-temp + curl --fail-with-body -SLo ".ci-temp/java.header" \ + "${CONFIG_FOLDER_URL}/java.header" || true + fi + + - name: Cache config files + uses: actions/cache@v4 + with: + path: | + .ci-temp/*.xml + .ci-temp/*.header + .ci-temp/projects.yml + .ci-temp/projects.properties + key: ${{ env.CACHE_KEY }}-config-files + + make_report: + needs: [ download_configs, checkout_and_cache ] + if: always() && needs.download_configs.result == 'success' + runs-on: ubuntu-latest + outputs: + message: ${{ steps.out.outputs.message }} + steps: + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: . + key: ${{ env.CACHE_KEY }} + fail-on-cache-miss: true + + - name: Restore config files from cache + uses: actions/cache/restore@v4 + with: + path: | + .ci-temp/*.xml + .ci-temp/*.header + .ci-temp/projects.yml + .ci-temp/projects.properties + key: ${{ env.CACHE_KEY }}-config-files + + - name: Restore local maven cache + uses: actions/cache/restore@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Download DiffTool JAR + uses: robinraju/release-downloader@v1.8 + with: + repository: "checkstyle/test-configs" + tag: "diff-java-tool-${{ env.DIFF_TOOL_VERSION }}" + fileName: "diff-java-tool-${{ env.DIFF_TOOL_VERSION }}-all.jar" + out-file-path: ".ci-temp" + + - name: Download patch-diff-report-tool JAR + uses: robinraju/release-downloader@v1.8 + with: + repository: "checkstyle/contribution" + tag: "patch-diff-report-tool-${{ env.PATCH_DIFF_TOOL_VERSION }}" + fileName: >- + patch-diff-report-tool-${{ env.PATCH_DIFF_TOOL_VERSION }}-jar-with-dependencies.jar + out-file-path: ".ci-temp" + + - name: Set up Java 21 + uses: actions/setup-java@v5 + with: + distribution: 'temurin' + java-version: '21' + + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@v5 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ env.AWS_REGION }} + + - name: Print config.xml + run: | + echo "Contents of config.xml:" + echo "-------------------------" + if [ -f .ci-temp/diff_config.xml ]; then + cat .ci-temp/diff_config.xml + else + echo "diff_config.xml not found" + fi + echo "-------------------------" + + - name: Print projects file + run: | + if [ -f .ci-temp/projects.yml ]; then + echo "Contents of projects.yml:" + echo "-------------------------------" + cat .ci-temp/projects.yml + echo "-------------------------------" + elif [ -f .ci-temp/projects.properties ]; then + echo "Contents of projects.properties:" + echo "-------------------------------" + cat .ci-temp/projects.properties + echo "-------------------------------" + else + echo "No projects file found" + fi + + - name: Print patch_config.xml + run: | + echo "Contents of patch_config.xml:" + echo "-----------------------------" + if [ -f .ci-temp/patch_config.xml ]; then + cat .ci-temp/patch_config.xml + else + echo "patch_config.xml not found" + fi + echo "-----------------------------" + + - name: Print new_module_config.xml + run: | + echo "Contents of new_module_config.xml:" + echo "-----------------------------------" + if [ -f .ci-temp/new_module_config.xml ]; then + cat .ci-temp/new_module_config.xml + else + echo "new_module_config.xml not found" + fi + echo "-----------------------------------" + + - name: Generate report + run: | + cd .ci-temp + bash + PR_BRANCH="${{ needs.checkout_and_cache.outputs.pr_branch }}" + REPO="${{ github.workspace }}/.ci-temp/checkstyle" + BASE_BRANCH="upstream/master" + export MAVEN_OPTS="-Xmx5g" + + # Paths to config files + DIFF_CONFIG="${{ github.workspace }}/.ci-temp/diff_config.xml" + PATCH_CONFIG="${{ github.workspace }}/.ci-temp/patch_config.xml" + NEW_MODULE_CONFIG="${{ github.workspace }}/.ci-temp/new_module_config.xml" + + # Determine the projects file path + if [ -f "${{ github.workspace }}/.ci-temp/projects.yml" ]; then + PROJECTS_FILE="${{ github.workspace }}/.ci-temp/projects.yml" + elif [ -f "${{ github.workspace }}/.ci-temp/projects.properties" ]; then + PROJECTS_FILE="${{ github.workspace }}/.ci-temp/projects.properties" + else + echo "Error: Projects file not found." + exit 1 + fi + + # Paths to the JAR files + DIFFTOOL_JAR="diff-java-tool-${{ env.DIFF_TOOL_VERSION }}-all.jar" + PATCH_DIFF_TOOL_JAR="patch-diff-report-tool-\ + ${{ env.PATCH_DIFF_TOOL_VERSION }}-jar-with-dependencies.jar" + + CONFIG_DIR="${{ github.workspace }}/.ci-temp/config" + EXTRA_MVN_OPTIONS="-Dcheckstyle.failsOnError=false -Dconfig.folder=${CONFIG_DIR}" + + # Run DiffTool with appropriate arguments + if [ -f "$NEW_MODULE_CONFIG" ]; then + echo "Generating report for new module" + java -jar "$DIFFTOOL_JAR" \ + -r "$REPO" \ + -p "$PR_BRANCH" \ + -pc "$NEW_MODULE_CONFIG" \ + -m single \ + -l "$PROJECTS_FILE" \ + -xm "$EXTRA_MVN_OPTIONS" \ + --allowExcludes \ + --diffToolJarPath "$PATCH_DIFF_TOOL_JAR" + elif [ -f "$PATCH_CONFIG" ]; then + echo "Generating report with patch config" + java -jar "$DIFFTOOL_JAR" \ + -r "$REPO" \ + -b "$BASE_BRANCH" \ + -p "$PR_BRANCH" \ + -bc "$DIFF_CONFIG" \ + -pc "$PATCH_CONFIG" \ + -l "$PROJECTS_FILE" \ + -xm "$EXTRA_MVN_OPTIONS" \ + --allowExcludes \ + --diffToolJarPath "$PATCH_DIFF_TOOL_JAR" + else + echo "Generating standard diff report" + java -jar "$DIFFTOOL_JAR" \ + -r "$REPO" \ + -b "$BASE_BRANCH" \ + -p "$PR_BRANCH" \ + -c "$DIFF_CONFIG" \ + -l "$PROJECTS_FILE" \ + -xm "$EXTRA_MVN_OPTIONS" \ + --allowExcludes \ + --diffToolJarPath "$PATCH_DIFF_TOOL_JAR" + fi + + - name: Copy Report to AWS S3 Bucket + env: + LABEL: ${{ needs.download_configs.outputs.report_label }} + COMMIT_SHA: ${{ needs.checkout_and_cache.outputs.commit_sha }} + run: | + bash + TIME=$(date +%Y%H%M%S) + FOLDER="${COMMIT_SHA}_$TIME" + DIFF="./.ci-temp/reports/diff" + LINK="https://${{env.AWS_BUCKET_NAME}}.s3.${{env.AWS_REGION}}.amazonaws.com" + aws s3 cp $DIFF "s3://${{env.AWS_BUCKET_NAME}}/$FOLDER/reports/diff/" --recursive + if [ -n "$LABEL" ]; then + echo "$LABEL: " > .ci-temp/message + fi + echo "$LINK/$FOLDER/reports/diff/index.html" >> .ci-temp/message + + - name: Set output + id: out + run: | + ./.ci/append-to-github-output.sh "message" "$(cat .ci-temp/message)" + + add_sad_Emoji: + needs: [ check_pr_status, parse_comment, make_report ] + if: cancelled() + runs-on: ubuntu-latest + steps: + - name: Add sad Emoji + uses: actions/github-script@v8 + with: + github-token: ${{secrets.GITHUB_TOKEN}} + script: | + github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: context.payload.comment.id, + content: 'confused' + }); + + # should be always last step + send_message: + runs-on: ubuntu-latest + needs: [ + check_pr_status, + checkout_and_cache, + parse_comment, + handle_existing_config_bundle, + handle_generated_config_bundle, + handle_configs_in_pr_description, + download_configs, + make_report, + add_sad_Emoji + ] + if: always() + && (needs.make_report.result == 'failure' + || needs.make_report.outputs.message != '' + || needs.download_configs.result == 'failure' + || needs.handle_existing_config_bundle.result == 'failure' + || needs.handle_generated_config_bundle.result == 'failure' + || needs.handle_configs_in_pr_description.result == 'failure' + || needs.check_pr_status.result == 'failure' + || needs.checkout_and_cache.result == 'failure' + || needs.parse_comment.result == 'failure' + || needs.add_sad_Emoji.result == 'failure') + steps: + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: . + key: ${{ env.CACHE_KEY }} + fail-on-cache-miss: true + + - name: Get message + env: + MSG: ${{ needs.make_report.outputs.message }} + DOWNLOAD_RESULT: ${{ needs.download_configs.result }} + MAKE_REPORT_RESULT: ${{ needs.make_report.result }} + EXISTING_CONFIG_RESULT: ${{ needs.handle_existing_config_bundle.result }} + GENERATED_CONFIG_RESULT: ${{ needs.handle_generated_config_bundle.result }} + CONFIGS_IN_PR_RESULT: ${{ needs.handle_configs_in_pr_description.result }} + PR_STATUS_RESULT: ${{ needs.check_pr_status.result }} + CHECKOUT_RESULT: ${{ needs.checkout_and_cache.result }} + PARSE_RESULT: ${{ needs.parse_comment.result }} + ADD_SAD_RESULT: ${{ needs.add_sad_Emoji.result }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mkdir -p .ci-temp + JOBS_LINK="https://github.com/checkstyle/checkstyle/actions/runs/${{github.run_id}}" + if [ "$ADD_SAD_RESULT" == "failure" ]; then + { + echo "Failed to add reaction to comment after cancellation." + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ "$PR_STATUS_RESULT" == "failure" ]; then + { + echo "PR is not active. Only active PRs are allowed for report generation." + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ "$DOWNLOAD_RESULT" == "failure" ]; then + { + echo "Failed to download or process the specified configuration(s)." + echo "Error details: $DOWNLOAD_ERROR" + echo "
    Please ensure you've used one of the following commands correctly:" + echo "- 'GitHub, generate report for '" + echo "- 'GitHub, generate report by config from '" + echo "- 'GitHub, generate report for configs in PR description'" + echo "
    And check that all specified configs or files exist and are valid." + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ "$GENERATED_CONFIG_RESULT" == "failure" ]; then + { + echo "Failed to generate config from the specified file." + echo "Please ensure the file exists and the path is correct." + echo "
    Usage: 'GitHub, generate report by config from '" + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ "$CONFIGS_IN_PR_RESULT" == "failure" ]; then + { + echo "Failed to process configs in PR description." + echo "Please check the PR description format and config links." + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ "$EXISTING_CONFIG_RESULT" == "failure" ]; then + { + echo "Failed to process existing config bundle." + echo "Please verify the config bundle path is correct." + echo "
    Usage: 'GitHub, generate report for '" + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ "$MAKE_REPORT_RESULT" == "failure" ]; then + { + echo "Report generation failed. Please check the logs for more details." + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ "$CHECKOUT_RESULT" == "failure" ]; then + { + echo "Failed to checkout repository or set up cache." + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ "$PARSE_RESULT" == "failure" ]; then + { + echo "Failed to parse comment command." + echo "
    Please ensure you've used one of the valid command formats." + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + elif [ -z "$MSG" ]; then + API_LINK="https://api.github.com/repos/checkstyle/checkstyle/actions/runs/${{github.run_id}}/jobs" + curl --fail-with-body -X GET "${API_LINK}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o .ci-temp/info.json + jq '.jobs' .ci-temp/info.json > ".ci-temp/jobs" + jq '.[] | select(.conclusion == "failure") | .name' .ci-temp/jobs > .ci-temp/job_name + jq '.[] | select(.conclusion == "failure") | .steps' .ci-temp/jobs > .ci-temp/steps + jq '.[] | select(.conclusion == "failure") | .name' .ci-temp/steps > .ci-temp/step_name + { + echo "Report generation failed on phase $(cat .ci-temp/job_name)," + echo "step $(cat .ci-temp/step_name)." + echo "
    Link: $JOBS_LINK" + } > .ci-temp/message + else + echo "$MSG" > .ci-temp/message + fi + + - name: Set message + id: out + run: | + ./.ci/append-to-github-output.sh "message" "$(cat .ci-temp/message)" + + - name: Comment PR + uses: peter-evans/create-or-update-comment@v5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + repository: ${{ github.repository }} + issue-number: ${{ github.event.issue.number }} + body: ${{ steps.out.outputs.message }} diff --git a/.github/workflows/release-copy-github-io-to-sourceforge.yml b/.github/workflows/release-copy-github-io-to-sourceforge.yml new file mode 100644 index 000000000000..6eba7def8605 --- /dev/null +++ b/.github/workflows/release-copy-github-io-to-sourceforge.yml @@ -0,0 +1,47 @@ +############################################################################# +# GitHub Action to Copy github.io to sourceforge.org. +# +############################################################################# +name: "R: Copy github.io to sourceforge.org" +run-name: "R: Copy github.io to sourceforge.org ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + copy-github-io-to-sourceforge: + name: Copy github.io to sourceforge.org ${{ inputs.version }} + runs-on: ubuntu-latest + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + + - name: Configure SSH + env: + SF_SSH_KEY: ${{ secrets.SF_SSH_KEY }} + run: | + mkdir -p ~/.ssh/ + eval "$(ssh-agent -s)" + echo "$SF_SSH_KEY" > ~/.ssh/private_sourceforge_key + chmod 400 ~/.ssh/private_sourceforge_key + ssh-add ~/.ssh/private_sourceforge_key + ssh-keyscan -t ed25519 shell.sourceforge.net >> ~/.ssh/known_hosts + ssh-keyscan -t ed25519 web.sourceforge.net >> ~/.ssh/known_hosts + + - name: Run Shell Script + env: + SF_USER: ${{ secrets.SF_USER }} + run: | + ./.ci/release-copy-github-io-to-sourceforge.sh ${{ inputs.version }} diff --git a/.github/workflows/release-maven-perform.yml b/.github/workflows/release-maven-perform.yml new file mode 100644 index 000000000000..938e6c76c2d7 --- /dev/null +++ b/.github/workflows/release-maven-perform.yml @@ -0,0 +1,61 @@ +############################################################################# +# GitHub Action to Run Perform goal of Maven Release plugin. +# +############################################################################# +name: "R: Maven Perform" +run-name: "R: Maven Perform ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + maven-perform: + name: Maven Perform ${{ inputs.version }} + runs-on: ubuntu-latest + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + with: + fetch-depth: 0 + ref: master + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Configure GPG + env: + GPG_SECRET_KEY: ${{ secrets.GPG_SECRET_KEY }} + run: | + mkdir -p ~/.gnupg/ + echo "$GPG_SECRET_KEY" > ~/.gnupg/private.key + gpg --batch --import ~/.gnupg/private.key + chmod 600 ~/.gnupg/private.key + chmod 700 ~/.gnupg + + - name: Prepare release settings + env: + SONATYPE_USER: ${{ secrets.SONATYPE_USER }} + SONATYPE_PWD: ${{ secrets.SONATYPE_PWD }} + GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} + GPG_KEYNAME: ${{ secrets.GPG_KEYNAME }} + run: | + ./.ci/release-create-maven-settings-xml.sh + + - name: Run Shell Script + run: | + ./.ci/release-maven-perform.sh ${{ inputs.version }} diff --git a/.github/workflows/release-maven-prepare.yml b/.github/workflows/release-maven-prepare.yml new file mode 100644 index 000000000000..77fa1b618f93 --- /dev/null +++ b/.github/workflows/release-maven-prepare.yml @@ -0,0 +1,54 @@ +############################################################################# +# GitHub Action to Run Prepare goal of Maven Release plugin. +# +############################################################################# +name: "R: Maven Prepare" +run-name: "R: Maven Prepare ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +permissions: + contents: write + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + maven-prepare: + name: Maven Prepare ${{ inputs.version }} + runs-on: ubuntu-latest + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + with: + fetch-depth: 0 + ref: master + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Commit and Push Credentials + run: | + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + + - name: Run Shell Script + run: | + ./.ci/release-maven-prepare.sh ${{ inputs.version }} + + - name: Push commit + run: | + git push origin master --tags diff --git a/.github/workflows/release-new-milestone-and-issues-in-other-repos.yml b/.github/workflows/release-new-milestone-and-issues-in-other-repos.yml new file mode 100644 index 000000000000..09733b059fea --- /dev/null +++ b/.github/workflows/release-new-milestone-and-issues-in-other-repos.yml @@ -0,0 +1,59 @@ +############################################################################# +# GitHub Action to Create New Milestone and Issues in Other Repositories. +# +############################################################################# +name: "R: New Milestone, Create issues" +run-name: "R: New Milestone, Create issues ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +permissions: + contents: write + issues: write + +concurrency: + group: ${{ github.workflow }} + -${{ github.event.pull_request.number || github.ref }}-new-milestone-and-issues-in-other-repos + cancel-in-progress: true + +jobs: + new-milestone-and-issues-in-other-repos: + name: New Milestone, Create issues for ${{ inputs.version }} + runs-on: ubuntu-24.04 + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + with: + fetch-depth: 0 + ref: master + + - name: Download ncal + run: | + sudo apt-get install ncal + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Close/Create Milestone + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + ./.ci/release-close-create-milestone.sh + + - name: Creation of issue in other Repositories + env: + GITHUB_TOKEN: ${{ secrets.PAT }} + run: | + ./.ci/release-create-issues-in-other-repos.sh ${{ inputs.version }} diff --git a/.github/workflows/release-publish-releasenotes-twitter.yml b/.github/workflows/release-publish-releasenotes-twitter.yml new file mode 100644 index 000000000000..13538052f575 --- /dev/null +++ b/.github/workflows/release-publish-releasenotes-twitter.yml @@ -0,0 +1,48 @@ +############################################################################# +# GitHub Action to Publish Release Notes on Twitter. +# +############################################################################# +name: "R: Publish Release Notes on Twitter" +run-name: "R: Publish Release Notes on Twitter ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +concurrency: + group: ${{ github.workflow }} + -${{ github.event.pull_request.number || github.ref }}-publish-releasenotes-twitter + cancel-in-progress: true + +jobs: + publish-releasenotes-twitter: + name: Publish Release Notes on Twitter ${{ inputs.version }} + runs-on: ubuntu-24.04 + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + with: + fetch-depth: 0 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Run Shell Script + env: + GITHUB_READ_ONLY_TOKEN: ${{ secrets.READ_ONLY_TOKEN_GITHUB }} + TWITTER_CONSUMER_KEY: ${{ secrets.TWITTER_CONSUMER_KEY }} + TWITTER_CONSUMER_SECRET: ${{ secrets.TWITTER_CONSUMER_SECRET }} + TWITTER_ACCESS_TOKEN: ${{ secrets.TWITTER_ACCESS_TOKEN }} + TWITTER_ACCESS_TOKEN_SECRET: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} + run: | + ./.ci/release-publish-releasenotes-twitter.sh ${{ inputs.version }} diff --git a/.github/workflows/release-update-github-io.yml b/.github/workflows/release-update-github-io.yml new file mode 100644 index 000000000000..eab90fbb0559 --- /dev/null +++ b/.github/workflows/release-update-github-io.yml @@ -0,0 +1,54 @@ +############################################################################# +# GitHub Action to Update GitHub.io. +# +############################################################################# +name: "R: Update GitHub.io" +run-name: "R: Update GitHub.io ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +concurrency: + group: ${{ github.workflow }} + -${{ github.event.pull_request.number || github.ref }}-update-github-io + cancel-in-progress: true + +jobs: + update-github-io: + name: Update GitHub.io ${{ inputs.version }} + runs-on: ubuntu-latest + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + with: + repository: ${{ github.repository_owner }}/checkstyle + fetch-depth: 0 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Run Shell Script + run: | + ./.ci/generate-website.sh ${{ inputs.version }} + + - name: Checkout checkstyle.github.io repo + uses: actions/checkout@v5 + with: + repository: ${{ github.repository_owner }}/checkstyle.github.io + token: ${{ secrets.PAT }} + path: .ci-temp/checkstyle.github.io/ + + - name: Commit and Push to checkstyle.github.io repo + run: | + ./.ci/release-update-github-io.sh ${{ inputs.version }} diff --git a/.github/workflows/release-update-github-page.yml b/.github/workflows/release-update-github-page.yml new file mode 100644 index 000000000000..87ab08e203b5 --- /dev/null +++ b/.github/workflows/release-update-github-page.yml @@ -0,0 +1,44 @@ +############################################################################# +# GitHub Action to Publish Release Notes to GitHub Release Page. +# +############################################################################# +name: "R: Update GitHub Page" +run-name: "R: Update GitHub Page ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +concurrency: + group: ${{ github.workflow }} + -${{ github.event.pull_request.number || github.ref }}-update-github-page + cancel-in-progress: true + +jobs: + update-github-page: + name: Update GitHub Page ${{ inputs.version }} + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Run Shell Script + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + ./.ci/release-update-github-page.sh ${{ inputs.version }} diff --git a/.github/workflows/release-update-xdoc-with-releasenotes.yml b/.github/workflows/release-update-xdoc-with-releasenotes.yml new file mode 100644 index 000000000000..fd866d6d079c --- /dev/null +++ b/.github/workflows/release-update-xdoc-with-releasenotes.yml @@ -0,0 +1,50 @@ +############################################################################# +# GitHub Action to Commit and Push Release Notes to releasenotes.xml File. +# +############################################################################# +name: "R: Update xdoc with Release Notes" +run-name: "R: Update xdoc with Release Notes ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + update-xdoc-with-releasenotes: + name: Update xdoc with Release Notes ${{ inputs.version }} + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Run Shell Script + env: + READ_ONLY_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + ./.ci/release-update-xdoc-with-releasenotes.sh ${{ inputs.version }} + + - name: Commit and Push + run: | + git config user.name 'github-actions[bot]' + git config user.email 'github-actions[bot]@users.noreply.github.com' + git add . && git commit -m "doc: release notes for ${{ inputs.version }}" + git push origin master diff --git a/.github/workflows/release-upload-all-jar.yml b/.github/workflows/release-upload-all-jar.yml new file mode 100644 index 000000000000..8120fe26d4b9 --- /dev/null +++ b/.github/workflows/release-upload-all-jar.yml @@ -0,0 +1,48 @@ +############################################################################# +# GitHub Action to Upload '-all' Jar. +# +############################################################################# +name: "R: Upload '-all' Jar" +run-name: "R: Upload '-all' Jar ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + workflow_call: + inputs: + version: + type: string + required: true + +permissions: + contents: write + +concurrency: + group: ${{ github.workflow }} + -${{ github.event.pull_request.number || github.ref }}-upload-all-jar + cancel-in-progress: true + +jobs: + upload-all-jar: + name: Upload '-all' jar ${{ inputs.version }} + runs-on: ubuntu-24.04 + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + with: + fetch-depth: 0 + ref: master + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Run GitHub Update Script + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + ./.ci/release-upload-all-jar.sh ${{ inputs.version }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000000..0736a12661a4 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,91 @@ +############################################################################# +# GitHub Action to run all phases of the release. +# +############################################################################# +name: "R: Release" +run-name: "R: Release ${{ inputs.version }}" +on: + workflow_dispatch: + inputs: + version: + description: 'POM version without (-SNAPSHOT)' + required: true + +concurrency: + group: Caller-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + update-xdoc-with-releasenotes: + uses: ./.github/workflows/release-update-xdoc-with-releasenotes.yml + with: + version: ${{ inputs.version }} + permissions: + contents: write + + maven-prepare: + uses: ./.github/workflows/release-maven-prepare.yml + needs: update-xdoc-with-releasenotes + with: + version: ${{ inputs.version }} + permissions: + contents: write + + maven-perform: + uses: ./.github/workflows/release-maven-perform.yml + needs: maven-prepare + with: + version: ${{ inputs.version }} + secrets: inherit + permissions: + contents: read + + update-github-page: + uses: ./.github/workflows/release-update-github-page.yml + needs: maven-perform + with: + version: ${{ inputs.version }} + secrets: inherit + permissions: + contents: write + + upload-all-jar: + uses: ./.github/workflows/release-upload-all-jar.yml + needs: update-github-page + with: + version: ${{ inputs.version }} + secrets: inherit + permissions: + contents: write + + new-milestone-and-issues-in-other-repos: + uses: ./.github/workflows/release-new-milestone-and-issues-in-other-repos.yml + needs: update-github-page + with: + version: ${{ inputs.version }} + secrets: inherit + permissions: + contents: write + issues: write + + # until https://github.com/checkstyle/checkstyle/issues/13094 + # publish-releasenotes-twitter: + # uses: ./.github/workflows/release-publish-releasenotes-twitter.yml + # needs: update-github-page + # with: + # version: ${{ inputs.version }} + # secrets: inherit + + update-github-io: + uses: ./.github/workflows/release-update-github-io.yml + needs: maven-perform + with: + version: ${{ inputs.version }} + secrets: inherit + + copy-github-io-to-sourceforge: + uses: ./.github/workflows/release-copy-github-io-to-sourceforge.yml + needs: update-github-io + with: + version: ${{ inputs.version }} + secrets: inherit diff --git a/.github/workflows/releasenotes-gen.yml b/.github/workflows/releasenotes-gen.yml new file mode 100644 index 000000000000..0bce5fe3923a --- /dev/null +++ b/.github/workflows/releasenotes-gen.yml @@ -0,0 +1,30 @@ +name: "Generate release notes" + +on: + workflow_dispatch: null + push: + branches: + - master + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + generate: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-24.04 + steps: + - name: Download checkstyle + uses: actions/checkout@v5 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Generate release notes + env: + READ_ONLY_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: ./.ci/releasenotes-gen.sh diff --git a/.github/workflows/remainder-bot.yml b/.github/workflows/remainder-bot.yml new file mode 100644 index 000000000000..46bbedd16dcc --- /dev/null +++ b/.github/workflows/remainder-bot.yml @@ -0,0 +1,78 @@ +##################################################################################### +# Remainder Bot +# +# Workflow starts when: +# 1) every day at 00:00 UTC +# +# Workflow: +# 1) Check and close inactive issues and PRs +# 2) Remind user to provide the requested feedback for issues +# 3) Remind user to provide the requested feedback for PRs +# 4) If no response is received in the next 15 days, we will close this issue +# 5) If no response is received in the next 15 days, we will close this pull request +# 6) Close the issue with a message after 60 days +# 7) Close the pull request with a message after 60 days +##################################################################################### + +name: "feedback-reminder-bot" + +on: + schedule: + # every day at 00:00 UTC + - cron: "0 0 * * *" + +permissions: + contents: read + issues: write + pull-requests: write +concurrency: + group: feedback-reminder-bot + cancel-in-progress: true +jobs: + close-inactive-issues: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: check and close inactive issues and PRs + uses: actions/stale@v10 + with: + only-issue-labels: "awaiting response" + only-pr-labels: "awaiting changes" + labels-to-remove-when-unstale: "awaiting response,awaiting changes" + + days-before-stale: 15 + stale-issue-message: | + Hello 👋! + + It looks like this issue has been inactive for a while. + Could you provide the requested feedback? + If no response is received in the next 60 days, we will close this issue. + + 🚧 This Github Action is under testing, please let us know if it is misbehaving. 🚧 + + stale-pr-message: | + Hello 👋! + + It looks like this pull request has been inactive for a while. + Could you provide the requested feedback? + If no response is received in the next 60 days, we will close this pull request. + + 🚧 This Github Action is under testing, please let us know if it is misbehaving. 🚧 + + days-before-close: 60 + close-issue-message: | + Hello 👋! + + Since we haven't received any feedback, we are closing this issue. + If you have any questions or need further assistance, + please feel free to reopen this issue. + + 🚧 This Github Action is under testing, please let us know if it is misbehaving. 🚧 + close-pr-message: | + Hello 👋! + + Since we haven't received any feedback, we are closing this pull request. + If you have any questions or need further assistance, + please feel free to reopen this pull request. + + 🚧 This Github Action is under testing, please let us know if it is misbehaving. 🚧 diff --git a/.github/workflows/run-checkstyle-ast-print.yml b/.github/workflows/run-checkstyle-ast-print.yml new file mode 100644 index 000000000000..14959bae62c8 --- /dev/null +++ b/.github/workflows/run-checkstyle-ast-print.yml @@ -0,0 +1,64 @@ +##################################################################################### +# GitHub Action to run checkstyle with: +# +# target java file URL to print its AST +# +# Output is printed in console terminal +# +##################################################################################### +name: Run-Checkstyle-Ast-Print + +on: + workflow_dispatch: + inputs: + java-source-url: + description: 'url to java source' + required: true + compile: + description: 'compile java by javac' + required: true + default: 'false' + +concurrency: + group: ${{ github.run_id }} + cancel-in-progress: true + +jobs: + test: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - uses: robinraju/release-downloader@v1 + with: + repository: 'checkstyle/checkstyle' + latest: true + fileName: 'checkstyle-*.*.*-all.jar' + + - name: Download target java source + run: | + curl --fail-with-body -X GET "${{ inputs.java-source-url }}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -o "Test.java" + + - name: Run checkstyle AST printing + run: | + pwd + ls -la + echo "Content of Test.java:" + cat -n Test.java + echo "" + if [[ "${{ inputs.compile }}" == "true" ]]; then + echo "javac Test.java:" + javac Test.java + fi + echo "" + JAR_NAME=$(find . -name "*-all.jar") + echo "Executing: java -jar ""$JAR_NAME"" -J Test.java" + java -jar "$JAR_NAME" -J Test.java diff --git a/.github/workflows/run-checkstyle.yml b/.github/workflows/run-checkstyle.yml new file mode 100644 index 000000000000..49b18f1fb11c --- /dev/null +++ b/.github/workflows/run-checkstyle.yml @@ -0,0 +1,77 @@ +##################################################################################### +# GitHub Action to run checkstyle with: +# config URL +# target java file URL +# +# Output is printed in console terminal +# +##################################################################################### +name: Run-Checkstyle + +on: + workflow_dispatch: + inputs: + config-url: + description: 'url to xml config' + required: true + java-source-url: + description: 'url to java source' + required: true + compile: + description: 'compile java by javac' + required: true + default: 'false' + +concurrency: + group: ${{ github.run_id }} + cancel-in-progress: true + +jobs: + test: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: 21 + distribution: 'temurin' + + - uses: robinraju/release-downloader@v1 + with: + repository: 'checkstyle/checkstyle' + latest: true + fileName: 'checkstyle-*.*.*-all.jar' + + - name: Download config + run: | + curl --fail-with-body -X GET "${{ inputs.config-url }}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -o "config.xml" + + - name: Download target java source + run: | + curl --fail-with-body -X GET "${{ inputs.java-source-url }}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ + -o "Test.java" + + - name: Run checkstyle + run: | + pwd + ls -la + echo "Content of config.xml:" + cat config.xml + echo "" + echo "Content of Test.java:" + cat -n Test.java + echo "" + if [[ "${{ inputs.compile }}" == "true" ]]; then + echo "javac Test.java:" + javac Test.java + fi + echo "" + JAR_NAME=$(find . -name "*-all.jar") + echo "Executing: java -jar ""$JAR_NAME"" -c config.xml Test.java" + java -jar "$JAR_NAME" -c config.xml Test.java diff --git a/.github/workflows/run-link-check.yml b/.github/workflows/run-link-check.yml new file mode 100644 index 000000000000..9b19c899cda9 --- /dev/null +++ b/.github/workflows/run-link-check.yml @@ -0,0 +1,33 @@ +##################################################################################### +# GitHub Action to run link checks. +# +# Workflow starts when: +# 1) push on master branch +# +##################################################################################### +name: "Check no broken links" + +on: + push: + branches: [ master ] + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + check_issues: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-24.04 + steps: + - name: Download checkstyle + uses: actions/checkout@v5 + + - name: Setup local maven cache + uses: actions/cache@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Check links + run: ./.ci/run-link-check-plugin.sh diff --git a/.github/workflows/set-milestone-on-referenced-issue.yml b/.github/workflows/set-milestone-on-referenced-issue.yml new file mode 100644 index 000000000000..46fb49518738 --- /dev/null +++ b/.github/workflows/set-milestone-on-referenced-issue.yml @@ -0,0 +1,45 @@ +############################################################################# +# GitHub action to set latest milestone on issue of merged PR. +# +############################################################################# +name: 'Milestone issue closed by PR' + +on: + push: + branches: + - master + workflow_dispatch: + inputs: + commits: + description: 'Json array of Github commits' + required: true + type: string + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +permissions: + issues: write + pull-requests: write + +jobs: + set-milestone: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-24.04 + steps: + - name: Checkout the latest code + uses: actions/checkout@v5 + + - name: Set milestone on issue + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_INPUT_COMMITS: ${{ inputs.commits }} + GITHUB_EVENT_COMMITS: ${{ toJSON(github.event.commits) }} + run: | + if [[ -z "$GITHUB_INPUT_COMMITS" ]]; then + COMMITS="$GITHUB_EVENT_COMMITS" + else + COMMITS="$GITHUB_INPUT_COMMITS" + fi + ./.ci/set-milestone-on-referenced-issue.sh "$COMMITS" diff --git a/.github/workflows/shellcheck.yml b/.github/workflows/shellcheck.yml new file mode 100644 index 000000000000..d3244c1e7e34 --- /dev/null +++ b/.github/workflows/shellcheck.yml @@ -0,0 +1,27 @@ +name: "shellcheck" + +on: + push: + branches: + - master + pull_request: + branches: '*' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + # this execution should stay on GitHub actions due to time/ memory limits in other CI + shellcheck: + if: github.repository == 'checkstyle/checkstyle' + runs-on: ubuntu-latest + steps: + - name: Install dependencies + run: sudo apt install shellcheck + + - name: Checkout repository + uses: actions/checkout@v5 + + - name: Execute shellcheck + run: shellcheck ./.ci/*.sh diff --git a/.github/workflows/site.yml b/.github/workflows/site.yml new file mode 100644 index 000000000000..3d5c42cffaf9 --- /dev/null +++ b/.github/workflows/site.yml @@ -0,0 +1,206 @@ +##################################################################################### +# GitHub Action to generate Checkstyle site. +# +# Workflow starts when: +# 1) issue comment - created, edited +# +# Requirements: +# 1) secrets.AWS_ACCESS_KEY_ID - access key for AWS S3 service user +# 2) secrets.AWS_SECRET_ACCESS_KEY - security access key for AWS S3 service user +# +# If you need to change bucket name or region, change AWS_REGION and AWS_BUCKET_NAME variables. +# For another bucket, you will need to change the secrets. +##################################################################################### +name: "Site" + +env: + AWS_REGION: "us-east-2" + AWS_BUCKET_NAME: "checkstyle-diff-reports" + +on: + issue_comment: + types: [ created, edited ] + workflow_dispatch: + inputs: + pr-number: + description: 'PR number' + required: true + type: string + +permissions: + contents: read + pull-requests: write + +concurrency: + group: ${{ github.workflow }}-${{ inputs.pr-number || github.event.issue.number || github.ref }} + cancel-in-progress: false + +jobs: + parse_pr_info: + if: github.event.comment.body == 'GitHub, generate web site' + || github.event.comment.body == 'GitHub, generate website' + || github.event.comment.body == 'GitHub, generate site' + || inputs.pr-number != '' + runs-on: ubuntu-latest + outputs: + branch: ${{ steps.branch.outputs.ref }} + commit_sha: ${{ steps.branch.outputs.commit_sha }} + + steps: + - name: Getting PR description + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + mkdir -p .ci-temp + if [ -z "${{inputs.pr-number}}" ]; then + URL="${{github.event.issue.pull_request.url}}" + else + URL="https://api.github.com/repos/checkstyle/checkstyle/pulls/""${{inputs.pr-number}}" + fi + curl --fail-with-body -X GET "$URL" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o .ci-temp/info.json + + jq .head.ref .ci-temp/info.json > .ci-temp/branch + jq .head.sha .ci-temp/info.json > .ci-temp/commit_sha + + - name: Set branch + id: branch + run: | + echo "ref=$(xargs < .ci-temp/branch)" >> "$GITHUB_OUTPUT" + echo "commit_sha=$(xargs < .ci-temp/commit_sha | cut -c 1-7)" >> "$GITHUB_OUTPUT" + + generate_site: + needs: parse_pr_info + runs-on: ubuntu-latest + steps: + # fetch-depth - number of commits to fetch. + # 0 indicates all history for all branches and tags. + # 0, because we need access to all branches to create a report. + # ref - branch to checkout. + - name: Download checkstyle for PR + uses: actions/checkout@v5 + with: + ref: refs/pull/${{ inputs.pr-number || github.event.issue.number }}/head + path: .ci-temp/checkstyle + fetch-depth: 0 + + - name: Setup local maven cache + uses: actions/cache/restore@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Generate site + run: | + bash + cd .ci-temp/checkstyle + mvn -e --no-transfer-progress clean site -Pno-validations \ + -Dmaven.javadoc.skip=false -Djdepend.skip=false + + - name: Setup local maven cache + uses: actions/cache/save@v4 + with: + path: .ci-temp/checkstyle/target/site + key: checkstyle-site-cache-${{ github.run_id }} + + + publish_site: + needs: [ parse_pr_info, generate_site ] + runs-on: ubuntu-latest + outputs: + message: ${{ steps.out.outputs.message}} + steps: + - name: Checkout master branch + uses: actions/checkout@v5 + with: + repository: checkstyle/checkstyle + + - name: Setup local maven cache + uses: actions/cache/restore@v4 + with: + path: ~/.m2/repository + key: checkstyle-maven-cache-${{ hashFiles('**/pom.xml') }} + + - name: Setup local maven cache + uses: actions/cache/restore@v4 + with: + path: .ci-temp/checkstyle/target/site + key: checkstyle-site-cache-${{ github.run_id }} + + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@v5 + with: + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + aws-region: ${{ env.AWS_REGION }} + + - name: Copy site to AWS S3 Bucket + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + bash + TIME=$(date +%Y%m%d%H%M%S) + FOLDER="${{needs.parse_pr_info.outputs.commit_sha}}_$TIME" + SITE=".ci-temp/checkstyle/target/site" + LINK="https://${{env.AWS_BUCKET_NAME}}.s3.${{env.AWS_REGION}}.amazonaws.com" + aws s3 cp "$SITE" "s3://${{env.AWS_BUCKET_NAME}}/$FOLDER/" --recursive + echo "$LINK/$FOLDER/index.html" > .ci-temp/message + PR_NUMBER="${{ inputs.pr-number || github.event.issue.number }}" + ./.ci/generate-extra-site-links.sh "$PR_NUMBER" "$LINK/$FOLDER" + + - name: Set output + id: out + run: | + ./.ci/append-to-github-output.sh "message" "$(cat .ci-temp/message)" + + # should be always last step + send_message: + runs-on: ubuntu-latest + needs: [ publish_site ] + if: failure() || success() + steps: + - name: Checkout master branch + uses: actions/checkout@v5 + with: + repository: checkstyle/checkstyle + + - name: Get message + env: + MSG: ${{needs.publish_site.outputs.message}} + run: | + mkdir -p .ci-temp + if [ -z "$MSG" ]; then + JOBS_LINK="https://github.com/checkstyle/checkstyle/actions/runs/${{github.run_id}}" + API_LINK="https://api.github.com/repos/checkstyle/checkstyle/actions/runs/" + API_LINK="${API_LINK}${{github.run_id}}/jobs" + echo "API_LINK=${API_LINK}" + + curl --fail-with-body -X GET "${API_LINK}" \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: token $GITHUB_TOKEN" \ + -o .ci-temp/info.json + + jq '.jobs' .ci-temp/info.json > ".ci-temp/jobs" + jq '.[] | select(.conclusion == "failure") | .name' .ci-temp/jobs > .ci-temp/job_name + jq '.[] | select(.conclusion == "failure") | .steps' .ci-temp/jobs > .ci-temp/steps + jq '.[] | select(.conclusion == "failure") | .name' .ci-temp/steps > .ci-temp/step_name + echo "Site generation job failed on phase $(cat .ci-temp/job_name)," > .ci-temp/message + echo "step $(cat .ci-temp/step_name).
    Link: $JOBS_LINK" >> .ci-temp/message + else + echo "$MSG" > .ci-temp/message + fi + + - name: Set message + id: out + run: | + ./.ci/append-to-github-output.sh "message" "$(cat .ci-temp/message)" + + - name: Comment PR + uses: peter-evans/create-or-update-comment@v5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + repository: ${{ github.repository }} + issue-number: ${{ inputs.pr-number || github.event.issue.number }} + body: ${{ steps.out.outputs.message }} diff --git a/.gitignore b/.gitignore index 01633ce0511c..f33d3827e0c2 100644 --- a/.gitignore +++ b/.gitignore @@ -18,12 +18,19 @@ nb-configuration.xml target bin +# Maven Wrapper (modern setup — do not include jar/downloader) +.mvn/wrapper/maven-wrapper.jar +.mvn/wrapper/MavenWrapperDownloader.java + # IDEA project files checkstyle.iml checkstyle.ipr checkstyle.iws .idea +# Vscode project files +.vscode + # Temp files *~ @@ -40,7 +47,6 @@ replay_pid* # temp folder for files/folders of ci validations .ci-temp -#side effect of jsoref-spellchecker tools usage -.ci/jsoref-spellchecker/spelling-unknown-word-splitter.pl -.ci/jsoref-spellchecker/unknown.words -.ci/jsoref-spellchecker/english.words +# antlr4 grammar generates these +**/gen +**/JavaLanguageLexer.tokens diff --git a/.mdlrc b/.mdlrc new file mode 100644 index 000000000000..f953099fed6a --- /dev/null +++ b/.mdlrc @@ -0,0 +1 @@ +style "#{File.dirname(__FILE__)}/config/markdownlint.rb" diff --git a/.mvn/jvm.config b/.mvn/jvm.config new file mode 100644 index 000000000000..32599cefea51 --- /dev/null +++ b/.mvn/jvm.config @@ -0,0 +1,10 @@ +--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED +--add-opens jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED +--add-opens jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000000..48a56c99aa96 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip diff --git a/.semaphore/semaphore.yml b/.semaphore/semaphore.yml new file mode 100644 index 000000000000..f368194cf4ba --- /dev/null +++ b/.semaphore/semaphore.yml @@ -0,0 +1,104 @@ +version: v1.0 +name: "Checkstyle CI pipeline on Semaphore" +agent: + machine: + type: e1-standard-2 + os_image: ubuntu2004 +auto_cancel: + running: + when: "branch != 'master'" +blocks: + - name: "Linux openjdk build" + task: + prologue: + commands: + - checkout + - cache restore m2 + - eval "export M2_CACHE_SIZE=$(du -s $HOME/.m2 | cut -f1)" + - sudo apt-get update + - sudo apt-get install -y ant groovy xsltproc xmlstarlet + - sudo apt-get install -y openjdk-21-jdk + - export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64 + - export PATH=$JAVA_HOME/bin:$PATH + - java -version + - export GRADLE_OPTS=-Dorg.gradle.console=plain + epilogue: + commands: + - | + if [[ ${M2_CACHE_SIZE} -ne $(du -s $HOME/.m2 | cut -f1) ]] + then + cache delete m2 + cache store m2 $HOME/.m2 + fi + jobs: + - name: sevntu + commands: + - ./mvnw -e --no-transfer-progress compile antrun:run@ant-phase-verify-sevntu -Psevntu + + - name: codenarc analysis + commands: + - rm -rf $HOME/.m2 + - ./.ci/codenarc.sh + + - name: ensure that all modules are used in no exception configs + commands: + - export PULL_REQUEST=$SEMAPHORE_GIT_PR_NUMBER + - ./.ci/validation.sh verify-no-exception-configs + + - name: Validation (openjdk21, fast pool) + matrix: + - env_var: CMD + values: + - .ci/validation.sh all-sevntu-checks + - .ci/validation.sh check-missing-pitests + - .ci/validation.sh eclipse-static-analysis + - .ci/validation.sh verify-regexp-id + - .ci/no-exception-test.sh guava-with-google-checks + - .ci/no-exception-test.sh guava-with-sun-checks + - .ci/no-exception-test.sh no-exception-samples-ant + # permanently disabled as it is very unstable in execution + # - .ci/validation.sh nondex + commands: + - echo "eval of CMD is starting"; + - echo "CMD=$CMD"; + - eval $CMD; + - echo "eval of CMD is completed"; + - ./.ci/validation.sh git-diff + + - name: No Error Test (openjdk21, fast pool) + matrix: + - env_var: CMD + values: + - .ci/validation.sh no-error-orekit + - .ci/validation.sh no-error-checkstyles-sevntu + - .ci/validation.sh no-error-sevntu-checks + - .ci/validation.sh no-error-contribution + - .ci/validation.sh no-error-methods-distance + - .ci/validation.sh no-error-equalsverifier + - .ci/validation.sh jacoco + + commands: + - echo "eval of CMD is starting"; + - echo "CMD=$CMD"; + - eval $CMD; + - echo "eval of CMD is completed"; + - ./.ci/validation.sh git-diff + + - name: Validation (openjdk21, slow pool) + priority: + - value: 80 + when: true + matrix: + - env_var: CMD + values: + - "true" + # until https://github.com/checkstyle/checkstyle/issues/9248 + # - ./mvnw -e clean install -Pno-validations + # && .ci/validation.sh no-violation-test-configurate + commands: + - echo "eval of CMD is starting"; + - echo "CMD=$CMD"; + - eval $CMD; + - echo "eval of CMD is completed"; + - ./.ci/validation.sh git-diff + - ./.ci/validation.sh ci-temp-check diff --git a/.shellcheckrc b/.shellcheckrc new file mode 100644 index 000000000000..8acfdad3fd2a --- /dev/null +++ b/.shellcheckrc @@ -0,0 +1,25 @@ +# until https://github.com/checkstyle/checkstyle/issues/11637 + +disable=SC2207 # (warning): Prefer mapfile or read -a to split command output. +# SC2002 permanently disabled, rightward flow of logic (via pipe) is simple to understand +disable=SC2002 # (style): Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..' instead. +disable=SC2035 # (info): Use ./glob or -- glob so names with dashes won't become options. +disable=SC2185 # (info): Some finds don't have a default path. Specify '.' explicitly. +disable=SC2155 # (warning): Declare and assign separately to avoid masking return values. +disable=SC2034 # (warning): RUN_JOB appears unused. Verify use (or export if used externally). +disable=SC2216 # (warning): Piping to 'true', a command that doesn't read stdin. +disable=SC2013 # (info): To read lines rather than words, pipe/redirect to a 'while read' loop. +disable=SC2206 # (warning): Quote to prevent word splitting/globbing. +disable=SC2143 # (style): Use grep -q instead of comparing output with [ -n .. ]. +disable=SC2004 # (style): $/${} is unnecessary on arithmetic variables. +disable=SC2087 # (warning): Quote 'EOF' to make here document expansions happen on the server-side. +disable=SC2102 # (info): Ranges can only match single chars (mentioned due to duplicates). +disable=SC2242 # (error): Can only exit with status 0-255. +disable=SC2115 # (warning): Use "${var:?}" to ensure this never expands to /* . +disable=SC2128 # (warning): Expanding an array without an index only gives the first element. +disable=SC2063 # (warning): Grep uses regex, but this looks like a glob. +# SC2126 permanently disabled, 'grep | wc -l' is easier to read than 'grep -c || true' +disable=SC2126 # (style): Consider using grep -c instead of grep|wc -l. +disable=SC2015 # (info): Note that A && B || C is not if-then-else. C may run when A is true. +disable=SC2230 # which is non-standard. Use builtin 'command -v' instead. +disable=SC2153 # Possible misspelling: LINKED_ISSUES may not be assigned, but LINKED_ISSUE is. diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index c823a709c825..000000000000 --- a/.travis.yml +++ /dev/null @@ -1,382 +0,0 @@ -language: java -sudo: false - -cache: - directories: - - ~/.m2 - -addons: - apt: - packages: - - xsltproc - - xmlstarlet - -branches: - only: - - master - -install: - - "" - -matrix: - fast_finish: true - include: - # testing age of pr - - env: - - DESC="test Commits Since Latest Master" - - CMD="./.ci/travis/travis.sh pr-age" - - SKIP_JOB_BY_FILES="false" - - # testing of PR format - - env: - - DESC="test Issue ref in PR description" - - CMD="./.ci/travis/travis.sh pr-description" - - SKIP_JOB_BY_FILES="false" - - # new questionably spelled words - - env: - - DESC="spell checker" - - CMD="./.ci/test-spelling-unknown-words.sh" - - SKIP_JOB_BY_FILES="false" - - # unit tests (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests and deploy" - - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Xms1024m -Xmx2048m'" - - DEPLOY="true" - - USE_MAVEN_REPO="true" - - # checkstyle (openjdk8) - - jdk: openjdk8 - env: - - DESC="checkstyle and sevntu-checkstyle" - - CMD="./.ci/travis/travis.sh checkstyle-and-sevntu" - - SKIP_JOB_BY_FILES="false" - - USE_MAVEN_REPO="true" - - # jacoco and codecov (openjdk8) - - jdk: openjdk8 - env: - - DESC="jacoco and codecov" - - CMD="./.ci/travis/travis.sh jacoco" - - CMD_AFTER_SUCCESS="bash <(curl -s https://codecov.io/bash)" - - USE_MAVEN_REPO="true" - - # spotbugs and pmd (openjdk8) - - jdk: openjdk8 - env: - - DESC="spotbugs,pmd" - - CMD="export MAVEN_OPTS='-Xmx2000m' && mvn -e clean compile pmd:check spotbugs:check" - - USE_MAVEN_REPO="true" - - # spotbugs and pmd (openjdk11) - - jdk: openjdk11 - env: - - DESC="spotbugs,pmd" - - CMD="export MAVEN_OPTS='-Xmx2000m' && mvn -e clean compile pmd:check spotbugs:check" - - USE_MAVEN_REPO="true" - - # spotbugs and pmd (openjdk13) - - jdk: openjdk13 - env: - - DESC="spotbugs,pmd" - - CMD="export MAVEN_OPTS='-Xmx2000m' && mvn -e clean compile pmd:check spotbugs:check" - - USE_MAVEN_REPO="true" - - # eclipse static analysis - - jdk: openjdk8 - env: - - DESC="eclipse static analysis" - - CMD="mvn -e clean compile exec:exec -Peclipse-compiler" - - USE_MAVEN_REPO="true" - - # Releasenotes generation - validation - - jdk: openjdk8 - env: - - DESC="Releasenotes generation" - - CMD="./.ci/travis/travis.sh releasenotes-gen" - - SKIP_JOB_BY_FILES="false" - - USE_MAVEN_REPO="true" - - # NonDex (openjdk8) - - jdk: openjdk8 - env: - - DESC="NonDex" - - CMD="./.ci/travis/travis.sh nondex" - - USE_MAVEN_REPO="true" - - # site - - jdk: openjdk8 - env: - - DESC="site without validations" - - CMD="./.ci/travis/travis.sh site" - - USE_MAVEN_REPO="true" - - # unit tests in German locale (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests de" - - CMD="./.ci/travis/travis.sh test-de" - - USE_MAVEN_REPO="true" - # unit tests in Spanish locale (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests es" - - CMD="./.ci/travis/travis.sh test-es" - - USE_MAVEN_REPO="true" - # unit tests in Finnish locale (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests fi" - - CMD="./.ci/travis/travis.sh test-fi" - - USE_MAVEN_REPO="true" - # unit tests in French locale (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests fr" - - CMD="./.ci/travis/travis.sh test-fr" - - USE_MAVEN_REPO="true" - # unit tests in Chinese locale (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests zh" - - CMD="./.ci/travis/travis.sh test-zh" - - USE_MAVEN_REPO="true" - # unit tests in Japanese locale (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests ja" - - CMD="./.ci/travis/travis.sh test-ja" - - USE_MAVEN_REPO="true" - # unit tests in Portuguese locale (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests pt" - - CMD="./.ci/travis/travis.sh test-pt" - - USE_MAVEN_REPO="true" - # unit tests in Turkish locale (openjdk8) - - jdk: openjdk8 - env: - - DESC="tests tr" - - CMD="./.ci/travis/travis.sh test-tr" - - USE_MAVEN_REPO="true" - - # assembly (openjdk8) - - jdk: openjdk8 - env: - - DESC="assembly & run '-all' jar" - - CMD="./.ci/travis/travis.sh assembly-run-all-jar" - - USE_MAVEN_REPO="true" - - # NoExceptiontest - Guava with google_checks (openjdk8) - - jdk: openjdk8 - env: - - DESC="NoExceptionTest - Guava with google_checks" - - CMD="./.ci/travis/travis.sh no-exception-test-guava-with-google-checks" - - USE_MAVEN_REPO="true" - - # NoExceptiontest - Guava with sun_checks (openjdk8) - - jdk: openjdk8 - env: - - DESC="NoExceptionTest - Guava with sun_checks" - - CMD="./.ci/travis/travis.sh no-exception-test-guava-with-sun-checks" - - USE_MAVEN_REPO="true" - - # release dry run (openjdk8) - - jdk: openjdk8 - env: - - DESC="release dry run" - - CMD="./.ci/travis/travis.sh release-dry-run" - - USE_MAVEN_REPO="true" - - # Check the chmod on files. - - env: - - DESC="check permissions on all files" - - CMD="./.ci/travis/travis.sh check-chmod" - - SKIP_JOB_BY_FILES="false" - - # Ensure that all Sevntu check are kused - - jdk: openjdk8 - env: - - DESC="All sevntu checks should be used" - - CMD="./.ci/travis/travis.sh all-sevntu-checks" - - # MacOS JDK8 verify (till cache is not working, we can not do verify) - - os: osx - osx_image: xcode9.3 - env: - - DESC="MacOS JDK8 verify, site, assembly - - CMD1="./.ci/travis/travis.sh osx-package" - - CMD2="./.ci/travis/travis.sh osx-assembly" - - CMD="$CMD1 && $CMD2" - - # MacOS JDK11 verify (till cache is not working, we can not do verify) - - os: osx - osx_image: xcode10.1 - env: - - DESC="MacOS JDK11 verify, site, assembly - - CMD1="./.ci/travis/travis.sh osx-package" - - CMD2="./.ci/travis/travis.sh osx-assembly" - - CMD="$CMD1 && $CMD2" - - # MacOS JDK13 verify (till cache is not working, we can not do verify) - - os: osx - osx_image: xcode11.2 - env: - - DESC="MacOS JDK13 verify, site, assembly - - CMD1="./.ci/travis/travis.sh osx-jdk13-package" - - CMD2="./.ci/travis/travis.sh osx-jdk13-assembly" - - CMD="$CMD1 && $CMD2" - - # No error testing - simple-binary-encoding - - jdk: openjdk8 - env: - - DESC="no error test on simple-binary-encoding" - - USE_MAVEN_REPO="true" - - CMD="./.ci/travis/travis.sh no-error-test-sbe" - - # versions to update - - jdk: openjdk8 - env: - - DESC="print versions to update" - - USE_MAVEN_REPO="true" - - CMD="./.ci/travis/travis.sh versions" - - SKIP_JOB_BY_FILES="false" - - # OpenJDK11 verify - - jdk: openjdk11 - env: - - DESC="verify with OpenJDK11" - - USE_MAVEN_REPO="true" - - CMD="mvn -e verify" - - # OpenJDK11 assembly/site - - jdk: openjdk11 - env: - - DESC="assembly/site with OpenJDK11" - - USE_MAVEN_REPO="true" - - CMD="mvn -e package -Passembly && mvn -e site -Dlinkcheck.skip=true" - - # OpenJDK13 build - - jdk: openjdk13 - env: - - DESC="build with OpenJDK13" - - USE_MAVEN_REPO="true" - - CMD="./.ci/travis/travis.sh jdk13-assembly-site" - - # OpenJDK13 verify limited - - jdk: openjdk13 - env: - - DESC="verify limited with OpenJDK13" - - USE_MAVEN_REPO="true" - - CMD="./.ci/travis/travis.sh jdk13-verify-limited" - - # OpenJDK11 compile input files with jdk9 specific syntax - - jdk: openjdk11 - env: - - DESC="compile input files with jdk9 specific syntax" - - CMD="./.ci/travis/travis.sh javac9" - - # compile input files compilation that are not compiled by eclipse - - jdk: openjdk8 - env: - - DESC="compile input files that are not compiled by eclipse" - - CMD="./.ci/travis/travis.sh javac8" - - # OpenJDK13 compile input files with jdk13 specific syntax - - jdk: openjdk13 - env: - - DESC="compile input files with jdk13 specific syntax" - - CMD="./.ci/travis/travis.sh javac13" - - # find missing pitests - - env: - - DESC="find missing pitests" - - CMD="./.ci/travis/travis.sh check-missing-pitests" - - # Ensure that all modules are used in no exception configs - - env: - - DESC="ensure that all modules are used in no exception configs" - - CMD="./.ci/travis/travis.sh verify-no-exception-configs" - - - env: - - DESC="ensure that no files are in changed state after clone" - - CMD="./.ci/travis/travis.sh git-status" - - - env: - - DESC="validate since javadoc tag if new module is created" - - CMD="./.ci/travis/travis.sh check-since-version" - -script: - - SKIP_FILES1=".github|codeship-*|buddy.yml|appveyor.yml|circleci" - - SKIP_FILES2="|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr" - - SKIP_FILES3="|shippable.yml|shippable.sh|wercker.yml|wercker.sh|intellij-idea-inspections.xml" - - SKIP_FILES4="|Jenkinsfile" - - SKIP_FILES=$SKIP_FILES1$SKIP_FILES2$SKIP_FILES3$SKIP_FILES4 - - export RUN_JOB=1 - #- source ./.ci/common.sh -# - | -# if [ -z ${SKIP_JOB_BY_FILES+x} ]; then -# SKIP_JOB_BY_FILES="recheck"; -# fi - # should_run_job will change RUN_JOB variable -# - should_run_job $SKIP_JOB_BY_FILES $SKIP_FILES - - | - set -e - if [[ $RUN_JOB == 1 ]]; then - MVN_SETTINGS=${TRAVIS_HOME}/.m2/settings.xml - if [[ -f ${MVN_SETTINGS} ]]; then - if [[ $TRAVIS_OS_NAME == 'osx' ]]; then - sed -i'' -e "//,/<\/mirrors>/ d" $MVN_SETTINGS - else - xmlstarlet ed --inplace -d "//mirrors" $MVN_SETTINGS - fi - fi - if [[ $USE_MAVEN_REPO == 'true' && ! -d "~/.m2" ]]; then - echo "Maven local repo cache is not found, initializing it ..." - mvn -B install -Pno-validations; - fi - echo "eval of CMD is starting"; - echo "CMD=$CMD"; - eval $CMD; - echo "eval of CMD is completed"; - else - echo "CI is skipped"; - fi - sleep 5s - -after_success: - - | - set -e - if [[ -n $CMD_AFTER_SUCCESS - && $RUN_JOB == 1 - ]]; - then - echo "CMD_AFTER_SUCCESS is starting"; - eval $CMD_AFTER_SUCCESS; - echo "CMD_AFTER_SUCCESS is finished"; - fi - sleep 5s - - - | - set -e - SKIP_DEPLOY=false - if [ $(git log -1 | grep -E "\[maven-release-plugin\] prepare release" | cat | wc -l) -lt 1 ]; - then - SKIP_DEPLOY=false; - else - SKIP_DEPLOY=true; - fi; - if [[ $TRAVIS_REPO_SLUG == 'checkstyle/checkstyle' - && $TRAVIS_BRANCH == 'master' - && $TRAVIS_PULL_REQUEST == 'false' - && $DEPLOY == 'true' - && $RUN_JOB == 1 - && $SKIP_DEPLOY == 'false' - ]]; - then - mvn -e -s config/deploy-settings.xml -Pno-validations deploy; - echo "deploy to maven snapshot repository is finished"; - fi - sleep 5s diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index 79e27adddc44..000000000000 --- a/Jenkinsfile +++ /dev/null @@ -1,93 +0,0 @@ -// Node label that specifies on which slave(s) the job should run -BUILD_SLAVES_LABEL = 'build-servers' - -// 'sha1' envvar is injected by Jenkins GHPRB plugin in case if build is started by pull request -IS_TRIGGERED_BY_PR = env.sha1?.trim() - -GIT_BRANCH = '' - -// Text colours definition -def GREEN( String msg ) { return "\u001B[32m${msg}\u001B[0m" } -def YELLOW( String msg ) { return "\u001B[33m${msg}\u001B[0m" } -def RED( String msg ) { return "\u001B[31m${msg}\u001B[0m" } - -def getCause(def build) { - while(build.previousBuild) { - build = build.previousBuild - } - - return build.rawBuild.getCause(hudson.model.Cause$UserIdCause) -} - -def getCauseDescription(def build) { - return getCause(build).shortDescription -} - -pipeline { - - agent { - label "${BUILD_SLAVES_LABEL}" - } - - options { - ansiColor('xterm') - } - - stages { - - stage ("Initial") { - steps { - echo GREEN("${getCauseDescription(currentBuild)}") - - script { - // If build is triggered by PR, use PR branch, otherwise use master - if (IS_TRIGGERED_BY_PR) { - GIT_BRANCH = env.sha1 - } else { - GIT_BRANCH = 'master' - } - } - - echo GREEN("Branch: $GIT_BRANCH") - - // Debug: print all the build envvars - // echo sh(returnStdout: true, script: 'env') - - sh "mvn --version" - } - } - - stage ("Prepare (triggered by PR)") { - when { expression { IS_TRIGGERED_BY_PR } } - steps { - echo "${GREEN('PR:')} ${ghprbPullAuthorLoginMention} ${ghprbPullLink} $ghprbPullTitle" - } - } - - stage ("Prepare (triggered by hand)") { - when { not { expression { IS_TRIGGERED_BY_PR } } } - steps { - echo GREEN("Triggered by hand, so building for master branch") - deleteDir() /* clean up workspace */ - git 'git@github.com:checkstyle/checkstyle.git' /* clone the master branch */ - } - } - - stage('Build') { - parallel { - stage('Package') { - steps { - sh "mvn -B package" - } - } - } - } - } - - post { - always { - // Clean up workspace - deleteDir() - } - } -} diff --git a/LICENSE.apache20 b/LICENSE.apache20 index d64569567334..62589edd12a3 100644 --- a/LICENSE.apache20 +++ b/LICENSE.apache20 @@ -1,7 +1,7 @@ Apache License Version 2.0, January 2004 - http://www.apache.org/licenses/ + https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION @@ -193,7 +193,7 @@ you may not use this file except in compliance with the License. You may obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, diff --git a/README.md b/README.md index ea31e6ec3abf..aba36e0bb4d0 100644 --- a/README.md +++ b/README.md @@ -1,174 +1,181 @@ -[![][travis img]][travis] +# Checkstyle - Java Code Quality Tool + +![](https://raw.githubusercontent.com/checkstyle/resources/master/img/checkstyle-logos/checkstyle-logo-260x99.png) + +-------------------------- + +*Checkstyle is a tool that ensures adherence to a code standard or a set of best practices.* + [![][appveyor img]][appveyor] -[![][teamcity img]][teamcity] [![][circleci img]][circleci] -[![][wercker img]][wercker] -[![][shippable img]][shippable] +[![][cirrusci img]][cirrusci] [![][coverage img]][coverage] [![][snyk img]][snyk] - -[![][codeship img]][codeship] +[![][semaphoreci img]][semaphoreci] +[![][azure img]][azure] +[![][error prone img]][error prone] +[![][pitest img]][pitest] +[![][checker framework img]][checker framework] [![][dependabot img]][dependabot] -[![][buddy img]][buddy] +[![][release notes/version img]][release notes/version] +[![][closed issues img]][closed issues] +[![][link check img]][link check] +[![][milestone img]][milestone] [![][mavenbadge img]][mavenbadge] -[![][sonar img]][sonar] - -Members chat: [![][gitter_mem img]][gitter_mem] -Contributors chat: [![][gitter_con img]][gitter_con] - -![](https://raw.githubusercontent.com/checkstyle/resources/master/img/checkstyle-logos/checkstyle-logo-260x99.png) - - -Checkstyle is a tool for checking Java source code for adherence to a Code Standard -or set of validation rules (best practices). The latest release version can be found at [GitHub releases](https://github.com/checkstyle/checkstyle/releases/) -or at [Maven repo](http://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/). - -Each-commit builds of maven artifacts can be found at -[Maven Snapshot repository](https://oss.sonatype.org/content/repositories/snapshots/com/puppycrawl/tools/checkstyle/) . - -Documentation is available in HTML format, see https://checkstyle.org/checks.html. - -Build instructions and Contribution -====================== - -[Build instructions](https://checkstyle.org/contributing.html#Build) - -[Setup IDE for development](https://checkstyle.org/beginning_development.html) - -[Explanation on how to create your own module](https://checkstyle.org/extending.html) - -[Verification of code quality](https://checkstyle.org/contributing.html#Quality_matters) - -[Sending Pull Request](https://checkstyle.org/contributing.html#Submitting_your_contribution) - -[Report Issue](https://checkstyle.org/contributing.html#Report_an_issue) - -Continuous integration and Quality reports -====================== -Travis (Linux & MacOS build): [![][travis img]][travis] -AppVeyor (Windows build): [![][appveyor img]][appveyor] - -Quality reports: https://checkstyle.org/project-reports.html - -JavaScript, CSS and Java source file analysis on Codacy: [![][codacy img]][codacy] - -Feedback/Support -======== - -Please send any feedback to https://groups.google.com/forum/?hl=en#!forum/checkstyle +or at [Maven repo](https://repo1.maven.org/maven2/com/puppycrawl/tools/checkstyle/). + +Documentation is available in HTML format, see https://checkstyle.org/checks.html . + +## Table of Contents + +- [Quick Start](#quick-start) +- [Contributing](#contributing) +- [Feedback and Support](#feedback-and-support) +- [Javadoc](#javadoc) +- [Sponsor Checkstyle](#sponsor-checkstyle) +- [Licensing](#licensing) + +## Quick Start + +- Download our [Latest Release](https://github.com/checkstyle/checkstyle/releases/) from GitHub + or Add Checkstyle to your build from [Maven Central](https://mvnrepository.com/artifact/com.puppycrawl.tools/checkstyle). +- Read our Documentation for [usage](https://checkstyle.org/cmdline.html) + and [configuration](https://checkstyle.org/config.html). + +```bash +$ cat config.xml + + + + + + + + +$ cat Test.java +class Test { + public void foo() { + int i = 0; + while (i >= 0) { + switch (i) { + case 1: + case 2: + i++; + case 3: // violation 'fall from previous branch of the switch' + i++; + } + } + } +} + +$ java -jar checkstyle-10.18.1-all.jar -c config.xml Test.java +Starting audit... +[ERROR] Test.java:9:9: Fall through from previous branch of switch statement [FallThrough] +Audit done. +Checkstyle ends with 1 errors. +``` + +## Contributing + +Thanks for your interest in contributing to CheckStyle! Please see the +[Contribution Guidelines](https://github.com/checkstyle/checkstyle/blob/master/.github/CONTRIBUTING.md) +for information on how to contribute to the project. This includes creating issues, submitting pull +requests, and setting up your development environment. + +## Build Instructions + +Please see the [CheckStyle Documentation](https://checkstyle.org/contributing.html#Build) for +information on how to build the project. + +## Feedback and Support + +- Visit our [Discussions Page](https://github.com/checkstyle/checkstyle/discussions), where you + can ask questions and discuss the project with other users and contributors. This is our + preferred method of communication for topics + like usage and configuration questions, debugging, and other feedback. +- [Stack Overflow](https://stackoverflow.com/questions/tagged/checkstyle) is another place to + ask questions about Checkstyle usage. +- If you are interested in contributing to the project, you can join our + [Discord Contributors Chat](https://discord.com/channels/845645228467159061/1216455699488313554) + [with invite link](https://discord.gg/FsUsYC2ura). +- Our [Google Groups Forum](https://groups.google.com/forum/?hl=en#!forum/checkstyle) is a + mailing list for discussion and support; however, we may be slow to respond there. + +## Javadoc + +Take a look at our [javadoc](https://checkstyle.org/apidocs/index.html) to see +our API documentation. + +## Sponsor Checkstyle + +Checkstyle is an open-source project that is developed and maintained by volunteers. If you +find Checkstyle useful, please consider sponsoring the project. Your support helps us to +maintain and improve Checkstyle. + +- [Liberapay](https://liberapay.com/checkstyle/) +- [OpenCollective](https://opencollective.com/checkstyle/) -Questions and Answers from community: [![][stackoverflow img]][stackoverflow] - -Bugs and Feature requests (not the questions): https://github.com/checkstyle/checkstyle/issues - - -Support/Sponsor checkstyle -======== - -If you want to speed up fixing of issue and want to encourage somebody in -internet to resolve any issue: -[![][bountysource img]][bountysource] -[![][salt.bountysource img]][salt.bountysource] -[![][flattr img]][flattr] -[![][liberapay img]][liberapay] [![][backers.opencollective img]][backers.opencollective] -[![][sponsors.opencollective img]][sponsors.opencollective] - -Licensing -========= +[![][sponsors.opencollective img]][sponsors.opencollective] -[![][license img]][license] +## Licensing -This software is licensed under the terms in the file named "LICENSE" in this -directory. +Checkstyle is licensed under the [GNU LGPL v2.1 License](LICENSE). +Checkstyle uses libraries: -The software uses the ANTLR package (https://www.antlr.org/). Its license terms -are in the file named "RIGHTS.antlr" in this directory. +- [ANTLR](https://www.antlr.org/) +- [Apache Commons](https://commons.apache.org/) +- [Google Guava](https://github.com/google/guava/) +- [Picocli](https://github.com/remkop/picocli/) -This product includes software developed by -The Apache Software Foundation (http://www.apache.org/). +## Development Tools Powered by -The software uses the Logging and Beanutils packages from the -Apache Commons project (http://commons.apache.org/). The license terms -of these packages are in the file named "LICENSE.apache20" in this -directory. +[![JetBrains logo.][jetbrains img]][jetbrains] -The software uses the Google Guava Libraries -(https://github.com/google/guava/). The license terms of -these packages are in the file named "LICENSE.apache20" in this -directory. +[![JProfiler logo.][jprofiler img]][jprofiler] -The software uses the Picocli Library -(https://github.com/remkop/picocli/). Its license terms -are in the file named "LICENSE.apache20" in this directory. +[jetbrains]:https://jb.gg/OpenSource +[jetbrains img]:https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.svg -[travis]:https://travis-ci.org/checkstyle/checkstyle/builds -[travis img]:https://travis-ci.org/checkstyle/checkstyle.svg +[jprofiler]:https://www.ej-technologies.com/jprofiler +[jprofiler img]:https://www.ej-technologies.com/images/product_banners/jprofiler_medium.png [appveyor]:https://ci.appveyor.com/project/checkstyle/checkstyle/history [appveyor img]:https://ci.appveyor.com/api/projects/status/rw6bw3dl9kph6ucc?svg=true -[sonar]:https://sonarcloud.io/dashboard?id=org.checkstyle%3Acheckstyle -[sonar img]:https://sonarcloud.io/api/project_badges/measure?project=org.checkstyle%3Acheckstyle&metric=sqale_index - -[codacy]:https://www.codacy.com/app/checkstyle/checkstyle -[codacy img]:https://api.codacy.com/project/badge/3adf12d434314ba8b38277ea46d3c44b - [coverage]:https://codecov.io/github/checkstyle/checkstyle?branch=master [coverage img]:https://codecov.io/github/checkstyle/checkstyle/coverage.svg?branch=master -[license]:LICENSE -[license img]:https://img.shields.io/badge/license-GNU%20LGPL%20v2.1-blue.svg - [mavenbadge]:https://search.maven.org/search?q=g:%22com.puppycrawl.tools%22%20AND%20a:%22checkstyle%22 [mavenbadge img]:https://img.shields.io/maven-central/v/com.puppycrawl.tools/checkstyle.svg?label=Maven%20Central -[gitter_mem]:https://gitter.im/checkstyle -[gitter_mem img]:https://img.shields.io/badge/gitter-JOIN%20CHAT-blue.svg - -[gitter_con]:https://gitter.im/checkstyle/checkstyle -[gitter_con img]:https://badges.gitter.im/Join%20Chat.svg - [stackoverflow]:https://stackoverflow.com/questions/tagged/checkstyle [stackoverflow img]:https://img.shields.io/badge/stackoverflow-CHECKSTYLE-blue.svg [teamcity]:https://teamcity.jetbrains.com/viewType.html?buildTypeId=Checkstyle_IdeaInspectionsMaster [teamcity img]:https://teamcity.jetbrains.com/app/rest/builds/buildType:(id:Checkstyle_IdeaInspectionsMaster)/statusIcon -[codeship]: https://codeship.com/projects/124310 -[codeship img]:https://codeship.com/projects/67b814a0-8fee-0133-9b59-02a170289b8c/status?branch=master - [circleci]: https://circleci.com/gh/checkstyle/checkstyle/tree/master [circleci img]: https://circleci.com/gh/checkstyle/checkstyle/tree/master.svg?style=svg -[wercker]: https://app.wercker.com/project/bykey/cd383127330ff96f89f1a78e8fd1a557 -[wercker img]: https://app.wercker.com/status/cd383127330ff96f89f1a78e8fd1a557/s/master - -[shippable]: https://app.shippable.com/projects/577032be3be4f4faa56adb38 -[shippable img]: https://img.shields.io/shippable/577032be3be4f4faa56adb38/master.svg?label=shippable - -[buddy]: https://app.buddy.works/ivanovjr/checkstyle/pipelines/pipeline/135806 -[buddy img]: https://app.buddy.works/ivanovjr/checkstyle/pipelines/pipeline/135806/badge.svg?token=240176b1ce495d0a03a141f3f2f77971f43fe892a98de31cbc0e392ce5341f76 "buddy pipeline" +[cirrusci]: https://cirrus-ci.com/github/checkstyle/checkstyle +[cirrusci img]: https://api.cirrus-ci.com/github/checkstyle/checkstyle.svg?branch=master [snyk]: https://snyk.io/test/github/checkstyle/checkstyle?targetFile=pom.xml [snyk img]: https://snyk.io/test/github/checkstyle/checkstyle/badge.svg -[flattr]:https://flattr.com/submit/auto?fid=g39d10&url=https%3A%2F%2Fcheckstyle.org -[flattr img]:https://button.flattr.com/flattr-badge-large.png +[semaphoreci]: https://checkstyle.semaphoreci.com/projects/checkstyle +[semaphoreci img]: https://checkstyle.semaphoreci.com/badges/checkstyle/branches/master.svg?style=shields -[liberapay]:https://liberapay.com/checkstyle/ -[liberapay img]:https://liberapay.com/assets/widgets/donate.svg - -[bountysource]:https://www.bountysource.com/teams/checkstyle/issues -[bountysource img]:https://api.bountysource.com/badge/team?team_id=3568&style=bounties_posted - -[salt.bountysource]:https://salt.bountysource.com/teams/checkstyle -[salt.bountysource img]:https://img.shields.io/bountysource/team/checkstyle/activity.svg?label=salt.bountysource +[azure]:https://dev.azure.com/romanivanovjr/romanivanovjr/_build/latest?definitionId=1&branchName=master +[azure img]:https://dev.azure.com/romanivanovjr/romanivanovjr/_apis/build/status/checkstyle.checkstyle?branchName=master [backers.opencollective]:https://opencollective.com/checkstyle/ [backers.opencollective img]:https://opencollective.com/checkstyle/backers/badge.svg @@ -176,5 +183,26 @@ are in the file named "LICENSE.apache20" in this directory. [sponsors.opencollective]:https://opencollective.com/checkstyle/ [sponsors.opencollective img]:https://opencollective.com/checkstyle/sponsors/badge.svg -[dependabot]:https://dependabot.com -[dependabot img]:https://api.dependabot.com/badges/status?host=github&repo=checkstyle/checkstyle +[dependabot]:https://github.com/dependabot +[dependabot img]:https://img.shields.io/badge/dependabot-025E8C?style=for-the-badge&logo=dependabot + +[closed issues]:https://github.com/checkstyle/checkstyle/actions/workflows/no-old-refs.yml +[closed issues img]:https://github.com/checkstyle/checkstyle/actions/workflows/no-old-refs.yml/badge.svg + +[release notes/version]:https://github.com/checkstyle/checkstyle/actions/workflows/releasenotes-gen.yml +[release notes/version img]:https://github.com/checkstyle/checkstyle/actions/workflows/releasenotes-gen.yml/badge.svg + +[link check]:https://github.com/checkstyle/checkstyle/actions/workflows/run-link-check.yml +[link check img]:https://github.com/checkstyle/checkstyle/actions/workflows/run-link-check.yml/badge.svg + +[error prone]:https://github.com/checkstyle/checkstyle/actions/workflows/error-prone.yml +[error prone img]:https://github.com/checkstyle/checkstyle/actions/workflows/error-prone.yml/badge.svg + +[pitest]:https://github.com/checkstyle/checkstyle/actions/workflows/pitest.yml +[pitest img]:https://github.com/checkstyle/checkstyle/actions/workflows/pitest.yml/badge.svg + +[checker framework]:https://github.com/checkstyle/checkstyle/actions/workflows/checker-framework.yml +[checker framework img]:https://github.com/checkstyle/checkstyle/actions/workflows/checker-framework.yml/badge.svg + +[milestone]:https://github.com/checkstyle/checkstyle/actions/workflows/set-milestone-on-referenced-issue.yml +[milestone img]:https://github.com/checkstyle/checkstyle/actions/workflows/set-milestone-on-referenced-issue.yml/badge.svg diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000000..9a11d82fd673 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,25 @@ +# Security Policy + +## Supported Versions + +We do not support any old versions, all updates for bugs/features/security +will be released in next planned version. + +| Version | Supported | +|-------------|--------------------| +| LATEST only | :white_check_mark: | + +## Reporting a Vulnerability + +List of maintainers: https://checkstyle.org/team.html +Mail-list for any questions: https://checkstyle.org/mailing-lists.html +You can find admin emails in mail-list. +You can find emails of maintainers in commits, you can clone our repo and see it by "git log". + +If we are not responding, please keep pining us. As final resort, create an issue at +https://github.com/checkstyle/checkstyle/issues with a note that you have a security issue. + +If the vulnerability is accepted, we will create an issue (without much details) +on GitHub Issue tracker and we put label "approved" on it. +If the vulnerability is declined, we can keep it private +or if you would like to keep record of it in issue tracker, you can do this also. diff --git a/appveyor.yml b/appveyor.yml index 02cfdfca998d..353ddf0b6612 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,4 @@ -os: Windows Server 2012 +image: Visual Studio 2019 version: '{build}' skip_tags: true @@ -8,25 +8,15 @@ branches: - master except: - gh-pages + install: - - ps: | - Add-Type -AssemblyName System.IO.Compression.FileSystem - if (!(Test-Path -Path "C:\maven\apache-maven-3.2.5" )) { - (new-object System.Net.WebClient).DownloadFile( - 'http://www.us.apache.org/dist/maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.zip', - 'C:\maven-bin.zip' - ) - [System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven") - } - - cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5 - - cmd: SET PATH=%M2_HOME%\bin;%JAVA_HOME%\bin;%PATH% - cmd: git config core.autocrlf - - cmd: mvn --version + - cmd: .\mvnw.cmd --version - cmd: java -version cache: - - C:\maven\apache-maven-3.2.5 - C:\Users\appveyor\.m2 + - .mvn\wrapper matrix: fast_finish: true @@ -34,37 +24,25 @@ matrix: environment: global: CMD: " " - # We do matrix as AppVeyor could fail to finish simple "mvn verify" - # if he loose maven cache (happens from time to time) + # https://stackoverflow.com/questions/42024619/maven-build-gets-connection-reset-when-downloading-artifacts + MAVEN_OPTS: "-Dhttp.keepAlive=false -Dmaven.wagon.http.retryHandler.count=3" matrix: - # checkstyle and sevntu.checkstyle - - JAVA_HOME: C:\Program Files\Java\jdk1.8.0 - DESC: "checkstyle and sevntu.checkstyle" - CMD: "./.ci/appveyor.bat sevntu" - # verify without checkstyle (JDK8) - - JAVA_HOME: C:\Program Files\Java\jdk1.8.0 - DESC: "verify without checkstyle (JDK8)" - CMD: "./.ci/appveyor.bat verify_without_checkstyle" - # verify without checkstyle (JDK11) - - JAVA_HOME: C:\Program Files\Java\jdk11 - DESC: "verify without checkstyle (JDK11)" - CMD: "./.ci/appveyor.bat verify_without_checkstyle_JDK11" - # verify without checkstyle (JDK13) - - JAVA_HOME: C:\Program Files\Java\jdk13 - DESC: "verify without checkstyle (JDK13)" - CMD: "./.ci/appveyor.bat verify_without_checkstyle_JDK13" - # site, without verify (JDK8) - - JAVA_HOME: C:\Program Files\Java\jdk1.8.0 - DESC: "site, without verify (JDK8)" - CMD: "./.ci/appveyor.bat site_without_verify" - # site, without verify (JDK11) - - JAVA_HOME: C:\Program Files\Java\jdk11 - DESC: "site, without verify (JDK11)" - CMD: "./.ci/appveyor.bat site_without_verify" - # site, without verify (JDK13) - - JAVA_HOME: C:\Program Files\Java\jdk13 - DESC: "site, without verify (JDK13)" - CMD: "./.ci/appveyor.bat site_without_verify" + # sevntu (JDK21) + - JAVA_HOME: C:\Program Files\Java\JDK21 + DESC: "sevntu (JDK21)" + CMD: "./.ci/validation.cmd sevntu" + # run checkstyle (JDK21) + - JAVA_HOME: C:\Program Files\Java\JDK21 + DESC: "run checkstyle (JDK21)" + CMD: "./.ci/validation.cmd run_checkstyle" + # verify without checkstyle (JDK21) + - JAVA_HOME: C:\Program Files\Java\JDK21 + DESC: "verify without checkstyle (JDK21)" + CMD: "./.ci/validation.cmd verify_without_checkstyle" + # site, without verify (JDK21) + - JAVA_HOME: C:\Program Files\Java\JDK21 + DESC: "site, without verify (JDK21)" + CMD: "./.ci/validation.cmd site_without_verify" build_script: - ps: | @@ -80,6 +58,6 @@ build_script: } else { Write-Host "build is skipped ..." } + - ps: ./.ci/validation.cmd git_diff - ps: echo "Size of caches (bytes):" - - ps: Get-ChildItem -Recurse 'C:\maven\apache-maven-3.2.5' | Measure-Object -Property Length -Sum - ps: Get-ChildItem -Recurse 'C:\Users\appveyor\.m2' | Measure-Object -Property Length -Sum diff --git a/azure-pipelines.yml b/azure-pipelines.yml new file mode 100644 index 000000000000..d51b61415941 --- /dev/null +++ b/azure-pipelines.yml @@ -0,0 +1,171 @@ +# Maven +# Build your Java project and run tests with Apache Maven. +# Add steps that analyze code, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/languages/java + +schedules: + - cron: "1 0 * * 0" + displayName: Weekly weekend build + branches: + include: + - master + +trigger: + - master + +pr: + - master + +strategy: + matrix: + # testing age of pr + 'pr-age': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh pr-age" + skipCache: true + + # spelling + 'spelling': + image: 'ubuntu-24.04' + cmd: "./.ci/test-spelling-unknown-words.sh" + skipCache: true + + # unit tests (openjdk21) + 'test': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test" + + # unit tests in German locale (openjdk21) + 'test-de': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-de" + + # unit tests in Spanish locale (openjdk21) + 'test-es': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-es" + + # unit tests in Finnish locale (openjdk21) + 'test-fi': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-fi" + + # unit tests in French locale (openjdk21) + 'test-fr': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-fr" + + # unit tests in Chinese locale (openjdk21) + 'test-zh': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-zh" + + # unit tests in Japanese locale (openjdk21) + 'test-ja': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-ja" + + # unit tests in Portuguese locale (openjdk21) + 'test-pt': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-pt" + + # unit tests in Turkish locale (openjdk21) + 'test-tr': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-tr" + + # unit tests in Russian locale (openjdk21) + 'test-ru': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-ru" + + # unit tests in Albanian locale (openjdk21) + 'test-al': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh test-al" + + # OpenJDK21 verify + 'OpenJDK21 verify': + image: 'ubuntu-24.04' + cmd: "./mvnw -e --no-transfer-progress verify" + + # MacOS JDK21 verify + 'MacOS JDK21 verify': + image: 'macOS-14' + cmd: "JAVA_HOME=$JAVA_HOME_21_X64 ./mvnw -e --no-transfer-progress verify" + + # versions to update + 'versions': + image: 'ubuntu-24.04' + cmd: "./.ci/validation.sh versions" + onCronOnly: true + + # lint for .md files, OSX is used because there is problem to install gem on linux + 'markdownlint': + image: 'macOS-14' + cmd: "./.ci/validation.sh markdownlint" + skipCache: true + needMdl: true + +pool: + vmImage: $(image) + +variables: + MAVEN_CACHE_FOLDER: $(Pipeline.Workspace)/.m2/repository + MAVEN_OPTS: '--show-version -Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' + SKIP_CACHE: $(skipCache) + IMAGE: $(image) + ON_CRON_ONLY: $(onCronOnly) + NEED_XMLSTARLET: $(needXmlstarlet) + NEED_MDL: $(needMdl) + BUILD_REASON: $[variables['Build.Reason']] + +steps: + - bash: | + apt-fast install -y xmlstarlet + condition: | + and( + ne(variables['Agent.OS'], 'Darwin'), + eq(variables.NEED_XMLSTARLET, 'true') + ) + + - bash: | + gem install mdl + condition: eq(variables.NEED_MDL, 'true') + + - task: JavaToolInstaller@0 + inputs: + versionSpec: 21 + jdkArchitectureOption: 'X64' + jdkSourceOption: 'PreInstalled' + + - task: Cache@2 + inputs: + key: 'maven | "$(Agent.OS)" | **/pom.xml' + restoreKeys: | + maven | "$(Agent.OS)" + maven + path: | + $(MAVEN_CACHE_FOLDER) + .mvn/wrapper + displayName: Cache Maven local repo and wrapper + condition: ne(variables.SKIP_CACHE, 'true') + + - bash: | + set -e + ./mvnw --version + echo "ON_CRON_ONLY:"$ON_CRON_ONLY + echo "BUILD_REASON:"$BUILD_REASON + echo "cmd: "$(cmd) + eval "$(cmd)" + ./.ci/validation.sh git-diff + ./.ci/validation.sh ci-temp-check + condition: | + or ( + ne(variables.ON_CRON_ONLY, 'true'), + and( + eq(variables.ON_CRON_ONLY, 'true'), + eq(variables['Build.Reason'], 'Schedule') + ) + ) diff --git a/buddy.yml b/buddy.yml deleted file mode 100644 index 288efeae1466..000000000000 --- a/buddy.yml +++ /dev/null @@ -1,76 +0,0 @@ -- pipeline: "versions" - trigger_mode: "ON_EVERY_PUSH" - ref_name: "master" - ref_type: "BRANCH" - actions: - - action: "Execute: ./.ci/travis/travis.sh versions" - type: "BUILD" - working_directory: "/buddy/checkstyle" - docker_image_name: "library/maven" - docker_image_tag: "3.3.3" - execute_commands: - - "./.ci/travis/travis.sh versions" - cached_dirs: - - "/root/.m2/repository" - mount_filesystem_path: "/buddy/checkstyle" - shell: "BASH" - trigger_condition: "ALWAYS" - -- pipeline: "releasenotes-gen" - trigger_mode: "ON_EVERY_PUSH" - ref_name: "master" - ref_type: "BRANCH" - actions: - - action: "Execute: ./.ci/travis/travis.sh releasenotes-gen" - type: "BUILD" - working_directory: "/buddy/checkstyle" - docker_image_name: "checkstyle/maven-builder-image" - docker_image_tag: "latest" - execute_commands: - - "export TRAVIS_PULL_REQUEST=master" - - "./.ci/travis/travis.sh releasenotes-gen" - cached_dirs: - - "/buddy/checkstyle/.m2" - mount_filesystem_path: "/buddy/checkstyle" - shell: "BASH" - trigger_condition: "ALWAYS" - -# - pipeline: "check-chmod" -# trigger_mode: "ON_EVERY_PUSH" -# ref_name: "master" -# ref_type: "BRANCH" -# actions: -# - action: "Execute: ./.ci/travis/travis.sh check-chmod" -# type: "BUILD" -# working_directory: "/buddy/checkstyle" -# docker_image_name: "checkstyle/maven-builder-image" -# docker_image_tag: "latest" -# execute_commands: -# - "ls -la" -# # "find: unrecognized: -executable" -# #- "./.ci/travis/travis.sh check-chmod" -# cached_dirs: -# - "/buddy/checkstyle/.m2" -# mount_filesystem_path: "/buddy/checkstyle" -# shell: "BASH" -# trigger_condition: "ALWAYS" - -# - pipeline: "spell checker" -# trigger_mode: "ON_EVERY_PUSH" -# ref_name: "master" -# ref_type: "BRANCH" -# actions: -# - action: "Execute: ./.ci/test-spelling-unknown-words.sh" -# type: "BUILD" -# working_directory: "/buddy/checkstyle" -# docker_image_name: "checkstyle/maven-builder-image" -# docker_image_tag: "latest" -# execute_commands: -# - "ls -la" -# # "perl,unxz not found" -# #- "./.ci/test-spelling-unknown-words.sh" -# cached_dirs: -# - "/buddy/checkstyle/.m2" -# mount_filesystem_path: "/buddy/checkstyle" -# shell: "BASH" -# trigger_condition: "ALWAYS" diff --git a/cdg-pitest-licence.txt b/cdg-pitest-licence.txt new file mode 100644 index 000000000000..62cdb43ba32a --- /dev/null +++ b/cdg-pitest-licence.txt @@ -0,0 +1,7 @@ +#Licence file for pitest extensions +#Sun Jul 14 10:23:06 BST 2024 +expires=14/07/2027 +keyVersion=1 +packages=com.puppycrawl.tools.checkstyle.* +signature=Ls/M9iIyyhZMIneDBFLvafXWNzQxDW0BZb7flHoRpETrI16BU417Vyxg3Wi2wjItk9bhjf2pAQttctSH7XBE4MM3qtxr9VUZWljPjF1Mxn9REzWqs+Uj2SZ/ZLntA2nWURtM+/3XGudKequ6r3kDmtdcpSPg3WNffEjEGTkWtIo\= +type=OSSS diff --git a/codeship-services.yml b/codeship-services.yml deleted file mode 100644 index e903a0c71c5a..000000000000 --- a/codeship-services.yml +++ /dev/null @@ -1,4 +0,0 @@ -system: - image: checkstyle/maven-builder-image:latest - volumes: - - .:/usr/local/checkstyle diff --git a/codeship-steps.yml b/codeship-steps.yml deleted file mode 100644 index bf5a81dfe545..000000000000 --- a/codeship-steps.yml +++ /dev/null @@ -1,10 +0,0 @@ -- type: parallel - # Codeship does not support PR from fork, it supports only builds of branches - # so to keep running validation at least from main repo branches we should not define tag - #tag: master - service: system - steps: - #- command: ./.ci/travis/travis.sh site - #- command: ./.ci/travis/travis.sh nondex - - command: ls -la - - command: .ci/run-link-check-plugin.sh diff --git a/config/ant-phase-verify-sevntu.xml b/config/ant-phase-verify-sevntu.xml new file mode 100644 index 000000000000..68c8631dd96c --- /dev/null +++ b/config/ant-phase-verify-sevntu.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + Checkstyle started (${check.config}): ${STARTED} + + + + + + + + + + + + Checkstyle finished (${check.config}): ${FINISHED} + + + + diff --git a/config/ant-phase-verify.xml b/config/ant-phase-verify.xml index 59a6e40058bd..0e3c6f6237f2 100644 --- a/config/ant-phase-verify.xml +++ b/config/ant-phase-verify.xml @@ -1,28 +1,35 @@ - - - + + + + + + + - + - - + + location="config/checkstyle-non-main-files-checks.xml"/> + location="config/checkstyle-resources-checks.xml"/> + + - Checkstyle started (checkstyle_checks.xml): ${STARTED} + Checkstyle started (checkstyle-checks.xml): ${STARTED} + test/resources/**/*,test/resources-noncompilable/**/*,**/gen/**, + xdocs-examples/resources/**/*,xdocs-examples/resources-noncompilable/**/*"/> - + - + + - Checkstyle finished (checkstyle_checks.xml) : ${FINISHED} + Checkstyle finished (checkstyle-checks.xml): ${FINISHED} - Checkstyle started (checkstyle_non_main_files_checks.xml): ${STARTED} + Checkstyle started (checkstyle-non-main-files-checks.xml): ${STARTED} + + + + @@ -92,6 +107,11 @@ + + + + + @@ -114,22 +134,28 @@ + + + + + + - - Checkstyle finished (checkstyle_non_main_files_checks.xml): ${FINISHED} + Checkstyle finished (checkstyle-non-main-files-checks.xml): ${FINISHED} + - Checkstyle started (checkstyle_resources_checks.xml): ${STARTED} + Checkstyle started (checkstyle-resources-checks.xml): ${STARTED} - - - - - - - - + + + + + + + + + + + + + - - Checkstyle finished (checkstyle_resources_checks.xml): ${FINISHED} + Checkstyle finished (checkstyle-resources-checks.xml): ${FINISHED} + + + + + Checkstyle started (checkstyle-input-checks.xml): ${STARTED} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Checkstyle finished (checkstyle-input-checks.xml): ${FINISHED} + + + + + + + Checkstyle started (checkstyle-examples-checks.xml): ${STARTED} + + + + + + + + + + + + + + + Checkstyle finished (checkstyle-examples-checks.xml): ${FINISHED} diff --git a/config/assembly-bin.xml b/config/assembly-bin.xml index ba6bf794754b..32515c1a3aa9 100644 --- a/config/assembly-bin.xml +++ b/config/assembly-bin.xml @@ -2,7 +2,7 @@ bin @@ -19,10 +19,6 @@ true - config/checkstyle_checks.xml - config/import-control.xml - config/suppressions.xml - config/java.header LICENSE* README RIGHTS.antlr diff --git a/config/assembly-src.xml b/config/assembly-src.xml index 15584109778e..03d483b8c696 100644 --- a/config/assembly-src.xml +++ b/config/assembly-src.xml @@ -2,7 +2,7 @@ src @@ -15,9 +15,6 @@ true target/** - *.launch - nbactions.xml - lib/** diff --git a/config/benchmark-config.xml b/config/benchmark-config.xml new file mode 100644 index 000000000000..eaf42a71e7e3 --- /dev/null +++ b/config/benchmark-config.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + diff --git a/config/benchmark-javadoc-config.xml b/config/benchmark-javadoc-config.xml new file mode 100644 index 000000000000..b877a8cda06d --- /dev/null +++ b/config/benchmark-javadoc-config.xml @@ -0,0 +1,11 @@ + + + + + + + + + + diff --git a/config/checker-framework-suppressions/checker-formatter-suppressions.xml b/config/checker-framework-suppressions/checker-formatter-suppressions.xml new file mode 100644 index 000000000000..91ad94ff6cc1 --- /dev/null +++ b/config/checker-framework-suppressions/checker-formatter-suppressions.xml @@ -0,0 +1,23 @@ + + + + src/main/java/com/puppycrawl/tools/checkstyle/LocalizedMessage.java + i18nformat.key.not.found + a key doesn't exist in the provided translation file + final String pattern = resourceBundle.getString(key); + + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + i18nformat.key.not.found + a key doesn't exist in the provided translation file + result.put(key, bundle.getString(key)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + i18nformat.key.not.found + a key doesn't exist in the provided translation file + return bundle.getString(name); + + diff --git a/config/checker-framework-suppressions/checker-index-suppressions.xml b/config/checker-framework-suppressions/checker-index-suppressions.xml new file mode 100644 index 000000000000..3cdb8beade56 --- /dev/null +++ b/config/checker-framework-suppressions/checker-index-suppressions.xml @@ -0,0 +1,2888 @@ + + + + src/main/java/com/puppycrawl/tools/checkstyle/AstTreeStringPrinter.java + argument + incompatible argument for parameter arg1 of String.substring. + baseIndentation = baseIndentation.substring(0, baseIndentation.length() - 2); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return getBranchTokenTypes().get(tokenType); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + argument + incompatible argument for parameter arg0 of BitSet.set. + branchTokenTypes.set(type); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final String ruleName = recognizer.getRuleNames()[ruleIndex]; +
    + found : int + required: @IndexFor("recognizer.getRuleNames()") or @LTLengthOf("recognizer.getRuleNames()") -- an integer less than recognizer.getRuleNames()'s length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final String ruleName = recognizer.getRuleNames()[ruleIndex]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + argument + incompatible argument for parameter arg1 of String.substring. + final String packageName = fullQualifiedName.substring(0, lastDot); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (ent.charAt(0) == '&' && ent.endsWith(";")) { +
    + found : @UpperBoundLiteral(0) int + required: @LTLengthOf("ent") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (ent.charAt(1) == '#') { +
    + found : @UpperBoundLiteral(1) int + required: @LTLengthOf("ent") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (ent.charAt(2) == 'x') { +
    + found : @UpperBoundLiteral(2) int + required: @LTLengthOf("ent") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java + argument + incompatible argument for parameter arg0 of String.substring. + ent.substring(prefixLength, ent.length() - 1), radix); +
    + found : int + required: @LTEqLengthOf("ent") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + getLines()[ast.getLineNo() - 1], ast.getColumnNo(), tabWidth); +
    + found : int + required: @IndexFor("this.getLines()") or @LTLengthOf("this.getLines()") -- an integer less than this.getLines()'s length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + getLines()[lineNo - 1], colNo, tabWidth); +
    + found : int + required: @IndexFor("this.getLines()") or @LTLengthOf("this.getLines()") -- an integer less than this.getLines()'s length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + getLines()[ast.getLineNo() - 1], ast.getColumnNo(), tabWidth); +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + getLines()[lineNo - 1], colNo, tabWidth); +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg0 of String.substring. + final String[] txt = {line.substring(startColNo)}; +
    + found : int + required: @LTEqLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg0 of String.substring. + returnValue[0] = line(startLineNo - 1).substring(startColNo); +
    + found : int + required: @LTEqLengthOf("this.line(startLineNo - 1)") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg0 of String.substring. + returnValue[0] = line(startLineNo - 1).substring(startColNo, +
    + found : int + required: @LTEqLengthOf("this.line(startLineNo - 1)") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg0 of String.substring. + final String[] txt = {line.substring(startColNo)}; +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg0 of String.substring. + returnValue[0] = line(startLineNo - 1).substring(startColNo); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg0 of String.substring. + returnValue[0] = line(startLineNo - 1).substring(startColNo, +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg1 of String.substring. + endColNo + 1); +
    + found : int + required: @LTEqLengthOf("this.line(endLineNo - 1)") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg1 of String.substring. + endColNo + 1); +
    + found : int + required: @LTEqLengthOf("this.line(startLineNo - 1)") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg1 of String.substring. + endColNo + 1); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + argument + incompatible argument for parameter arg1 of String.substring. + endColNo + 1); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + returnValue[i - startLineNo + 1] = line(i); +
    + found : int + required: @IndexFor("returnValue") or @LTLengthOf("returnValue") -- an integer less than returnValue's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + returnValue[0] = line(startLineNo - 1).substring(startColNo); +
    + found : String [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + returnValue[returnValue.length - 1] = line(endLineNo - 1).substring(0, +
    + found : @GTENegativeOne int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + returnValue[i - startLineNo + 1] = line(i); +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + array.length.negative + Variable used in array creation could be negative. + returnValue = new String[endLineNo - startLineNo + 1]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final int startOfLine = lineBreakPositions[lineNo]; +
    + found : int + required: @IndexFor("lineBreakPositions") or @LTLengthOf("lineBreakPositions") -- an integer less than lineBreakPositions's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + lineBreakPositions[lineNo] = matcher.end(); +
    + found : int + required: @IndexFor("lineBreakPositions") or @LTLengthOf("lineBreakPositions") -- an integer less than lineBreakPositions's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + return lines[lineNo]; +
    + found : int + required: @IndexFor("this.lines") or @LTLengthOf("this.lines") -- an integer less than this.lines's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + lineBreakPositions[0] = 0; +
    + found : int [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final int startOfLine = lineBreakPositions[lineNo]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + return lines[lineNo]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + array.length.negative + Variable used in array creation could be negative. + final int[] lineBreakPositions = new int[size() + 1]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + comment.getEndColNo() + 1, codePoints.length)); +
    + found : int + required: @LTEqLengthOf("codePoints") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + comment.getEndColNo() + 1, codePoints.length)); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final int tokenCount = counts[element - 1]; +
    + found : int + required: @IndexFor("this.counts") or @LTLengthOf("this.counts") -- an integer less than this.counts's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + total += counts[element - 1]; +
    + found : int + required: @IndexFor("this.counts") or @LTLengthOf("this.counts") -- an integer less than this.counts's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + counts[type - 1]++; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final int tokenCount = counts[element - 1]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + total += counts[element - 1]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + && primitiveDataTypes.get(parameterType.getType())) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheck.java + argument + incompatible argument for parameter arg0 of RandomAccessFile.seek. + file.seek(file.length() - len); +
    + found : long + required: @NonNegative long +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheck.java + array.length.negative + Variable used in array creation could be negative. + final byte[] lastBytes = new byte[len]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolder.java + argument + incompatible argument for parameter arg0 of String.substring. + yield quotedText.substring(1, quotedText.length() - 1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("quotedText") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolder.java + argument + incompatible argument for parameter arg1 of String.substring. + yield quotedText.substring(1, quotedText.length() - 1); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolder.java + argument + incompatible argument for parameter arg1 of String.substring. + return sourceNameLower.substring(startIndex, endIndex); +
    + found : @LTEqLengthOf("sourceName") int + required: @LTEqLengthOf("sourceNameLower") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolder.java + argument + incompatible argument for parameter arg1 of String.substring. + return sourceNameLower.substring(startIndex, endIndex); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + lastChild.getColumnNo() + 2, lineCodePoints.length); +
    + found : int + required: @LTEqLengthOf("lineCodePoints") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + lastChild.getColumnNo() + 2, lineCodePoints.length); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + final String removePattern = regexp.substring("^.+".length()); +
    + found : @LTEqLengthOf(""^.+"") int + required: @LTEqLengthOf("regexp") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + .substring(0, fileNameWithPath.lastIndexOf(File.separator)); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/MissingDeprecatedCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + if (TYPES_HASH_SET.get(type)) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + return warning.substring(1, warning.length() - 1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("warning") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + return warning.substring(1, warning.length() - 1); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + slistColNo + 1, codePointsFirstLine.length); +
    + found : int + required: @LTEqLengthOf("codePointsFirstLine") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + slistColNo + 1, rcurlyColNo); +
    + found : int + required: @LTEqLengthOf("this.getLineCodePoints(slistLineNo - 1)") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + slistColNo + 1, codePointsFirstLine.length); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + slistColNo + 1, rcurlyColNo); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + || braceLine.charAt(brace.getColumnNo() + 1) != '}') { +
    + found : int + required: @LTLengthOf("braceLine") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + || braceLine.charAt(brace.getColumnNo() + 1) != '}') { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + token -> !IGNORED_TYPES.get(token.getType()); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return ASSIGN_OPERATOR_TYPES.get(parentType); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return LOOP_TYPES.get(ast); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (name.length() == 1 || !Character.isUpperCase(name.charAt(1))) { +
    + found : @UpperBoundLiteral(1) int + required: @LTLengthOf("name") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + setterName = name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("name") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + setterName = name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("name") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + && illegal.charAt(pkgNameLen) == '.' +
    + found : int + required: @LTLengthOf("illegal") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + && illegal.charAt(pkgNameLen) == '.' +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + if (memberModifiers.get(modifier.getType())) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/InnerAssignmentCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return COMPARISON_TYPES.get(astType); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/InnerAssignmentCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + while (skipTokens.get(result.getType())) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + if (!constantWaiverParentToken.get(type)) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return MUTATION_OPERATIONS.get(iteratingExpressionAST.getType()); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + if (ignoreOccurrenceContext.get(type)) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheck.java + argument + incompatible argument for parameter arg0 of BitSet.set. + ignoreOccurrenceContext.set(type); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/PackageDeclarationCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + return fileName.substring(0, lastSeparatorPos); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return ASSIGN_TOKENS.get(tokenType); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return COMPOUND_ASSIGN_TOKENS.get(tokenType); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DECLARATION_TOKENS.get(parentType); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/InnerTypeLastCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + && CLASS_MEMBER_TOKENS.get(nextSibling.getType())) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return ignoreLines.get(lineNo); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/RegexpHeaderCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return multiLines.get(lineNo + 1); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/AvoidStaticImportCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + excludeMinusDotStar.length() + 1); +
    + found : @LTLengthOf(value={"exclude.substring(0, exclude.length() - 2)", "excludeMinusDotStar"}, offset={"-2", "-2"}) int + required: @LTEqLengthOf("classOrStaticMember") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + ruleStr.indexOf(')')); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final String import1Token = import1Tokens[i]; +
    + found : int + required: @IndexFor("import1Tokens") or @LTLengthOf("import1Tokens") -- an integer less than import1Tokens's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final String import2Token = import2Tokens[i]; +
    + found : int + required: @IndexFor("import2Tokens") or @LTLengthOf("import2Tokens") -- an integer less than import2Tokens's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + if (CommonUtil.isBlank(lines[i - 1])) { +
    + found : int + required: @IndexFor("lines") or @LTLengthOf("lines") -- an integer less than lines's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + if (CommonUtil.isBlank(lines[i - 1])) { +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + return qualifiedImportName.substring(0, lastDotIndex); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + argument + incompatible argument for parameter arg0 of String.charAt. + && (pkg.length() == length || pkg.charAt(length) == '.'); +
    + found : @LTEqLengthOf("this.fullPackageName") int + required: @LTLengthOf("pkg") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/RedundantImportCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + final String front = importName.substring(0, index); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.java + return + incompatible types in return. + return methodIndex; +
    + type of expression: int + method return type: @LTLengthOf("input") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AbstractExpressionHandler.java + argument + incompatible argument for parameter arg0 of String.charAt. + while (Character.isWhitespace(line.charAt(index))) { +
    + found : int + required: @LTLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AnnotationArrayInitHandler.java + argument + incompatible argument for parameter arg0 of String.charAt. + && Character.isWhitespace(line.charAt(realColumnNo))) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AnnotationArrayInitHandler.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final String line = getIndentCheck().getLines()[lineNo - 1]; +
    + found : int + required: @IndexFor("this.getIndentCheck().getLines()") or @LTLengthOf("this.getIndentCheck().getLines()") -- an integer less than this.getIndentCheck().getLines()'s length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AnnotationArrayInitHandler.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final String line = getIndentCheck().getLines()[lineNo - 1]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ArrayInitHandler.java + argument + incompatible argument for parameter arg0 of String.charAt. + && Character.isWhitespace(line.charAt(realColumnNo))) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ArrayInitHandler.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final String line = getIndentCheck().getLines()[lineNo - 1]; +
    + found : int + required: @IndexFor("this.getIndentCheck().getLines()") or @LTLengthOf("this.getIndentCheck().getLines()") -- an integer less than this.getIndentCheck().getLines()'s length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ArrayInitHandler.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final String line = getIndentCheck().getLines()[lineNo - 1]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + while (Character.isWhitespace(line[lineStart])) { +
    + found : int + required: @IndexFor("line") or @LTLengthOf("line") -- an integer less than line's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final char[] line = getLines()[lineNo - 1].toCharArray(); +
    + found : int + required: @IndexFor("this.getLines()") or @LTLengthOf("this.getLines()") -- an integer less than this.getLines()'s length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + array.access.unsafe.high.range + Potentially unsafe array access: the index could be larger than the array's bound + if (CommonUtil.isBlank(lines[lineNo])) { +
    + index type found: @IntRange(from=-2147483648, to=2147483646) int + array type found: String [] + required : index of type @IndexFor("lines") or @LTLengthOf("lines"), or array of type @MinLen(2147483647) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final char[] line = getLines()[lineNo - 1].toCharArray(); +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + if (CommonUtil.isBlank(lines[lineNo])) { +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + types[index] = val; +
    + found : int + required: @IndexFor("types") or @LTLengthOf("types") -- an integer less than types's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return levels.get(indent); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.java + argument + incompatible argument for parameter arg0 of BitSet.set. + levels.set(i + offset); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.java + argument + incompatible argument for parameter arg0 of BitSet.set. + levels.set(indent); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.java + argument + incompatible argument for parameter arg0 of BitSet.set. + result.levels.set(addition); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.java + argument + incompatible argument for parameter arg0 of String.charAt. + while (Character.isWhitespace(line.charAt(index))) { +
    + found : int + required: @LTLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SlistHandler.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return PARENT_TOKEN_TYPES.get(parentType); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AtclauseOrderCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + if (target.get(parentType)) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/HtmlTag.java + argument + incompatible argument for parameter arg0 of String.charAt. + return position != text.length() - 1 && text.charAt(position + 1) == '/'; +
    + found : int + required: @LTLengthOf("this.text") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/HtmlTag.java + argument + incompatible argument for parameter arg0 of String.charAt. + return position != text.length() - 1 && text.charAt(position + 1) == '/'; +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/HtmlTag.java + argument + incompatible argument for parameter arg0 of String.substring. + return text.substring(startOfText, endOfText); +
    + found : int + required: @LTEqLengthOf("this.text") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/HtmlTag.java + argument + incompatible argument for parameter arg0 of String.substring. + return text.substring(startOfText, endOfText); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/HtmlTag.java + argument + incompatible argument for parameter arg1 of String.substring. + return text.substring(startOfText, endOfText); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocLeadingAsteriskAlignCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final String lastLine = fileLines[javadocEndToken.getLineNo() - 1]; +
    + found : int + required: @IndexFor("this.fileLines") or @LTLengthOf("this.fileLines") -- an integer less than this.fileLines's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocLeadingAsteriskAlignCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final String startLine = fileLines[rootAst.getLineNumber() - 1]; +
    + found : int + required: @IndexFor("this.fileLines") or @LTLengthOf("this.fileLines") -- an integer less than this.fileLines's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocLeadingAsteriskAlignCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final String lastLine = fileLines[javadocEndToken.getLineNo() - 1]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocLeadingAsteriskAlignCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final String startLine = fileLines[rootAst.getLineNumber() - 1]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + multilineCont = MATCH_JAVADOC_MULTILINE_CONT.matcher(lines[remIndex]); +
    + found : int + required: @IndexFor("lines") or @LTLengthOf("lines") -- an integer less than lines's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + multilineCont = MATCH_JAVADOC_MULTILINE_CONT.matcher(lines[remIndex]); +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMissingWhitespaceAfterAsteriskCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + && !Character.isWhitespace(text.charAt(lastAsteriskPosition + 1))) { +
    + found : int + required: @LTLengthOf("text") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMissingWhitespaceAfterAsteriskCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + && !Character.isWhitespace(text.charAt(lastAsteriskPosition + 1))) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + argument + incompatible argument for parameter arg0 of AbstractStringBuilder.charAt. + if (Character.isWhitespace(builder.charAt(index))) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + argument + incompatible argument for parameter arg0 of AbstractStringBuilder.charAt. + while (builder.charAt(index - 1) == '*') { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (line.charAt(textStart) == '@') { +
    + found : int + required: @LTLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (line.charAt(textStart) == '@') { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + builder.append(line.substring(textStart)); +
    + found : int + required: @LTEqLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + builder.append(line.substring(textStart)); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + argument + incompatible argument for parameter arg0 of StringBuilder.deleteCharAt. + builder.deleteCharAt(index - 1); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + argument + incompatible argument for parameter arg0 of StringBuilder.deleteCharAt. + builder.deleteCharAt(index); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + text[tag.getLineNo() - lineNo]); +
    + found : int + required: @IndexFor("text") or @LTLengthOf("text") -- an integer less than text's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + text[tag.getLineNo() - lineNo]); +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagContinuationIndentationCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + else if (!CommonUtil.isBlank(text.substring(1, offset + 1))) { +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("text") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagContinuationIndentationCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + else if (!CommonUtil.isBlank(text.substring(1, offset + 1))) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return DEF_TOKEN_TYPES_DEPRECATED.get(astType) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg0 of String.charAt. + && text[curr.lineNo()].charAt(curr.columnNo()) != character) { +
    + found : int + required: @LTLengthOf("text[curr.lineNo()]") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg0 of String.charAt. + .charAt(endTag.columnNo() - 1) == '/'; +
    + found : int + required: @LTLengthOf("text[endTag.lineNo()]") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg0 of String.charAt. + && text[curr.lineNo()].charAt(curr.columnNo()) != character) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg0 of String.charAt. + .charAt(endTag.columnNo() - 1) == '/'; +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (text.charAt(column) == '/') { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg0 of String.charAt. + || Character.isJavaIdentifierStart(text.charAt(column)) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg0 of String.charAt. + || text.charAt(column) == '/'; +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg0 of String.substring. + text = text.substring(column); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg1 of String.substring. + tagId = text.substring(0, position); +
    + found : int + required: @LTEqLengthOf("text") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg1 of String.substring. + .substring(0, toPoint.columnNo() + 1).endsWith("-->")) { +
    + found : int + required: @LTEqLengthOf("text[toPoint.lineNo()]") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + argument + incompatible argument for parameter arg1 of String.substring. + .substring(0, toPoint.columnNo() + 1).endsWith("-->")) { +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + String text = javadocText[tagStart.lineNo()]; +
    + found : int + required: @IndexFor("javadocText") or @LTLengthOf("javadocText") -- an integer less than javadocText's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final String text = javadocText[pos.lineNo()]; +
    + found : int + required: @IndexFor("javadocText") or @LTLengthOf("javadocText") -- an integer less than javadocText's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + return text[pos.lineNo()].startsWith("<!--", pos.columnNo()); +
    + found : int + required: @IndexFor("text") or @LTLengthOf("text") -- an integer less than text's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + text[position.lineNo()])); +
    + found : int + required: @IndexFor("text") or @LTLengthOf("text") -- an integer less than text's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.high.range + Potentially unsafe array access: the index could be larger than the array's bound + && text[endTag.lineNo()] +
    + index type found: @IntRange(from=-2147483648, to=2147483646) int + array type found: String [] + required : index of type @IndexFor("text") or @LTLengthOf("text"), or array of type @MinLen(2147483647) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + && text[curr.lineNo()].charAt(curr.columnNo()) != character) { +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + && text[endTag.lineNo()] +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + String text = javadocText[tagStart.lineNo()]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final String text = javadocText[pos.lineNo()]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + return text[pos.lineNo()].startsWith("<!--", pos.columnNo()); +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + text[position.lineNo()])); +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + while (line < text.length && column >= text[line].length()) { +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + while (toPoint.lineNo() < text.length && !text[toPoint.lineNo()] +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + final String content = commentValue.substring(contentStart); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + final String content = commentValue.substring(contentStart); +
    + found : int + required: @LTEqLengthOf("commentValue") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + final String remainder = line.substring(tagMatcher.end(1)); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + final String remainder = line.substring(tagMatcher.end(1)); +
    + found : int + required: @LTEqLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtil.java + argument + incompatible argument for parameter arg1 of String.subSequence. + final String precedingText = source.subSequence(0, index).toString(); +
    + found : int + required: @LTEqLengthOf("source") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtil.java + argument + incompatible argument for parameter arg1 of String.subSequence. + final String precedingText = source.subSequence(0, index).toString(); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + classNameWithPackage.substring(0, lastDotIndex); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + result = str.substring(beginIndex); +
    + found : int + required: @LTEqLengthOf("str") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + result = str.substring(beginIndex, endIndex); +
    + found : int + required: @LTEqLengthOf("str") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + result = str.substring(beginIndex); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + argument + incompatible argument for parameter arg0 of String.substring. + result = str.substring(beginIndex, endIndex); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + result = str.substring(beginIndex, endIndex); +
    + found : int + required: @LTEqLengthOf("str") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + argument + incompatible argument for parameter arg1 of String.substring. + result = str.substring(beginIndex, endIndex); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/SinglelineDetector.java + argument + incompatible argument for parameter arg0 of Matcher.find. + while (matcher.find(startPosition)) { +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheck.java + argument + incompatible argument for parameter arg0 of BitSet.set. + usedLines.set(lineIndex); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheck.java + argument + incompatible argument for parameter arg0 of BitSet.set. + usedLines.set(lineIndex, endLineIndex + 1); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheck.java + argument + incompatible argument for parameter arg1 of BitSet.set. + usedLines.set(lineIndex, endLineIndex + 1); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/AbstractParenPadCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + && line[before] != OPEN_PARENTHESIS) { +
    + found : int + required: @IndexFor("line") or @LTLengthOf("line") -- an integer less than line's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/AbstractParenPadCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + && line[after] != CLOSE_PARENTHESIS) { +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + .filter(index -> line[index] == '&') +
    + found : int + required: @IndexFor("line") or @LTLengthOf("line") -- an integer less than line's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + else if (line[after] == ' ') { +
    + found : int + required: @IndexFor("line") or @LTLengthOf("line") -- an integer less than line's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final char charAfter = Character.toChars(line[after])[0]; +
    + found : int + required: @IndexFor("line") or @LTLengthOf("line") -- an integer less than line's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + final char charAfter = Character.toChars(line[after])[0]; +
    + found : char [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + .filter(index -> line[index] == '&') +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + else if (line[after] == ' ') { +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final char charAfter = Character.toChars(line[after])[0]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return acceptableTokens.get(ast.getType()); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/SeparatorWrapCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + Arrays.copyOfRange(currentLine, colNo + text.length(), currentLine.length) +
    + found : @LTLengthOf(value={"ast.getText()", "text"}, offset={"-colNo - 1", "-colNo - 1"}) int + required: @LTEqLengthOf("currentLine") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/SeparatorWrapCheck.java + argument + incompatible argument for parameter arg1 of Arrays.copyOfRange. + Arrays.copyOfRange(currentLine, colNo + text.length(), currentLine.length) +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/SingleSpaceSeparatorCheck.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + return line[columnNo] == ' '; +
    + found : int + required: @IndexFor("line") or @LTLengthOf("line") -- an integer less than line's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/SingleSpaceSeparatorCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + return line[columnNo] == ' '; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final int codePoint = line[after]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAroundCheck.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + final char nextChar = Character.toChars(line[after])[0]; +
    + found : char [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAroundCheck.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final char nextChar = Character.toChars(line[after])[0]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + tagCommentLine(text[0], startLineNo); +
    + found : String [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + tagCommentLine(text[0], startLineNo, comment.getStartColNo()); +
    + found : String [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentation.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + return COLUMN_NAMES[column]; +
    + found : int + required: @IndexFor("com.puppycrawl.tools.checkstyle.gui.ParseTreeTablePresentation.class.COLUMN_NAMES") or @LTLengthOf("com.puppycrawl.tools.checkstyle.gui.ParseTreeTablePresentation.class.COLUMN_NAMES") -- an integer less than com.puppycrawl.tools.checkstyle.gui.ParseTreeTablePresentation.class.COLUMN_NAMES's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentation.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + return COLUMN_NAMES[column]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.java + override.return + Incompatible return type. + public int getColumnCount() { +
    + found : int + required: @NonNegative int + Consequence: method in TreeTableModelAdapter + int getColumnCount(TreeTableModelAdapter this) + cannot override method in TableModel + @NonNegative int getColumnCount(TableModel this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.java + override.return + Incompatible return type. + public int getRowCount() { +
    + found : int + required: @NonNegative int + Consequence: method in TreeTableModelAdapter + int getRowCount(TreeTableModelAdapter this) + cannot override method in TableModel + @NonNegative int getRowCount(TableModel this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + .substring(setterToString.length()); +
    + found : @LTEqLengthOf("setterToString") int + required: @LTEqLengthOf("firstJavadocParagraph") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + + unprocessedPropertyDescription.substring(1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("unprocessedPropertyDescription") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtil.java + argument + incompatible argument for parameter arg1 of String.substring. + .substring(0, 1) +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("unprocessedPropertyDescription") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + argument + incompatible argument for parameter arg0 of ArrayList constructor. + final List<ModulePropertyDetails> result = new ArrayList<>(propertyListLength); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + argument + incompatible argument for parameter arg0 of ArrayList constructor. + final List<String> listContent = new ArrayList<>(nodeListLength); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaWriter.java + argument + incompatible argument for parameter arg0 of String.substring. + + moduleFilePath.substring(indexOfCheckstyle + 1) + xmlExtension; +
    + found : @LTLengthOf(value={"checkstyleString", "moduleFilePath", "moduleFilePath"}, offset={"-moduleFilePath.indexOf(checkstyleString) - 2", "-11", "-checkstyleString.length() - 1"}) int + required: @LTEqLengthOf("moduleFilePath") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaWriter.java + argument + incompatible argument for parameter arg1 of String.substring. + + moduleFilePath.substring(0, indexOfCheckstyle) + "/meta/" +
    + found : @LTLengthOf(value={"checkstyleString", "moduleFilePath", "moduleFilePath"}, offset={"-moduleFilePath.indexOf(checkstyleString) - 1", "-10", "-checkstyleString.length()"}) int + required: @LTEqLengthOf("moduleFilePath") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ChecksXmlMacro.java + argument + incompatible argument for parameter arg0 of String.charAt. + || Character.isWhitespace(description.charAt(index + 1)) +
    + found : @LTEqLengthOf("description") int + required: @LTLengthOf("description") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ChecksXmlMacro.java + argument + incompatible argument for parameter arg0 of String.charAt. + || description.charAt(index + 1) == '<')) { +
    + found : @LTEqLengthOf("description") int + required: @LTLengthOf("description") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ClassAndPropertiesSettersJavadocScraper.java + argument + incompatible argument for parameter arg0 of String.substring. + return Introspector.decapitalize(setterName.substring("set".length())); +
    + found : @LTEqLengthOf(""set"") int + required: @LTEqLengthOf("setterName") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ModuleJavadocParsingUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + .substring(1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("javadocPortionLinesSplit[index]") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + description = firstLetterCapitalized + descriptionString.substring(1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("descriptionString") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + href = href.substring(1, href.length() - 1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("href") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + argument + incompatible argument for parameter arg1 of String.substring. + href = href.substring(1, href.length() - 1); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + argument + incompatible argument for parameter arg1 of String.substring. + final String firstLetterCapitalized = descriptionString.substring(0, 1) +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("descriptionString") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + final Class<?> parameterClass = (Class<?>) type.getActualTypeArguments()[0]; +
    + found : Type [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ChainedPropertyUtil.java + argument + incompatible argument for parameter arg1 of String.substring. + return variableExpression.substring(propertyStartIndex, propertyEndIndex); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg0 of String.charAt. + final boolean negative = txt.charAt(0) == '-'; +
    + found : @UpperBoundLiteral(0) int + required: @LTLengthOf("txt") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + returnString = line.substring(indent, lastNonWhitespace); +
    + found : int + required: @LTEqLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + returnString = line.substring(indent, lastNonWhitespace); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Integer.parseInt. + result = Integer.parseInt(txt, radix); +
    + found : int + required: @IntRange(from=2, to=36) int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Integer.parseInt. + result = Integer.parseInt(txt, radix); +
    + found : int + required: @Positive int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Integer.parseUnsignedInt. + result = Integer.parseUnsignedInt(txt, radix); +
    + found : int + required: @IntRange(from=2, to=36) int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Integer.parseUnsignedInt. + result = Integer.parseUnsignedInt(txt, radix); +
    + found : int + required: @Positive int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Long.parseLong. + result = Long.parseLong(txt, radix); +
    + found : int + required: @IntRange(from=2, to=36) int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Long.parseLong. + result = Long.parseLong(txt, radix); +
    + found : int + required: @Positive int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Long.parseUnsignedLong. + result = Long.parseUnsignedLong(txt, radix); +
    + found : int + required: @IntRange(from=2, to=36) int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Long.parseUnsignedLong. + result = Long.parseUnsignedLong(txt, radix); +
    + found : int + required: @Positive int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of String.substring. + returnString = line.substring(indent, lastNonWhitespace); +
    + found : int + required: @LTEqLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (filename.charAt(0) == '/') { +
    + found : @UpperBoundLiteral(0) int + required: @LTLengthOf("filename") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg0 of String.charAt. + isIdentifier = Character.isJavaIdentifierStart(str.charAt(0)); +
    + found : @UpperBoundLiteral(0) int + required: @LTLengthOf("str") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg0 of String.charAt. + if (!Character.isWhitespace(line.charAt(i))) { +
    + found : int + required: @LTLengthOf("line") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg0 of String.codePointAt. + if (inputString.codePointAt(idx) == '\t') { +
    + found : int + required: @LTLengthOf("inputString") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + .substring(lastIndexOfClasspathProtocol)); +
    + found : @LTEqLengthOf("com.puppycrawl.tools.checkstyle.utils.CommonUtil.class.CLASSPATH_URL_PROTOCOL") int + required: @LTEqLengthOf("filename") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + array.access.unsafe.high + Potentially unsafe array access: the index could be larger than the array's bound + final char character = Character.toChars(codePoints[index])[0]; +
    + found : int + required: @IndexFor("codePoints") or @LTLengthOf("codePoints") -- an integer less than codePoints's length +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + final char character = Character.toChars(codePoints[index])[0]; +
    + found : char [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + array.access.unsafe.low + Potentially unsafe array access: the index could be negative. + final char character = Character.toChars(codePoints[index])[0]; +
    + found : int + required: an integer >= 0 (@NonNegative or @Positive) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + return commentContent.getText().substring(1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("commentContent.getText()") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + methodref.param + Incompatible parameter type for arg0 + .collect(BitSet::new, BitSet::set, BitSet::or); +
    + found : @IntRangeFromNonNegative int + required: int + Consequence: method in BitSet + void set(BitSet this, @IntRangeFromNonNegative int p0) + is not a valid method reference for method in ObjIntConsumer<BitSet> + void accept(ObjIntConsumer<BitSet> this, BitSet p0, int p1) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + methodref.param + Incompatible parameter type for arg0 + .collect(BitSet::new, BitSet::set, BitSet::or); +
    + found : @IntRangeFromNonNegative int + required: int + Consequence: method in BitSet + void set(BitSet this, @IntRangeFromNonNegative int p0) + is not a valid method reference for method in ObjIntConsumer<BitSet> + void accept(ObjIntConsumer<BitSet> this, BitSet p0, int p1) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + methodref.param + Incompatible parameter type for arg0 + .collect(BitSet::new, BitSet::set, BitSet::or); +
    + found : @NonNegative int + required: int + Consequence: method in BitSet + void set(BitSet this, @NonNegative int p0) + is not a valid method reference for method in ObjIntConsumer<BitSet> + void accept(ObjIntConsumer<BitSet> this, BitSet p0, int p1) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + methodref.param + Incompatible parameter type for arg0 + .collect(BitSet::new, BitSet::set, BitSet::or); +
    + found : @NonNegative int + required: int + Consequence: method in BitSet + void set(BitSet this, @NonNegative int p0) + is not a valid method reference for method in ObjIntConsumer<BitSet> + void accept(ObjIntConsumer<BitSet> this, BitSet p0, int p1) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/UnmodifiableCollectionUtil.java + argument + incompatible argument for parameter arg1 of Arrays.copyOf. + return Arrays.copyOf(array, length); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/XpathUtil.java + argument + incompatible argument for parameter arg0 of BitSet.get. + return TOKEN_TYPES_WITH_TEXT_ATTRIBUTE.get(ast.getType()); +
    + found : int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/XpathUtil.java + argument + incompatible argument for parameter arg0 of String.substring. + text = text.substring(1, text.length() - 1); +
    + found : @UpperBoundLiteral(1) int + required: @LTEqLengthOf("text") int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/XpathUtil.java + argument + incompatible argument for parameter arg1 of String.substring. + text = text.substring(1, text.length() - 1); +
    + found : @GTENegativeOne int + required: @NonNegative int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.java + array.access.unsafe.high.constant + Potentially unsafe array access: the constant index 0 could be larger than the array's bound + sb.append(encodeCharacter(Character.toChars(chr)[0])); +
    + found : char [] + required: @MinLen(1) -- an array guaranteed to have at least 1 elements +
    +
    +
    diff --git a/config/checker-framework-suppressions/checker-lock-tainting-suppressions.xml b/config/checker-framework-suppressions/checker-lock-tainting-suppressions.xml new file mode 100644 index 000000000000..3e524033f9b8 --- /dev/null +++ b/config/checker-framework-suppressions/checker-lock-tainting-suppressions.xml @@ -0,0 +1,1575 @@ + + + + src/main/java/com/puppycrawl/tools/checkstyle/Checker.java + methodref.receiver.bound + Incompatible receiver type + .filter(ExternalResourceHolder.class::isInstance) +
    + found : @GuardedBy Class<@GuardedBy ExternalResourceHolder> + required: @GuardSatisfied Class<@GuardedBy ExternalResourceHolder> + Consequence: method + @GuardedBy Class<@GuardedBy ExternalResourceHolder> + is not a valid method reference for method in @GuardedBy Class<@GuardedBy ExternalResourceHolder> + @GuardedBy boolean isInstance(@GuardSatisfied Class<@GuardedBy ExternalResourceHolder> this, @GuardedBy Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + method.guarantee.violated + @SideEffectFree method toString calls method getColumnNo with a weaker @ReleasesNoLocks side effect guarantee + return text + "[" + getLineNo() + "x" + getColumnNo() + "]"; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + method.guarantee.violated + @SideEffectFree method toString calls method getLineNo with a weaker @ReleasesNoLocks side effect guarantee + return text + "[" + getLineNo() + "x" + getColumnNo() + "]"; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy DetailAstImpl + required: @GuardSatisfied Object + Consequence: method in @GuardedBy DetailAstImpl + @GuardedBy String toString(@GuardedBy DetailAstImpl this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + methodref.receiver.bound + Incompatible receiver type + messages.forEach(System.out::println); +
    + found : @GuardedBy PrintStream + required: @GuardSatisfied PrintStream + Consequence: method + @GuardedBy PrintStream + is not a valid method reference for method in @GuardedBy PrintStream + void println(@GuardSatisfied PrintStream this, @GuardedBy String p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy OutputFormat + required: @GuardSatisfied Object + Consequence: method in @GuardedBy OutputFormat + @GuardedBy String toString(@GuardedBy OutputFormat this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + methodref.receiver + Incompatible receiver type + .map(Entry::getKey) +
    + found : @GuardSatisfied Entry<@GuardedBy String, @GuardedBy String> + required: @GuardedBy Entry<@GuardedBy String, @GuardedBy String> + Consequence: method in @GuardedBy Entry<K extends @GuardedBy Object, V extends @GuardedBy Object> + @GuardedBy String getKey(@GuardSatisfied Entry<@GuardedBy String, @GuardedBy String> this) + is not a valid method reference for method in @GuardedBy Function<@GuardedBy Entry<@GuardedBy String, @GuardedBy String>, @GuardedBy String> + @GuardedBy String apply(@GuardedBy Function<@GuardedBy Entry<@GuardedBy String, @GuardedBy String>, @GuardedBy String> this, @GuardedBy Entry<@GuardedBy String, @GuardedBy String> p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertiesExpander.java + methodref.receiver.bound + Incompatible receiver type + Collectors.toUnmodifiableMap(Function.identity(), properties::getProperty)); +
    + found : @GuardedBy Properties + required: @GuardSatisfied Properties + Consequence: method + @GuardedBy Properties + is not a valid method reference for method in @GuardedBy Properties + @GuardedBy String getProperty(@GuardSatisfied Properties this, @GuardedBy String p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + methodref.param + Incompatible parameter type for arg0 + .filter(messages::containsKey).map(key -> { +
    + found : @GuardSatisfied Object + required: @GuardedBy String + Consequence: method in @GuardedBy Map<@GuardedBy String, @GuardedBy String> + @GuardedBy boolean containsKey(@GuardSatisfied Map<@GuardedBy String, @GuardedBy String> this, @GuardSatisfied Object p0) + is not a valid method reference for method in @GuardedBy Predicate<@GuardedBy String> + @GuardedBy boolean test(@GuardedBy Predicate<@GuardedBy String> this, @GuardedBy String p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + methodref.receiver.bound + Incompatible receiver type + .filter(messages::containsKey).map(key -> { +
    + found : @GuardedBy Map<@GuardedBy String, @GuardedBy String> + required: @GuardSatisfied Map<@GuardedBy String, @GuardedBy String> + Consequence: method + @GuardedBy Map<@GuardedBy String, @GuardedBy String> + is not a valid method reference for method in @GuardedBy Map<@GuardedBy String, @GuardedBy String> + @GuardedBy boolean containsKey(@GuardSatisfied Map<@GuardedBy String, @GuardedBy String> this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + methodref.receiver + Incompatible receiver type + .thenComparingInt(AbstractCheck::hashCode)); +
    + found : @GuardSatisfied Object + required: @GuardedBy AbstractCheck + Consequence: method in @GuardedBy AbstractCheck + @GuardedBy int hashCode(@GuardSatisfied Object this) + is not a valid method reference for method in @GuardedBy ToIntFunction<@GuardedBy AbstractCheck> + @GuardedBy int applyAsInt(@GuardedBy ToIntFunction<@GuardedBy AbstractCheck> this, @GuardedBy AbstractCheck p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + methodref.receiver.bound + Incompatible receiver type + .filter(ExternalResourceHolder.class::isInstance) +
    + found : @GuardedBy Class<@GuardedBy ExternalResourceHolder> + required: @GuardSatisfied Class<@GuardedBy ExternalResourceHolder> + Consequence: method + @GuardedBy Class<@GuardedBy ExternalResourceHolder> + is not a valid method reference for method in @GuardedBy Class<@GuardedBy ExternalResourceHolder> + @GuardedBy boolean isInstance(@GuardSatisfied Class<@GuardedBy ExternalResourceHolder> this, @GuardedBy Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java + method.guarantee.violated + @Pure method resolveEntity calls method getClassLoader with a weaker @ReleasesNoLocks side effect guarantee + final ClassLoader loader = getClass().getClassLoader(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java + method.guarantee.violated + @Pure method resolveEntity calls method getResourceAsStream with a weaker @ReleasesNoLocks side effect guarantee + final InputStream dtdIs = loader.getResourceAsStream(dtdResourceName); + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/BeforeExecutionFileFilterSet.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy BeforeExecutionFileFilterSet + required: @GuardSatisfied Object + Consequence: method in @GuardedBy BeforeExecutionFileFilterSet + @GuardedBy String toString(@GuardedBy BeforeExecutionFileFilterSet this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Comment.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy Comment + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Comment + @GuardedBy String toString(@GuardedBy Comment this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FilterSet.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy FilterSet + required: @GuardSatisfied Object + Consequence: method in @GuardedBy FilterSet + @GuardedBy String toString(@GuardedBy FilterSet this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FullIdent.java + method.guarantee.violated + @SideEffectFree method toString calls method getColumnNo with a weaker @ReleasesNoLocks side effect guarantee + + "[" + detailAst.getLineNo() + "x" + detailAst.getColumnNo() + "]"; + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FullIdent.java + method.guarantee.violated + @SideEffectFree method toString calls method getLineNo with a weaker @ReleasesNoLocks side effect guarantee + + "[" + detailAst.getLineNo() + "x" + detailAst.getColumnNo() + "]"; + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FullIdent.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy FullIdent + required: @GuardSatisfied Object + Consequence: method in @GuardedBy FullIdent + @GuardedBy String toString(@GuardedBy FullIdent this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/LineColumn.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy LineColumn + @GuardedBy boolean equals(@GuardedBy LineColumn this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/LineColumn.java + override.receiver + Incompatible receiver type + public int compareTo(LineColumn lineColumn) { +
    + found : @GuardedBy LineColumn + required: @GuardSatisfied Comparable<@GuardedBy LineColumn> + Consequence: method in @GuardedBy LineColumn + @GuardedBy int compareTo(@GuardedBy LineColumn this, @GuardedBy LineColumn p0) + cannot override method in @GuardedBy Comparable<@GuardedBy LineColumn> + @GuardedBy int compareTo(@GuardSatisfied Comparable<@GuardedBy LineColumn> this, @GuardedBy LineColumn p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/LineColumn.java + override.receiver + Incompatible receiver type + public boolean equals(Object other) { +
    + found : @GuardedBy LineColumn + required: @GuardSatisfied Object + Consequence: method in @GuardedBy LineColumn + @GuardedBy boolean equals(@GuardedBy LineColumn this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/LineColumn.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy LineColumn + required: @GuardSatisfied Object + Consequence: method in @GuardedBy LineColumn + @GuardedBy int hashCode(@GuardedBy LineColumn this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Scope.java + method.guarantee.violated + @SideEffectFree method toString calls method getName with a weaker @ReleasesNoLocks side effect guarantee + return getName(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Scope.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy Scope + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Scope + @GuardedBy String toString(@GuardedBy Scope this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/SeverityLevel.java + method.guarantee.violated + @SideEffectFree method toString calls method getName with a weaker @ReleasesNoLocks side effect guarantee + return getName(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/SeverityLevel.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy SeverityLevel + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SeverityLevel + @GuardedBy String toString(@GuardedBy SeverityLevel this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Violation.java + method.guarantee.violated + @Pure method compareTo calls method getViolation with a weaker @ReleasesNoLocks side effect guarantee + result = getViolation().compareTo(other.getViolation()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Violation.java + method.guarantee.violated + @Pure method compareTo calls method getViolation with a weaker @ReleasesNoLocks side effect guarantee + result = getViolation().compareTo(other.getViolation()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Violation.java + override.param + Incompatible parameter type for object. + public boolean equals(Object object) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Violation + @GuardedBy boolean equals(@GuardedBy Violation this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Violation.java + override.receiver + Incompatible receiver type + public int compareTo(Violation other) { +
    + found : @GuardedBy Violation + required: @GuardSatisfied Comparable<@GuardedBy Violation> + Consequence: method in @GuardedBy Violation + @GuardedBy int compareTo(@GuardedBy Violation this, @GuardedBy Violation p0) + cannot override method in @GuardedBy Comparable<@GuardedBy Violation> + @GuardedBy int compareTo(@GuardSatisfied Comparable<@GuardedBy Violation> this, @GuardedBy Violation p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Violation.java + override.receiver + Incompatible receiver type + public boolean equals(Object object) { +
    + found : @GuardedBy Violation + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Violation + @GuardedBy boolean equals(@GuardedBy Violation this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Violation.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy Violation + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Violation + @GuardedBy int hashCode(@GuardedBy Violation this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.java + override.receiver + Incompatible receiver type + public synchronized Object put(Object key, Object value) { +
    + found : @GuardedBy SequencedProperties + required: @GuardSatisfied Hashtable<@GuardedBy Object, @GuardedBy Object> + Consequence: method in @GuardedBy SequencedProperties + @GuardedBy Object put(@GuardedBy SequencedProperties this, @GuardedBy Object p0, @GuardedBy Object p1) + cannot override method in @GuardedBy Hashtable<@GuardedBy Object, @GuardedBy Object> + @GuardedBy Object put(@GuardSatisfied Hashtable<@GuardedBy Object, @GuardedBy Object> this, @GuardedBy Object p0, @GuardedBy Object p1) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java + override.receiver + Incompatible receiver type + public synchronized Object put(Object key, Object value) { +
    + found : @GuardedBy UniqueProperties + required: @GuardSatisfied Hashtable<@GuardedBy Object, @GuardedBy Object> + Consequence: method in @GuardedBy UniqueProperties + @GuardedBy Object put(@GuardedBy UniqueProperties this, @GuardedBy Object p0, @GuardedBy Object p1) + cannot override method in @GuardedBy Hashtable<@GuardedBy Object, @GuardedBy Object> + @GuardedBy Object put(@GuardSatisfied Hashtable<@GuardedBy Object, @GuardedBy Object> this, @GuardedBy Object p0, @GuardedBy Object p1) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/MissingOverrideCheck.java + type.arguments.not.inferred + Could not infer type arguments for Stream.iterate + Stream.iterate(startNode.getLastChild(), Objects::nonNull, +
    + unsatisfiable constraint: @GuardedBy DetailAST <: @GuardSatisfied Object + use of T from Stream.iterate(startNode.getLastChild(), Objects::nonNull, DetailAST::getPreviousSibling) <: @GuardSatisfied Object + From complementary bound.: Objects::nonNull -> inference type: java.util.function.Predicate<? super T> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ConstructorsDeclarationGroupingCheck.java + type.arguments.not.inferred + Could not infer type arguments for Optional.map + .map(children::indexOf); +
    + unsatisfiable constraint: @GuardedBy DetailAST <: @GuardSatisfied Object + children::indexOf -> inference type: java.util.function.Function<? super com.puppycrawl.tools.checkstyle.api.DetailAST,? extends U> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + methodref.param + Incompatible parameter type for arg0 + .filter(Objects::nonNull) +
    + found : @GuardSatisfied Object + required: @GuardedBy DetailAST + Consequence: method in @GuardedBy Objects + @GuardedBy boolean nonNull(@GuardSatisfied Object p0) + is not a valid method reference for method in @GuardedBy Predicate<@GuardedBy DetailAST> + @GuardedBy boolean test(@GuardedBy Predicate<@GuardedBy DetailAST> this, @GuardedBy DetailAST p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + type.arguments.not.inferred + Could not infer type arguments for Stream.iterate + result = Stream.iterate(nonCommentAst.getPreviousSibling(), +
    + unsatisfiable constraint: @GuardedBy DetailAST <: @GuardSatisfied Object + use of T from Stream.iterate(nonCommentAst.getPreviousSibling(), Objects::nonNull, DetailAST::getPreviousSibling) <: @GuardSatisfied Object + From complementary bound.: Objects::nonNull -> inference type: java.util.function.Predicate<? super T> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + methodref.param + Incompatible parameter type for arg0 + return initializedVariables.stream().filter(iteratingVariables::contains) +
    + found : @GuardSatisfied Object + required: @GuardedBy String + Consequence: method in @GuardedBy Set<@GuardedBy String> + @GuardedBy boolean contains(@GuardSatisfied Set<@GuardedBy String> this, @GuardSatisfied Object p0) + is not a valid method reference for method in @GuardedBy Predicate<@GuardedBy String> + @GuardedBy boolean test(@GuardedBy Predicate<@GuardedBy String> this, @GuardedBy String p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + methodref.receiver.bound + Incompatible receiver type + return initializedVariables.stream().filter(iteratingVariables::contains) +
    + found : @GuardedBy Set<@GuardedBy String> + required: @GuardSatisfied Set<@GuardedBy String> + Consequence: method + @GuardedBy Set<@GuardedBy String> + is not a valid method reference for method in @GuardedBy Set<@GuardedBy String> + @GuardedBy boolean contains(@GuardSatisfied Set<@GuardedBy String> this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + methodref.receiver.bound + Incompatible receiver type + instAndClassVarDeque.forEach(variablesStack::push); +
    + found : @GuardedBy Deque<@GuardedBy VariableDesc> + required: @GuardSatisfied Deque<@GuardedBy VariableDesc> + Consequence: method + @GuardedBy Deque<@GuardedBy VariableDesc> + is not a valid method reference for method in @GuardedBy Deque<@GuardedBy VariableDesc> + void push(@GuardSatisfied Deque<@GuardedBy VariableDesc> this, @GuardedBy VariableDesc p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + methodref.receiver + Incompatible receiver type + .map(Map.Entry::getValue) +
    + found : @GuardSatisfied Entry<@GuardedBy String, @GuardedBy ClassDesc> + required: @GuardedBy Entry<@GuardedBy String, @GuardedBy ClassDesc> + Consequence: method in @GuardedBy Entry<K extends @GuardedBy Object, V extends @GuardedBy Object> + @GuardedBy ClassDesc getValue(@GuardSatisfied Entry<@GuardedBy String, @GuardedBy ClassDesc> this) + is not a valid method reference for method in @GuardedBy Function<@GuardedBy Entry<@GuardedBy String, @GuardedBy ClassDesc>, @GuardedBy ClassDesc> + @GuardedBy ClassDesc apply(@GuardedBy Function<@GuardedBy Entry<@GuardedBy String, @GuardedBy ClassDesc>, @GuardedBy ClassDesc> this, @GuardedBy Entry<@GuardedBy String, @GuardedBy ClassDesc> p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.java + method.guarantee.violated + @SideEffectFree method toString calls method append with a weaker @ReleasesNoLocks side effect guarantee + sb.append(", "); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.java + method.guarantee.violated + @SideEffectFree method toString calls method append with a weaker @ReleasesNoLocks side effect guarantee + sb.append(i); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy IndentLevel + required: @GuardSatisfied Object + Consequence: method in @GuardedBy IndentLevel + @GuardedBy String toString(@GuardedBy IndentLevel this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.java + type.arguments.not.inferred + Could not infer type arguments for Stream.collect + .collect(Collectors.joining(", ")), +
    + unsatisfiable constraint: @GuardedBy String <: @GuardSatisfied Object + use of R from missingRequiredTokenNames.stream().map(String::valueOf).collect(Collectors.joining(", ")) <: @GuardSatisfied Object + From complementary bound.: use of R from missingRequiredTokenNames.stream().map(String::valueOf).collect(Collectors.joining(", ")) -> @GuardSatisfied Object + From: Constraint between method call type and target type for method call:missingRequiredTokenNames.stream().map(String::valueOf).collect(Collectors.joining(", ")) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/HtmlTag.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy HtmlTag + required: @GuardSatisfied Object + Consequence: method in @GuardedBy HtmlTag + @GuardedBy String toString(@GuardedBy HtmlTag this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.java + method.guarantee.violated + @SideEffectFree method toString calls method getColumnNumber with a weaker @ReleasesNoLocks side effect guarantee + return text + "[" + getLineNumber() + "x" + getColumnNumber() + "]"; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.java + method.guarantee.violated + @SideEffectFree method toString calls method getLineNumber with a weaker @ReleasesNoLocks side effect guarantee + return text + "[" + getLineNumber() + "x" + getColumnNumber() + "]"; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy JavadocNodeImpl + required: @GuardSatisfied Object + Consequence: method in @GuardedBy JavadocNodeImpl + @GuardedBy String toString(@GuardedBy JavadocNodeImpl this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTag.java + method.guarantee.violated + @SideEffectFree method toString calls method getName with a weaker @ReleasesNoLocks side effect guarantee + return "JavadocTag[tag='" + tagInfo.getName() + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTag.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy JavadocTag + required: @GuardSatisfied Object + Consequence: method in @GuardedBy JavadocTag + @GuardedBy String toString(@GuardedBy JavadocTag this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy JavadocTagInfo + required: @GuardSatisfied Object + Consequence: method in @GuardedBy JavadocTagInfo + @GuardedBy String toString(@GuardedBy JavadocTagInfo this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AccessModifierOption.java + method.guarantee.violated + @SideEffectFree method toString calls method getName with a weaker @ReleasesNoLocks side effect guarantee + return getName(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AccessModifierOption.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy AccessModifierOption + required: @GuardSatisfied Object + Consequence: method in @GuardedBy AccessModifierOption + @GuardedBy String toString(@GuardedBy AccessModifierOption this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheck.java + type.arguments.not.inferred + Could not infer type arguments for Stream.iterate + Stream.iterate( +
    + unsatisfiable constraint: @GuardedBy DetailAST <: @GuardSatisfied Object + use of T from Stream.iterate(node.getLastChild(), Objects::nonNull, DetailAST::getPreviousSibling) <: @GuardSatisfied Object + From complementary bound.: Objects::nonNull -> inference type: java.util.function.Predicate<? super T> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterElement.java + override.param + Incompatible parameter type for object. + public boolean equals(Object object) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy CsvFilterElement + @GuardedBy boolean equals(@GuardedBy CsvFilterElement this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterElement.java + override.receiver + Incompatible receiver type + public boolean equals(Object object) { +
    + found : @GuardedBy CsvFilterElement + required: @GuardSatisfied Object + Consequence: method in @GuardedBy CsvFilterElement + @GuardedBy boolean equals(@GuardedBy CsvFilterElement this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterElement.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy CsvFilterElement + required: @GuardSatisfied Object + Consequence: method in @GuardedBy CsvFilterElement + @GuardedBy int hashCode(@GuardedBy CsvFilterElement this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterElement.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy IntMatchFilterElement + required: @GuardSatisfied Record + Consequence: method in @GuardedBy IntMatchFilterElement + @GuardedBy String toString(@GuardedBy IntMatchFilterElement this) + cannot override method in @GuardedBy Record + @GuardedBy String toString(@GuardSatisfied Record this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterElement.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy IntRangeFilterElement + required: @GuardSatisfied Record + Consequence: method in @GuardedBy IntRangeFilterElement + @GuardedBy String toString(@GuardedBy IntRangeFilterElement this) + cannot override method in @GuardedBy Record + @GuardedBy String toString(@GuardSatisfied Record this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + && Objects.equals(getPatternSafely(checkRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + && Objects.equals(getPatternSafely(messageRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + getPatternSafely(suppressElement.checkRegexp)) + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + getPatternSafely(suppressElement.fileRegexp)) + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + getPatternSafely(suppressElement.messageRegexp)) + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + return Objects.equals(getPatternSafely(fileRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method hashCode calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + getPatternSafely(messageRegexp), moduleId, linesCsv, columnsCsv); + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method hashCode calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + return Objects.hash(getPatternSafely(fileRegexp), getPatternSafely(checkRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + method.guarantee.violated + @Pure method hashCode calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + return Objects.hash(getPatternSafely(fileRegexp), getPatternSafely(checkRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SuppressFilterElement + @GuardedBy boolean equals(@GuardedBy SuppressFilterElement this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + override.receiver + Incompatible receiver type + public boolean equals(Object other) { +
    + found : @GuardedBy SuppressFilterElement + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SuppressFilterElement + @GuardedBy boolean equals(@GuardedBy SuppressFilterElement this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy SuppressFilterElement + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SuppressFilterElement + @GuardedBy int hashCode(@GuardedBy SuppressFilterElement this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Tag + @GuardedBy boolean equals(@GuardedBy Tag this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy Tag + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Tag + @GuardedBy String toString(@GuardedBy Tag this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + override.receiver + Incompatible receiver type + public boolean equals(Object other) { +
    + found : @GuardedBy Tag + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Tag + @GuardedBy boolean equals(@GuardedBy Tag this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy Tag + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Tag + @GuardedBy int hashCode(@GuardedBy Tag this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + methodref.receiver.bound + Incompatible receiver type + suppression.ifPresent(currentFileSuppressionCache::add); +
    + found : @GuardedBy Collection<@GuardedBy Suppression> + required: @GuardSatisfied Collection<@GuardedBy Suppression> + Consequence: method + @GuardedBy Collection<@GuardedBy Suppression> + is not a valid method reference for method in @GuardedBy Collection<@GuardedBy Suppression> + @GuardedBy boolean add(@GuardSatisfied Collection<@GuardedBy Suppression> this, @GuardedBy Suppression p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Suppression + @GuardedBy boolean equals(@GuardedBy Suppression this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + override.receiver + Incompatible receiver type + public boolean equals(Object other) { +
    + found : @GuardedBy Suppression + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Suppression + @GuardedBy boolean equals(@GuardedBy Suppression this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy Suppression + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Suppression + @GuardedBy int hashCode(@GuardedBy Suppression this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Tag + @GuardedBy boolean equals(@GuardedBy Tag this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + override.receiver + Incompatible receiver type + public int compareTo(Tag object) { +
    + found : @GuardedBy Tag + required: @GuardSatisfied Comparable<@GuardedBy Tag> + Consequence: method in @GuardedBy Tag + @GuardedBy int compareTo(@GuardedBy Tag this, @GuardedBy Tag p0) + cannot override method in @GuardedBy Comparable<@GuardedBy Tag> + @GuardedBy int compareTo(@GuardSatisfied Comparable<@GuardedBy Tag> this, @GuardedBy Tag p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy Tag + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Tag + @GuardedBy String toString(@GuardedBy Tag this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + override.receiver + Incompatible receiver type + public boolean equals(Object other) { +
    + found : @GuardedBy Tag + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Tag + @GuardedBy boolean equals(@GuardedBy Tag this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy Tag + required: @GuardSatisfied Object + Consequence: method in @GuardedBy Tag + @GuardedBy int hashCode(@GuardedBy Tag this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java + override.param + Incompatible parameter type for obj. + public boolean equals(Object obj) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SuppressionXpathFilter + @GuardedBy boolean equals(@GuardedBy SuppressionXpathFilter this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java + override.receiver + Incompatible receiver type + public boolean equals(Object obj) { +
    + found : @GuardedBy SuppressionXpathFilter + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SuppressionXpathFilter + @GuardedBy boolean equals(@GuardedBy SuppressionXpathFilter this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy SuppressionXpathFilter + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SuppressionXpathFilter + @GuardedBy int hashCode(@GuardedBy SuppressionXpathFilter this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + && Objects.equals(getPatternSafely(checkRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + && Objects.equals(getPatternSafely(messageRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + getPatternSafely(xpathFilter.checkRegexp)) + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + getPatternSafely(xpathFilter.fileRegexp)) + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + getPatternSafely(xpathFilter.messageRegexp)) + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method equals calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + return Objects.equals(getPatternSafely(fileRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method hashCode calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + getPatternSafely(messageRegexp), moduleId, xpathQuery); + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method hashCode calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + return Objects.hash(getPatternSafely(fileRegexp), getPatternSafely(checkRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + method.guarantee.violated + @Pure method hashCode calls method getPatternSafely with a weaker @ReleasesNoLocks side effect guarantee + return Objects.hash(getPatternSafely(fileRegexp), getPatternSafely(checkRegexp), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy XpathFilterElement + @GuardedBy boolean equals(@GuardedBy XpathFilterElement this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + override.receiver + Incompatible receiver type + public boolean equals(Object other) { +
    + found : @GuardedBy XpathFilterElement + required: @GuardSatisfied Object + Consequence: method in @GuardedBy XpathFilterElement + @GuardedBy boolean equals(@GuardedBy XpathFilterElement this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy XpathFilterElement + required: @GuardSatisfied Object + Consequence: method in @GuardedBy XpathFilterElement + @GuardedBy int hashCode(@GuardedBy XpathFilterElement this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getCharPositionInLine with a weaker @ReleasesNoLocks side effect guarantee + && getCharPositionInLine() == other.getCharPositionInLine() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getCharPositionInLine with a weaker @ReleasesNoLocks side effect guarantee + && getCharPositionInLine() == other.getCharPositionInLine() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getLine with a weaker @ReleasesNoLocks side effect guarantee + && getLine() == other.getLine() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getLine with a weaker @ReleasesNoLocks side effect guarantee + && getLine() == other.getLine() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getStartIndex with a weaker @ReleasesNoLocks side effect guarantee + && getStartIndex() == other.getStartIndex() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getStartIndex with a weaker @ReleasesNoLocks side effect guarantee + && getStartIndex() == other.getStartIndex() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getStopIndex with a weaker @ReleasesNoLocks side effect guarantee + && getStopIndex() == other.getStopIndex(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getStopIndex with a weaker @ReleasesNoLocks side effect guarantee + && getStopIndex() == other.getStopIndex(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getText with a weaker @ReleasesNoLocks side effect guarantee + && getText().equals(other.getText()) + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getText with a weaker @ReleasesNoLocks side effect guarantee + && getText().equals(other.getText()) + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getTokenIndex with a weaker @ReleasesNoLocks side effect guarantee + && getTokenIndex() == other.getTokenIndex() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getTokenIndex with a weaker @ReleasesNoLocks side effect guarantee + && getTokenIndex() == other.getTokenIndex() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getType with a weaker @ReleasesNoLocks side effect guarantee + return getType() == other.getType() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method equals calls method getType with a weaker @ReleasesNoLocks side effect guarantee + return getType() == other.getType() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method hashCode calls method getCharPositionInLine with a weaker @ReleasesNoLocks side effect guarantee + getCharPositionInLine(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method hashCode calls method getLine with a weaker @ReleasesNoLocks side effect guarantee + getLine(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method hashCode calls method getStartIndex with a weaker @ReleasesNoLocks side effect guarantee + getStartIndex(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method hashCode calls method getStopIndex with a weaker @ReleasesNoLocks side effect guarantee + getStopIndex() + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method hashCode calls method getText with a weaker @ReleasesNoLocks side effect guarantee + getText(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method hashCode calls method getTokenIndex with a weaker @ReleasesNoLocks side effect guarantee + getTokenIndex(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + method.guarantee.violated + @Pure method hashCode calls method getType with a weaker @ReleasesNoLocks side effect guarantee + getType(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + override.param + Incompatible parameter type for obj. + public boolean equals(Object obj) { +
    + found : @GuardedBy Object + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SimpleToken + @GuardedBy boolean equals(@GuardedBy SimpleToken this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + override.receiver + Incompatible receiver type + public boolean equals(Object obj) { +
    + found : @GuardedBy SimpleToken + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SimpleToken + @GuardedBy boolean equals(@GuardedBy SimpleToken this, @GuardedBy Object p0) + cannot override method in @GuardedBy Object + @GuardedBy boolean equals(@GuardSatisfied Object this, @GuardSatisfied Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + override.receiver + Incompatible receiver type + public int hashCode() { +
    + found : @GuardedBy SimpleToken + required: @GuardSatisfied Object + Consequence: method in @GuardedBy SimpleToken + @GuardedBy int hashCode(@GuardedBy SimpleToken this) + cannot override method in @GuardedBy Object + @GuardedBy int hashCode(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.java + override.receiver + Incompatible receiver type + public String toString() { +
    + found : @GuardedBy ParseMode + required: @GuardSatisfied Object + Consequence: method in @GuardedBy ParseMode + @GuardedBy String toString(@GuardedBy ParseMode this) + cannot override method in @GuardedBy Object + @GuardedBy String toString(@GuardSatisfied Object this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateSink.java + override.receiver + Incompatible receiver type + public void println() { +
    + found : @GuardedBy CustomPrintWriter + required: @GuardSatisfied PrintWriter + Consequence: method in @GuardedBy CustomPrintWriter + void println(@GuardedBy CustomPrintWriter this) + cannot override method in @GuardedBy PrintWriter + void println(@GuardSatisfied PrintWriter this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateSink.java + override.receiver + Incompatible receiver type + public void write(String line, int offset, int length) { +
    + found : @GuardedBy CustomPrintWriter + required: @GuardSatisfied PrintWriter + Consequence: method in @GuardedBy CustomPrintWriter + void write(@GuardedBy CustomPrintWriter this, @GuardedBy String p0, @GuardedBy int p1, @GuardedBy int p2) + cannot override method in @GuardedBy PrintWriter + void write(@GuardSatisfied PrintWriter this, @GuardedBy String p0, @GuardedBy int p1, @GuardedBy int p2) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + methodref.receiver + Incompatible receiver type + .collect(Collectors.toUnmodifiableMap(Map.Entry::getValue, Map.Entry::getKey)); +
    + found : @GuardSatisfied Entry<@GuardedBy String, @GuardedBy Integer> + required: @GuardedBy Entry<@GuardedBy String, @GuardedBy Integer> + Consequence: method in @GuardedBy Entry<K extends @GuardedBy Object, V extends @GuardedBy Object> + @GuardedBy Integer getValue(@GuardSatisfied Entry<@GuardedBy String, @GuardedBy Integer> this) + is not a valid method reference for method in @GuardedBy Function<@GuardedBy Entry<@GuardedBy String, @GuardedBy Integer>, @GuardedBy Integer> + @GuardedBy Integer apply(@GuardedBy Function<@GuardedBy Entry<@GuardedBy String, @GuardedBy Integer>, @GuardedBy Integer> this, @GuardedBy Entry<@GuardedBy String, @GuardedBy Integer> p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + methodref.receiver + Incompatible receiver type + .collect(Collectors.toUnmodifiableMap(Map.Entry::getValue, Map.Entry::getKey)); +
    + found : @GuardSatisfied Entry<@GuardedBy String, @GuardedBy Integer> + required: @GuardedBy Entry<@GuardedBy String, @GuardedBy Integer> + Consequence: method in @GuardedBy Entry<K extends @GuardedBy Object, V extends @GuardedBy Object> + @GuardedBy String getKey(@GuardSatisfied Entry<@GuardedBy String, @GuardedBy Integer> this) + is not a valid method reference for method in @GuardedBy Function<@GuardedBy Entry<@GuardedBy String, @GuardedBy Integer>, @GuardedBy String> + @GuardedBy String apply(@GuardedBy Function<@GuardedBy Entry<@GuardedBy String, @GuardedBy Integer>, @GuardedBy String> this, @GuardedBy Entry<@GuardedBy String, @GuardedBy Integer> p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + type.arguments.not.inferred + Could not infer type arguments for IntStream.collect + .collect(BitSet::new, BitSet::set, BitSet::or); +
    + unsatisfiable constraint: @GuardedBy BitSet <: @GuardSatisfied BitSet + @GuardedBy BitSet <: use of R from Arrays.stream(tokens).map(String::trim).filter(Predicate.not(String::isEmpty)).mapToInt(TokenUtil::getTokenId).collect(BitSet::new, BitSet::set, BitSet::or) + From complementary bound.: @GuardedBy BitSet -> use of R from Arrays.stream(tokens).map(String::trim).filter(Predicate.not(String::isEmpty)).mapToInt(TokenUtil::getTokenId).collect(BitSet::new, BitSet::set, BitSet::or) + BitSet::new -> inference type: java.util.function.Supplier<R> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + type.arguments.not.inferred + Could not infer type arguments for IntStream.collect + .collect(BitSet::new, BitSet::set, BitSet::or); +
    + unsatisfiable constraint: @GuardedBy BitSet <: @GuardSatisfied BitSet + @GuardedBy BitSet <: use of R from IntStream.of(tokens).collect(BitSet::new, BitSet::set, BitSet::or) + From complementary bound.: @GuardedBy BitSet -> use of R from IntStream.of(tokens).collect(BitSet::new, BitSet::set, BitSet::or) + BitSet::new -> inference type: java.util.function.Supplier<R> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + type.arguments.not.inferred + Could not infer type arguments for Stream.collect + .collect(Collectors.toUnmodifiableMap( +
    + unsatisfiable constraint: @GuardedBy Field <: @GuardSatisfied Field + @GuardedBy Field <: use of T from Collectors.toUnmodifiableMap(Field::getName, (fld)->getIntFromField(fld, null)) + From complementary bound.: @GuardedBy Field <: use of captured T from Collectors.toUnmodifiableMap(Field::getName, (fld)->getIntFromField(fld, null)) + From complementary bound.: use of captured T from Collectors.toUnmodifiableMap(Field::getName, (fld)->getIntFromField(fld, null)) <= ? extends @GuardedBy Object super @GuardedBy Field + inference type: java.util.stream.Collector<T,A,R> <: inference type: java.util.stream.Collector<? super java.lang.reflect.Field,A,R> + inference type: java.util.stream.Collector<T,A,R> -> inference type: java.util.stream.Collector<? super java.lang.reflect.Field,A,R> + From: Captured constraint from method call: Collectors.toUnmodifiableMap(Field::getName, (fld)->getIntFromField(fld, null)) +
    +
    +
    diff --git a/config/checker-framework-suppressions/checker-methods-resource-fenum-suppressions.xml b/config/checker-framework-suppressions/checker-methods-resource-fenum-suppressions.xml new file mode 100644 index 000000000000..beba4ee207be --- /dev/null +++ b/config/checker-framework-suppressions/checker-methods-resource-fenum-suppressions.xml @@ -0,0 +1,405 @@ + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + required.method.not.called + @MustCall method close may not have been invoked on getOutputStream(options.outputPath) or any of its aliases. + getOutputStream(options.outputPath), +
    + The type of object is: java.io.OutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + required.method.not.called + @MustCall method close may not have been invoked on getOutputStream(options.outputPath) or any of its aliases. + listener = new XpathFileGeneratorAuditListener(getOutputStream(options.outputPath), +
    + The type of object is: java.io.OutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + required.method.not.called + @MustCall method close may not have been invoked on out or any of its aliases. + final OutputStream out = getOutputStream(outputLocation); +
    + The type of object is: java.io.OutputStream. + Reason for going out of scope: possible exceptional exit due to format.createListener(out, closeOutputStreamOption) with exception type java.io.IOException +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + return + incompatible types in return. + return instance; +
    + type of expression: @FenumTop Object + method return type: @FenumUnqualified Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java + required.method.not.called + @MustCall method close may not have been invoked on dtdIs or any of its aliases. + final InputStream dtdIs = loader.getResourceAsStream(dtdResourceName); +
    + The type of object is: java.io.InputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on Files.newOutputStream(toFile.toPath()) or any of its aliases. + sarifLogger = new SarifLogger(Files.newOutputStream(toFile.toPath()), +
    + The type of object is: java.io.OutputStream. + Reason for going out of scope: possible exceptional exit due to new SarifLogger(Files.newOutputStream(toFile.toPath()), OutputStreamOptions.CLOSE) with exception type java.io.IOException +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on Files.newOutputStream(toFile.toPath()) or any of its aliases. + xmlLogger = new XMLLogger(Files.newOutputStream(toFile.toPath()), +
    + The type of object is: java.io.OutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on debug or any of its aliases. + final OutputStream debug = new LogOutputStream(this, Project.MSG_DEBUG); +
    + The type of object is: java.io.OutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on err or any of its aliases. + final OutputStream err = new LogOutputStream(this, Project.MSG_ERR); +
    + The type of object is: java.io.OutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on infoStream or any of its aliases. + final OutputStream infoStream = Files.newOutputStream(toFile.toPath()); +
    + The type of object is: java.io.OutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on new LogOutputStream(task, Project.MSG_DEBUG) or any of its aliases. + new LogOutputStream(task, Project.MSG_DEBUG), +
    + The type of object is: org.apache.tools.ant.taskdefs.LogOutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on new LogOutputStream(task, Project.MSG_ERR) or any of its aliases. + new LogOutputStream(task, Project.MSG_ERR), +
    + The type of object is: org.apache.tools.ant.taskdefs.LogOutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on new LogOutputStream(task, Project.MSG_INFO) or any of its aliases. + sarifLogger = new SarifLogger(new LogOutputStream(task, Project.MSG_INFO), +
    + The type of object is: org.apache.tools.ant.taskdefs.LogOutputStream. + Reason for going out of scope: possible exceptional exit due to new SarifLogger(new LogOutputStream(task, Project.MSG_INFO), OutputStreamOptions.CLOSE) with exception type java.io.IOException +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + required.method.not.called + @MustCall method close may not have been invoked on new LogOutputStream(task, Project.MSG_INFO) or any of its aliases. + xmlLogger = new XMLLogger(new LogOutputStream(task, Project.MSG_INFO), +
    + The type of object is: org.apache.tools.ant.taskdefs.LogOutputStream. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + return + incompatible types in return. + return resultHandler; +
    + type of expression: @FenumTop AbstractExpressionHandler + method return type: @FenumUnqualified AbstractExpressionHandler +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + argument + incompatible argument for parameter arg1 of JLabel constructor. + final JLabel modesLabel = new JLabel("Modes:", SwingConstants.RIGHT); +
    + found : @SwingHorizontalOrientation int + required: @FenumUnqualified int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + required.method.not.called + @MustCall method close may not have been invoked on "XmlMetaReader.class.getResourceAsStream("/" +..." or any of its aliases. + moduleDetails = read(XmlMetaReader.class.getResourceAsStream("/" + fileName), +
    + The type of object is: java.io.InputStream. + Reason for going out of scope: possible exceptional exit due to throw new IllegalStateException("Problem to read all modules including third party if any. Problem detected at file: " + fileName, exc); with exception type java.lang.IllegalStateException +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + methodref.param + Incompatible parameter type for arg0 + .mapToInt(int.class::cast); +
    + found : @FenumUnqualified Object + required: capture extends @FenumTop Object + Consequence: method in @FenumUnqualified Class<@FenumUnqualified Integer> + @FenumUnqualified Integer cast(@FenumUnqualified Class<@FenumUnqualified Integer> this, @FenumUnqualified Object p0) + is not a valid method reference for method in @FenumUnqualified ToIntFunction<capture extends @FenumTop Object> + @FenumUnqualified int applyAsInt(@FenumUnqualified ToIntFunction<capture extends @FenumTop Object> this, capture extends @FenumTop Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + type.arguments.not.inferred + Could not infer type arguments for Stream.map + .map(Pattern.class::cast) +
    + unsatisfiable constraint: capture extends @FenumTop Object <: @FenumUnqualified Object + Pattern.class::cast -> inference type: java.util.function.Function<? super capture of ?,? extends R> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + type.arguments.not.inferred + Could not infer type arguments for Stream.map + .map(String.class::cast) +
    + unsatisfiable constraint: capture extends @FenumTop Object <: @FenumUnqualified Object + String.class::cast -> inference type: java.util.function.Function<? super capture of ?,? extends R> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateSink.java + required.method.not.called + @MustCall method close may not have been invoked on new CustomPrintWriter(writer) or any of its aliases. + super(new CustomPrintWriter(writer)); +
    + The type of object is: com.puppycrawl.tools.checkstyle.site.XdocsTemplateSink.CustomPrintWriter. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/UnmodifiableCollectionUtil.java + type.arguments.not.inferred + Could not infer type arguments for Stream.map + .map(elementType::cast) +
    + unsatisfiable constraint: S extends @FenumTop Object <: @FenumUnqualified Object + elementType::cast -> inference type: java.util.function.Function<? super S,? extends R> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractNode.java + required.method.not.called + @MustCall method close may not have been invoked on axisIterator or any of its aliases. + AxisIterator axisIterator = iterateAxis(axisNumber); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: variable overwritten by assignment axisIterator = new Navigator.AxisFilter(axisIterator, nodeTest) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.java + required.method.not.called + @MustCall method close may not have been invoked on SingleNodeIterator.makeIterator(start) or any of its aliases. + descendantEnum = SingleNodeIterator.makeIterator(start); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.java + required.method.not.called + @MustCall method close may not have been invoked on queue.poll().iterateAxis(AxisInfo.CHILD) or any of its aliases. + descendantEnum = queue.poll().iterateAxis(AxisInfo.CHILD); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.java + required.method.not.called + @MustCall method close may not have been invoked on start.iterateAxis(AxisInfo.CHILD) or any of its aliases. + descendantEnum = start.iterateAxis(AxisInfo.CHILD); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/FollowingIterator.java + required.method.not.called + @MustCall method close may not have been invoked on parent.iterateAxis(AxisInfo.FOLLOWING_SIBLING) or any of its aliases. + siblingEnum = parent.iterateAxis(AxisInfo.FOLLOWING_SIBLING); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/FollowingIterator.java + required.method.not.called + @MustCall method close may not have been invoked on result.iterateAxis(AxisInfo.DESCENDANT) or any of its aliases. + descendantEnum = result.iterateAxis(AxisInfo.DESCENDANT); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/FollowingIterator.java + required.method.not.called + @MustCall method close may not have been invoked on start.iterateAxis(AxisInfo.ANCESTOR) or any of its aliases. + ancestorEnum = start.iterateAxis(AxisInfo.ANCESTOR); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/FollowingIterator.java + required.method.not.called + @MustCall method close may not have been invoked on start.iterateAxis(AxisInfo.FOLLOWING_SIBLING) or any of its aliases. + siblingEnum = start.iterateAxis(AxisInfo.FOLLOWING_SIBLING); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/PrecedingIterator.java + required.method.not.called + @MustCall method close may not have been invoked on new ReverseDescendantIterator(result) or any of its aliases. + descendantEnum = new ReverseDescendantIterator(result); +
    + The type of object is: com.puppycrawl.tools.checkstyle.xpath.iterators.ReverseDescendantIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/PrecedingIterator.java + required.method.not.called + @MustCall method close may not have been invoked on result.iterateAxis(AxisInfo.PRECEDING_SIBLING) or any of its aliases. + previousSiblingEnum = result.iterateAxis(AxisInfo.PRECEDING_SIBLING); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/PrecedingIterator.java + required.method.not.called + @MustCall method close may not have been invoked on start.iterateAxis(AxisInfo.ANCESTOR) or any of its aliases. + ancestorEnum = start.iterateAxis(AxisInfo.ANCESTOR); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/PrecedingIterator.java + required.method.not.called + @MustCall method close may not have been invoked on start.iterateAxis(AxisInfo.PRECEDING_SIBLING) or any of its aliases. + previousSiblingEnum = start.iterateAxis(AxisInfo.PRECEDING_SIBLING); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseDescendantIterator.java + required.method.not.called + @MustCall method close may not have been invoked on queue.poll().iterateAxis(AxisInfo.CHILD) or any of its aliases. + pushToStack(queue.poll().iterateAxis(AxisInfo.CHILD)); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseDescendantIterator.java + required.method.not.called + @MustCall method close may not have been invoked on start.iterateAxis(AxisInfo.CHILD) or any of its aliases. + pushToStack(start.iterateAxis(AxisInfo.CHILD)); +
    + The type of object is: net.sf.saxon.tree.iter.AxisIterator. + Reason for going out of scope: regular method exit +
    +
    +
    diff --git a/config/checker-framework-suppressions/checker-nullness-optional-interning-suppressions.xml b/config/checker-framework-suppressions/checker-nullness-optional-interning-suppressions.xml new file mode 100644 index 000000000000..7dbbc0d8b289 --- /dev/null +++ b/config/checker-framework-suppressions/checker-nullness-optional-interning-suppressions.xml @@ -0,0 +1,9841 @@ + + + + src/main/java/com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.java + initialization.field.uninitialized + the default constructor does not initialize field configuration + private Configuration configuration; + + + + src/main/java/com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + return result.toArray(CommonUtil.EMPTY_STRING_ARRAY); + + + + src/main/java/com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + return result.toArray(EMPTY_MODIFIER_ARRAY); + + + + src/main/java/com/puppycrawl/tools/checkstyle/Checker.java + argument + incompatible argument for parameter args of Checker.getLocalizedMessage. + getLocalizedMessage("Checker.setupChildModule", name, exc.getMessage()), exc); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Checker.java + argument + incompatible argument for parameter args of Violation constructor. + new String[] {ioe.getMessage()}, null, getClass(), null)); +
    + found : @Initialized @Nullable String @Initialized @NonNull [] + required: @Initialized @NonNull Object @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Checker.java + argument + incompatible argument for parameter moduleId of Violation constructor. + new String[] {ioe.getMessage()}, null, getClass(), null)); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Checker.java + argument + incompatible argument for parameter moduleId of Violation constructor. + null, getClass(), null)); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Checker.java + initialization.fields.uninitialized + the constructor does not initialize fields: basedir, moduleFactory, moduleClassLoader, childContext, fileExtensions, cacheFile + public Checker() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/Checker.java + method.invocation + call to addListener(com.puppycrawl.tools.checkstyle.api.AuditListener) not allowed on the given receiver. + addListener(counter); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.class) @NonNull Checker + required: @Initialized @NonNull Checker +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ChecksAndFilesSuppressionFileGeneratorAuditListener.java + argument + incompatible argument for parameter fileName of ChecksAndFilesSuppressionFileGeneratorAuditListener.suppressXmlWriter. + suppressXmlWriter(fileName, checkName, moduleIdName); +
    + found : @Initialized @Nullable Path + required: @Initialized @NonNull Path +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java + argument + incompatible argument for parameter arg0 of Collection.add. + fragments.add(null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java + dereference.of.nullable + dereference of possibly-null reference parentModule + parentModule.removeChild(recentModule); + + + + src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java + dereference.of.nullable + dereference of possibly-null reference top + top.addChild(conf); + + + + src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java + dereference.of.nullable + dereference of possibly-null reference top + top.addMessage(key, value); + + + + src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java + dereference.of.nullable + dereference of possibly-null reference top + top.addProperty(name, value); + + + + src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java + initialization.fields.uninitialized + the constructor does not initialize fields: configuration + private InternalLoader() + + + + src/main/java/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java + return + incompatible types in return. + return children.toArray( +
    + type of expression: @Initialized @Nullable Configuration @Initialized @NonNull [] + method return type: @Initialized @NonNull Configuration @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java + return + incompatible types in return. + return keySet.toArray(CommonUtil.EMPTY_STRING_ARRAY); +
    + type of expression: @Initialized @Nullable String @Initialized @NonNull [] + method return type: @Initialized @NonNull String @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + return children.toArray( + + + + src/main/java/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + return keySet.toArray(CommonUtil.EMPTY_STRING_ARRAY); + + + + src/main/java/com/puppycrawl/tools/checkstyle/DefaultContext.java + return + incompatible types in return. + return entries.get(key); +
    + type of expression: @Initialized @Nullable Object + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + assignment + incompatible types in assignment. + prevParent.branchTokenTypes = null; +
    + found : null (NullType) + required: @Initialized @NonNull BitSet +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + assignment + incompatible types in assignment. + firstChild = null; +
    + found : null (NullType) + required: @Initialized @NonNull DetailAstImpl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + initialization.field.uninitialized + the default constructor does not initialize field branchTokenTypes + private BitSet branchTokenTypes; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + initialization.field.uninitialized + the default constructor does not initialize field firstChild + private DetailAstImpl firstChild; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + initialization.field.uninitialized + the default constructor does not initialize field hiddenAfter + private List<Token> hiddenAfter; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + initialization.field.uninitialized + the default constructor does not initialize field hiddenBefore + private List<Token> hiddenBefore; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + initialization.field.uninitialized + the default constructor does not initialize field nextSibling + private DetailAstImpl nextSibling; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + initialization.field.uninitialized + the default constructor does not initialize field parent + private DetailAstImpl parent; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + initialization.field.uninitialized + the default constructor does not initialize field previousSibling + private DetailAstImpl previousSibling; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + initialization.field.uninitialized + the default constructor does not initialize field text + private String text; + + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + return + incompatible types in return. + return returnList; +
    + type of expression: @Initialized @Nullable List<@Initialized @NonNull Token> + method return type: @Initialized @NonNull List<@Initialized @NonNull Token> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/DetailAstImpl.java + return + incompatible types in return. + return returnList; +
    + type of expression: @Initialized @Nullable List<@Initialized @NonNull Token> + method return type: @Initialized @NonNull List<@Initialized @NonNull Token> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + argument + incompatible argument for parameter child of DetailAstImpl.addChild. + bop.addChild(descendantList.poll()); +
    + found : @Initialized @Nullable DetailAstImpl + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + dereference.of.nullable + dereference of possibly-null reference ident + ident.addPreviousSibling(create(ctx.ELLIPSIS())); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + dereference.of.nullable + dereference of possibly-null reference type + type.addChild(visit(ctx.annotations())); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + dereference.of.nullable + dereference of possibly-null reference typeAst + ctx.cStyleArrDec.forEach(child -> typeAst.addChild(visit(child))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + dereference.of.nullable + dereference of possibly-null reference typeAst + ctx.cStyleArrDec.forEach(child -> typeAst.addChild(visit(child))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + dereference.of.nullable + dereference of possibly-null reference typeAst + ctx.cStyleArrDec.forEach(child -> typeAst.addChild(visit(child))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + initialization.field.uninitialized + the default constructor does not initialize field child + private DetailAstImpl child; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + initialization.field.uninitialized + the default constructor does not initialize field root + private DetailAstImpl root; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(() -> createImaginary(TokenTypes.ELIST)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(() -> createImaginary(TokenTypes.ELIST)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(() -> createImaginary(TokenTypes.ELIST)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(() -> createImaginary(TokenTypes.ELIST)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(() -> createImaginary(TokenTypes.ELIST)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(() -> createImaginary(TokenTypes.PARAMETERS)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + not.interned + attempting to use a non-@Interned comparison operand + else if (ctx.children.get(i) == expression) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + not.interned + attempting to use a non-@Interned comparison operand + else if (ctx.children.get(i) == expression) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + not.interned + attempting to use a non-@Interned comparison operand + if (ctx.children.get(i) == rbrack) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + not.interned + attempting to use a non-@Interned comparison operand + if (ctx.children.get(i) == rbrack) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + return + incompatible types in return. + return annotations; +
    + type of expression: @Initialized @Nullable DetailAstImpl + method return type: @Initialized @NonNull DetailAstImpl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + return + incompatible types in return. + return ast; +
    + type of expression: @Initialized @Nullable DetailAstImpl + method return type: @Initialized @NonNull DetailAstImpl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java + return + incompatible types in return. + return compilationUnit; +
    + type of expression: @Initialized @Nullable DetailAstImpl + method return type: @Initialized @NonNull DetailAstImpl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocCommentsAstVisitor.java + initialization.field.uninitialized + the default constructor does not initialize field startToken + private Token startToken; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocCommentsAstVisitor.java + initialization.fields.uninitialized + the constructor does not initialize fields: firstNonTightHtmlTag + public JavadocCommentsAstVisitor(CommonTokenStream tokens, + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.java + initialization.field.uninitialized + the default constructor does not initialize field errorMessage + private ParseErrorMessage errorMessage; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.java + initialization.field.uninitialized + the default constructor does not initialize field firstNonTightHtmlTag + private DetailNode firstNonTightHtmlTag; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.java + initialization.field.uninitialized + the default constructor does not initialize field parseErrorMessage + private ParseErrorMessage parseErrorMessage; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.java + initialization.field.uninitialized + the default constructor does not initialize field tree + private DetailNode tree; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + argument + incompatible argument for parameter ast of JavadocPropertiesGenerator.getFirstJavadocSentence. + final String firstJavadocSentence = getFirstJavadocSentence(modifiers); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + return ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + dereference.of.nullable + dereference of possibly-null reference modifiers + result = modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + dereference.of.nullable + dereference of possibly-null reference type + final DetailAST arrayDeclarator = type.getFirstChild().getNextSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + initialization.field.uninitialized + the default constructor does not initialize field inputFile + private File inputFile; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + initialization.field.uninitialized + the default constructor does not initialize field outputFile + private File outputFile; + + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + return + incompatible types in return. + return objBlock; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + return + incompatible types in return. + return firstSentence; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java + return + incompatible types in return. + return firstSentence; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/LocalizedMessage.java + argument + incompatible argument for parameter arg2 of ResourceBundle.getBundle. + return ResourceBundle.getBundle(bundle, sLocale, sourceClass.getClassLoader(), +
    + found : @Initialized @Nullable ClassLoader + required: @Initialized @NonNull ClassLoader +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/LocalizedMessage.java + assignment + incompatible types in assignment. + this.args = null; +
    + found : null (NullType) + required: @Initialized @NonNull Object @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/LocalizedMessage.java + return + incompatible types in return. + return resourceBundle; +
    + type of expression: @Initialized @Nullable ResourceBundle + method return type: @Initialized @NonNull ResourceBundle +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + argument + incompatible argument for parameter moduleClassLoader of Main.getRootModule. + final RootModule rootModule = getRootModule(config.getName(), moduleClassLoader); +
    + found : @Initialized @Nullable ClassLoader + required: @Initialized @NonNull ClassLoader +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + dereference.of.nullable + dereference of possibly-null reference Checker.class.getPackage() + Checker.class.getPackage().getName(), moduleClassLoader); + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + dereference.of.nullable + dereference of possibly-null reference Main.class.getPackage() + private final String packageName = Main.class.getPackage().getName(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + dereference.of.nullable + dereference of possibly-null reference Main.class.getPackage() + return Main.class.getPackage().getImplementationVersion(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + dereference.of.nullable + dereference of possibly-null reference logRecord.getLoggerName() + return logRecord.getLoggerName().startsWith(packageName); + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + dereference.of.nullable + dereference of possibly-null reference parentLogger + parentLogger.addHandler(handler); + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + initialization.field.uninitialized + the default constructor does not initialize field configurationFile + private String configurationFile; + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + initialization.field.uninitialized + the default constructor does not initialize field files + private List<File> files; + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + initialization.field.uninitialized + the default constructor does not initialize field outputPath + private Path outputPath; + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + initialization.field.uninitialized + the default constructor does not initialize field propertiesFile + private File propertiesFile; + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + initialization.field.uninitialized + the default constructor does not initialize field suppressionLineColumnNumber + private String suppressionLineColumnNumber; + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + initialization.field.uninitialized + the default constructor does not initialize field xpath + private String xpath; + + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable Configuration + method return type: @Initialized @NonNull Configuration +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/Main.java + return + incompatible types in return. + return Main.class.getPackage().getImplementationVersion(); +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + argument + incompatible argument for parameter arg0 of Optional.orElse. + .orElse(fullName); +
    + found : String + required: @KeyFor("com.puppycrawl.tools.checkstyle.PackageObjectFactory.class.NAME_TO_FULL_MODULE_NAME") String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + argument + incompatible argument for parameter arg0 of Set.contains. + if (packageNames.contains(null)) { +
    + found : null (NullType) + required: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + argument + incompatible argument for parameter args of LocalizedMessage constructor. + UNABLE_TO_INSTANTIATE_EXCEPTION_MESSAGE, name, attemptedNames); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + initialization.fields.uninitialized + the constructor does not initialize fields: thirdPartyNameToFullModuleNames + public PackageObjectFactory(Set<String> packageNames, ClassLoader moduleClassLoader, + + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + initialization.fields.uninitialized + the constructor does not initialize fields: thirdPartyNameToFullModuleNames, moduleLoadOption + public PackageObjectFactory(String packageName, ClassLoader moduleClassLoader) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + return + incompatible types in return. + return instance; +
    + type of expression: @Initialized @Nullable Object + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + return + incompatible types in return. + return instance; +
    + type of expression: @Initialized @Nullable Object + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + return + incompatible types in return. + return instance; +
    + type of expression: @Initialized @Nullable Object + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + return + incompatible types in return. + return instance; +
    + type of expression: @Initialized @Nullable Object + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + type.arguments.not.inferred + Could not infer type arguments for Stream.collect + .collect(Collectors.groupingBy(Class::getSimpleName, +
    + unsatisfiable constraint: @Initialized @Nullable String <: @Initialized @NonNull String + @Initialized @Nullable String <: use of U from Collectors.mapping(Class::getCanonicalName, Collectors.toCollection(HashSet::new)) + From complementary bound.: @Initialized @Nullable String -> use of U from Collectors.mapping(Class::getCanonicalName, Collectors.toCollection(HashSet::new)) + Class::getCanonicalName -> inference type: java.util.function.Function<? super java.lang.Class<?>,? extends U> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertiesExpander.java + methodref.return + Incompatible return type + Collectors.toUnmodifiableMap(Function.identity(), properties::getProperty)); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String + Consequence: method in @Initialized @NonNull Properties + @Initialized @Nullable String getProperty(@Initialized @NonNull Properties this, @Initialized @NonNull String p0) + is not a valid method reference for method in @Initialized @NonNull Function<@Initialized @NonNull String, @Initialized @NonNull String> + @Initialized @NonNull String apply(@Initialized @NonNull Function<@Initialized @NonNull String, @Initialized @NonNull String> this, @Initialized @NonNull String p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertiesExpander.java + return + incompatible types in return. + return values.get(name); +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + dereference.of.nullable + dereference of possibly-null reference cachedHashSum + if (!cachedHashSum.equals(contentHashSum)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + initialization.fields.uninitialized + the constructor does not initialize fields: configHash + public PropertyCacheFile(Configuration config, String fileName) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + return + incompatible types in return. + return details.getProperty(name); +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + argument + incompatible argument for parameter arg1 of Map.putIfAbsent. + ruleMetadata.putIfAbsent(key, module); +
    + found : @Initialized @Nullable ModuleDetails + required: @Initialized @NonNull ModuleDetails +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + argument + incompatible argument for parameter arg2 of ResourceBundle.getBundle. + moduleClass.getClassLoader(), +
    + found : @Initialized @Nullable ClassLoader + required: @Initialized @NonNull ClassLoader +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + argument + incompatible argument for parameter value of SarifLogger.escape. + .replace("${text}", escape(message)); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + dereference.of.nullable + dereference of possibly-null reference SarifLogger.class.getPackage() + final String version = SarifLogger.class.getPackage().getImplementationVersion(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + method.invocation + call to loadModuleMetadata() not allowed on the given receiver. + loadModuleMetadata(); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.class) @NonNull SarifLogger + required: @Initialized @NonNull SarifLogger +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SuppressionsStringPrinter.java + argument + incompatible argument for parameter arg0 of Integer.parseInt. + final int columnNumber = Integer.parseInt(matcher.group(2)); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SuppressionsStringPrinter.java + argument + incompatible argument for parameter arg0 of Integer.parseInt. + final int lineNumber = Integer.parseInt(matcher.group(1)); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + argument + incompatible argument for parameter args of Violation constructor. + new Object[] {exc.getMessage()}, javaParseExceptionSeverity, null, +
    + found : @Initialized @Nullable Object @Initialized @NonNull [] + required: @Initialized @NonNull Object @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + argument + incompatible argument for parameter ast of TreeWalker.walk. + walk(rootAST, contents, AstState.ORDINARY); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + argument + incompatible argument for parameter moduleId of Violation constructor. + new Object[] {exc.getMessage()}, javaParseExceptionSeverity, null, +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + argument + incompatible argument for parameter root of JavaParser.appendHiddenCommentNodes. + final DetailAST astWithComments = JavaParser.appendHiddenCommentNodes(rootAST); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + argument + incompatible argument for parameter rootAST of TreeWalker.getFilteredViolations. + getFilteredViolations(file.getAbsolutePath(), contents, rootAST); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + initialization.fields.uninitialized + the constructor does not initialize fields: childContext, moduleFactory + public TreeWalker() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + method.invocation + call to setFileExtensions(java.lang.String...) not allowed on the given receiver. + setFileExtensions("java"); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck.class) @NonNull TreeWalker + required: @Initialized @NonNull AbstractFileSetCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/TreeWalker.java + return + incompatible types in return. + return visitors; +
    + type of expression: @Initialized @Nullable Collection<@Initialized @NonNull AbstractCheck> + method return type: @Initialized @NonNull Collection<@Initialized @NonNull AbstractCheck> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java + argument + incompatible argument for parameter messages of XMLLogger.writeFileMessages. + writeFileMessages(fileName, messages); +
    + found : @Initialized @Nullable FileMessages + required: @Initialized @NonNull FileMessages +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java + dereference.of.nullable + dereference of possibly-null reference XMLLogger.class.getPackage() + final String version = XMLLogger.class.getPackage().getImplementationVersion(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java + argument + incompatible argument for parameter arg0 of InputSource constructor. + inputSource = new InputSource(dtdIs); +
    + found : @Initialized @Nullable InputStream + required: @Initialized @NonNull InputStream +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java + argument + incompatible argument for parameter handler of XmlLoader.createXmlReader. + parser = createXmlReader(this); +
    + found : @UnderInitialization(org.xml.sax.helpers.DefaultHandler.class) @NonNull XmlLoader + required: @Initialized @NonNull DefaultHandler +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java + dereference.of.nullable + dereference of possibly-null reference loader + final InputStream dtdIs = loader.getResourceAsStream(dtdResourceName); + + + + src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java + override.param + Incompatible parameter type for publicId. + public InputSource resolveEntity(String publicId, String systemId) { +
    + found : @Initialized @NonNull String + required: @Initialized @Nullable String + Consequence: method in @Initialized @NonNull XmlLoader + @Initialized @NonNull InputSource resolveEntity(@Initialized @NonNull XmlLoader this, @Initialized @NonNull String p0, @Initialized @NonNull String p1) + cannot override method in @Initialized @NonNull EntityResolver + @Initialized @Nullable InputSource resolveEntity(@Initialized @NonNull EntityResolver this, @Initialized @Nullable String p0, @Initialized @NonNull String p1) throws @Initialized @NonNull SAXException@Initialized @NonNull IOException +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java + return + incompatible types in return. + return inputSource; +
    + type of expression: @Initialized @Nullable InputSource + method return type: @Initialized @NonNull InputSource +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/XpathFileGeneratorAstFilter.java + return + incompatible types in return. + return MESSAGE_QUERY_MAP.get(event.getViolation()); +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + argument + incompatible argument for parameter moduleClassLoader of PackageObjectFactory constructor. + Checker.class.getPackage().getName() + ".", moduleClassLoader); +
    + found : @Initialized @Nullable ClassLoader + required: @Initialized @NonNull ClassLoader +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + argument + incompatible argument for parameter moduleClassLoader of RootModule.setModuleClassLoader. + rootModule.setModuleClassLoader(moduleClassLoader); +
    + found : @Initialized @Nullable ClassLoader + required: @Initialized @NonNull ClassLoader +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + dereference.of.nullable + dereference of possibly-null reference Checker.class.getPackage() + Checker.class.getPackage().getName() + ".", moduleClassLoader); + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + dereference.of.nullable + dereference of possibly-null reference CheckstyleAntTask.class.getPackage() + CheckstyleAntTask.class.getPackage().getImplementationVersion(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + initialization.field.uninitialized + the default constructor does not initialize field config + private String config; + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + initialization.field.uninitialized + the default constructor does not initialize field failureProperty + private String failureProperty; + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + initialization.field.uninitialized + the default constructor does not initialize field fileName + private String fileName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + initialization.field.uninitialized + the default constructor does not initialize field key + private String key; + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + initialization.field.uninitialized + the default constructor does not initialize field properties + private Path properties; + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + initialization.field.uninitialized + the default constructor does not initialize field toFile + private File toFile; + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + initialization.field.uninitialized + the default constructor does not initialize field type + private FormatterType type; + + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + initialization.field.uninitialized + the default constructor does not initialize field value + private String value; + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java + initialization.field.uninitialized + the default constructor does not initialize field fileContents + private FileContents fileContents; + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java + type.argument + incompatible type argument for type parameter T of ThreadLocal. + private final ThreadLocal<FileContext> context = ThreadLocal.withInitial(FileContext::new); +
    + found : @Initialized @NonNull FileContext + required: [extends @Initialized @Nullable Object super null (NullType)] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java + initialization.field.uninitialized + the default constructor does not initialize field fileContents + private FileContents fileContents; + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java + initialization.field.uninitialized + the default constructor does not initialize field fileExtensions + private String[] fileExtensions; + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java + initialization.field.uninitialized + the default constructor does not initialize field messageDispatcher + private MessageDispatcher messageDispatcher; + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.java + type.argument + incompatible type argument for type parameter T of ThreadLocal. + private final ThreadLocal<FileContext> context = ThreadLocal.withInitial(FileContext::new); +
    + found : @Initialized @NonNull FileContext + required: [extends @Initialized @Nullable Object super null (NullType)] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.java + initialization.field.uninitialized + the default constructor does not initialize field id + private String id; + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AuditEvent.java + argument + incompatible argument for parameter fileName of AuditEvent constructor. + this(source, null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/AuditEvent.java + argument + incompatible argument for parameter violation of AuditEvent constructor. + this(src, fileName, null); +
    + found : null (NullType) + required: @Initialized @NonNull Violation +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java + return + incompatible types in return. + return javadocComments.get(lineNo); +
    + type of expression: @Initialized @Nullable TextBlock + method return type: @Initialized @NonNull TextBlock +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + assignment + incompatible types in assignment. + lines = textLines.toArray(CommonUtil.EMPTY_STRING_ARRAY); +
    + found : @Initialized @Nullable String @Initialized @NonNull [] + required: @Initialized @NonNull String @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + assignment + incompatible types in assignment. + this.lines = lines.toArray(CommonUtil.EMPTY_STRING_ARRAY); +
    + found : @Initialized @Nullable String @Initialized @NonNull [] + required: @Initialized @NonNull String @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + assignment + incompatible types in assignment. + charset = null; +
    + found : null (NullType) + required: @Initialized @NonNull Charset +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + initialization.fields.uninitialized + the constructor does not initialize fields: lineBreaks + public FileText(File file, List<String> lines) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + initialization.fields.uninitialized + the constructor does not initialize fields: lineBreaks + public FileText(File file, String charsetName) throws IOException { + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + initialization.fields.uninitialized + the constructor does not initialize fields: lineBreaks + public FileText(FileText fileText) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + lines = textLines.toArray(CommonUtil.EMPTY_STRING_ARRAY); + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + this.lines = lines.toArray(CommonUtil.EMPTY_STRING_ARRAY); + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/FullIdent.java + initialization.fields.uninitialized + the constructor does not initialize fields: detailAst + private FullIdent() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/api/LineColumn.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull LineColumn + @Initialized @NonNull boolean equals(@Initialized @NonNull LineColumn this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Violation.java + assignment + incompatible types in assignment. + this.args = null; +
    + found : null (NullType) + required: @Initialized @NonNull Object @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/api/Violation.java + override.param + Incompatible parameter type for object. + public boolean equals(Object object) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull Violation + @Initialized @NonNull boolean equals(@Initialized @NonNull Violation this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + initialization.field.uninitialized + the default constructor does not initialize field blockComments + private Map<Integer, List<TextBlock>> blockComments; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + initialization.field.uninitialized + the default constructor does not initialize field singlelineComments + private Map<Integer, TextBlock> singlelineComments; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.java + initialization.field.uninitialized + the default constructor does not initialize field maximumMessage + private String maximumMessage; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.java + initialization.field.uninitialized + the default constructor does not initialize field minimumMessage + private String minimumMessage; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java + argument + incompatible argument for parameter param of FinalParametersCheck.checkParam. + checkParam(catchClause.findFirstToken(TokenTypes.PARAMETER_DEF)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java + argument + incompatible argument for parameter root of TokenUtil.forEachChild. + TokenUtil.forEachChild(parameters, TokenTypes.PARAMETER_DEF, this::checkParam); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java + dereference.of.nullable + dereference of possibly-null reference param.findFirstToken(TokenTypes.MODIFIERS) + if (param.findFirstToken(TokenTypes.MODIFIERS).findFirstToken(TokenTypes.FINAL) == null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java + dereference.of.nullable + dereference of possibly-null reference paramName + MSG_KEY, paramName.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java + dereference.of.nullable + dereference of possibly-null reference type + final DetailAST parameterType = type.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.java + argument + incompatible argument for parameter args of AbstractFileSetCheck.log. + log(1, MSG_IO_EXCEPTION_KEY, file.getPath(), exc.getLocalizedMessage()); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.java + contracts.postcondition + postcondition of put is not satisfied. + public synchronized Object put(Object key, Object value) { +
    + found : key is @UnknownKeyFor + required: key is @KeyFor("this") +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.java + method.invocation + call to setFileExtensions(java.lang.String...) not allowed on the given receiver. + setFileExtensions("properties"); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.OrderedPropertiesCheck.class) @NonNull OrderedPropertiesCheck + required: @Initialized @NonNull OrderedPropertiesCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.java + override.return + Incompatible return type. + public Enumeration<Object> keys() { +
    + found : Enumeration<Object> + required: Enumeration<@KeyFor("this") Object> + Consequence: method in SequencedProperties + Enumeration<Object> keys(SequencedProperties this) + cannot override method in Hashtable<Object, Object> + Enumeration<@KeyFor("this") Object> keys(Hashtable<Object, Object> this) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheck.java + assignment + incompatible types in assignment. + wrongType = null; +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + final String outerTypeName = ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + if (modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheck.java + initialization.field.uninitialized + the default constructor does not initialize field fileName + private String fileName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheck.java + initialization.field.uninitialized + the default constructor does not initialize field wrongType + private DetailAST wrongType; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolder.java + type.argument + incompatible type argument for type parameter T of ThreadLocal. + private static final ThreadLocal<List<Entry>> ENTRIES = +
    + found : @Initialized @NonNull List<@Initialized @NonNull Entry> + required: [extends @Initialized @Nullable Object super null (NullType)] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheck.java + initialization.field.uninitialized + the default constructor does not initialize field legalComment + private Pattern legalComment; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java + argument + incompatible argument for parameter args of Violation constructor. + args, +
    + found : @Initialized @NonNull String @Initialized @Nullable [] + required: @Initialized @NonNull Object @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java + argument + incompatible argument for parameter languageCode of TranslationCheck.getMissingFileName. + getMissingFileName(bundle, null) +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java + assignment + incompatible types in assignment. + args = new String[] {exception.getMessage()}; +
    + found : @Initialized @Nullable String @Initialized @NonNull [] + required: @Initialized @NonNull String @UnknownInitialization @Nullable [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java + method.invocation + call to setFileExtensions(java.lang.String...) not allowed on the given receiver. + setFileExtensions("properties"); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck.class) @NonNull TranslationCheck + required: @Initialized @NonNull TranslationCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + argument + incompatible argument for parameter ast of FullIdent.createFullIdent. + packageName = FullIdent.createFullIdent(null); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + currentClass = packageName.getText() + "." + ident.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + return "main".equals(ident.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + dereference.of.nullable + dereference of possibly-null reference method.findFirstToken(TokenTypes.TYPE) + method.findFirstToken(TokenTypes.TYPE).getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + return modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + dereference.of.nullable + dereference of possibly-null reference parameterType + parameterType.findFirstToken(TokenTypes.ARRAY_DECLARATOR) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + dereference.of.nullable + dereference of possibly-null reference params + if (params.getChildCount() == 1) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + initialization.field.uninitialized + the default constructor does not initialize field currentClass + private String currentClass; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.java + initialization.field.uninitialized + the default constructor does not initialize field packageName + private FullIdent packageName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java + argument + incompatible argument for parameter args of AbstractFileSetCheck.log. + exc.getLocalizedMessage()); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java + contracts.postcondition + postcondition of put is not satisfied. + public synchronized Object put(Object key, Object value) { +
    + found : key is @KeyFor("super") + required: key is @KeyFor("this") +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java + method.invocation + call to setFileExtensions(java.lang.String...) not allowed on the given receiver. + setFileExtensions("properties"); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.UniquePropertiesCheck.class) @NonNull UniquePropertiesCheck + required: @Initialized @NonNull UniquePropertiesCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationLocationCheck.java + argument + incompatible argument for parameter modifierNode of AnnotationLocationCheck.checkAnnotations. + checkAnnotations(node, getExpectedAnnotationIndentation(node)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationLocationCheck.java + argument + incompatible argument for parameter node of AnnotationLocationCheck.getExpectedAnnotationIndentation. + checkAnnotations(node, getExpectedAnnotationIndentation(node)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationLocationCheck.java + dereference.of.nullable + dereference of possibly-null reference annotation.findFirstToken(TokenTypes.DOT) + identNode = annotation.findFirstToken(TokenTypes.DOT).findFirstToken(TokenTypes.IDENT); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationLocationCheck.java + dereference.of.nullable + dereference of possibly-null reference identNode + return identNode.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationOnSameLineCheck.java + dereference.of.nullable + dereference of possibly-null reference annotation.findFirstToken(TokenTypes.DOT) + identNode = annotation.findFirstToken(TokenTypes.DOT).getLastChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationOnSameLineCheck.java + dereference.of.nullable + dereference of possibly-null reference nodeWithAnnotations + DetailAST modifiersNode = nodeWithAnnotations.findFirstToken(TokenTypes.MODIFIERS); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleCheck.java + dereference.of.nullable + dereference of possibly-null reference rCurly + final DetailAST comma = rCurly.getPreviousSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleCheck.java + dereference.of.nullable + dereference of possibly-null reference valuePair + valuePair.getFirstChild().getText())) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/MissingOverrideCheck.java + dereference.of.nullable + dereference of possibly-null reference startNode + Stream.iterate(startNode.getLastChild(), Objects::nonNull, + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/MissingOverrideCheck.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElse(modifiers); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsCheck.java + dereference.of.nullable + dereference of possibly-null reference colon + return colon.getNextSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsCheck.java + dereference.of.nullable + dereference of possibly-null reference colon + return colon.getPreviousSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheck.java + argument + incompatible argument for parameter arg0 of Optional.of. + leftCurly = Optional.of(ast.findFirstToken(TokenTypes.SLIST)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheck.java + dereference.of.nullable + dereference of possibly-null reference rcurlyAST + final int rcurlyLineNo = rcurlyAST.getLineNo(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheck.java + argument + incompatible argument for parameter ast of AbstractCheck.log. + log(catchAst.findFirstToken(TokenTypes.SLIST), MSG_KEY_CATCH_BLOCK_EMPTY); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheck.java + dereference.of.nullable + dereference of possibly-null reference parameterDef + final DetailAST variableName = parameterDef.findFirstToken(TokenTypes.IDENT); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheck.java + dereference.of.nullable + dereference of possibly-null reference slistToken + DetailAST catchBlockStmt = slistToken.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheck.java + dereference.of.nullable + dereference of possibly-null reference variableName + return variableName.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.java + return + incompatible types in return. + return annotation; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/NeedBracesCheck.java + argument + incompatible argument for parameter ast1 of TokenUtil.areOnSameLine. + result = TokenUtil.areOnSameLine(ifCondition, block); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/NeedBracesCheck.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElse(Boolean.TRUE); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter lcurly of Details constructor. + return new Details(lcurly, rcurly, getNextToken(ast), true); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter lcurly of Details constructor. + return new Details(lcurly, rcurly, nextToken, false); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter lcurly of Details constructor. + return new Details(lcurly, rcurly, nextToken, true); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter lcurly of Details constructor. + return new Details(lcurly.orElse(null), rcurly, nextToken.orElse(null), true); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter nextToken of Details constructor. + return new Details(lcurly, rcurly, nextToken, false); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter nextToken of Details constructor. + return new Details(lcurly, rcurly, nextToken, true); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter nextToken of Details constructor. + return new Details(lcurly.orElse(null), rcurly, nextToken.orElse(null), true); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter rcurly of Details constructor. + return new Details(lcurly, rcurly, getNextToken(ast), true); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter rcurly of Details constructor. + return new Details(lcurly, rcurly, nextToken, false); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter rcurly of Details constructor. + return new Details(lcurly, rcurly, nextToken, shouldCheckLastRcurly); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter rcurly of Details constructor. + return new Details(lcurly, rcurly, nextToken, true); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + argument + incompatible argument for parameter rcurly of Details constructor. + return new Details(lcurly.orElse(null), rcurly, nextToken.orElse(null), true); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.java + return + incompatible types in return. + return next; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.java + argument + incompatible argument for parameter ast of AbstractCheck.log. + log(nameAST, MSG_KEY, nameAST.getText()); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAST + && modifiersAST.findFirstToken(TokenTypes.LITERAL_NATIVE) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.java + dereference.of.nullable + dereference of possibly-null reference nameAST + final String name = nameAST.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.java + dereference.of.nullable + dereference of possibly-null reference nameAST + log(nameAST, MSG_KEY, nameAST.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.java + dereference.of.nullable + dereference of possibly-null reference params + overridingMethod = !params.hasChildren(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ArrayTrailingCommaCheck.java + dereference.of.nullable + dereference of possibly-null reference rcurly + final DetailAST previousSibling = rcurly.getPreviousSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AvoidNoArgumentSuperConstructorCallCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.ELIST) + && ast.findFirstToken(TokenTypes.ELIST).getChildCount() == 0) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ConstructorsDeclarationGroupingCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.OBJBLOCK) + DetailAST child = ast.findFirstToken(TokenTypes.OBJBLOCK).getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.java + argument + incompatible argument for parameter ast of AbstractCheck.log. + log(nameNode, MSG_KEY); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.java + argument + incompatible argument for parameter ast of FullIdent.createFullIdentBelow. + final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.java + dereference.of.nullable + dereference of possibly-null reference paramNode + final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.java + dereference.of.nullable + dereference of possibly-null reference paramsNode + paramsNode.findFirstToken(TokenTypes.PARAMETER_DEF); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.java + argument + incompatible argument for parameter ast of DeclarationOrderCheck.getAllTokensOfType. + final Set<DetailAST> exprIdents = getAllTokensOfType(exprStartIdent, TokenTypes.IDENT); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.java + argument + incompatible argument for parameter state of DeclarationOrderCheck.processModifiersState. + final boolean isStateValid = processModifiersState(ast, state); +
    + found : @Initialized @Nullable ScopeState + required: @Initialized @NonNull ScopeState +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.java + dereference.of.nullable + dereference of possibly-null reference fieldDef + classFieldNames.add(fieldDef.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.java + dereference.of.nullable + dereference of possibly-null reference state + if (state.currentScopeState > STATE_CTOR_DEF) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.java + dereference.of.nullable + dereference of possibly-null reference state + state.currentScopeState = STATE_METHOD_DEF; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.java + initialization.field.uninitialized + the default constructor does not initialize field classFieldNames + private Set<String> classFieldNames; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.java + initialization.field.uninitialized + the default constructor does not initialize field scopeStates + private Deque<ScopeState> scopeStates; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + argument + incompatible argument for parameter parent of FieldFrame constructor. + currentFrame = new FieldFrame(null); +
    + found : null (NullType) + required: @Initialized @NonNull FieldFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + frame.setFrameName(ast.findFirstToken(TokenTypes.IDENT).getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + dereference.of.nullable + dereference of possibly-null reference elist + return elist.getChildCount() == 1; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + dereference.of.nullable + dereference of possibly-null reference field.findFirstToken(TokenTypes.IDENT) + return field.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + dereference.of.nullable + dereference of possibly-null reference field.findFirstToken(TokenTypes.TYPE) + final DetailAST identAst = field.findFirstToken(TokenTypes.TYPE) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + dereference.of.nullable + dereference of possibly-null reference methodCall.findFirstToken(TokenTypes.ELIST) + final DetailAST expr = methodCall.findFirstToken(TokenTypes.ELIST).getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + initialization.field.uninitialized + the default constructor does not initialize field currentFrame + private FieldFrame currentFrame; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + initialization.fields.uninitialized + the constructor does not initialize fields: frameName + private FieldFrame(FieldFrame parent) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + return + incompatible types in return. + return fieldNameToAst.get(name); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java + return + incompatible types in return. + return fieldType; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheck.java + argument + incompatible argument for parameter ast of FullIdent.createFullIdentBelow. + final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheck.java + dereference.of.nullable + dereference of possibly-null reference methodName + return "hashCode".equals(methodName.getText()) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheck.java + dereference.of.nullable + dereference of possibly-null reference parameters + && isObjectParam(parameters.getFirstChild()) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheck.java + dereference.of.nullable + dereference of possibly-null reference parameters + && parameters.getFirstChild() == null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + argument + incompatible argument for parameter ast of AbstractCheck.log. + log(ident, MSG_KEY, ident.getText(), "0"); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + argument + incompatible argument for parameter ast of AbstractCheck.log. + log(ident, MSG_KEY, ident.getText(), "\\0"); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + argument + incompatible argument for parameter ast of AbstractCheck.log. + log(ident, MSG_KEY, ident.getText(), "false"); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + argument + incompatible argument for parameter ast of AbstractCheck.log. + log(ident, MSG_KEY, ident.getText(), "null"); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + dereference.of.nullable + dereference of possibly-null reference assign + assign.getFirstChild().getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + dereference.of.nullable + dereference of possibly-null reference assign + assign.getFirstChild().getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + log(ident, MSG_KEY, ident.getText(), "0"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + log(ident, MSG_KEY, ident.getText(), "\\0"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + log(ident, MSG_KEY, ident.getText(), "false"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + log(ident, MSG_KEY, ident.getText(), "null"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + skipCase = modifiers.findFirstToken(TokenTypes.FINAL) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.java + dereference.of.nullable + dereference of possibly-null reference type + final int primitiveType = type.getFirstChild().getType(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + argument + incompatible argument for parameter ast of FallThroughCheck.getNextNonCommentAst. + final DetailAST thenStmt = getNextNonCommentAst(ast.findFirstToken(TokenTypes.RPAREN)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + argument + incompatible argument for parameter ast of FallThroughCheck.isTerminated. + && isTerminated(finalStmt.findFirstToken(TokenTypes.SLIST), +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + argument + incompatible argument for parameter ast of FallThroughCheck.isTerminated. + isTerminated = isTerminated(catchBody, useBreak, useContinue, labels); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + argument + incompatible argument for parameter ast of FallThroughCheck.isTerminated. + synchronizedAst.findFirstToken(TokenTypes.SLIST), useBreak, useContinue, labels); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + dereference.of.nullable + dereference of possibly-null reference caseGroup + while (isTerminated && caseGroup.getType() != TokenTypes.RCURLY) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + dereference.of.nullable + dereference of possibly-null reference lparen + loopBody = lparen.getPreviousSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + dereference.of.nullable + dereference of possibly-null reference rparen + loopBody = rparen.getNextSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .isPresent(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + argument + incompatible argument for parameter variableIdent of FinalVariableCandidate constructor. + final FinalVariableCandidate candidate = new FinalVariableCandidate(astNode); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + || !"_".equals(ast.findFirstToken(TokenTypes.IDENT).getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.MODIFIERS) + && ast.findFirstToken(TokenTypes.MODIFIERS) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.MODIFIERS) + && ast.findFirstToken(TokenTypes.MODIFIERS) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference astNode + scope.put(astNode.getText(), candidate); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference astNode + scope.put(astNode.getText(), new FinalVariableCandidate(astNode)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference candidate + shouldRemove = candidate.alreadyAssigned; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference currentScopeAssignedVariables.peek() + currentScopeAssignedVariables.peek().add(ast); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference currentScopeAssignedVariables.peek() + final Iterator<DetailAST> iterator = currentScopeAssignedVariables.peek().iterator(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference scopeData + scopeData.uninitializedVariables.forEach(prevScopeUninitializedVariableData::push); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference scopeStack.peek() + case TokenTypes.LITERAL_BREAK -> scopeStack.peek().containsBreak = true; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference scopeStack.peek() + containsBreak = scopeStack.peek().containsBreak; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference scopeStack.peek() + final Map<String, FinalVariableCandidate> scope = scopeStack.peek().scope; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference scopeStack.peek() + final Map<String, FinalVariableCandidate> scope = scopeStack.peek().scope; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference scopeStack.peek() + scopeStack.peek().uninitializedVariables.add(astNode); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference typeAst + return typeAst.findFirstToken(TokenTypes.BOR) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + .findFirstToken(TokenTypes.CASE_GROUP) == ast.getParent()) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + .findFirstToken(TokenTypes.CASE_GROUP) == ast.getParent()) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + == parentAst) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (currAstLoopAstParent == currVarLoopAstParent) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (currAstLoopAstParent == currVarLoopAstParent) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + result = findLastCaseGroupWhichContainsSlist(ast.getParent()) != ast; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + result = findLastCaseGroupWhichContainsSlist(ast.getParent()) != ast; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + return classOrMethodOfAst1 == classOrMethodOfAst2 && ast1.getText().equals(ast2.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + return classOrMethodOfAst1 == classOrMethodOfAst2 && ast1.getText().equals(ast2.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + || findLastCaseGroupWhichContainsSlist(parentAst.getParent()) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java + return + incompatible types in return. + return returnValue; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + argument + incompatible argument for parameter frameName of FieldFrame constructor. + final FieldFrame newFrame = new FieldFrame(frame, isStaticInnerType, frameName); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + argument + incompatible argument for parameter frameName of FieldFrame constructor. + frame = new FieldFrame(null, true, null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + argument + incompatible argument for parameter parent of FieldFrame constructor. + frame = new FieldFrame(null, true, null); +
    + found : null (NullType) + required: @Initialized @NonNull FieldFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + argument + incompatible argument for parameter root of TokenUtil.forEachChild. + TokenUtil.forEachChild(recordComponents, +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference aMethodAST.findFirstToken(TokenTypes.IDENT) + aMethodAST.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + frameName = ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference child.findFirstToken(TokenTypes.IDENT) + child.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference mods + if (mods.findFirstToken(TokenTypes.LITERAL_STATIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference mods + inStatic = mods.findFirstToken(TokenTypes.LITERAL_STATIC) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference mods + result = mods.findFirstToken(TokenTypes.ABSTRACT) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference nameAST + final String name = nameAST.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference node.findFirstToken(TokenTypes.IDENT) + final String name = node.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + dereference.of.nullable + dereference of possibly-null reference typeAST + final String returnType = typeAST.getFirstChild().getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + initialization.field.uninitialized + the default constructor does not initialize field frame + private FieldFrame frame; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.java + initialization.field.uninitialized + the default constructor does not initialize field ignoreFormat + private Pattern ignoreFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalCatchCheck.java + dereference.of.nullable + dereference of possibly-null reference excTypeParent + DetailAST currentNode = excTypeParent.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalCatchCheck.java + dereference.of.nullable + dereference of possibly-null reference parameterDef + parameterDef.findFirstToken(TokenTypes.TYPE); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java + assignment + incompatible types in assignment. + pkgName = null; +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java + dereference.of.nullable + dereference of possibly-null reference identToken + final String className = identToken.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java + initialization.field.uninitialized + the default constructor does not initialize field pkgName + private String pkgName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java + return + incompatible types in return. + return fullClassName; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java + return + incompatible types in return. + return illegalType; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalThrowsCheck.java + dereference.of.nullable + dereference of possibly-null reference methodDef.findFirstToken(TokenTypes.IDENT) + return shouldIgnoreMethod(methodDef.findFirstToken(TokenTypes.IDENT).getText()) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java + argument + incompatible argument for parameter modifiers of IllegalTypeCheck.isContainVerifiableType. + result = isContainVerifiableType(modifiersAst); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java + argument + incompatible argument for parameter type of IllegalTypeCheck.checkType. + checkType(type); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.java + dereference.of.nullable + dereference of possibly-null reference identAST + if ("hashCode".equals(identAST.getText())) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAST + if (modifiersAST.findFirstToken(TokenTypes.FINAL) != null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.java + dereference.of.nullable + dereference of possibly-null reference paramAST + inHashCodeMethod = !paramAST.hasChildren(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (astNode != constantDefAST) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (astNode != constantDefAST) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.java + return + incompatible types in return. + return constantDef; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheck.java + initialization.field.uninitialized + the default constructor does not initialize field xpathExpression + private XPathExpression xpathExpression; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MissingCtorCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.OBJBLOCK) + && ast.findFirstToken(TokenTypes.OBJBLOCK) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MissingCtorCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + if (modifiers.findFirstToken(TokenTypes.ABSTRACT) == null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MissingNullCaseInSwitchCheck.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .isPresent(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + argument + incompatible argument for parameter ast of ModifiedControlVariableCheck.findChildrenOfExpressionType. + findChildrenOfExpressionType(forUpdateListAST).stream() +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + argument + incompatible argument for parameter paramDef of ModifiedControlVariableCheck.leaveForEach. + leaveForEach(paramDef); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference forInitAST + for (DetailAST parameterDefAST = forInitAST.findFirstToken(TokenTypes.VARIABLE_DEF); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference forIteratorAST + final DetailAST forUpdateListAST = forIteratorAST.findFirstToken(TokenTypes.ELIST); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference param + initializedVariables.add(param.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference paramName + getCurrentVariables().push(paramName.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.java + return + incompatible types in return. + return variableStack.peek(); +
    + type of expression: @Initialized @Nullable Deque<@Initialized @NonNull String> + method return type: @Initialized @NonNull Deque<@Initialized @NonNull String> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheck.java + assignment + incompatible types in assignment. + this.ignoreStringsRegexp = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheck.java + initialization.fields.uninitialized + the constructor does not initialize fields: ignoreStringsRegexp + public MultipleStringLiteralsCheck() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheck.java + method.invocation + call to setIgnoreStringsRegexp(java.util.regex.Pattern) not allowed on the given receiver. + setIgnoreStringsRegexp(Pattern.compile("^\"\"$")); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.api.AbstractCheck.class) @NonNull MultipleStringLiteralsCheck + required: @Initialized @NonNull MultipleStringLiteralsCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/NoArrayTrailingCommaCheck.java + dereference.of.nullable + dereference of possibly-null reference rcurly + final DetailAST previousSibling = rcurly.getPreviousSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheck.java + dereference.of.nullable + dereference of possibly-null reference mid + final String name = mid.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheck.java + dereference.of.nullable + dereference of possibly-null reference params + params.findFirstToken(TokenTypes.PARAMETER_DEF) == null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/NoEnumTrailingCommaCheck.java + argument + incompatible argument for parameter root of TokenUtil.findFirstTokenByPredicate. + TokenUtil.findFirstTokenByPredicate(enumBlock, +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/NoFinalizerCheck.java + dereference.of.nullable + dereference of possibly-null reference mid + final String name = mid.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/NoFinalizerCheck.java + dereference.of.nullable + dereference of possibly-null reference params + params.findFirstToken(TokenTypes.PARAMETER_DEF) == null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/OverloadMethodsDeclarationOrderCheck.java + dereference.of.nullable + dereference of possibly-null reference currentToken.findFirstToken(TokenTypes.IDENT) + currentToken.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/OverloadMethodsDeclarationOrderCheck.java + unboxing.of.nullable + unboxing a possibly-null reference methodLineNumberMap.get(methodName) + methodLineNumberMap.get(methodName); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ParameterAssignmentCheck.java + argument + incompatible argument for parameter ast of ParameterAssignmentCheck.visitMethodParameters. + visitMethodParameters(ast.findFirstToken(TokenTypes.PARAMETERS)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ParameterAssignmentCheck.java + dereference.of.nullable + dereference of possibly-null reference param + parameterNames.add(param.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ParameterAssignmentCheck.java + initialization.field.uninitialized + the default constructor does not initialize field parameterNames + private Set<String> parameterNames; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/PatternVariableAssignmentCheck.java + argument + incompatible argument for parameter arg0 of List.add. + innerPatternVariable.findFirstToken(TokenTypes.IDENT)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/PatternVariableAssignmentCheck.java + argument + incompatible argument for parameter arg0 of List.add. + outermostPatternVariable.findFirstToken(TokenTypes.IDENT)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/PatternVariableAssignmentCheck.java + argument + incompatible argument for parameter bound of PatternVariableAssignmentCheck.traverseUntilNeededBranchType. + branchLeadingToReassignedVar, TokenTypes.EXPR)) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/PatternVariableAssignmentCheck.java + argument + incompatible argument for parameter startingBranch of PatternVariableAssignmentCheck.traverseUntilNeededBranchType. + assignIdent, assignToken.getFirstChild(), TokenTypes.IDENT) != null) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter arg0 of Deque.push. + current.push(frames.get(ast)); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter arg0 of Deque.push. + current.push(frames.get(ast)); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter arg1 of Map.put. + frames.put(ast, frameStack.poll()); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter arg1 of Map.put. + frames.put(ast, frameStack.poll()); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter blockStartToken of RequireThisCheck.getBlockEndToken. + final DetailAST blockEndToken = getBlockEndToken(blockFrameNameIdent, blockStartToken); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter blockStartToken of RequireThisCheck.getBlockEndToken. + final DetailAST blockEndToken = getBlockEndToken(blockFrameNameIdent, blockStartToken); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter frame of RequireThisCheck.collectMethodDeclarations. + case TokenTypes.METHOD_DEF -> collectMethodDeclarations(frameStack, ast, frame); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter frame of RequireThisCheck.collectVariableDeclarations. + case TokenTypes.VARIABLE_DEF -> collectVariableDeclarations(ast, frame); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter frame of RequireThisCheck.findFrame. + frame = findFrame(frame, name, lookForMethod); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter frame of RequireThisCheck.findFrame. + return findFrame(current.peek(), name, lookForMethod); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ClassFrame constructor. + frameStack.addFirst(new ClassFrame(frame, classFrameNameIdent)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ClassFrame constructor. + super(parent, null); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ClassFrame.addInstanceMember. + ((ClassFrame) frame).addInstanceMember(componentIdent); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ClassFrame.addInstanceMember. + ((ClassFrame) frame).addInstanceMember(ident); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ClassFrame.addInstanceMethod. + ((ClassFrame) frame).addInstanceMethod(methodFrameNameIdent); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ClassFrame.addStaticMember. + ((ClassFrame) frame).addStaticMember(ident); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ClassFrame.addStaticMember. + ((ClassFrame) frame).addStaticMember(ident); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ClassFrame.addStaticMethod. + ((ClassFrame) frame).addStaticMethod(methodFrameNameIdent); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter ident of ConstructorFrame constructor. + frameStack.addFirst(new ConstructorFrame(frame, ctorFrameNameIdent)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter identToAdd of AbstractFrame.addIdent. + frame.addIdent(ident); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter identToAdd of AbstractFrame.addIdent. + frame.addIdent(parameterIdent); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter parent of AnonymousClassFrame constructor. + frameStack.addFirst(new AnonymousClassFrame(frame, ast.toString())); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter parent of BlockFrame constructor. + case TokenTypes.SLIST -> frameStack.addFirst(new BlockFrame(frame, ast)); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter parent of CatchFrame constructor. + final AbstractFrame catchFrame = new CatchFrame(frame, ast); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter parent of ClassFrame constructor. + frameStack.addFirst(new ClassFrame(frame, classFrameNameIdent)); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter parent of ConstructorFrame constructor. + frameStack.addFirst(new ConstructorFrame(frame, ctorFrameNameIdent)); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter parent of ForFrame constructor. + final AbstractFrame forFrame = new ForFrame(frame, ast); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + argument + incompatible argument for parameter parent of TryWithResourcesFrame constructor. + frameStack.addFirst(new TryWithResourcesFrame(frame, ast)); +
    + found : @Initialized @Nullable AbstractFrame + required: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference ((ClassFrame)frame) + ((ClassFrame) frame).addInstanceMember(componentIdent); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference ((ClassFrame)frame) + ((ClassFrame) frame).addStaticMember(ident); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.getParent().findFirstToken(TokenTypes.PARAMETERS) + ast.getParent().findFirstToken(TokenTypes.PARAMETERS).getChildCount(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference current.peek() + if (current.peek().getType() == FrameType.TRY_WITH_RESOURCES_FRAME) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference frame + frame.addIdent(parameterIdent); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference frame + frame.addIdent(resourceIdent); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference frame + while (frame.getType() != FrameType.CLASS_FRAME) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference mods + final boolean finalMod = mods.findFirstToken(TokenTypes.FINAL) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference mods + if (mods.findFirstToken(TokenTypes.LITERAL_STATIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + dereference.of.nullable + dereference of possibly-null reference mods + || mods.findFirstToken(TokenTypes.LITERAL_STATIC) != null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + initialization.field.uninitialized + the default constructor does not initialize field frames + private Map<DetailAST, AbstractFrame> frames; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + return + incompatible types in return. + return frame; +
    + type of expression: @Initialized @Nullable AbstractFrame + method return type: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + return + incompatible types in return. + return frame; +
    + type of expression: @Initialized @Nullable AbstractFrame + method return type: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + return + incompatible types in return. + return frameWhereViolationIsFound; +
    + type of expression: @Initialized @Nullable AbstractFrame + method return type: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable AbstractFrame + method return type: @Initialized @NonNull AbstractFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java + return + incompatible types in return. + return blockEndToken; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java + dereference.of.nullable + dereference of possibly-null reference methodNameAST + final boolean check = !format.matcher(methodNameAST.getText()).find(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java + initialization.field.uninitialized + the default constructor does not initialize field context + private Context context; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java + initialization.fields.uninitialized + the constructor does not initialize fields: maxAllowed + private Context(boolean checking) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheck.java + dereference.of.nullable + dereference of possibly-null reference parameters.getFirstChild().findFirstToken(TokenTypes.TYPE) + && !parameters.getFirstChild().findFirstToken(TokenTypes.TYPE).hasChildren()) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheck.java + initialization.field.uninitialized + the default constructor does not initialize field parentToSkip + private DetailAST parentToSkip; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (parentToSkip != ast && isExprSurrounded(ast)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (parentToSkip != ast && isExprSurrounded(ast)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessarySemicolonAfterTypeMemberDeclarationCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.OBJBLOCK) + ast.findFirstToken(TokenTypes.OBJBLOCK).getFirstChild().getNextSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessarySemicolonInEnumerationCheck.java + dereference.of.nullable + dereference of possibly-null reference enumBlock + final DetailAST semicolon = enumBlock.findFirstToken(TokenTypes.SEMI); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedCatchParameterShouldBeUnnamedCheck.java + assignment + incompatible types in assignment. + enclosingCatchClause.findFirstToken(TokenTypes.PARAMETER_DEF); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedCatchParameterShouldBeUnnamedCheck.java + dereference.of.nullable + dereference of possibly-null reference parameterDefinition.findFirstToken(TokenTypes.IDENT) + name = parameterDefinition.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLambdaParameterShouldBeUnnamedCheck.java + argument + incompatible argument for parameter identifierAst of LambdaParameterDetails constructor. + new LambdaParameterDetails(ast, ast.findFirstToken(TokenTypes.IDENT)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLambdaParameterShouldBeUnnamedCheck.java + argument + incompatible argument for parameter identifierAst of LambdaParameterDetails constructor. + new LambdaParameterDetails(ast, identifierAst); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLambdaParameterShouldBeUnnamedCheck.java + dereference.of.nullable + dereference of possibly-null reference lambdaParameters.peek() + && ast.equals(lambdaParameters.peek().enclosingLambda)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + argument + incompatible argument for parameter arg1 of Map.put. + anonInnerAstToTypeDeclDesc.put(literalNewAst, typeDeclarations.peek()); +
    + found : @Initialized @Nullable TypeDeclDesc + required: @Initialized @NonNull TypeDeclDesc +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + argument + incompatible argument for parameter outerClassQualifiedName of CheckUtil.getQualifiedTypeDeclarationName. + .getQualifiedTypeDeclarationName(packageName, outerClassQualifiedName, className); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + argument + incompatible argument for parameter scope of VariableDesc constructor. + this(name, null, null); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + argument + incompatible argument for parameter typeAst of VariableDesc constructor. + varDefAst.findFirstToken(TokenTypes.TYPE), findScopeOfVariable(varDefAst)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + argument + incompatible argument for parameter typeAst of VariableDesc constructor. + this(name, null, null); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + argument + incompatible argument for parameter typeAst of VariableDesc constructor. + this(name, null, scope); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + assignment + incompatible types in assignment. + packageName = null; +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference anonInnerAstToTypeDeclDesc.get(literalNewAst) + anonInnerAstToTypeDeclDesc.get(literalNewAst).getQualifiedName(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + final VariableDesc desc = new VariableDesc(ident.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + final VariableDesc desc = new VariableDesc(ident.getText(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + return allowUnnamedVariables && "_".equals(ident.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference typeDeclAst.findFirstToken(TokenTypes.IDENT) + final String className = typeDeclAst.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference typeDeclAstToTypeDeclDesc.get(obtainedClass.getTypeDeclAst()) + .get(obtainedClass.getTypeDeclAst()) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference typeDeclAstToTypeDeclDesc.get(parentAst.getParent()) + typeDeclAstToTypeDeclDesc.get(parentAst.getParent()).addInstOrClassVar(desc); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference typeDeclarations.peek() + outerClassQualifiedName = typeDeclarations.peek().getQualifiedName(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference variablesStack.peek() + while (!variablesStack.isEmpty() && variablesStack.peek().getScope() == scopeAst) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + initialization.field.uninitialized + the default constructor does not initialize field packageName + private String packageName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + && identAst != parent.getLastChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + && identAst != parent.getLastChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + && parent.getFirstChild() != identAst; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + && parent.getFirstChild() != identAst; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (!variablesStack.isEmpty() && variablesStack.peek().getScope() == scopeAst) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (!variablesStack.isEmpty() && variablesStack.peek().getScope() == scopeAst) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (currNode != ast && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (currNode != ast && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java + return + incompatible types in return. + return obtainedClass; +
    + type of expression: @Initialized @Nullable TypeDeclDesc + method return type: @Initialized @NonNull TypeDeclDesc +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + dereference.of.nullable + dereference of possibly-null reference ast + while (ast.getType() != TokenTypes.RPAREN) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + dereference.of.nullable + dereference of possibly-null reference block.findFirstToken(TokenTypes.RPAREN) + currentNode = block.findFirstToken(TokenTypes.RPAREN).getNextSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + dereference.of.nullable + dereference of possibly-null reference currentSiblingAst.findFirstToken(TokenTypes.IDENT) + currentSiblingAst.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + dereference.of.nullable + dereference of possibly-null reference variable + if (!isVariableMatchesIgnorePattern(variable.getText())) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (curNode == parent) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (curNode == parent) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + return + incompatible types in return. + return new SimpleEntry<>(variableUsageAst, dist); +
    + type of expression: @Initialized @NonNull SimpleEntry<@Initialized @Nullable DetailAST, @Initialized @NonNull Integer> + method return type: @Initialized @NonNull Entry<@Initialized @NonNull DetailAST, @Initialized @NonNull Integer> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + return + incompatible types in return. + return new SimpleEntry<>(variableUsageAst, dist); +
    + type of expression: @Initialized @NonNull SimpleEntry<@Initialized @Nullable DetailAST, @Initialized @NonNull Integer> + method return type: @Initialized @NonNull Entry<@Initialized @NonNull DetailAST, @Initialized @NonNull Integer> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + return + incompatible types in return. + return firstNodeInsideBlock; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + return + incompatible types in return. + return firstNodeInsideBlock; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + return + incompatible types in return. + return firstNodeInsideBlock; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + return + incompatible types in return. + return variableUsageNode; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + type.arguments.not.inferred + Could not infer type arguments for SimpleEntry constructor + return new SimpleEntry<>(variableUsageAst, dist); +
    + unsatisfiable constraint: @Initialized @Nullable DetailAST <: @Initialized @NonNull DetailAST + use of K from new SimpleEntry<>(variableUsageAst, dist) <: @Initialized @NonNull DetailAST + From complementary bound.: use of K from new SimpleEntry<>(variableUsageAst, dist) <= @Initialized @NonNull DetailAST + inference type: java.util.AbstractMap.SimpleEntry<K,V> <: @Initialized @NonNull Entry<@Initialized @NonNull DetailAST, @Initialized @NonNull Integer> + inference type: java.util.AbstractMap.SimpleEntry<K,V> -> @Initialized @NonNull Entry<@Initialized @NonNull DetailAST, @Initialized @NonNull Integer> + From: Constraint between method call type and target type for method call:new SimpleEntry<>(variableUsageAst, dist) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java + type.arguments.not.inferred + Could not infer type arguments for SimpleEntry constructor + return new SimpleEntry<>(variableUsageAst, dist); +
    + unsatisfiable constraint: @Initialized @Nullable DetailAST <: @Initialized @NonNull DetailAST + use of K from new SimpleEntry<>(variableUsageAst, dist) <: @Initialized @NonNull DetailAST + From complementary bound.: use of K from new SimpleEntry<>(variableUsageAst, dist) <= @Initialized @NonNull DetailAST + inference type: java.util.AbstractMap.SimpleEntry<K,V> <: @Initialized @NonNull Entry<@Initialized @NonNull DetailAST, @Initialized @NonNull Integer> + inference type: java.util.AbstractMap.SimpleEntry<K,V> -> @Initialized @NonNull Entry<@Initialized @NonNull DetailAST, @Initialized @NonNull Integer> + From: Constraint between method call type and target type for method call:new SimpleEntry<>(variableUsageAst, dist) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/WhenShouldBeUsedCheck.java + return + incompatible types in return. + return caseParent.findFirstToken(TokenTypes.SLIST); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + argument + incompatible argument for parameter root of TokenUtil.findFirstTokenByPredicate. + final Optional<DetailAST> annotation = TokenUtil.findFirstTokenByPredicate(modifiers, +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + argument + incompatible argument for parameter token of DesignForExtensionCheck.branchContainsJavadocComment. + return branchContainsJavadocComment(token); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + final String methodName = ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference classDef.findFirstToken(TokenTypes.IDENT) + final String className = classDef.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference ctorMods + if (ctorMods.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference methodImplOpenBrace + final DetailAST methodImplCloseBrace = methodImplOpenBrace.getLastChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.FINAL) == null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference mods + return mods.findFirstToken(TokenTypes.LITERAL_NATIVE) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference objBlock + DetailAST candidate = objBlock.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + dereference.of.nullable + dereference of possibly-null reference parent.findFirstToken(TokenTypes.IDENT) + return parent.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (curNode == token) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (curNode == token) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + not.interned + attempting to use a non-@Interned comparison operand + return currentNode != methodImplCloseBrace + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.java + not.interned + attempting to use a non-@Interned comparison operand + return currentNode != methodImplCloseBrace + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + argument + incompatible argument for parameter outerClassQualifiedName of CheckUtil.getQualifiedTypeDeclarationName. + outerTypeDeclarationQualifiedName, +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + declaredAsFinal = modifiers.findFirstToken(TokenTypes.FINAL) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + if (modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + dereference.of.nullable + dereference of possibly-null reference typeDeclarationAst.findFirstToken(TokenTypes.IDENT) + final String className = typeDeclarationAst.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + dereference.of.nullable + dereference of possibly-null reference typeDeclarations.peek() + .put(ast, typeDeclarations.peek().getQualifiedName()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + dereference.of.nullable + dereference of possibly-null reference typeDeclarations.peek() + outerTypeDeclarationQualifiedName = typeDeclarations.peek().getQualifiedName(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + initialization.field.uninitialized + the default constructor does not initialize field anonInnerClassToOuterTypeDecl + private Map<DetailAST, String> anonInnerClassToOuterTypeDecl; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + initialization.field.uninitialized + the default constructor does not initialize field innerClasses + private Map<String, ClassDesc> innerClasses; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + initialization.field.uninitialized + the default constructor does not initialize field packageName + private String packageName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + initialization.field.uninitialized + the default constructor does not initialize field typeDeclarations + private Deque<TypeDeclarationDescription> typeDeclarations; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java + return + incompatible types in return. + return superClassName; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.MODIFIERS) + return ast.findFirstToken(TokenTypes.MODIFIERS) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.MODIFIERS) + return ast.findFirstToken(TokenTypes.MODIFIERS) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + if (modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheck.java + dereference.of.nullable + dereference of possibly-null reference objBlock + DetailAST child = objBlock.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/InterfaceIsTypeCheck.java + dereference.of.nullable + dereference of possibly-null reference objBlock + objBlock.findFirstToken(TokenTypes.METHOD_DEF); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + final String className = ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + log(ast, MSG_KEY, ast.findFirstToken(TokenTypes.IDENT).getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAST + if (modifiersAST.findFirstToken(TokenTypes.FINAL) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/OneTopLevelClassCheck.java + argument + incompatible argument for parameter typeDef of OneTopLevelClassCheck.isPublic. + if (publicTypeFound && !isPublic(firstType)) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/OneTopLevelClassCheck.java + dereference.of.nullable + dereference of possibly-null reference currentNode.findFirstToken(TokenTypes.IDENT) + .findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/OneTopLevelClassCheck.java + dereference.of.nullable + dereference of possibly-null reference firstType.findFirstToken(TokenTypes.IDENT) + .findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/OneTopLevelClassCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + return modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/SealedShouldHavePermitsListCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + final boolean isSealed = modifiers.findFirstToken(TokenTypes.LITERAL_SEALED) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheck.java + dereference.of.nullable + dereference of possibly-null reference methodModifiers + return methodModifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + DetailAST child = modifiers.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheck.java + dereference.of.nullable + dereference of possibly-null reference parent.findFirstToken(TokenTypes.IDENT) + return parent.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.java + argument + incompatible argument for parameter type of VisibilityModifierCheck.getCanonicalName. + final String typeName = getCanonicalName(type); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.java + argument + incompatible argument for parameter type of VisibilityModifierCheck.isCanonicalName. + final boolean isCanonicalName = isCanonicalName(type); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + return modifiers.findFirstToken(TokenTypes.FINAL) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference variableDef.findFirstToken(TokenTypes.TYPE) + final DetailAST varNameAST = variableDef.findFirstToken(TokenTypes.TYPE) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.java + initialization.field.uninitialized + the default constructor does not initialize field ignoreAnnotationShortNames + private Set<String> ignoreAnnotationShortNames; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.java + initialization.field.uninitialized + the default constructor does not initialize field immutableClassShortNames + private Set<String> immutableClassShortNames; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.java + return + incompatible types in return. + return matchingAnnotation; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.java + return + incompatible types in return. + return typeArgs; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/AbstractHeaderCheck.java + initialization.field.uninitialized + the default constructor does not initialize field charset + private Charset charset; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/AbstractHeaderCheck.java + initialization.field.uninitialized + the default constructor does not initialize field headerFile + private URI headerFile; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/MultiFileRegexpHeaderCheck.java + argument + incompatible argument for parameter messageArg of MatchResult constructor. + return new MatchResult(true, 0, null, null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/MultiFileRegexpHeaderCheck.java + argument + incompatible argument for parameter messageKey of MatchResult constructor. + return new MatchResult(true, 0, null, null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/MultiFileRegexpHeaderCheck.java + initialization.field.uninitialized + the default constructor does not initialize field headerFiles + private String headerFiles; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + argument + incompatible argument for parameter ast of FullIdent.createFullIdent. + ident = FullIdent.createFullIdent(token.findFirstToken(TokenTypes.DOT)).getText(); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + argument + incompatible argument for parameter previousImport of CustomImportOrderCheck.isAlphabeticalOrderBroken. + if (isAlphabeticalOrderBroken(previousImportFromCurrentGroup, fullImportIdent)) { +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + argument + incompatible argument for parameter previousImport of CustomImportOrderCheck.validateExtraEmptyLine. + validateExtraEmptyLine(previousImportObjectFromCurrentGroup, +
    + found : @Initialized @Nullable ImportDetails + required: @Initialized @NonNull ImportDetails +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java + argument + incompatible argument for parameter previousImport of CustomImportOrderCheck.validateMissedEmptyLine. + validateMissedEmptyLine(previousImportObjectFromCurrentGroup, +
    + found : @Initialized @Nullable ImportDetails + required: @Initialized @NonNull ImportDetails +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/FileImportControl.java + return + incompatible types in return. + return finestMatch; +
    + type of expression: @Initialized @Nullable AbstractImportControl + method return type: @Initialized @NonNull AbstractImportControl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheck.java + initialization.fields.uninitialized + the constructor does not initialize fields: illegalPkgs, illegalClasses + public IllegalImportCheck() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheck.java + method.invocation + call to setIllegalPkgs(java.lang.String...) not allowed on the given receiver. + setIllegalPkgs("sun"); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.api.AbstractCheck.class) @NonNull IllegalImportCheck + required: @Initialized @NonNull IllegalImportCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.java + assignment + incompatible types in assignment. + currentImportControl = null; +
    + found : null (NullType) + required: @Initialized @NonNull AbstractImportControl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.java + initialization.field.uninitialized + the default constructor does not initialize field currentImportControl + private AbstractImportControl currentImportControl; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.java + initialization.field.uninitialized + the default constructor does not initialize field file + private URI file; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.java + initialization.field.uninitialized + the default constructor does not initialize field fileName + private String fileName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.java + initialization.field.uninitialized + the default constructor does not initialize field packageName + private String packageName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.java + initialization.field.uninitialized + the default constructor does not initialize field root + private PkgImportControl root; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java + argument + incompatible argument for parameter parent of FileImportControl constructor. + final AbstractImportControl importControl = new FileImportControl(parentImportControl, +
    + found : @Initialized @Nullable PkgImportControl + required: @Initialized @NonNull PkgImportControl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java + argument + incompatible argument for parameter parent of PkgImportControl constructor. + final AbstractImportControl importControl = new PkgImportControl(parentImportControl, +
    + found : @Initialized @Nullable PkgImportControl + required: @Initialized @NonNull PkgImportControl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java + dereference.of.nullable + dereference of possibly-null reference parentImportControl + parentImportControl.addChild(importControl); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java + dereference.of.nullable + dereference of possibly-null reference parentImportControl + parentImportControl.addChild(importControl); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java + dereference.of.nullable + dereference of possibly-null reference stack.peek() + stack.peek().addImportRule(rule); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java + return + incompatible types in return. + return (PkgImportControl) stack.peek(); +
    + type of expression: @Initialized @Nullable PkgImportControl + method return type: @Initialized @NonNull PkgImportControl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.SEMI) + lastImportLine = ast.findFirstToken(TokenTypes.SEMI).getLineNo(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java + initialization.field.uninitialized + the default constructor does not initialize field lastImport + private String lastImport; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + argument + incompatible argument for parameter parent of AbstractImportControl constructor. + super(null, strategyOnMismatch); +
    + found : null (NullType) + required: @Initialized @NonNull AbstractImportControl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + assignment + incompatible types in assignment. + patternForExactMatch = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + assignment + incompatible types in assignment. + patternForExactMatch = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + assignment + incompatible types in assignment. + patternForPartialMatch = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + assignment + incompatible types in assignment. + patternForPartialMatch = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + return + incompatible types in return. + return finestMatch; +
    + type of expression: @Initialized @Nullable AbstractImportControl + method return type: @Initialized @NonNull AbstractImportControl +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/RedundantImportCheck.java + assignment + incompatible types in assignment. + pkgName = null; +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/RedundantImportCheck.java + initialization.field.uninitialized + the default constructor does not initialize field pkgName + private String pkgName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.java + argument + incompatible argument for parameter parent of Frame constructor. + return new Frame(null); +
    + found : null (NullType) + required: @Initialized @NonNull Frame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.java + argument + incompatible argument for parameter type of UnusedImportsCheck.topLevelType. + references.add(topLevelType(matcher.group(1))); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.java + initialization.field.uninitialized + the default constructor does not initialize field currentFrame + private Frame currentFrame; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AbstractExpressionHandler.java + argument + incompatible argument for parameter ast of AnnotationUtil.containsAnnotation. + result = !AnnotationUtil.containsAnnotation(parameterAst); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AbstractExpressionHandler.java + dereference.of.nullable + dereference of possibly-null reference modifiers + for (DetailAST modifier = modifiers.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AbstractExpressionHandler.java + initialization.fields.uninitialized + the constructor does not initialize fields: indent + protected AbstractExpressionHandler(IndentationCheck indentCheck, String typeName, + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AbstractExpressionHandler.java + not.interned + attempting to use a non-@Interned comparison operand + while (curNode != ast && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AbstractExpressionHandler.java + not.interned + attempting to use a non-@Interned comparison operand + while (curNode != ast && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AnnotationArrayInitHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.RCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/AnnotationArrayInitHandler.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ArrayInitHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.RCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ArrayInitHandler.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + dereference.of.nullable + dereference of possibly-null reference getMainAst().findFirstToken(TokenTypes.RPAREN) + return getMainAst().findFirstToken(TokenTypes.RPAREN).getNextSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + dereference.of.nullable + dereference of possibly-null reference slist + return slist.findFirstToken(TokenTypes.RCURLY); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + not.interned + attempting to use a non-@Interned comparison operand + if (nonList != nonListStartAst) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + not.interned + attempting to use a non-@Interned comparison operand + if (nonList != nonListStartAst) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.LPAREN); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.RPAREN); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.SLIST); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.SLIST); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.java + return + incompatible types in return. + return slist.findFirstToken(TokenTypes.RCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CatchHandler.java + dereference.of.nullable + dereference of possibly-null reference getMainAst().findFirstToken(TokenTypes.LPAREN) + final DetailAST condAst = getMainAst().findFirstToken(TokenTypes.LPAREN) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + argument + incompatible argument for parameter ast of AbstractExpressionHandler.getLineStart. + final int lineStart = getLineStart(ident); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + argument + incompatible argument for parameter ast of AbstractExpressionHandler.isOnStartOfLine. + if (isOnStartOfLine(atAst)) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + dereference.of.nullable + dereference of possibly-null reference getMainAst().findFirstToken(TokenTypes.OBJBLOCK) + return getMainAst().findFirstToken(TokenTypes.OBJBLOCK) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + dereference.of.nullable + dereference of possibly-null reference getMainAst().findFirstToken(TokenTypes.OBJBLOCK) + return getMainAst().findFirstToken(TokenTypes.OBJBLOCK) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + dereference.of.nullable + dereference of possibly-null reference modifiers + if (modifiers.hasChildren()) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + return + incompatible types in return. + .findFirstToken(TokenTypes.LCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + return + incompatible types in return. + .findFirstToken(TokenTypes.RCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.OBJBLOCK); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (nextToken != null && nextToken != currentStatement && isComment(nextToken)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (nextToken != null && nextToken != currentStatement && isComment(nextToken)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + return + incompatible types in return. + return methodCall.findFirstToken(TokenTypes.ELIST); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + return + incompatible types in return. + return prevCaseToken; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + return + incompatible types in return. + return prevStmt; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + return + incompatible types in return. + return previousStatement; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + return + incompatible types in return. + return previousStatement; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.java + return + incompatible types in return. + return tokenWhichBeginsTheLine; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/DetailAstSet.java + return + incompatible types in return. + return astLines.get(lineNum); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/DetailAstSet.java + return + incompatible types in return. + return startColumn; +
    + type of expression: @Initialized @Nullable Integer + method return type: @Initialized @NonNull Integer +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/DoWhileHandler.java + argument + incompatible argument for parameter ast of AbstractExpressionHandler.isOnStartOfLine. + if (isOnStartOfLine(whileAst) +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/DoWhileHandler.java + dereference.of.nullable + dereference of possibly-null reference getMainAst().findFirstToken(TokenTypes.LPAREN) + final DetailAST condAst = getMainAst().findFirstToken(TokenTypes.LPAREN).getNextSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ForHandler.java + argument + incompatible argument for parameter tree of AbstractExpressionHandler.checkExpressionSubtree. + checkExpressionSubtree(cond, expected, false, false); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ForHandler.java + argument + incompatible argument for parameter tree of AbstractExpressionHandler.checkExpressionSubtree. + checkExpressionSubtree(forEach, expected, false, false); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ForHandler.java + argument + incompatible argument for parameter tree of AbstractExpressionHandler.checkExpressionSubtree. + checkExpressionSubtree(forIterator, expected, false, false); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ForHandler.java + return + incompatible types in return. + return literalForAst.findFirstToken(TokenTypes.RPAREN); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + argument + incompatible argument for parameter constructor of CommonUtil.invokeConstructor. + handlerCtor, indentCheck, ast, parent); +
    + found : @Initialized @Nullable Constructor<capture extends @Initialized @Nullable Object> + required: @Initialized @NonNull Constructor<@Initialized @Nullable Object> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.ANNOTATION_ARRAY_INIT, AnnotationArrayInitHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.ANNOTATION_DEF, ClassDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.ANNOTATION_FIELD_DEF, MethodDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.ARRAY_INIT, ArrayInitHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.CASE_GROUP, CaseHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.CLASS_DEF, ClassDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.COMPACT_CTOR_DEF, MethodDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.CTOR_CALL, MethodCallHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.CTOR_DEF, MethodDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.ENUM_DEF, ClassDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.IMPORT, ImportHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.INDEX_OP, IndexHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.INSTANCE_INIT, SlistHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.INTERFACE_DEF, ClassDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LABELED_STAT, LabelHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LAMBDA, LambdaHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_CATCH, CatchHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_DO, DoWhileHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_ELSE, ElseHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_FINALLY, FinallyHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_FOR, ForHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_IF, IfHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_NEW, NewHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_SWITCH, SwitchHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_SYNCHRONIZED, SynchronizedHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_TRY, TryHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_WHILE, WhileHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.LITERAL_YIELD, YieldHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.METHOD_CALL, MethodCallHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.METHOD_DEF, MethodDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.OBJBLOCK, ObjectBlockHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.PACKAGE_DEF, PackageDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.RECORD_DEF, ClassDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.SLIST, SlistHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.STATIC_INIT, StaticInitHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.SUPER_CTOR_CALL, MethodCallHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.SWITCH_RULE, SwitchRuleHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + method.invocation + call to <T>register(int,java.lang.Class<T>) not allowed on the given receiver. + register(TokenTypes.VARIABLE_DEF, MemberDefHandler.class); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory.class) @NonNull HandlerFactory + required: @Initialized @NonNull HandlerFactory +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.java + return + incompatible types in return. + return resultHandler; +
    + type of expression: @Initialized @Nullable AbstractExpressionHandler + method return type: @Initialized @NonNull AbstractExpressionHandler +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IfHandler.java + dereference.of.nullable + dereference of possibly-null reference getMainAst().findFirstToken(TokenTypes.LPAREN) + final DetailAST condAst = getMainAst().findFirstToken(TokenTypes.LPAREN) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IfHandler.java + return + incompatible types in return. + return literalIfAst.findFirstToken(TokenTypes.RPAREN); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ImportHandler.java + argument + incompatible argument for parameter lastNode of AbstractExpressionHandler.checkWrappingIndentation. + checkWrappingIndentation(getMainAst(), semi); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheck.java + argument + incompatible argument for parameter instance of LineWrappingHandler constructor. + private final LineWrappingHandler lineWrappingHandler = new LineWrappingHandler(this); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.api.AbstractCheck.class) @NonNull IndentationCheck + required: @Initialized @NonNull IndentationCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheck.java + argument + incompatible argument for parameter parent of HandlerFactory.getHandler. + handlers.peek()); +
    + found : @Initialized @Nullable AbstractExpressionHandler + required: @Initialized @NonNull AbstractExpressionHandler +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheck.java + assignment + incompatible types in assignment. + private final LineWrappingHandler lineWrappingHandler = new LineWrappingHandler(this); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.indentation.LineWrappingHandler.class) @NonNull LineWrappingHandler + required: @Initialized @NonNull LineWrappingHandler +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheck.java + initialization.field.uninitialized + the default constructor does not initialize field incorrectIndentationLines + private Set<Integer> incorrectIndentationLines; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.java + not.interned + attempting to use a non-@Interned comparison operand + while (curNode != lastNode) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.java + not.interned + attempting to use a non-@Interned comparison operand + while (curNode != lastNode) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MemberDefHandler.java + argument + incompatible argument for parameter ast of AbstractExpressionHandler.getFirstToken. + final DetailAST ident = AbstractExpressionHandler.getFirstToken(type); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MemberDefHandler.java + argument + incompatible argument for parameter ast of AbstractExpressionHandler.isOnStartOfLine. + if (isOnStartOfLine(modifier) +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MemberDefHandler.java + dereference.of.nullable + dereference of possibly-null reference modifiersNode + if (modifiersNode.hasChildren()) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MemberDefHandler.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElse(assign); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodCallHandler.java + argument + incompatible argument for parameter ast of AbstractExpressionHandler.getLineStart. + if (getLineStart(rparen) == rparen.getColumnNo()) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodCallHandler.java + argument + incompatible argument for parameter ast1 of TokenUtil.areOnSameLine. + if (!TokenUtil.areOnSameLine(rparen, lparen)) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodCallHandler.java + argument + incompatible argument for parameter ast1 of TokenUtil.areOnSameLine. + return TokenUtil.areOnSameLine(rparen, ast2); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodCallHandler.java + argument + incompatible argument for parameter tree of AbstractExpressionHandler.checkExpressionSubtree. + getMainAst().findFirstToken(TokenTypes.ELIST), +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodDefHandler.java + argument + incompatible argument for parameter ast of AbstractExpressionHandler.isOnStartOfLine. + if (isOnStartOfLine(modifier) +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodDefHandler.java + dereference.of.nullable + dereference of possibly-null reference mainAst.findFirstToken(TokenTypes.IDENT) + int lineStart = mainAst.findFirstToken(TokenTypes.IDENT).getLineNo(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodDefHandler.java + dereference.of.nullable + dereference of possibly-null reference mainAst.findFirstToken(TokenTypes.MODIFIERS) + for (DetailAST node = mainAst.findFirstToken(TokenTypes.MODIFIERS).getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodDefHandler.java + return + incompatible types in return. + return methodDefAst.findFirstToken(TokenTypes.RPAREN); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/MethodDefHandler.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.java + argument + incompatible argument for parameter expression of NewHandler.checkNestedNew. + if (checkNestedNew(expression) && isOnStartOfLine(expression)) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.java + argument + incompatible argument for parameter lparen of AbstractExpressionHandler.checkLeftParen. + checkLeftParen(lparen); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ObjectBlockHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.LCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ObjectBlockHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.RCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/ObjectBlockHandler.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/PackageDefHandler.java + argument + incompatible argument for parameter lastNode of AbstractExpressionHandler.checkWrappingIndentation. + checkWrappingIndentation(getMainAst(), semi); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/PrimordialHandler.java + argument + incompatible argument for parameter expr of AbstractExpressionHandler constructor. + super(indentCheck, null, null, null); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/PrimordialHandler.java + argument + incompatible argument for parameter parent of AbstractExpressionHandler constructor. + super(indentCheck, null, null, null); +
    + found : null (NullType) + required: @Initialized @NonNull AbstractExpressionHandler +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/PrimordialHandler.java + argument + incompatible argument for parameter typeName of AbstractExpressionHandler constructor. + super(indentCheck, null, null, null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SlistHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.RCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SlistHandler.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler.java + dereference.of.nullable + dereference of possibly-null reference getMainAst().findFirstToken(TokenTypes.LPAREN) + getMainAst().findFirstToken(TokenTypes.LPAREN).getNextSibling(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.LCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler.java + return + incompatible types in return. + return getMainAst().findFirstToken(TokenTypes.RCURLY); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SynchronizedHandler.java + dereference.of.nullable + dereference of possibly-null reference getMainAst().findFirstToken(TokenTypes.LPAREN) + final DetailAST syncAst = getMainAst().findFirstToken(TokenTypes.LPAREN) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/SynchronizedHandler.java + return + incompatible types in return. + return syncStatementAST.findFirstToken(TokenTypes.RPAREN); +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java + dereference.of.nullable + dereference of possibly-null reference resourcesAst + DetailAST resourceAst = resourcesAst.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/WhileHandler.java + argument + incompatible argument for parameter tree of AbstractExpressionHandler.checkExpressionSubtree. + checkExpressionSubtree(condAst, expected, false, false); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.java + initialization.field.uninitialized + the default constructor does not initialize field blockCommentAst + private DetailAST blockCommentAst; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.java + type.argument + incompatible type argument for type parameter T of ThreadLocal. + private final ThreadLocal<FileContext> context = ThreadLocal.withInitial(FileContext::new); +
    + found : @Initialized @NonNull FileContext + required: [extends @Initialized @Nullable Object super null (NullType)] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.java + type.argument + incompatible type argument for type parameter T of ThreadLocal. + private static final ThreadLocal<Map<Integer, ParseStatus>> TREE_CACHE = +
    + found : @Initialized @NonNull Map<@Initialized @NonNull Integer, @Initialized @NonNull ParseStatus> + required: [extends @Initialized @Nullable Object super null (NullType)] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocBlockTagLocationCheck.java + argument + incompatible argument for parameter arg0 of Set.contains. + if (tags.contains(tagName)) { +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocBlockTagLocationCheck.java + initialization.fields.uninitialized + the constructor does not initialize fields: tags + public JavadocBlockTagLocationCheck() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocBlockTagLocationCheck.java + method.invocation + call to setTags(java.lang.String...) not allowed on the given receiver. + setTags(DEFAULT_TAGS); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck.class) @NonNull JavadocBlockTagLocationCheck + required: @Initialized @NonNull JavadocBlockTagLocationCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocLeadingAsteriskAlignCheck.java + initialization.field.uninitialized + the default constructor does not initialize field fileLines + private String[] fileLines; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + argument + incompatible argument for parameter arg0 of List.add. + components.add(child.findFirstToken(TokenTypes.IDENT)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + argument + incompatible argument for parameter firstArg of JavadocTag constructor. + javadocArgMatcher.group(2))); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + argument + incompatible argument for parameter firstArg of JavadocTag constructor. + javadocArgMissingDescriptionMatcher.group(2))); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + argument + incompatible argument for parameter tag of JavadocTag constructor. + javadocArgMissingDescriptionMatcher.group(1), +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + argument + incompatible argument for parameter tag of JavadocTag constructor. + tags.add(new JavadocTag(currentLine, 0, noargCurlyMatcher.group(1))); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + argument + incompatible argument for parameter tag of JavadocTag constructor. + tags.add(new JavadocTag(currentLine, col, javadocArgMatcher.group(1), +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + argument + incompatible argument for parameter tag of JavadocTag constructor. + tags.add(new JavadocTag(currentLine, col, javadocNoargMatcher.group(1))); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + argument + incompatible argument for parameter tag of JavadocTag constructor. + tags.add(new JavadocTag(tagLine, col, param1)); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference params + DetailAST child = params.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference recordDecl + DetailAST child = recordDecl.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference typeParam.findFirstToken(TokenTypes.IDENT) + ELEMENT_START + typeParam.findFirstToken(TokenTypes.IDENT).getText() + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference typeParam.findFirstToken(TokenTypes.IDENT) + if (typeParam.findFirstToken(TokenTypes.IDENT).getText() + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (curNode != root) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (curNode != root) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + return ancestor != methodBodyAst; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + return ancestor != methodBodyAst; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (ancestor != methodBodyAst) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (ancestor != methodBodyAst) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + } while (curNode != root); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + } while (curNode != root); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.java + initialization.field.uninitialized + the default constructor does not initialize field firstChild + private JavadocNodeImpl firstChild; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.java + initialization.field.uninitialized + the default constructor does not initialize field nextSibling + private JavadocNodeImpl nextSibling; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.java + initialization.field.uninitialized + the default constructor does not initialize field parent + private JavadocNodeImpl parent; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.java + initialization.field.uninitialized + the default constructor does not initialize field previousSibling + private JavadocNodeImpl previousSibling; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.java + initialization.field.uninitialized + the default constructor does not initialize field text + private String text; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheck.java + argument + incompatible argument for parameter arg0 of Set.add. + final boolean isDirChecked = !directoriesChecked.add(dir); +
    + found : @Initialized @Nullable File + required: @Initialized @NonNull File +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheck.java + dereference.of.nullable + dereference of possibly-null reference dir + final Path packageInfo = Path.of(dir.getPath(), "package-info.java"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheck.java + method.invocation + call to setFileExtensions(java.lang.String...) not allowed on the given receiver. + setFileExtensions("java"); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocPackageCheck.class) @NonNull JavadocPackageCheck + required: @Initialized @NonNull JavadocPackageCheck +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + initialization.field.uninitialized + the default constructor does not initialize field excludeScope + private Scope excludeScope; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTag.java + argument + incompatible argument for parameter firstArg of JavadocTag constructor. + this(line, column, tag, null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.MODIFIERS) + && ast.findFirstToken(TokenTypes.MODIFIERS) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + dereference.of.nullable + dereference of possibly-null reference methodNameAst + final String methodName = methodNameAst.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + dereference.of.nullable + dereference of possibly-null reference returnType + && returnType.getFirstChild().getType() != TokenTypes.LITERAL_VOID; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.java + dereference.of.nullable + dereference of possibly-null reference varType + && varType.getFirstChild().getType() == TokenTypes.ARRAY_DECLARATOR + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + componentList.add(ident.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheck.java + dereference.of.nullable + dereference of possibly-null reference matchInAngleBrackets.group(1) + typeParamName = matchInAngleBrackets.group(1).trim(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheck.java + initialization.field.uninitialized + the default constructor does not initialize field authorFormat + private Pattern authorFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheck.java + initialization.field.uninitialized + the default constructor does not initialize field excludeScope + private Scope excludeScope; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheck.java + initialization.field.uninitialized + the default constructor does not initialize field versionFormat + private Pattern versionFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocVariableCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + final String name = ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocVariableCheck.java + initialization.field.uninitialized + the default constructor does not initialize field ignoreNamePattern + private Pattern ignoreNamePattern; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference ident + final String methodName = ident.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference params + final boolean noParams = params.getChildCount(TokenTypes.PARAMETER_DEF) == 0; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference params + final boolean singleParam = params.getChildCount(TokenTypes.PARAMETER_DEF) == 1; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference type + final String name = type.getNextSibling().getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + dereference.of.nullable + dereference of possibly-null reference type + final String name = type.getNextSibling().getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + initialization.field.uninitialized + the default constructor does not initialize field excludeScope + private Scope excludeScope; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + initialization.field.uninitialized + the default constructor does not initialize field ignoreMethodNamesRegex + private Pattern ignoreMethodNamesRegex; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (lcurly.getFirstChild() == rcurly) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (lcurly.getFirstChild() == rcurly) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocTypeCheck.java + initialization.field.uninitialized + the default constructor does not initialize field excludeScope + private Scope excludeScope; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/SummaryJavadocCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (curNode != descriptionNode && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/SummaryJavadocCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (curNode != descriptionNode && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.java + method.invocation + call to parseTags(java.lang.String[],int) not allowed on the given receiver. + parseTags(text, lineNo); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.class) @NonNull TagParser + required: @Initialized @NonNull TagParser +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + cmt = modifiers.findFirstToken(TokenTypes.BLOCK_COMMENT_BEGIN); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.java + initialization.field.uninitialized + the default constructor does not initialize field tag + private String tag; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.java + initialization.field.uninitialized + the default constructor does not initialize field tagFormat + private Pattern tagFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.java + initialization.field.uninitialized + the default constructor does not initialize field tagRegExp + private Pattern tagRegExp; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtil.java + argument + incompatible argument for parameter name of TagInfo constructor. + tags.add(new TagInfo(tagName, tagValue, position)); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtil.java + argument + incompatible argument for parameter name of TagInfo constructor. + tags.add(new TagInfo(tagName, tagValue, position)); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtil.java + argument + incompatible argument for parameter source of InlineTagUtil.removeLeadingJavaDoc. + matchedTagValue = removeLeadingJavaDoc(matchedTagValue); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java + argument + incompatible argument for parameter ast of ClassContext constructor. + classesContexts.push(new ClassContext("", null)); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java + dereference.of.nullable + dereference of possibly-null reference classDef.findFirstToken(TokenTypes.IDENT) + final String className = classDef.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java + dereference.of.nullable + dereference of possibly-null reference classesContexts.peek() + classesContexts.peek().addReferencedClassName(type.getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java + dereference.of.nullable + dereference of possibly-null reference classesContexts.peek() + classesContexts.peek().visitLiteralNew(ast); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java + dereference.of.nullable + dereference of possibly-null reference classesContexts.peek() + classesContexts.peek().visitLiteralThrows(ast); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java + dereference.of.nullable + dereference of possibly-null reference classesContexts.peek() + classesContexts.peek().visitType(ast); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java + initialization.fields.uninitialized + the constructor does not initialize fields: packageName + protected AbstractClassCouplingCheck(int defaultMax) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/JavaNCSSCheck.java + initialization.field.uninitialized + the default constructor does not initialize field counters + private Deque<Counter> counters; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.java + dereference.of.nullable + dereference of possibly-null reference bracketed + bracketed.getType() != TokenTypes.RPAREN; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.java + initialization.field.uninitialized + the default constructor does not initialize field currentRangeValue + private BigInteger currentRangeValue; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/ClassMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/ClassMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/ClassMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.FINAL) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + && modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.java + dereference.of.nullable + dereference of possibly-null reference typeToken + final int methodReturnType = typeToken.getLastChild().getType(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.java + return + incompatible types in return. + return offendingModifier; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + argument + incompatible argument for parameter ast of RedundantModifierCheck.checkUnnamedVariables. + checkUnnamedVariables(ast.findFirstToken(TokenTypes.PARAMETER_DEF)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + argument + incompatible argument for parameter root of TokenUtil.findFirstTokenByPredicate. + modifiers, mod -> mod.getType() != TokenTypes.ANNOTATION +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + argument + incompatible argument for parameter root of TokenUtil.forEachChild. + TokenUtil.forEachChild(modifiers, TokenTypes.ANNOTATION, annotationsList::add); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + argument + incompatible argument for parameter root of TokenUtil.forEachChild. + TokenUtil.forEachChild(parameters, TokenTypes.PARAMETER_DEF, paramDef -> { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + return "_".equals(ast.findFirstToken(TokenTypes.IDENT).getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference classModifiers + checkFinal = classModifiers.findFirstToken(TokenTypes.FINAL) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference classModifiers + return classModifiers.findFirstToken(TokenTypes.LITERAL_PROTECTED) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + DetailAST modifier = modifiers.getFirstChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiers + modifiers.findFirstToken(tokenType); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAst + modifiersAst.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .ifPresent(modifiers -> { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + dereference.of.nullable + dereference of possibly-null reference nameAst + final String typeName = nameAst.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractAccessControlNameCheck.java + argument + incompatible argument for parameter modifiers of AbstractAccessControlNameCheck.shouldCheckInScope. + return shouldCheckInScope(ast.findFirstToken(TokenTypes.MODIFIERS)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.MODIFIERS) + final DetailAST abstractAST = ast.findFirstToken(TokenTypes.MODIFIERS) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractNameCheck.java + dereference.of.nullable + dereference of possibly-null reference nameAST + if (!format.matcher(nameAST.getText()).find()) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/ConstantNameCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAST + modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/ConstantNameCheck.java + dereference.of.nullable + dereference of possibly-null reference nameAST + if (!"serialVersionUID".equals(nameAST.getText()) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAST + || modifiersAST.findFirstToken(TokenTypes.FINAL) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/LocalVariableNameCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + final String variableName = ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/LocalVariableNameCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAST + final boolean isFinal = modifiersAST.findFirstToken(TokenTypes.FINAL) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/MemberNameCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAST + final boolean isStatic = modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheck.java + dereference.of.nullable + dereference of possibly-null reference method + && method.getText().equals(classIdent.getText())) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/naming/StaticVariableNameCheck.java + dereference.of.nullable + dereference of possibly-null reference modifiersAST + final boolean isStatic = modifiersAST.findFirstToken(TokenTypes.LITERAL_STATIC) != null; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.java + assignment + incompatible types in assignment. + pattern = Optional.ofNullable(format).map(this::createPattern).orElse(null); +
    + found : @Initialized @Nullable Pattern + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.java + initialization.fields.uninitialized + the constructor does not initialize fields: reporter, format, message, suppressor, pattern + private DetectorOptions() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + message = Optional.ofNullable(message).orElse(""); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + pattern = Optional.ofNullable(format).map(this::createPattern).orElse(null); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + suppressor = Optional.ofNullable(suppressor).orElse(NeverSuppress.INSTANCE); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/MultilineDetector.java + initialization.fields.uninitialized + the constructor does not initialize fields: matcher, text + /* package */ MultilineDetector(DetectorOptions options) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpCheck.java + initialization.field.uninitialized + the default constructor does not initialize field message + private String message; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheck.java + initialization.field.uninitialized + the default constructor does not initialize field detector + private MultilineDetector detector; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheck.java + initialization.field.uninitialized + the default constructor does not initialize field message + private String message; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpOnFilenameCheck.java + initialization.field.uninitialized + the default constructor does not initialize field fileNamePattern + private Pattern fileNamePattern; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpOnFilenameCheck.java + initialization.field.uninitialized + the default constructor does not initialize field folderPattern + private Pattern folderPattern; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpOnFilenameCheck.java + return + incompatible types in return. + return file.getCanonicalFile().getParent(); +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineCheck.java + initialization.field.uninitialized + the default constructor does not initialize field detector + private SinglelineDetector detector; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineCheck.java + initialization.field.uninitialized + the default constructor does not initialize field message + private String message; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.java + argument + incompatible argument for parameter val of Builder.suppressor. + .suppressor(suppressor) +
    + found : @Initialized @Nullable MatchSuppressor + required: @Initialized @NonNull MatchSuppressor +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.java + initialization.field.uninitialized + the default constructor does not initialize field message + private String message; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/AnonInnerLengthCheck.java + dereference.of.nullable + dereference of possibly-null reference closingBrace + closingBrace.getLineNo() - openingBrace.getLineNo() + 1; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheck.java + argument + incompatible argument for parameter ast of Context constructor. + context = new Context(null); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheck.java + initialization.fields.uninitialized + the constructor does not initialize fields: context + public ExecutableStatementCountCheck() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (parent == contextAST) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheck.java + not.interned + attempting to use a non-@Interned comparison operand + if (parent == contextAST) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java + dereference.of.nullable + dereference of possibly-null reference actualCounter + actualCounter.increment(scope); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java + dereference.of.nullable + dereference of possibly-null reference counters.peek() + final DetailAST latestDefinition = counters.peek().getScopeDefinition(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java + not.interned + attempting to use a non-@Interned comparison operand + result = latestDefinition == methodDef.getParent().getParent(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java + not.interned + attempting to use a non-@Interned comparison operand + result = latestDefinition == methodDef.getParent().getParent(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheck.java + argument + incompatible argument for parameter closingBrace of MethodLengthCheck.getLengthOfBlock. + length = getLengthOfBlock(openingBrace, closingBrace); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheck.java + dereference.of.nullable + dereference of possibly-null reference ast.findFirstToken(TokenTypes.IDENT) + final String methodName = ast.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/ParameterNumberCheck.java + argument + incompatible argument for parameter ast of AbstractCheck.log. + log(name, MSG_KEY, max, count); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/ParameterNumberCheck.java + dereference.of.nullable + dereference of possibly-null reference params + final int count = params.getChildCount(TokenTypes.PARAMETER_DEF); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/RecordComponentNumberCheck.java + argument + incompatible argument for parameter recordComponents of RecordComponentNumberCheck.countComponents. + final int componentCount = countComponents(recordComponents); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheck.java + dereference.of.nullable + dereference of possibly-null reference token.findFirstToken(TokenTypes.TYPE) + for (DetailAST typeChild = token.findFirstToken(TokenTypes.TYPE).getLastChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheck.java + dereference.of.nullable + dereference of possibly-null reference token.findFirstToken(TokenTypes.TYPE) + for (DetailAST typeChild = token.findFirstToken(TokenTypes.TYPE).getLastChild(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java + dereference.of.nullable + dereference of possibly-null reference endOfParams + after = endOfParams.getColumnNo() + 1; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java + dereference.of.nullable + dereference of possibly-null reference parent.findFirstToken(TokenTypes.TYPE_ARGUMENTS) + typeLastNode = parent.findFirstToken(TokenTypes.TYPE_ARGUMENTS) + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java + prefer.map.and.orelse + It is better style to use map and orElse. + else if (objectArrayType.isPresent()) { +
    + Consider changing to: + typeLastNode.map(ENCLOSINGCLASS::orElseThrow).orElse(parent.getFirstChild()) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java + return + incompatible types in return. + return switch (ast.getType()) { +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java + return + incompatible types in return. + return typeLastNode; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheck.java + dereference.of.nullable + dereference of possibly-null reference node.findFirstToken(TokenTypes.COLON) + rightNode = node.findFirstToken(TokenTypes.COLON).getPreviousSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast of AbstractParenPadCheck.processLeft. + processLeft(ast.findFirstToken(TokenTypes.LPAREN)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast of AbstractParenPadCheck.processLeft. + processLeft(ast.findFirstToken(TokenTypes.LPAREN)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast of AbstractParenPadCheck.processRight. + processRight(ast.findFirstToken(TokenTypes.RPAREN)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast of AbstractParenPadCheck.processRight. + processRight(ast.findFirstToken(TokenTypes.RPAREN)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast of AbstractParenPadCheck.processRight. + processRight(ast.findFirstToken(TokenTypes.RPAREN)); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast of ParenPadCheck.hasPrecedingSemiColon. + if (!hasPrecedingSemiColon(rparen)) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast of ParenPadCheck.isFollowsEmptyForIterator. + if (!isFollowsEmptyForIterator(rparen)) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast of ParenPadCheck.isPrecedingEmptyForInit. + if (!isPrecedingEmptyForInit(lparen)) { +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + argument + incompatible argument for parameter ast1 of TokenUtil.areOnSameLine. + if (TokenUtil.areOnSameLine(firstRparen, ast) +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + dereference.of.nullable + dereference of possibly-null reference forIterator + result = !forIterator.hasChildren(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + dereference.of.nullable + dereference of possibly-null reference forIterator + result = !forIterator.hasChildren(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (currentNode.getNextSibling() == null && currentNode.getParent() != ast) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.java + not.interned + attempting to use a non-@Interned comparison operand + while (currentNode.getNextSibling() == null && currentNode.getParent() != ast) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/TypecastParenPadCheck.java + not.interned + attempting to use a non-@Interned comparison operand + && ast.getParent().findFirstToken(TokenTypes.RPAREN) == ast) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/TypecastParenPadCheck.java + not.interned + attempting to use a non-@Interned comparison operand + && ast.getParent().findFirstToken(TokenTypes.RPAREN) == ast) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck.java + dereference.of.nullable + dereference of possibly-null reference targetAST + final int[] line = getLineCodePoints(targetAST.getLineNo() - 1); + + + + src/main/java/com/puppycrawl/tools/checkstyle/filefilters/BeforeExecutionExclusionFileFilter.java + initialization.field.uninitialized + the default constructor does not initialize field fileNamePattern + private Pattern fileNamePattern; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterElement.java + method.invocation + call to addFilter(com.puppycrawl.tools.checkstyle.filters.IntFilterElement) not allowed on the given receiver. + addFilter(new IntMatchFilterElement(matchValue)); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.filters.CsvFilterElement.class) @NonNull CsvFilterElement + required: @Initialized @NonNull CsvFilterElement +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterElement.java + method.invocation + call to addFilter(com.puppycrawl.tools.checkstyle.filters.IntFilterElement) not allowed on the given receiver. + addFilter(new IntRangeFilterElement(lowerBound, upperBound)); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.filters.CsvFilterElement.class) @NonNull CsvFilterElement + required: @Initialized @NonNull CsvFilterElement +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterElement.java + override.param + Incompatible parameter type for object. + public boolean equals(Object object) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull CsvFilterElement + @Initialized @NonNull boolean equals(@Initialized @NonNull CsvFilterElement this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + assignment + incompatible types in assignment. + columnFilter = null; +
    + found : null (NullType) + required: @Initialized @NonNull CsvFilterElement +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + assignment + incompatible types in assignment. + lineFilter = null; +
    + found : null (NullType) + required: @Initialized @NonNull CsvFilterElement +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + assignment + incompatible types in assignment. + columnsCsv = null; +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + assignment + incompatible types in assignment. + linesCsv = null; +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull SuppressFilterElement + @Initialized @NonNull boolean equals(@Initialized @NonNull SuppressFilterElement this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable Pattern + method return type: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + argument + incompatible argument for parameter text of SuppressWithNearbyCommentFilter.addTag. + addTag(matcher.group(0), line); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + assignment + incompatible types in assignment. + tagIdRegexp = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + assignment + incompatible types in assignment. + tagMessageRegexp = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + initialization.field.uninitialized + the default constructor does not initialize field idFormat + private String idFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + initialization.field.uninitialized + the default constructor does not initialize field messageFormat + private String messageFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + not.interned + attempting to use a non-@Interned comparison operand + if (getFileContents() != currentContents) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + not.interned + attempting to use a non-@Interned comparison operand + if (getFileContents() != currentContents) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull Tag + @Initialized @NonNull boolean equals(@Initialized @NonNull Tag this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + return + incompatible types in return. + return fileContentsReference.get(); +
    + type of expression: @Initialized @Nullable FileContents + method return type: @Initialized @NonNull FileContents +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + argument + incompatible argument for parameter text of Suppression constructor. + suppression = new Suppression(text, lineNo + 1, this); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + initialization.field.uninitialized + the default constructor does not initialize field idPattern + private String idPattern; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + initialization.field.uninitialized + the default constructor does not initialize field messagePattern + private String messagePattern; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + initialization.fields.uninitialized + the constructor does not initialize fields: eventMessageRegexp, eventIdRegexp + private Suppression( + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable FileText + method return type: @Initialized @NonNull FileText +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + return + incompatible types in return. + return suppression; +
    + type of expression: @Initialized @Nullable Suppression + method return type: @Initialized @NonNull Suppression +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + argument + incompatible argument for parameter text of Suppression constructor. + suppression = new Suppression(offCommentMatcher.group(0), +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + argument + incompatible argument for parameter text of Suppression constructor. + suppression = new Suppression(onCommentMatcher.group(0), +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + assignment + incompatible types in assignment. + eventIdRegexp = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + assignment + incompatible types in assignment. + eventMessageRegexp = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + initialization.field.uninitialized + the default constructor does not initialize field idFormat + private String idFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + initialization.field.uninitialized + the default constructor does not initialize field messageFormat + private String messageFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull Suppression + @Initialized @NonNull boolean equals(@Initialized @NonNull Suppression this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable FileText + method return type: @Initialized @NonNull FileText +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + return + incompatible types in return. + .orElse(null); +
    + type of expression: @Initialized @Nullable Suppression + method return type: @Initialized @NonNull Suppression +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + argument + incompatible argument for parameter text of SuppressionCommentFilter.addTag. + addTag(offMatcher.group(0), line, column, TagType.OFF); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + argument + incompatible argument for parameter text of SuppressionCommentFilter.addTag. + addTag(onMatcher.group(0), line, column, TagType.ON); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + assignment + incompatible types in assignment. + tagIdRegexp = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + assignment + incompatible types in assignment. + tagMessageRegexp = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + initialization.field.uninitialized + the default constructor does not initialize field idFormat + private String idFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + initialization.field.uninitialized + the default constructor does not initialize field messageFormat + private String messageFormat; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + not.interned + attempting to use a non-@Interned comparison operand + if (getFileContents() != currentContents) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + not.interned + attempting to use a non-@Interned comparison operand + if (getFileContents() != currentContents) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull Tag + @Initialized @NonNull boolean equals(@Initialized @NonNull Tag this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + return + incompatible types in return. + return fileContentsReference.get(); +
    + type of expression: @Initialized @Nullable FileContents + method return type: @Initialized @NonNull FileContents +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable Tag + method return type: @Initialized @NonNull Tag +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilter.java + initialization.field.uninitialized + the default constructor does not initialize field file + private String file; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field checks + private Pattern checks; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field columns + private String columns; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field files + private Pattern files; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field filter + private SuppressFilterElement filter; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field id + private String id; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field lines + private String lines; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field message + private Pattern message; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java + initialization.field.uninitialized + the default constructor does not initialize field file + private String file; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java + override.param + Incompatible parameter type for obj. + public boolean equals(Object obj) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull SuppressionXpathFilter + @Initialized @NonNull boolean equals(@Initialized @NonNull SuppressionXpathFilter this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + assignment + incompatible types in assignment. + this.checks = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + assignment + incompatible types in assignment. + this.files = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + assignment + incompatible types in assignment. + this.message = null; +
    + found : null (NullType) + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field checks + private Pattern checks; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field files + private Pattern files; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field id + private String id; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field message + private Pattern message; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field query + private String query; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + initialization.field.uninitialized + the default constructor does not initialize field xpathFilter + private XpathFilterElement xpathFilter; + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + argument + incompatible argument for parameter checks of XpathFilterElement constructor. + Optional.ofNullable(checks).map(CommonUtil::createPattern).orElse(null), +
    + found : @Initialized @Nullable Pattern + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + argument + incompatible argument for parameter contextItem of XPathExpression.createDynamicContext. + xpathExpression.createDynamicContext(rootNode); +
    + found : @Initialized @Nullable RootNode + required: @Initialized @NonNull Item +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + argument + incompatible argument for parameter files of XpathFilterElement constructor. + this(Optional.ofNullable(files).map(Pattern::compile).orElse(null), +
    + found : @Initialized @Nullable Pattern + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + argument + incompatible argument for parameter message of XpathFilterElement constructor. + Optional.ofNullable(message).map(Pattern::compile).orElse(null), +
    + found : @Initialized @Nullable Pattern + required: @Initialized @NonNull Pattern +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + assignment + incompatible types in assignment. + .toList(); +
    + found : @Initialized @NonNull List<@Initialized @PolyNull AbstractNode> + required: @UnknownInitialization @Nullable List<@Initialized @NonNull AbstractNode> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + assignment + incompatible types in assignment. + xpathExpression = null; +
    + found : null (NullType) + required: @Initialized @NonNull XPathExpression +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + Optional.ofNullable(checks).map(CommonUtil::createPattern).orElse(null), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + Optional.ofNullable(message).map(Pattern::compile).orElse(null), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + this(Optional.ofNullable(files).map(Pattern::compile).orElse(null), + + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + override.param + Incompatible parameter type for other. + public boolean equals(Object other) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull XpathFilterElement + @Initialized @NonNull boolean equals(@Initialized @NonNull XpathFilterElement this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/grammar/SimpleToken.java + override.param + Incompatible parameter type for obj. + public boolean equals(Object obj) { +
    + found : @Initialized @NonNull Object + required: @Initialized @Nullable Object + Consequence: method in @Initialized @NonNull SimpleToken + @Initialized @NonNull boolean equals(@Initialized @NonNull SimpleToken this, @Initialized @NonNull Object p0) + cannot override method in @Initialized @NonNull Object + @Initialized @NonNull boolean equals(@Initialized @NonNull Object this, @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/BaseCellEditor.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + argument + incompatible argument for parameter arg0 of Toolkit.getImage. + setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource(ICON))); +
    + found : @Initialized @Nullable URL + required: @Initialized @NonNull URL +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + argument + incompatible argument for parameter event of ReloadAction.actionPerformed. + reloadAction.actionPerformed(null); +
    + found : null (NullType) + required: @Initialized @NonNull ActionEvent +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + argument + incompatible argument for parameter sourceFile of MainFrame.openFile. + openFile(file); +
    + found : @Initialized @Nullable File + required: @Initialized @NonNull File +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + initialization.fields.uninitialized + the constructor does not initialize fields: textArea, xpathTextArea, treeTable + public MainFrame() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + method.invocation + call to createContent() not allowed on the given receiver. + createContent(); +
    + found : @UnderInitialization(javax.swing.JFrame.class) @NonNull MainFrame + required: @Initialized @NonNull MainFrame +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.java + argument + incompatible argument for parameter parseTree of ParseTreeTableModel constructor. + parseTreeTableModel = new ParseTreeTableModel(null); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.java + initialization.fields.uninitialized + the constructor does not initialize fields: currentFile, text + public MainFrameModel() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.java + return + incompatible types in return. + return lastDirectory; +
    + type of expression: @Initialized @Nullable File + method return type: @Initialized @NonNull File +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTableModel.java + argument + incompatible argument for parameter childIndices of ParseTreeTableModel.fireTreeStructureChanged. + fireTreeStructureChanged(this, path, null, CommonUtil.EMPTY_OBJECT_ARRAY); +
    + found : null (NullType) + required: @Initialized @NonNull int @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTableModel.java + method.invocation + call to setParseTree(com.puppycrawl.tools.checkstyle.api.DetailAST) not allowed on the given receiver. + setParseTree(parseTree); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel.class) @NonNull ParseTreeTableModel + required: @Initialized @NonNull ParseTreeTableModel +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentation.java + initialization.fields.uninitialized + the constructor does not initialize fields: parseMode + public ParseTreeTablePresentation(DetailAST parseTree) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentation.java + return + incompatible types in return. + return switch (column) { +
    + type of expression: @Initialized @Nullable Object + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentation.java + return + incompatible types in return. + return switch (column) { +
    + type of expression: @Initialized @Nullable Object + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + argument + incompatible argument for parameter arg0 of JComponent.getFontMetrics. + final FontMetrics fontMetrics = getFontMetrics(getFont()); +
    + found : @Initialized @Nullable Font + required: @Initialized @NonNull Font +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + argument + incompatible argument for parameter arg0 of JTree.setSelectionModel. + tree.setSelectionModel(selectionWrapper); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.gui.ListToTreeSelectionModelWrapper.class) @NonNull ListToTreeSelectionModelWrapper + required: @Initialized @NonNull TreeSelectionModel +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + argument + incompatible argument for parameter jTreeTable of ListToTreeSelectionModelWrapper constructor. + ListToTreeSelectionModelWrapper(this); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull TreeTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + argument + incompatible argument for parameter treeTable of TreeTableCellRenderer constructor. + tree = new TreeTableCellRenderer(this, treeTableModel); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull TreeTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + assignment + incompatible types in assignment. + tree = new TreeTableCellRenderer(this, treeTableModel); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.gui.TreeTableCellRenderer.class) @NonNull TreeTableCellRenderer + required: @Initialized @NonNull TreeTableCellRenderer +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + initialization.fields.uninitialized + the constructor does not initialize fields: editor, xpathEditor, linePositionList + public TreeTable(ParseTreeTableModel treeTableModel) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to addMouseListener(java.awt.event.MouseListener) not allowed on the given receiver. + addMouseListener(new MouseAdapter() { +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull Component +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to expandSelectedNode() not allowed on the given receiver. + expandSelectedNode(); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull TreeTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to expandSelectedNode() not allowed on the given receiver. + expandSelectedNode(); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull TreeTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to getActionMap() not allowed on the given receiver. + getActionMap().put(command, expand); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JComponent +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to getInputMap() not allowed on the given receiver. + getInputMap().put(stroke, command); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JComponent +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to getListSelectionModel() not allowed on the given receiver. + setSelectionModel(selectionWrapper.getListSelectionModel()); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.gui.ListToTreeSelectionModelWrapper.class) @NonNull ListToTreeSelectionModelWrapper + required: @Initialized @NonNull ListToTreeSelectionModelWrapper +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to getRowHeight() not allowed on the given receiver. + final int height = getRowHeight(); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to setColumnsInitialWidth() not allowed on the given receiver. + setColumnsInitialWidth(); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull TreeTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to setDefaultEditor(java.lang.Class<?>,javax.swing.table.TableCellEditor) not allowed on the given receiver. + setDefaultEditor(ParseTreeTableModel.class, new TreeTableCellEditor()); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to setDefaultRenderer(java.lang.Class<?>,javax.swing.table.TableCellRenderer) not allowed on the given receiver. + setDefaultRenderer(ParseTreeTableModel.class, tree); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to setIntercellSpacing(java.awt.Dimension) not allowed on the given receiver. + setIntercellSpacing(new Dimension(0, 0)); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to setModel(javax.swing.table.TableModel) not allowed on the given receiver. + setModel(new TreeTableModelAdapter(treeTableModel, tree)); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to setRowHeight(int) not allowed on the given receiver. + setRowHeight(height); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull TreeTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to setSelectionModel(javax.swing.ListSelectionModel) not allowed on the given receiver. + setSelectionModel(selectionWrapper.getListSelectionModel()); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + method.invocation + call to setShowGrid(boolean) not allowed on the given receiver. + setShowGrid(false); +
    + found : @UnderInitialization(javax.swing.JTable.class) @NonNull TreeTable + required: @Initialized @NonNull JTable +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + type.arguments.not.inferred + Could not infer type arguments for Stream.map + .map(ElementNode::getUnderlyingNode) +
    + unsatisfiable constraint: @Initialized @PolyNull ElementNode <: @Initialized @NonNull ElementNode + ElementNode::getUnderlyingNode -> inference type: java.util.function.Function<? super com.puppycrawl.tools.checkstyle.xpath.ElementNode,? extends R> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/JavadocMetadataScraperUtil.java + not.interned + attempting to use a non-@Interned comparison operand + while (curNode != endNode && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/JavadocMetadataScraperUtil.java + not.interned + attempting to use a non-@Interned comparison operand + while (curNode != endNode && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtil.java + argument + incompatible argument for parameter message of CheckstyleException constructor. + throw new CheckstyleException(macroException.getMessage(), macroException); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtil.java + argument + incompatible argument for parameter propertyJavadoc of MetadataGeneratorUtil.getPropertyDescription. + javadocs.get(property)); +
    + found : @Initialized @Nullable DetailNode + required: @Initialized @NonNull DetailNode +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtil.java + return + incompatible types in return. + return validationType; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/ModuleDetails.java + initialization.fields.uninitialized + the constructor does not initialize fields: name, fullQualifiedName, parent, description, moduleType + public ModuleDetails() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/ModulePropertyDetails.java + initialization.fields.uninitialized + the constructor does not initialize fields: name, type, defaultValue, validationType, description + public ModulePropertyDetails() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + argument + incompatible argument for parameter description of ModuleDetails.setDescription. + .getFirstChild().getNodeValue()); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + argument + incompatible argument for parameter description of ModulePropertyDetails.setDescription. + .get(0).getFirstChild().getNodeValue()); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + argument + incompatible argument for parameter element of XmlMetaReader.getAttributeValue. + listContent.add(getAttributeValue((Element) nodeList.item(j), attribute)); +
    + found : @Initialized @Nullable Element + required: @Initialized @NonNull Element +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + argument + incompatible argument for parameter element of XmlMetaReader.getAttributeValue. + propertyDetails.setName(getAttributeValue(prop, XML_TAG_NAME)); +
    + found : @Initialized @Nullable Element + required: @Initialized @NonNull Element +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + argument + incompatible argument for parameter moduleMetadataStream of XmlMetaReader.read. + moduleDetails = read(XmlMetaReader.class.getResourceAsStream("/" + fileName), +
    + found : @Initialized @Nullable InputStream + required: @Initialized @NonNull InputStream +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + dereference.of.nullable + dereference of possibly-null reference children.item(i) + if (children.item(i).getParentNode().equals(element)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + dereference.of.nullable + dereference of possibly-null reference children.item(i).getParentNode() + if (children.item(i).getParentNode().equals(element)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + dereference.of.nullable + dereference of possibly-null reference element.getAttributes() + return element.getAttributes().getNamedItem(attribute).getNodeValue(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + dereference.of.nullable + dereference of possibly-null reference element.getAttributes().getNamedItem(attribute) + return element.getAttributes().getNamedItem(attribute).getNodeValue(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + dereference.of.nullable + dereference of possibly-null reference getDirectChildsByTag(mod, XML_TAG_DESCRIPTION).get(0).getFirstChild() + .getFirstChild().getNodeValue()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + dereference.of.nullable + dereference of possibly-null reference getDirectChildsByTag(prop, XML_TAG_DESCRIPTION).get(0).getFirstChild() + .get(0).getFirstChild().getNodeValue()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable List<@Initialized @NonNull String> + method return type: @Initialized @NonNull List<@Initialized @NonNull String> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable ModuleDetails + method return type: @Initialized @NonNull ModuleDetails +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.java + return + incompatible types in return. + return element.getAttributes().getNamedItem(attribute).getNodeValue(); +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ClassAndPropertiesSettersJavadocScraper.java + dereference.of.nullable + dereference of possibly-null reference classDef.findFirstToken(TokenTypes.IDENT) + final String className = classDef.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ClassAndPropertiesSettersJavadocScraper.java + dereference.of.nullable + dereference of possibly-null reference classDef.findFirstToken(TokenTypes.IDENT) + final String className = classDef.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ClassAndPropertiesSettersJavadocScraper.java + dereference.of.nullable + dereference of possibly-null reference methodDef.findFirstToken(TokenTypes.IDENT) + final String methodName = methodDef.findFirstToken(TokenTypes.IDENT).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ClassAndPropertiesSettersJavadocScraper.java + dereference.of.nullable + dereference of possibly-null reference type + final String name = type.getNextSibling().getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/JavadocScraperResultUtil.java + assignment + incompatible types in assignment. + moduleJavadocNode = null; +
    + found : null (NullType) + required: @Initialized @NonNull DetailNode +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/JavadocScraperResultUtil.java + initialization.static.field.uninitialized + static field moduleJavadocNode not initialized + private static DetailNode moduleJavadocNode; + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ModuleJavadocParsingUtil.java + return + incompatible types in return. + .orElse(null); +
    + type of expression: @Initialized @Nullable DetailNode + method return type: @Initialized @NonNull DetailNode +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ModuleJavadocParsingUtil.java + return + incompatible types in return. + return notesStartNode; +
    + type of expression: @Initialized @Nullable DetailNode + method return type: @Initialized @NonNull DetailNode +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/PropertiesMacro.java + argument + incompatible argument for parameter justification of XdocSink.tableRows. + sink.tableRows(null, false); +
    + found : null (NullType) + required: @Initialized @NonNull int @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/PropertiesMacro.java + argument + incompatible argument for parameter propertyJavadoc of PropertiesMacro.writePropertyRow. + writePropertyRow(sink, property, propertyJavadoc, instance, currentModuleJavadoc); +
    + found : @Initialized @Nullable DetailNode + required: @Initialized @NonNull DetailNode +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + annotations.on.use + invalid type: annotations [@Initialized, @Nullable] conflict with declaration of type java.util.Optional + private static Optional<String> getPropertyVersionFromItsJavadoc(DetailNode propertyJavadoc) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + argument + incompatible argument for parameter classLoader of PackageNamesLoader.getPackageNames. + final Set<String> packageNames = PackageNamesLoader.getPackageNames(cl); +
    + found : @Initialized @Nullable ClassLoader + required: @Initialized @NonNull ClassLoader +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + argument + incompatible argument for parameter message of MacroExecutionException constructor. + throw new MacroExecutionException(exc.getMessage(), exc); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + argument + incompatible argument for parameter moduleClassLoader of Checker.setModuleClassLoader. + checker.setModuleClassLoader(Checker.class.getClassLoader()); +
    + found : @Initialized @Nullable ClassLoader + required: @Initialized @NonNull ClassLoader +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + dereference.of.nullable + dereference of possibly-null reference currentClass + result = currentClass.getDeclaredField(propertyName); + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + dereference.of.nullable + dereference of possibly-null reference specifiedPropertyVersionInPropertyJavadoc + if (specifiedPropertyVersionInPropertyJavadoc.isPresent()) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElse(null); + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(fieldClass::getTypeName); + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + methodref.return + Incompatible return type + .mapToInt(int.class::cast); +
    + found : @Initialized @Nullable Integer + required: @Initialized @NonNull int + Consequence: method in @Initialized @NonNull Class<@Initialized @NonNull Integer> + @Initialized @Nullable Integer cast(@Initialized @NonNull Class<@Initialized @NonNull Integer> this, @Initialized @Nullable Object p0) + is not a valid method reference for method in @Initialized @NonNull ToIntFunction<capture extends @Initialized @Nullable Object> + @Initialized @NonNull int applyAsInt(@Initialized @NonNull ToIntFunction<capture extends @Initialized @Nullable Object> this, capture extends @Initialized @Nullable Object p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + not.interned + attempting to use a non-@Interned comparison operand + while (node != endNode && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + not.interned + attempting to use a non-@Interned comparison operand + while (node != endNode && toVisit == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable Class<capture extends @Initialized @Nullable Object> + method return type: @Initialized @NonNull Class<? extends @Initialized @Nullable Object> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + return + incompatible types in return. + return javadocTagWithSince; +
    + type of expression: @Initialized @Nullable DetailNode + method return type: @Initialized @NonNull DetailNode +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable Field + method return type: @Initialized @NonNull Field +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + return + incompatible types in return. + return fieldValue; +
    + type of expression: @Initialized @Nullable Object + method return type: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + return + incompatible types in return. + .orElse(null); +
    + type of expression: @Initialized @Nullable Path + method return type: @Initialized @NonNull Path +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + type.arguments.not.inferred + Could not infer type arguments for Stream.collect + .collect(Collectors.toCollection(ArrayList<String>::new)); +
    + unsatisfiable constraint: @Initialized @PolyNull String <: @Initialized @NonNull String + @Initialized @NonNull String = use of T from Collectors.toCollection(ArrayList<String>::new) + From complementary bound.: @Initialized @NonNull String <= use of T from Collectors.toCollection(ArrayList<String>::new) + @Initialized @NonNull ArrayList<@Initialized @NonNull String> <: inference type: java.util.Collection<T> + @Initialized @NonNull ArrayList<@Initialized @NonNull String> <: use of C from Collectors.toCollection(ArrayList<String>::new) + From complementary bound.: @Initialized @NonNull ArrayList<@Initialized @NonNull String> -> use of C from Collectors.toCollection(ArrayList<String>::new) + ArrayList<String>::new -> inference type: java.util.function.Supplier<C> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + type.arguments.not.inferred + Could not infer type arguments for Stream.map + .map(Pattern.class::cast) +
    + unsatisfiable constraint: capture extends @Initialized @Nullable Object <: @Initialized @PolyNull Object + Pattern.class::cast -> inference type: java.util.function.Function<? super capture of ?,? extends R> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + unnecessary.equals + use of .equals can be safely replaced by ==/!= + while (!Object.class.equals(currentClass)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ViolationMessagesMacro.java + dereference.of.nullable + dereference of possibly-null reference clss.getPackage() + + clss.getPackage().getName().replace(".", "%2F") + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateParser.java + argument + incompatible argument for parameter arg0 of XmlPullParser.getAttributeValue. + .getAttributeValue(null, Attribute.NAME.toString()); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateParser.java + argument + incompatible argument for parameter arg0 of XmlPullParser.getAttributeValue. + .getAttributeValue(null, Attribute.VALUE.toString()); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateParser.java + argument + incompatible argument for parameter arg0 of XmlPullParser.getAttributeValue. + macroName = parser.getAttributeValue(null, Attribute.NAME.toString()); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateParser.java + assignment + incompatible types in assignment. + sourceContent = null; +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateParser.java + initialization.field.uninitialized + the default constructor does not initialize field macroName + private String macroName; + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateParser.java + initialization.field.uninitialized + the default constructor does not initialize field sourceContent + private String sourceContent; + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtil.java + argument + incompatible argument for parameter ast of FullIdent.createFullIdent. + annotationString = FullIdent.createFullIdent(dotNode).getText(); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtil.java + dereference.of.nullable + dereference of possibly-null reference firstChild + FullIdent.createFullIdent(firstChild.getNextSibling()).getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtil.java + return + incompatible types in return. + return annotationHolder; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtil.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable DetailAST + method return type: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ChainedPropertyUtil.java + argument + incompatible argument for parameter arg0 of Pattern.matcher. + final Matcher matcher = PROPERTY_VARIABLE_PATTERN.matcher(propertyValue); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull CharSequence +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg0 of List.add. + typeParams.add(typeParam); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter modifiersToken of CheckUtil.getAccessModifierFromModifiersTokenDirectly. + accessModifier = getAccessModifierFromModifiersTokenDirectly(modsToken); +
    + found : @Initialized @Nullable DetailAST + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + dereference.of.nullable + dereference of possibly-null reference modifiers + modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + dereference.of.nullable + dereference of possibly-null reference nameNode + final String name = nameNode.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + dereference.of.nullable + dereference of possibly-null reference paramsNode + equalsMethod = paramsNode.getChildCount() == 1; + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + dereference.of.nullable + dereference of possibly-null reference sibling.findFirstToken(TokenTypes.IDENT) + sibling.findFirstToken(TokenTypes.IDENT).getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + dereference.of.nullable + dereference of possibly-null reference typeAST + if (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) == null) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + dereference.of.nullable + dereference of possibly-null reference typeParam + DetailAST sibling = typeParam.getNextSibling(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + dereference.of.nullable + dereference of possibly-null reference typeParam + typeParam.findFirstToken(TokenTypes.IDENT).getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + dereference.of.nullable + dereference of possibly-null reference typeParam.findFirstToken(TokenTypes.IDENT) + typeParam.findFirstToken(TokenTypes.IDENT).getText()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + return + incompatible types in return. + return returnValue; +
    + type of expression: @Initialized @Nullable AccessModifierOption + method return type: @Initialized @NonNull AccessModifierOption +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg1 of String.replaceAll. + result = result.replaceAll("\\$" + i, matcher.group(i)); +
    + found : @Initialized @Nullable String + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + return + incompatible types in return. + return uri; +
    + type of expression: @Initialized @Nullable URI + method return type: @Initialized @NonNull URI +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + return + incompatible types in return. + return CommonUtil.class.getResource(name); +
    + type of expression: @Initialized @Nullable URL + method return type: @Initialized @NonNull URL +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtil.java + return + incompatible types in return. + return returnValue; +
    + type of expression: @Initialized @Nullable DetailNode + method return type: @Initialized @NonNull DetailNode +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtil.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(() -> getDefaultScope(aMods)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtil.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElseGet(() -> getDefaultScope(ast)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtil.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable Scope + method return type: @Initialized @NonNull Scope +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtil.java + return + incompatible types in return. + return returnValue; +
    + type of expression: @Initialized @Nullable Scope + method return type: @Initialized @NonNull Scope +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + argument + incompatible argument for parameter object of TokenUtil.getIntFromField. + Field::getName, fld -> getIntFromField(fld, null)) +
    + found : null (NullType) + required: @Initialized @NonNull Object +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/UnmodifiableCollectionUtil.java + return + incompatible types in return. + .toList(); +
    + type of expression: @Initialized @NonNull List<T extends @Initialized @PolyNull Object> + method return type: @Initialized @NonNull List<T extends @Initialized @Nullable Object> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/UnmodifiableCollectionUtil.java + return + incompatible types in return. + return Arrays.copyOf(array, length); +
    + type of expression: T[ extends @Initialized @Nullable Object super @Initialized @Nullable Void] @Initialized @NonNull [] + method return type: T[ extends @Initialized @Nullable Object super @Initialized @NonNull Void] @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/UnmodifiableCollectionUtil.java + type.arguments.not.inferred + Could not infer type arguments for Map.copyOf + return Map.copyOf(map); +
    + unsatisfiable constraint: K extends @Initialized @Nullable Object <: @Initialized @NonNull Object + capture extends K extends @Initialized @Nullable Object <: use of K from Map.copyOf(map) + From complementary bound.: capture extends K extends @Initialized @Nullable Object <= inference type: ? extends K + @Initialized @NonNull Map<capture extends K extends @Initialized @Nullable Object, capture extends V extends @Initialized @Nullable Object> <: inference type: java.util.Map<? extends K,? extends V> + @Initialized @NonNull Map<capture extends K extends @Initialized @Nullable Object, capture extends V extends @Initialized @Nullable Object> -> inference type: java.util.Map<? extends K,? extends V> + map -> inference type: java.util.Map<? extends K,? extends V> + From: Argument constraint + V extends @Initialized @Nullable Object <: @Initialized @NonNull Object + capture extends V extends @Initialized @Nullable Object <: use of V from Map.copyOf(map) + From complementary bound.: capture extends V extends @Initialized @Nullable Object <= inference type: ? extends V + @Initialized @NonNull Map<capture extends K extends @Initialized @Nullable Object, capture extends V extends @Initialized @Nullable Object> <: inference type: java.util.Map<? extends K,? extends V> + @Initialized @NonNull Map<capture extends K extends @Initialized @Nullable Object, capture extends V extends @Initialized @Nullable Object> -> inference type: java.util.Map<? extends K,? extends V> + map -> inference type: java.util.Map<? extends K,? extends V> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/UnmodifiableCollectionUtil.java + type.arguments.not.inferred + Could not infer type arguments for Stream.map + .map(elementType::cast) +
    + unsatisfiable constraint: S extends @Initialized @Nullable Object <: @Initialized @PolyNull Object + elementType::cast -> inference type: java.util.function.Function<? super S,? extends R> + From: Argument constraint +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + argument + incompatible argument for parameter name of AttributeNode constructor. + private static final AttributeNode ATTRIBUTE_NODE_UNINITIALIZED = new AttributeNode(null, null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + argument + incompatible argument for parameter nodes of OfNodes constructor. + getChildren().toArray(EMPTY_ABSTRACT_NODE_ARRAY)); +
    + found : @Initialized @Nullable AbstractNode @Initialized @NonNull [] + required: @Initialized @NonNull AbstractNode @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + argument + incompatible argument for parameter nodes of OfNodes constructor. + getFollowingSiblings().toArray(EMPTY_ABSTRACT_NODE_ARRAY)); +
    + found : @Initialized @Nullable AbstractNode @Initialized @NonNull [] + required: @Initialized @NonNull AbstractNode @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + argument + incompatible argument for parameter value of AttributeNode constructor. + private static final AttributeNode ATTRIBUTE_NODE_UNINITIALIZED = new AttributeNode(null, null); +
    + found : null (NullType) + required: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + introduce.eliminate + It is bad style to create an Optional just to chain methods to get a non-optional value. + .orElse(null); + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + not.interned + attempting to use a non-@Interned comparison operand + if (attributeNode == ATTRIBUTE_NODE_UNINITIALIZED) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + not.interned + attempting to use a non-@Interned comparison operand + if (attributeNode == ATTRIBUTE_NODE_UNINITIALIZED) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable String + method return type: @Initialized @NonNull String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + getChildren().toArray(EMPTY_ABSTRACT_NODE_ARRAY)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + getFollowingSiblings().toArray(EMPTY_ABSTRACT_NODE_ARRAY)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractNode.java + initialization.fields.uninitialized + the constructor does not initialize fields: children + protected AbstractNode(TreeInfo treeInfo) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractNode.java + not.interned + attempting to use a non-@Interned comparison operand + return this == nodeInfo; + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractNode.java + not.interned + attempting to use a non-@Interned comparison operand + return this == nodeInfo; + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractRootNode.java + argument + incompatible argument for parameter nodes of OfNodes constructor. + getChildren().toArray(EMPTY_ABSTRACT_NODE_ARRAY)); +
    + found : @Initialized @Nullable AbstractNode @Initialized @NonNull [] + required: @Initialized @NonNull AbstractNode @Initialized @NonNull [] +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractRootNode.java + return + incompatible types in return. + return null; +
    + type of expression: null (NullType) + method return type: @Initialized @NonNull NodeInfo +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AbstractRootNode.java + toarray.nullable.elements.not.newarray + call of toArray on collection of non-null elements yields an array of possibly-null elements; omit the argument to toArray or make it an explicit array constructor + getChildren().toArray(EMPTY_ABSTRACT_NODE_ARRAY)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/AttributeNode.java + argument + incompatible argument for parameter treeInfo of AbstractNode constructor. + super(null); +
    + found : null (NullType) + required: @Initialized @NonNull TreeInfo +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/ElementNode.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable AttributeNode + method return type: @Initialized @NonNull AttributeNode +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.java + argument + incompatible argument for parameter root of XpathQueryGenerator.getXpathQuery. + final StringBuilder xpathQueryBuilder = new StringBuilder(getXpathQuery(null, ast)); +
    + found : null (NullType) + required: @Initialized @NonNull DetailAST +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.java + not.interned + attempting to use a non-@Interned comparison operand + if (child != null && child != ast) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.java + not.interned + attempting to use a non-@Interned comparison operand + if (child != null && child != ast) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.java + not.interned + attempting to use a non-@Interned comparison operand + while (cur != root) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.java + not.interned + attempting to use a non-@Interned comparison operand + while (cur != root) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.java + assignment + incompatible types in assignment. + descendantEnum = null; +
    + found : null (NullType) + required: @Initialized @NonNull AxisIterator +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.java + dereference.of.nullable + dereference of possibly-null reference queue.poll() + descendantEnum = queue.poll().iterateAxis(AxisInfo.CHILD); + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.java + initialization.fields.uninitialized + the constructor does not initialize fields: descendantEnum + public DescendantIterator(NodeInfo start, StartWith startWith) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable NodeInfo + method return type: @Initialized @NonNull NodeInfo +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/FollowingIterator.java + assignment + incompatible types in assignment. + siblingEnum = null; +
    + found : null (NullType) + required: @Initialized @NonNull AxisIterator +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/FollowingIterator.java + initialization.fields.uninitialized + the constructor does not initialize fields: descendantEnum + public FollowingIterator(NodeInfo start) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/FollowingIterator.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable NodeInfo + method return type: @Initialized @NonNull NodeInfo +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/PrecedingIterator.java + assignment + incompatible types in assignment. + previousSiblingEnum = null; +
    + found : null (NullType) + required: @Initialized @NonNull AxisIterator +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/PrecedingIterator.java + initialization.fields.uninitialized + the constructor does not initialize fields: descendantEnum + public PrecedingIterator(NodeInfo start) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseDescendantIterator.java + dereference.of.nullable + dereference of possibly-null reference queue.poll() + pushToStack(queue.poll().iterateAxis(AxisInfo.CHILD)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseDescendantIterator.java + method.invocation + call to pushToStack(net.sf.saxon.tree.iter.AxisIterator) not allowed on the given receiver. + pushToStack(start.iterateAxis(AxisInfo.CHILD)); +
    + found : @UnderInitialization(com.puppycrawl.tools.checkstyle.xpath.iterators.ReverseDescendantIterator.class) @NonNull ReverseDescendantIterator + required: @Initialized @NonNull ReverseDescendantIterator +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseDescendantIterator.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable NodeInfo + method return type: @Initialized @NonNull NodeInfo +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseListIterator.java + assignment + incompatible types in assignment. + this.items = null; +
    + found : null (NullType) + required: @Initialized @NonNull List<? extends @Initialized @NonNull NodeInfo> +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseListIterator.java + return + incompatible types in return. + return result; +
    + type of expression: @Initialized @Nullable NodeInfo + method return type: @Initialized @NonNull NodeInfo +
    +
    +
    diff --git a/config/checker-framework-suppressions/checker-purity-value-returns-suppressions.xml b/config/checker-framework-suppressions/checker-purity-value-returns-suppressions.xml new file mode 100644 index 000000000000..59f6553f31f7 --- /dev/null +++ b/config/checker-framework-suppressions/checker-purity-value-returns-suppressions.xml @@ -0,0 +1,76 @@ + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Integer.parseInt. + result = Integer.parseInt(txt, radix); +
    + found : int + required: @IntRange(from=2, to=36) int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Integer.parseUnsignedInt. + result = Integer.parseUnsignedInt(txt, radix); +
    + found : int + required: @IntRange(from=2, to=36) int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Long.parseLong. + result = Long.parseLong(txt, radix); +
    + found : int + required: @IntRange(from=2, to=36) int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CheckUtil.java + argument + incompatible argument for parameter arg1 of Long.parseUnsignedLong. + result = Long.parseUnsignedLong(txt, radix); +
    + found : int + required: @IntRange(from=2, to=36) int +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + methodref.param + Incompatible parameter type for arg0 + .collect(BitSet::new, BitSet::set, BitSet::or); +
    + found : @IntRangeFromNonNegative int + required: int + Consequence: method in BitSet + void set(BitSet this, @IntRangeFromNonNegative int p0) + is not a valid method reference for method in ObjIntConsumer<BitSet> + void accept(ObjIntConsumer<BitSet> this, BitSet p0, int p1) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + methodref.param + Incompatible parameter type for arg0 + .collect(BitSet::new, BitSet::set, BitSet::or); +
    + found : @IntRangeFromNonNegative int + required: int + Consequence: method in BitSet + void set(BitSet this, @IntRangeFromNonNegative int p0) + is not a valid method reference for method in ObjIntConsumer<BitSet> + void accept(ObjIntConsumer<BitSet> this, BitSet p0, int p1) +
    +
    +
    diff --git a/config/checker-framework-suppressions/checker-regex-property-key-compiler-message-suppressions.xml b/config/checker-framework-suppressions/checker-regex-property-key-compiler-message-suppressions.xml new file mode 100644 index 000000000000..4da135e6bf4f --- /dev/null +++ b/config/checker-framework-suppressions/checker-regex-property-key-compiler-message-suppressions.xml @@ -0,0 +1,824 @@ + + + + src/main/java/com/puppycrawl/tools/checkstyle/LocalizedMessage.java + argument + incompatible argument for parameter arg0 of ResourceBundle.getString. + final String pattern = resourceBundle.getString(key); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertiesExpander.java + methodref.param + Incompatible parameter type for arg0 + Collectors.toUnmodifiableMap(Function.identity(), properties::getProperty)); +
    + found : @PropertyKey String + required: @UnknownPropertyKey String + Consequence: method in @UnknownPropertyKey Properties + @UnknownPropertyKey String getProperty(@UnknownPropertyKey Properties this, @PropertyKey String p0) + is not a valid method reference for method in @UnknownPropertyKey Function<@UnknownPropertyKey String, @UnknownPropertyKey String> + @UnknownPropertyKey String apply(@UnknownPropertyKey Function<@UnknownPropertyKey String, @UnknownPropertyKey String> this, @UnknownPropertyKey String p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + argument + incompatible argument for parameter arg0 of Properties.getProperty. + final String cachedConfigHash = details.getProperty(CONFIG_HASH_KEY); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + argument + incompatible argument for parameter arg0 of Properties.getProperty. + final String cachedHashSum = details.getProperty(location); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + argument + incompatible argument for parameter arg0 of Properties.getProperty. + final String cachedHashSum = details.getProperty(resource.location); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + argument + incompatible argument for parameter arg0 of Properties.getProperty. + final String lastChecked = details.getProperty(uncheckedFileName); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + argument + incompatible argument for parameter arg0 of Properties.getProperty. + return details.getProperty(name); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + argument + incompatible argument for parameter arg0 of Properties.setProperty. + .forEach(resource -> details.setProperty(resource.location, resource.contentHashSum)); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + argument + incompatible argument for parameter arg0 of Properties.setProperty. + details.setProperty(CONFIG_HASH_KEY, configHash); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java + argument + incompatible argument for parameter arg0 of Properties.setProperty. + details.setProperty(checkedFileName, Long.toString(timestamp)); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + argument + incompatible argument for parameter arg0 of ResourceBundle.getString. + result.put(key, bundle.getString(key)); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + argument + incompatible argument for parameter arg0 of Properties.setProperty. + returnValue.setProperty(entry.getKey(), value); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.java + argument + incompatible argument for parameter arg0 of Properties.setProperty. + returnValue.setProperty(p.getKey(), p.getValue()); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + + "|\"" +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + return Pattern.compile(keyPatternString); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java + argument + incompatible argument for parameter arg0 of Pattern.matches. + if (Pattern.matches(fileNameRegexp, currentFile.getName())) { +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java + argument + incompatible argument for parameter arg0 of String.replaceAll. + return fileName.replaceAll(removePattern, ""); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + return Pattern.compile(keyPatternString); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheck.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + private Pattern extendedClassNameFormat = Pattern.compile(DEFAULT_FORMAT); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/MultiFileRegexpHeaderCheck.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + Pattern.compile(input); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/MultiFileRegexpHeaderCheck.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + result = Pattern.compile(validateRegex(line)); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/header/RegexpHeaderCheck.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + headerRegexps.add(Pattern.compile(line)); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ClassImportRule.java + argument + incompatible argument for parameter arg0 of String.matches. + classMatch = forImport.matches(className); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/FileImportControl.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + return Pattern.compile(expression); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + grp = Pattern.compile(pkg); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + return Pattern.compile(expression + "(?:\\..*)?"); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + return Pattern.compile(expression); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportRule.java + argument + incompatible argument for parameter arg0 of String.matches. + pkgMatch = !forImport.matches(pkgName + "\\..*\\..*"); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/PkgImportRule.java + argument + incompatible argument for parameter arg0 of String.matches. + pkgMatch = forImport.matches(pkgName + "\\..*"); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for matcher. + references.add(topLevelType(matcher.group(1))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.java + group.count.unknown + unable to verify non-literal groups parameter. + final String methodPart = matcher.group(methodIndex); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for javadocArgMatcher. + tags.add(new JavadocTag(currentLine, col, javadocArgMatcher.group(1), + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for javadocArgMissingDescriptionMatcher. + javadocArgMissingDescriptionMatcher.group(1), + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for javadocNoargMatcher. + tags.add(new JavadocTag(currentLine, col, javadocNoargMatcher.group(1))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for javadocTagMatchResult. + int col = javadocTagMatchResult.start(1) - 1; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for multilineCont. + final String lFin = multilineCont.group(1); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for noargCurlyMatcher. + tags.add(new JavadocTag(currentLine, 0, noargCurlyMatcher.group(1))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for noargMultilineStart. + final String param1 = noargMultilineStart.group(1); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for noargMultilineStart. + final int col = noargMultilineStart.start(1) - 1; + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 2. Only 0 groups are guaranteed to exist for javadocArgMatcher. + javadocArgMatcher.group(2))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java + group.count + invalid groups parameter 2. Only 0 groups are guaranteed to exist for javadocArgMissingDescriptionMatcher. + javadocArgMissingDescriptionMatcher.group(2))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.java + methodref.receiver.bound + Incompatible receiver type + .map(INLINE_RETURN_TAG_PATTERN::matcher) +
    + found : @Regex Pattern + required: @PolyRegex Pattern + Consequence: method + @Regex Pattern + is not a valid method reference for method in @Regex Pattern + @PolyRegex Matcher matcher(@PolyRegex Pattern this, CharSequence p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.java + group.count + invalid groups parameter 1. Only 0 groups are guaranteed to exist for matcher. + final int contentStart = matcher.start(1); + + + + src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + return Pattern.compile(formatValue, options); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + result = Pattern.compile(regex); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + private Pattern commentFormat = Pattern.compile(DEFAULT_COMMENT_FORMAT); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + tagCheckRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + tagIdRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + tagMessageRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + eventIdRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + eventMessageRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + eventSourceRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + private Pattern nearbyTextPattern = Pattern.compile(DEFAULT_NEARBY_TEXT_PATTERN); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + eventIdRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + eventMessageRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + eventSourceRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + private Pattern offCommentFormat = Pattern.compile(DEFAULT_OFF_FORMAT); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + private Pattern onCommentFormat = Pattern.compile(DEFAULT_ON_FORMAT); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + tagCheckRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + tagIdRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + tagMessageRegexp = Pattern.compile(format); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + this.checks = Pattern.compile(checks); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + this.checks = Pattern.compile(checks); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + this.files = Pattern.compile(files); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + this.message = Pattern.compile(message); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + methodref.param + Incompatible parameter type for arg0 + Optional.ofNullable(message).map(Pattern::compile).orElse(null), +
    + found : @Regex String + required: String + Consequence: method in Pattern + Pattern compile(@Regex String p0) + is not a valid method reference for method in Function<String, Pattern> + Pattern apply(Function<String, Pattern> this, String p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.java + methodref.param + Incompatible parameter type for arg0 + this(Optional.ofNullable(files).map(Pattern::compile).orElse(null), +
    + found : @Regex String + required: String + Consequence: method in Pattern + Pattern compile(@Regex String p0) + is not a valid method reference for method in Function<String, Pattern> + Pattern apply(Function<String, Pattern> this, String p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/meta/JavadocMetadataScraperUtil.java + methodref.receiver.bound + Incompatible receiver type + .map(pattern::matcher) +
    + found : Pattern + required: @PolyRegex Pattern + Consequence: method + Pattern + is not a valid method reference for method in Pattern + @PolyRegex Matcher matcher(@PolyRegex Pattern this, CharSequence p0) +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/ModuleJavadocParsingUtil.java + argument + incompatible argument for parameter arg0 of String.split. + .replace("\r", "")); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/site/SiteUtil.java + argument + incompatible argument for parameter arg0 of String.matches. + .filter(path -> path.toString().matches(fileNamePattern)) +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ChainedPropertyUtil.java + argument + incompatible argument for parameter arg0 of Properties.getProperty. + String propertyValue = properties.getProperty(propertyName); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ChainedPropertyUtil.java + argument + incompatible argument for parameter arg0 of Properties.getProperty. + properties.getProperty(unresolvedPropertyName); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/ChainedPropertyUtil.java + argument + incompatible argument for parameter arg0 of Properties.setProperty. + properties.setProperty(propertyName, propertyValue); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + Pattern.compile(pattern); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg0 of Pattern.compile. + return Pattern.compile(pattern, flags); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + argument + incompatible argument for parameter arg0 of String.replaceAll. + result = result.replaceAll("\\$" + i, matcher.group(i)); +
    + found : String + required: @Regex String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtil.java + group.count.unknown + unable to verify non-literal groups parameter. + result = result.replaceAll("\\$" + i, matcher.group(i)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/utils/TokenUtil.java + argument + incompatible argument for parameter arg0 of ResourceBundle.getString. + return bundle.getString(name); +
    + found : @UnknownPropertyKey String + required: @PropertyKey String +
    +
    +
    diff --git a/config/checker-framework-suppressions/checker-signature-gui-units-init-suppressions.xml b/config/checker-framework-suppressions/checker-signature-gui-units-init-suppressions.xml new file mode 100644 index 000000000000..3d0b210499d7 --- /dev/null +++ b/config/checker-framework-suppressions/checker-signature-gui-units-init-suppressions.xml @@ -0,0 +1,1185 @@ + + + + src/main/java/com/puppycrawl/tools/checkstyle/LocalizedMessage.java + argument + incompatible argument for parameter arg0 of Control.toBundleName. + final String bundleName = toBundleName(baseName, locale); +
    + found : @SignatureUnknown String + required: @BinaryName String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/LocalizedMessage.java + argument + incompatible argument for parameter arg0 of ResourceBundle.getBundle. + return ResourceBundle.getBundle(bundle, sLocale, sourceClass.getClassLoader(), +
    + found : @SignatureUnknown String + required: @BinaryName String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java + argument + incompatible argument for parameter arg0 of Class.forName. + clazz = Class.forName(className, true, moduleClassLoader); +
    + found : @SignatureUnknown String + required: @ClassGetName String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + argument + incompatible argument for parameter arg0 of Class.forName. + final Class<?> moduleClass = Class.forName(fullQualifiedName); +
    + found : @SignatureUnknown String + required: @ClassGetName String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java + argument + incompatible argument for parameter arg0 of ResourceBundle.getBundle. + bundleName, +
    + found : @SignatureUnknown String + required: @BinaryName String +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/BaseCellEditor.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + ((CellEditorListener) listeners[i + 1]).editingCanceled(new ChangeEvent(this)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/BaseCellEditor.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + ((CellEditorListener) listeners[i + 1]).editingStopped(new ChangeEvent(this)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/BaseCellEditor.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final Object[] listeners = listenerList.getListenerList(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/BaseCellEditor.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final Object[] listeners = listenerList.getListenerList(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/BaseCellEditor.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + listenerList.add(CellEditorListener.class, listener); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/BaseCellEditor.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + listenerList.remove(CellEditorListener.class, listener); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/CodeSelector.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + editor.moveCaretPosition(pModel.getSelectionEnd()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/CodeSelector.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + editor.requestFocusInWindow(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/CodeSelector.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + editor.setCaretPosition(pModel.getSelectionStart()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/CodeSelector.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + editor.setSelectedTextColor(Color.blue); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ListToTreeSelectionModelWrapper.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final TreePath selPath = treeTable.getTree().getPathForRow(counter); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ListToTreeSelectionModelWrapper.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final int max = listSelectionModel.getMaxSelectionIndex(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ListToTreeSelectionModelWrapper.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final int min = listSelectionModel.getMinSelectionIndex(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ListToTreeSelectionModelWrapper.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getListSelectionModel().addListSelectionListener(event -> { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ListToTreeSelectionModelWrapper.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + if (listSelectionModel.isSelectedIndex(counter)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/Main.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainFrame.pack(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/Main.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/Main.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainFrame.setTitle("Checkstyle GUI"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/Main.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainFrame.setVisible(true); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + JOptionPane.showMessageDialog(this, exc.getMessage()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + add(splitPane, BorderLayout.CENTER); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + add(xpathAreaPanel, BorderLayout.PAGE_END); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + buttonPanel.add(openFileButton); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + buttonPanel.add(reloadFileButton); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + buttonPanel.setLayout(new GridLayout(1, 2)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + expandButton.setName("expandButton"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + expandButton.setText("Expand/Collapse"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + fileChooser.setFileFilter(filter); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final Border title = BorderFactory.createTitledBorder("Xpath Query"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final File file = fileChooser.getSelectedFile(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final int returnCode = fileChooser.showOpenDialog(MainFrame.this); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + findNodeButton.setName("findNodeButton"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + findNodeButton.setText("Find node by Xpath"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainPanel.add(buttonPanel); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainPanel.add(modesPanel, BorderLayout.LINE_END); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainPanel.add(xpathButtonsPanel, BorderLayout.LINE_START); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainPanel.setLayout(new BorderLayout()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mainPanel.setLayout(new BorderLayout()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesCombobox.addActionListener(event -> { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesCombobox.setName("modesCombobox"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesCombobox.setSelectedIndex(0); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesLabel.setBorder(BorderFactory.createEmptyBorder(0, leftIndentation, 0, 0)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesLabel.setBorder(BorderFactory.createEmptyBorder(0, leftIndentation, 0, 0)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesLabel.setDisplayedMnemonic(KeyEvent.VK_M); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesLabel.setLabelFor(modesCombobox); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesPanel.add(modesCombobox); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + modesPanel.add(modesLabel); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + openFileButton.setMnemonic(KeyEvent.VK_O); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + openFileButton.setName("openFileButton"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + openFileButton.setText("Open File"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + private final class ExpandCollapseAction extends AbstractAction { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + private final class FileSelectionAction extends AbstractAction { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + private final class FindNodeByXpathAction extends AbstractAction { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + private final class ReloadAction extends AbstractAction { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + public MainFrame() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + reloadAction.setEnabled(false); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + reloadAction.setEnabled(model.isReloadActionEnabled()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + reloadFileButton.setMnemonic(KeyEvent.VK_R); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + reloadFileButton.setText("Reload File"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource(ICON))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource(ICON))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource(ICON))); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setLayout(new BorderLayout()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setTitle(model.getTitle()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + splitPane.setResizeWeight(0.7); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + textArea.setEditable(false); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + textAreaPanel.add(createButtonsPanel(), BorderLayout.PAGE_END); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + textAreaPanel.add(textAreaScrollPane); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + textAreaPanel.setLayout(new BorderLayout()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathAreaPanel.add(createXpathButtonsPanel(), BorderLayout.PAGE_END); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathAreaPanel.add(xpathTextArea); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathAreaPanel.setBorder(title); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathAreaPanel.setLayout(new BorderLayout()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathButtonsPanel.add(expandButton); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathButtonsPanel.add(findNodeButton); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathButtonsPanel.setLayout(new FlowLayout()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathTextArea.setName("xpathTextArea"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathTextArea.setVisible(!xpathTextArea.isVisible()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathTextArea.setVisible(!xpathTextArea.isVisible()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathTextArea.setVisible(false); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTableModel.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + ((TreeModelListener) listeners[i + 1]).treeStructureChanged(event); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTableModel.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final Object[] listeners = listenerList.getListenerList(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTableModel.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + listenerList.add(TreeModelListener.class, listener); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTableModel.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + listenerList.remove(TreeModelListener.class, listener); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + LookAndFeel.installColorsAndFont(this, "Tree.background", + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + Math.toIntExact(Math.round(getPreferredSize().getWidth() * 0.6)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + Math.toIntExact(Math.round(getPreferredSize().getWidth() * 0.6)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + addMouseListener(new MouseAdapter() { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final Class<?> editingClass = getColumnClass(editingColumn); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final DetailAST rootAST = (DetailAST) tree.getModel().getRoot(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final FontMetrics fontMetrics = getFontMetrics(getFont()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final FontMetrics fontMetrics = getFontMetrics(getFont()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final KeyStroke stroke = KeyStroke.getKeyStroke("ENTER"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final MouseEvent newMouseEvent = new MouseEvent(tree, mouseEvent.getID(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final String xpath = xpathEditor.getText(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final TreePath selected = tree.getSelectionPath(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final int height = getRowHeight(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final int widthOfSixCharacterString = fontMetrics.stringWidth("XXXXXX"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + fontMetrics.stringWidth("XXXXXXXXXXXXXXXXXXXXXXXXXXXX"); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + for (int counter = getColumnCount() - 1; counter >= 0; + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getActionMap().put(command, expand); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getActionMap().put(command, expand); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getColumn("Column").setMaxWidth(widthOfColumnContainingSixCharacterString); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getColumn("Line").setMaxWidth(widthOfColumnContainingSixCharacterString); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getColumn("Tree").setPreferredWidth(preferredTreeColumnWidth); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getColumn("Type").setPreferredWidth(preferredTypeColumnWidth); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getInputMap().put(stroke, command); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + getInputMap().put(stroke, command); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + if (!tree.isExpanded(path)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + if (getColumnClass(counter) == ParseTreeTableModel.class) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + if (tree != null && tree.getRowHeight() != newRowHeight) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + if (tree.getLastSelectedPathComponent() instanceof DetailAST ast) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + if (tree.getRowHeight() < 1) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + if (tree.isExpanded(selected)) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mouseEvent.getWhen(), mouseEvent.getModifiersEx(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mouseEvent.getWhen(), mouseEvent.getModifiersEx(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mouseEvent.getX() - getCellRect(0, counter, true).x, + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mouseEvent.getX() - getCellRect(0, counter, true).x, + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mouseEvent.getY(), mouseEvent.getClickCount(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mouseEvent.getY(), mouseEvent.getClickCount(), + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + mouseEvent.isPopupTrigger()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + new CodeSelector(tree.getLastSelectedPathComponent(), editor, linePositionList).select(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + public TreeTable(ParseTreeTableModel treeTableModel) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setDefaultEditor(ParseTreeTableModel.class, new TreeTableCellEditor()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setDefaultRenderer(ParseTreeTableModel.class, tree); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setIntercellSpacing(new Dimension(0, 0)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setModel(new TreeTableModelAdapter(treeTableModel, tree)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setSelectionModel(selectionWrapper.getListSelectionModel()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setShowGrid(false); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + super.setRowHeight(newRowHeight); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + super.updateUI(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.collapsePath(selected); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.dispatchEvent(newMouseEvent); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.expandPath(path); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.expandPath(selected); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.setRowHeight(getRowHeight()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.setSelectionModel(selectionWrapper); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.setSelectionPath(path); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.setSelectionPath(selected); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + xpathEditor.setText(xpathEditor.getText() + NEWLINE + exception.getMessage()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTable.java + override.effect.warning.inheritance + method in com.puppycrawl.tools.checkstyle.gui.TreeTable.TreeTableCellEditor + public boolean isCellEditable(EventObject event) { +
    + isCellEditable(java.util.EventObject) + overrides a method with @UI effect in javax.swing.CellEditor + isCellEditable(java.util.EventObject) + and another method with an @AlwaysSafe effect in com.puppycrawl.tools.checkstyle.gui.BaseCellEditor + isCellEditable(java.util.EventObject) + This is discouraged. +
    +
    + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + && treeTable.getRowHeight() != newRowHeight) { + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + UIManager.getColor(COLOR_KEY_TABLE_SELECTION_BACKGROUND)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + UIManager.getColor(COLOR_KEY_TABLE_SELECTION_FOREGROUND)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final TreeCellRenderer tcr = getCellRenderer(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + graph.translate(0, -visibleRow * getRowHeight()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + graph.translate(0, -visibleRow * getRowHeight()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setBackground(UIManager.getColor(colorKey)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + setBackground(UIManager.getColor(colorKey)); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + super(model); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + super.paint(graph); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + super.setBounds(x, 0, w, treeTable.getHeight()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + super.setBounds(x, 0, w, treeTable.getHeight()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + super.setRowHeight(newRowHeight); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + super.updateUI(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + treeTable.setRowHeight(getRowHeight()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + final TreePath treePath = tree.getPathForRow(row); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + return tree.getRowCount(); + + + + src/main/java/com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + tree.addTreeExpansionListener(new UpdatingTreeExpansionListener()); + + + + src/main/java/com/puppycrawl/tools/checkstyle/site/XdocsTemplateSink.java + call.ui + Calling a method with UIEffect effect from a context limited to SafeEffect effects. + attributes.addAttribute(SinkEventAttributes.HREF, href); + +
    diff --git a/config/checkstyle-checks.xml b/config/checkstyle-checks.xml new file mode 100644 index 000000000000..73ca91c313b7 --- /dev/null +++ b/config/checkstyle-checks.xml @@ -0,0 +1,1028 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-examples-checks.xml b/config/checkstyle-examples-checks.xml new file mode 100644 index 000000000000..a3d2be893b3a --- /dev/null +++ b/config/checkstyle-examples-checks.xml @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-examples-suppressions.xml b/config/checkstyle-examples-suppressions.xml new file mode 100644 index 000000000000..39e4e716d3ed --- /dev/null +++ b/config/checkstyle-examples-suppressions.xml @@ -0,0 +1,167 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-input-checks.xml b/config/checkstyle-input-checks.xml new file mode 100644 index 000000000000..d87e6dd0e50f --- /dev/null +++ b/config/checkstyle-input-checks.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-input-suppressions.xml b/config/checkstyle-input-suppressions.xml new file mode 100644 index 000000000000..b45cde085e31 --- /dev/null +++ b/config/checkstyle-input-suppressions.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-non-main-files-checks.xml b/config/checkstyle-non-main-files-checks.xml new file mode 100644 index 000000000000..9152ea242c3b --- /dev/null +++ b/config/checkstyle-non-main-files-checks.xml @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-non-main-files-suppressions.xml b/config/checkstyle-non-main-files-suppressions.xml new file mode 100644 index 000000000000..1614ea8e7028 --- /dev/null +++ b/config/checkstyle-non-main-files-suppressions.xml @@ -0,0 +1,336 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-report-1.0.0.xsd b/config/checkstyle-report-1.0.0.xsd new file mode 100644 index 000000000000..a314f8ab0fd9 --- /dev/null +++ b/config/checkstyle-report-1.0.0.xsd @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-resources-checks.xml b/config/checkstyle-resources-checks.xml new file mode 100644 index 000000000000..8312528e2ef7 --- /dev/null +++ b/config/checkstyle-resources-checks.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-resources-suppressions.xml b/config/checkstyle-resources-suppressions.xml new file mode 100644 index 000000000000..74c9e325eaeb --- /dev/null +++ b/config/checkstyle-resources-suppressions.xml @@ -0,0 +1,671 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle-sevntu-checks.xml b/config/checkstyle-sevntu-checks.xml new file mode 100644 index 000000000000..190066df587b --- /dev/null +++ b/config/checkstyle-sevntu-checks.xml @@ -0,0 +1,222 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle_checks.xml b/config/checkstyle_checks.xml deleted file mode 100644 index b339309d5cc2..000000000000 --- a/config/checkstyle_checks.xml +++ /dev/null @@ -1,781 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/checkstyle_non_main_files_checks.xml b/config/checkstyle_non_main_files_checks.xml deleted file mode 100644 index 9030692a1572..000000000000 --- a/config/checkstyle_non_main_files_checks.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/config/checkstyle_non_main_files_suppressions.xml b/config/checkstyle_non_main_files_suppressions.xml deleted file mode 100644 index 86af45277060..000000000000 --- a/config/checkstyle_non_main_files_suppressions.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/checkstyle_resources_checks.xml b/config/checkstyle_resources_checks.xml deleted file mode 100644 index 5109a02642a6..000000000000 --- a/config/checkstyle_resources_checks.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/checkstyle_resources_suppressions.xml b/config/checkstyle_resources_suppressions.xml deleted file mode 100644 index d066c60b3dc4..000000000000 --- a/config/checkstyle_resources_suppressions.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/checkstyle_sevntu_checks.xml b/config/checkstyle_sevntu_checks.xml deleted file mode 100644 index c213a5d0bd82..000000000000 --- a/config/checkstyle_sevntu_checks.xml +++ /dev/null @@ -1,220 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/codenarc-rules.groovy.txt b/config/codenarc-rules.groovy.txt new file mode 100644 index 000000000000..bf2b99ba195a --- /dev/null +++ b/config/codenarc-rules.groovy.txt @@ -0,0 +1,462 @@ +ruleset { + + description ''' + A Sample Groovy RuleSet containing all CodeNarc Rules, grouped by category. + You can use this as a template for your own custom RuleSet. + Just delete the rules that you don't want to include. + ''' + + // rulesets/basic.xml + AssertWithinFinallyBlock + AssignmentInConditional + BigDecimalInstantiation + BitwiseOperatorInConditional + BooleanGetBoolean + BrokenNullCheck + BrokenOddnessCheck + ClassForName + ComparisonOfTwoConstants + ComparisonWithSelf + ConstantAssertExpression + ConstantIfExpression + ConstantTernaryExpression + DeadCode + DoubleNegative + DuplicateCaseStatement + DuplicateMapKey + DuplicateSetValue + EmptyCatchBlock + EmptyClass + EmptyElseBlock + EmptyFinallyBlock + EmptyForStatement + EmptyIfStatement + EmptyInstanceInitializer + EmptyMethod + EmptyStaticInitializer + EmptySwitchStatement + EmptySynchronizedStatement + EmptyTryBlock + EmptyWhileStatement + EqualsAndHashCode + EqualsOverloaded + ExplicitGarbageCollection + ForLoopShouldBeWhileLoop + HardCodedWindowsFileSeparator + HardCodedWindowsRootDirectory + IntegerGetInteger + MultipleUnaryOperators + RandomDoubleCoercedToZero + RemoveAllOnSelf + ReturnFromFinallyBlock + ThrowExceptionFromFinallyBlock + + // rulesets/braces.xml + ElseBlockBraces + ForStatementBraces + IfStatementBraces + WhileStatementBraces + + // rulesets/concurrency.xml + BusyWait + DoubleCheckedLocking + InconsistentPropertyLocking + InconsistentPropertySynchronization + NestedSynchronization + StaticCalendarField + StaticConnection + StaticDateFormatField + StaticMatcherField + StaticSimpleDateFormatField + SynchronizedMethod + SynchronizedOnBoxedPrimitive + SynchronizedOnGetClass + SynchronizedOnReentrantLock + SynchronizedOnString + SynchronizedOnThis + SynchronizedReadObjectMethod + SystemRunFinalizersOnExit + ThisReferenceEscapesConstructor + ThreadGroup + ThreadLocalNotStaticFinal + ThreadYield + UseOfNotifyMethod + VolatileArrayField + VolatileLongOrDoubleField + WaitOutsideOfWhileLoop + + // rulesets/convention.xml + ConfusingTernary + + // Disabled as the Elvis operator is a very weird language structure. It may lead to potential + // bugs and introduce mess in the code. It is better to use traditional if-else block. + // CouldBeElvis + + HashtableIsObsolete + IfStatementCouldBeTernary + InvertedIfElse + LongLiteralWithLowerCaseL + + // def is commonly used in Groovy, as it provides greater flexibility and readability. + // The keyword removes boilerplate explicit type declaration. + // NoDef + + NoTabCharacter + ParameterReassignment + TernaryCouldBeElvis + TrailingComma + VectorIsObsolete + + // rulesets/design.xml + AbstractClassWithPublicConstructor + AbstractClassWithoutAbstractMethod + AssignmentToStaticFieldFromInstanceMethod + BooleanMethodReturnsNull + BuilderMethodWithSideEffects + CloneableWithoutClone + CloseWithoutCloseable + CompareToWithoutComparable + ConstantsOnlyInterface + EmptyMethodInAbstractClass + FinalClassWithProtectedMember + ImplementationAsType + + // Using instanceof in equals method is alright + Instanceof { + ignoreTypeNames = 'CheckerFrameworkError' + } + + LocaleSetDefault + NestedForLoop + PrivateFieldCouldBeFinal + PublicInstanceField + ReturnsNullInsteadOfEmptyArray + ReturnsNullInsteadOfEmptyCollection + SimpleDateFormatMissingLocale + StatelessSingleton + ToStringReturnsNull + + // rulesets/dry.xml + DuplicateListLiteral + DuplicateMapLiteral + + // it is ok to use duplication, every number cannot be represented by the same logic + //DuplicateNumberLiteral + + // it is ok to use simple duplication in scripts + //DuplicateStringLiteral + + // rulesets/enhanced.xml + CloneWithoutCloneable + JUnitAssertEqualsConstantActualValue + UnsafeImplementationAsMap + + // rulesets/exceptions.xml + CatchArrayIndexOutOfBoundsException + CatchError + CatchException + CatchIllegalMonitorStateException + CatchIndexOutOfBoundsException + CatchNullPointerException + CatchRuntimeException + CatchThrowable + ConfusingClassNamedException + ExceptionExtendsError + ExceptionExtendsThrowable + ExceptionNotThrown + MissingNewInThrowStatement + ReturnNullFromCatchBlock + SwallowThreadDeath + ThrowError + ThrowException + ThrowNullPointerException + ThrowRuntimeException + ThrowThrowable + + // rulesets/formatting.xml + BlankLineBeforePackage + BracesForClass + BracesForForLoop + BracesForIfElse + BracesForMethod + BracesForTryCatchFinally + ClassJavadoc + ClosureStatementOnOpeningLineOfMultipleLineClosure + ConsecutiveBlankLines + FileEndsWithoutNewline + LineLength + MissingBlankLineAfterImports + MissingBlankLineAfterPackage + SpaceAfterCatch + SpaceAfterClosingBrace + SpaceAfterComma + SpaceAfterFor + SpaceAfterIf + SpaceAfterOpeningBrace + SpaceAfterSemicolon + SpaceAfterSwitch + SpaceAfterWhile + SpaceAroundClosureArrow + + // The rule makes the Groovy map initializers hard to read. + // SpaceAroundMapEntryColon + + SpaceAroundOperator + SpaceBeforeClosingBrace + SpaceBeforeOpeningBrace + TrailingWhitespace + + // rulesets/generic.xml + IllegalClassMember + IllegalClassReference + IllegalPackageReference + IllegalRegex + IllegalString + IllegalSubclass + RequiredRegex + RequiredString + StatelessClass + + // rulesets/grails.xml + GrailsDomainHasEquals + GrailsDomainHasToString + GrailsDomainReservedSqlKeywordName + GrailsDomainWithServiceReference + GrailsDuplicateConstraint + GrailsDuplicateMapping + GrailsMassAssignment + GrailsPublicControllerMethod + GrailsServletContextReference + GrailsStatelessService + + // rulesets/groovyism.xml + AssignCollectionSort + AssignCollectionUnique + ClosureAsLastMethodParameter + CollectAllIsDeprecated + ConfusingMultipleReturns + + // Disabled as using 'new ArrayList<>()' is easier to read and understand. + // ExplicitArrayListInstantiation + + ExplicitCallToAndMethod + ExplicitCallToCompareToMethod + ExplicitCallToDivMethod + + // Groovy's `==` operator which is equivalent to 'equals' method from Java makes code weird to + // Java contributors. It is better to use direct call of 'equals' method to compare objects. + // ExplicitCallToEqualsMethod + + ExplicitCallToGetAtMethod + ExplicitCallToLeftShiftMethod + ExplicitCallToMinusMethod + ExplicitCallToModMethod + ExplicitCallToMultiplyMethod + ExplicitCallToOrMethod + ExplicitCallToPlusMethod + ExplicitCallToPowerMethod + ExplicitCallToRightShiftMethod + ExplicitCallToXorMethod + + // Suppressed as these rules make the code hard to understand. + // Disabling them helps to have the code more similar to Java. + // ExplicitHashMapInstantiation + // ExplicitHashSetInstantiation + // ExplicitLinkedHashMapInstantiation + // ExplicitLinkedListInstantiation + // ExplicitStackInstantiation + // ExplicitTreeSetInstantiation + + GStringAsMapKey + GStringExpressionWithinString + GetterMethodCouldBeProperty + GroovyLangImmutable + UseCollectMany + UseCollectNested + + // rulesets/imports.xml + DuplicateImport + ImportFromSamePackage + ImportFromSunPackages + MisorderedStaticImports + + // it is ok to keep scripts as small as possible in header + //NoWildcardImports + + UnnecessaryGroovyImport { + doNotApplyToFileNames = 'codenarc.groovy' + } + UnusedImport { + doNotApplyToFileNames = 'codenarc.groovy' + } + + // rulesets/jdbc.xml + DirectConnectionManagement + JdbcConnectionReference + JdbcResultSetReference + JdbcStatementReference + + // rulesets/junit.xml + ChainedTest + CoupledTestCase + JUnitAssertAlwaysFails + JUnitAssertAlwaysSucceeds + JUnitFailWithoutMessage + JUnitLostTest + JUnitPublicField + JUnitPublicNonTestMethod + JUnitPublicProperty + JUnitSetUpCallsSuper + JUnitStyleAssertions + JUnitTearDownCallsSuper + JUnitTestMethodWithoutAssert + JUnitUnnecessarySetUp + JUnitUnnecessaryTearDown + JUnitUnnecessaryThrowsException + SpockIgnoreRestUsed + UnnecessaryFail + UseAssertEqualsInsteadOfAssertTrue + UseAssertFalseInsteadOfNegation + UseAssertNullInsteadOfAssertEquals + UseAssertSameInsteadOfAssertTrue + UseAssertTrueInsteadOfAssertEquals + UseAssertTrueInsteadOfNegation + + // rulesets/logging.xml + LoggerForDifferentClass + LoggerWithWrongModifiers + LoggingSwallowsStacktrace + MultipleLoggers + PrintStackTrace + + // We use groovy as scripted java, usage of std output is required by design + //Println + + SystemErrPrint + SystemOutPrint + + // rulesets/naming.xml + AbstractClassName + ClassName + ClassNameSameAsFilename + ClassNameSameAsSuperclass + ConfusingMethodName + FactoryMethodName + FieldName + InterfaceName + InterfaceNameSameAsSuperInterface + MethodName + ObjectOverrideMisspelledMethodName + PackageName + PackageNameMatchesFilePath + ParameterName + PropertyName + VariableName { + finalRegex = null + ignoreVariableNames = 'PROFILES,USAGE_STRING' + } + + // rulesets/security.xml + FileCreateTempFile + InsecureRandom + + // we do not care about EJB container rules + //JavaIoPackageAccess + + NonFinalPublicField + NonFinalSubclassOfSensitiveInterface + ObjectFinalize + PublicFinalizeMethod + UnsafeArrayDeclaration + + // rulesets/serialization.xml + EnumCustomSerializationIgnored + SerialPersistentFields + SerialVersionUID + SerializableClassMustDefineSerialVersionUID + + // rulesets/size.xml + + // Requires the GMetrics jar + AbcMetric + + ClassSize + + // Requires the GMetrics jar and a Cobertura coverage file + CrapMetric + + // Requires the GMetrics jar + CyclomaticComplexity + MethodCount + MethodSize + NestedBlockDepth + ParameterCount + + // rulesets/unnecessary.xml + AddEmptyString + ConsecutiveLiteralAppends + ConsecutiveStringConcatenation + UnnecessaryBigDecimalInstantiation + UnnecessaryBigIntegerInstantiation + UnnecessaryBooleanExpression + UnnecessaryBooleanInstantiation + UnnecessaryCallForLastElement + UnnecessaryCallToSubstring + UnnecessaryCast + UnnecessaryCatchBlock + UnnecessaryCollectCall + UnnecessaryCollectionCall + UnnecessaryConstructor + UnnecessaryDefInFieldDeclaration + UnnecessaryDefInMethodDeclaration + UnnecessaryDefInVariableDeclaration + UnnecessaryDotClass + UnnecessaryDoubleInstantiation + UnnecessaryElseStatement + UnnecessaryFinalOnPrivateMethod + UnnecessaryFloatInstantiation + + // just to be the same as in java, as our primary language + //UnnecessaryGString + + // we are ok with code to looks like Java + //UnnecessaryGetter + UnnecessaryIfStatement + UnnecessaryInstanceOfCheck + UnnecessaryInstantiationToGetClass + UnnecessaryIntegerInstantiation + UnnecessaryLongInstantiation + UnnecessaryModOne + UnnecessaryNullCheck + UnnecessaryNullCheckBeforeInstanceOf + UnnecessaryObjectReferences + UnnecessaryOverridingMethod + UnnecessaryPackageReference + UnnecessaryParenthesesForMethodCallWithClosure + UnnecessaryPublicModifier + + // Disabled as it makes the code unclear. It becomes hard to understand what value + // is returned by a method. + // UnnecessaryReturnKeyword + + UnnecessarySafeNavigationOperator + UnnecessarySelfAssignment + UnnecessarySemicolon + UnnecessaryStringInstantiation + + // Suppressed to avoid weird code and make the code more similar to Java. + // UnnecessarySubstring + + UnnecessaryTernaryExpression + UnnecessaryToString + UnnecessaryTransientModifier + + // rulesets/unused.xml + UnusedArray + UnusedMethodParameter + UnusedObject + UnusedPrivateField + UnusedPrivateMethod + UnusedPrivateMethodParameter + UnusedVariable +} diff --git a/config/configuration-1-3.xsd b/config/configuration-1-3.xsd new file mode 100644 index 000000000000..c04629f8c321 --- /dev/null +++ b/config/configuration-1-3.xsd @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/default_sonar_profile.xml b/config/default_sonar_profile.xml deleted file mode 100644 index 7a81d3b7d619..000000000000 --- a/config/default_sonar_profile.xml +++ /dev/null @@ -1,1804 +0,0 @@ - - - - checkstyle-profile - java - - - - - squid - AssignmentInSubExpressionCheck - MAJOR - - - - - - squid - ClassVariableVisibilityCheck - MINOR - - - - - - squid - EmptyStatementUsageCheck - MINOR - - - - squid - ForLoopCounterChangedCheck - MAJOR - - - - squid - HiddenFieldCheck - MAJOR - - - - squid - LabelsShouldNotBeUsedCheck - MAJOR - - - - - - - - - squid - ModifiersOrderCheck - MINOR - - - - squid - ObjectFinalizeCheck - MAJOR - - - - squid - ObjectFinalizeOverridenCallsSuperFinalizeCheck - CRITICAL - - - - squid - ObjectFinalizeOverridenCheck - MAJOR - - - - squid - RedundantThrowsDeclarationCheck - MINOR - - - - squid - S00100 - MINOR - - - format - ^[a-z][a-zA-Z0-9]*$ - - - - - squid - S00101 - MINOR - - - format - ^[A-Z][a-zA-Z0-9]*$ - - - - - - - squid - S00108 - MAJOR - - - - - - squid - S00114 - MINOR - - - format - ^[A-Z][a-zA-Z0-9]*$ - - - - - - - squid - S00116 - MINOR - - - format - ^[a-z][a-zA-Z0-9]*$ - - - - - squid - S00117 - MINOR - - - format - ^[a-z][a-zA-Z0-9]*$ - - - - - squid - S00119 - MINOR - - - format - ^[A-Z][0-9]?$ - - - - - squid - S00120 - MINOR - - - format - ^[a-z]+(\.[a-z][a-z0-9]*)*$ - - - - - - - squid - S1065 - MAJOR - - - - - - squid - S1068 - MAJOR - - - - squid - S1075 - MINOR - - - - squid - S1118 - MAJOR - - - - squid - S1125 - MINOR - - - - squid - S1126 - MINOR - - - - - - - - - - squid - S1141 - MAJOR - - - - squid - S1143 - MAJOR - - - - - - squid - S1149 - MAJOR - - - - squid - S1150 - MAJOR - - - - squid - S1153 - MINOR - - - - squid - S1155 - MINOR - - - - squid - S1157 - MINOR - - - - squid - S1158 - MINOR - - - - squid - S1161 - MAJOR - - - - squid - S1163 - CRITICAL - - - - squid - S1165 - MINOR - - - - squid - S1168 - MAJOR - - - - squid - S1170 - MINOR - - - - squid - S1171 - MAJOR - - - - - - squid - S1174 - CRITICAL - - - - squid - S1175 - CRITICAL - - - - - - squid - S1182 - MINOR - - - - squid - S1185 - MINOR - - - - squid - S1186 - CRITICAL - - - - squid - S1190 - BLOCKER - - - - - - squid - S1192 - CRITICAL - - - threshold - 3 - - - - - squid - S1193 - MAJOR - - - - squid - S1195 - MINOR - - - - squid - S1197 - MINOR - - - - squid - S1199 - MINOR - - - - squid - S1201 - MAJOR - - - - squid - S1206 - MINOR - - - - squid - S1210 - MINOR - - - - squid - S1214 - CRITICAL - - - - squid - S1215 - CRITICAL - - - - squid - S1217 - MAJOR - - - - squid - S1219 - BLOCKER - - - - squid - S1220 - MINOR - - - - squid - S1221 - MAJOR - - - - squid - S1223 - MAJOR - - - - squid - S1226 - MINOR - - - - squid - S1244 - MAJOR - - - - squid - S1264 - MINOR - - - - squid - S128 - BLOCKER - - - - squid - S1301 - MINOR - - - - squid - S1313 - MINOR - - - - squid - S1317 - MAJOR - - - - squid - S1319 - MINOR - - - - squid - S135 - MINOR - - - - squid - S1444 - MINOR - - - - squid - S1450 - MINOR - - - - squid - S1452 - CRITICAL - - - - squid - S1479 - MAJOR - - - maximum - 30 - - - - - squid - S1481 - MINOR - - - - squid - S1488 - MINOR - - - - squid - S1596 - MINOR - - - - squid - S1598 - CRITICAL - - - - - - squid - S1604 - MAJOR - - - - squid - S1607 - MAJOR - - - - squid - S1610 - MINOR - - - - squid - S1611 - MINOR - - - - - - squid - S1640 - MINOR - - - - squid - S1643 - MINOR - - - - squid - S1656 - MAJOR - - - - squid - S1659 - MINOR - - - - squid - S1700 - MAJOR - - - - squid - S1710 - MINOR - - - - squid - S1751 - MAJOR - - - - squid - S1764 - MAJOR - - - - squid - S1844 - MAJOR - - - - - - squid - S1849 - MAJOR - - - - squid - S1854 - MAJOR - - - - squid - S1858 - MINOR - - - - squid - S1860 - MAJOR - - - - squid - S1862 - MAJOR - - - - squid - S1871 - MAJOR - - - - squid - S1872 - MAJOR - - - - squid - S1905 - MINOR - - - - squid - S1940 - MINOR - - - - - - squid - S1989 - MINOR - - - - squid - S1994 - CRITICAL - - - - squid - S2055 - MINOR - - - - squid - S2060 - MAJOR - - - - squid - S2061 - MAJOR - - - - squid - S2062 - CRITICAL - - - - squid - S2065 - MINOR - - - - squid - S2066 - MINOR - - - - squid - S2068 - BLOCKER - - - - squid - S2077 - BLOCKER - - - - squid - S2092 - MINOR - - - - - - squid - S2094 - MINOR - - - - - - squid - S2097 - MINOR - - - - squid - S2109 - MAJOR - - - - squid - S2110 - MAJOR - - - - squid - S2111 - MAJOR - - - - squid - S2112 - MAJOR - - - - squid - S2114 - MAJOR - - - - squid - S2116 - MAJOR - - - - squid - S2118 - MAJOR - - - - squid - S2122 - CRITICAL - - - - squid - S2123 - MAJOR - - - - squid - S2127 - MAJOR - - - - squid - S2129 - MAJOR - - - - squid - S2130 - MINOR - - - - squid - S2131 - MAJOR - - - - squid - S2133 - MAJOR - - - - squid - S2134 - MAJOR - - - - squid - S2140 - MINOR - - - - squid - S2142 - MAJOR - - - - squid - S2147 - MINOR - - - - squid - S2151 - CRITICAL - - - - squid - S2153 - MINOR - - - - squid - S2154 - MAJOR - - - - squid - S2157 - MAJOR - - - - squid - S2159 - MAJOR - - - - - - squid - S2165 - MINOR - - - - squid - S2166 - MAJOR - - - - squid - S2167 - MINOR - - - - squid - S2168 - BLOCKER - - - - squid - S2175 - MAJOR - - - - squid - S2176 - CRITICAL - - - - squid - S2177 - MAJOR - - - - squid - S2178 - BLOCKER - - - - squid - S2183 - MINOR - - - - squid - S2184 - MINOR - - - - squid - S2185 - MAJOR - - - - squid - S2186 - CRITICAL - - - - squid - S2187 - BLOCKER - - - - squid - S2188 - BLOCKER - - - - squid - S2189 - BLOCKER - - - - squid - S2200 - MINOR - - - - - - squid - S2204 - MAJOR - - - - squid - S2209 - MAJOR - - - - squid - S2222 - CRITICAL - - - - squid - S2225 - MAJOR - - - - squid - S2226 - MAJOR - - - - squid - S2230 - MAJOR - - - - squid - S2232 - MAJOR - - - - squid - S2235 - CRITICAL - - - - squid - S2236 - BLOCKER - - - - squid - S2251 - MAJOR - - - - squid - S2252 - MAJOR - - - - squid - S2254 - CRITICAL - - - - - - squid - S2272 - MINOR - - - - squid - S2273 - MAJOR - - - - squid - S2274 - CRITICAL - - - - squid - S2275 - BLOCKER - - - - squid - S2276 - BLOCKER - - - - squid - S2277 - CRITICAL - - - - squid - S2278 - BLOCKER - - - - squid - S2293 - MINOR - - - - squid - S2326 - MAJOR - - - - squid - S2386 - MINOR - - - - squid - S2387 - BLOCKER - - - - squid - S2388 - MAJOR - - - - squid - S2390 - MAJOR - - - - squid - S2391 - BLOCKER - - - - squid - S2437 - BLOCKER - - - - squid - S2438 - MAJOR - - - - squid - S2440 - MAJOR - - - - squid - S2441 - MAJOR - - - - squid - S2442 - MAJOR - - - - squid - S2445 - MAJOR - - - - squid - S2446 - MAJOR - - - - squid - S2447 - CRITICAL - - - - squid - S2583 - MAJOR - - - - squid - S2589 - MAJOR - - - - squid - S2629 - MAJOR - - - - squid - S2637 - MINOR - - - - squid - S2638 - CRITICAL - - - - squid - S2639 - MAJOR - - - - squid - S2653 - CRITICAL - - - - squid - S2674 - MINOR - - - - squid - S2675 - MAJOR - - - - squid - S2676 - MINOR - - - - squid - S2677 - MAJOR - - - - squid - S2681 - MAJOR - - - - squid - S2692 - CRITICAL - - - - squid - S2695 - BLOCKER - - - - squid - S2696 - CRITICAL - - - - squid - S2718 - MAJOR - - - - squid - S2786 - MINOR - - - - squid - S2789 - MAJOR - - - - squid - S2864 - MAJOR - - - - squid - S2885 - MAJOR - - - - squid - S2886 - MAJOR - - - - squid - S2912 - MINOR - - - - squid - S2924 - MINOR - - - - - - squid - S2970 - BLOCKER - - - - squid - S2975 - BLOCKER - - - - squid - S2976 - CRITICAL - - - - squid - S3008 - MINOR - - - format - ^[a-z][a-zA-Z0-9]*$ - - - - - squid - S3010 - MAJOR - - - - squid - S3020 - MINOR - - - - squid - S3027 - MAJOR - - - - squid - S3034 - MAJOR - - - - squid - S3038 - MINOR - - - - squid - S3042 - MAJOR - - - - squid - S3046 - BLOCKER - - - - squid - S3066 - MINOR - - - - squid - S3067 - MAJOR - - - - squid - S3281 - BLOCKER - - - - squid - S3346 - MAJOR - - - - squid - S3355 - CRITICAL - - - - squid - S3358 - MAJOR - - - - - - squid - S3400 - MINOR - - - - squid - S3421 - MINOR - - - - squid - S3422 - CRITICAL - - - - squid - S3437 - MINOR - - - - squid - S3438 - MAJOR - - - - squid - S3457 - MAJOR - - - - squid - S3518 - CRITICAL - - - - squid - S3599 - MINOR - - - - squid - S3631 - MAJOR - - - - squid - S3655 - MAJOR - - - - squid - S3725 - MAJOR - - - - - - squid - S3923 - MAJOR - - - - squid - S899 - MINOR - - - - squid - SwitchLastCaseIsDefaultCheck - CRITICAL - - - - - - squid - UselessImportCheck - MINOR - - - - squid - UselessParenthesesCheck - MAJOR - - - - diff --git a/config/deploy-settings.xml b/config/deploy-settings.xml deleted file mode 100644 index 5cdb6062d829..000000000000 --- a/config/deploy-settings.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - sonatype-nexus-snapshots - ${env.CI_DEPLOY_USERNAME} - ${env.CI_DEPLOY_PASSWORD} - - - diff --git a/config/error-prone-suppressions/compile-phase-suppressions.xml b/config/error-prone-suppressions/compile-phase-suppressions.xml new file mode 100644 index 000000000000..bddcc7a8c98a --- /dev/null +++ b/config/error-prone-suppressions/compile-phase-suppressions.xml @@ -0,0 +1,10 @@ + + + + + SarifLogger.java + IdentityConversion + This method invocation appears redundant; remove it or suppress this warning and add a comment explaining its purpose + return report.replace(VERSION_PLACEHOLDER, String.valueOf(version)); + + diff --git a/config/error-prone-suppressions/test-compile-phase-suppressions.xml b/config/error-prone-suppressions/test-compile-phase-suppressions.xml new file mode 100644 index 000000000000..5c4a476545b3 --- /dev/null +++ b/config/error-prone-suppressions/test-compile-phase-suppressions.xml @@ -0,0 +1,4 @@ + + + + diff --git a/config/google-java-format/excluded/compilable-input-paths.txt b/config/google-java-format/excluded/compilable-input-paths.txt new file mode 100644 index 000000000000..fca292eda96e --- /dev/null +++ b/config/google-java-format/excluded/compilable-input-paths.txt @@ -0,0 +1,99 @@ +src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule231filetab/InputWhitespaceCharacters.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputSourceFileStructure.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapping.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing1.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing2.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing3.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing4.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing5.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingValid.java +src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingValid2.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputNonemptyBlocksLeftRightCurly.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyAnnotations.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyMethod.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurly.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyOther.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySwitchCase.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySwitchCasesBlocks.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputTryCatchIfElse.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputTryCatchIfElse2.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlocksAndCatchBlocks.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchEmptyComment.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputClassWithChainedMethods3.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCodeBlocks.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputColumnLimit.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputTextBlockColumnLimit.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputColumnLimitEdgeCase.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputOperatorWrap.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputMethodParamPad.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrap.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapComma.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapMethodRef.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapEllipsis.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapArrayDeclarator.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputLambdaBodyWrap.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputIllegalLineBreakAroundLambda.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordName.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordName2.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputClassWithChainedMethods2.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputVerticalWhitespace.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputEmptyLineSeparator3.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundBasic.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterBad.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterGood.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputParenPad.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEmptyForLoop.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeColonOfLabel.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeCaseDefaultColon.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeAnnotations.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputMethodParamPad2.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundGenerics.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundArrow.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespace.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterDoubleSlashes.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceBeforeLeftCurlyOfEmptyBlock.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEllipsis.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceInsideArrayInitializer.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputOneVariablePerDeclaration.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputClassWithChainedMethods.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultiline.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultiline2.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputNewKeywordChildren.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLineBreakAfterLeftCurlyOfBlockInSwitch.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputClassAnnotations.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputClassAnnotation2.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/InputMethodsAndConstructorsAnnotations.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/InputFieldAnnotations.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationCommentIsAtTheEndOfBlock.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInEmptyBlock.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInSwitchBlock.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationSurroundingCode.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrder.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrderSealed.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrderNonSealed.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputTextBlocksGeneralForm.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputTextBlocksIndentation.java +src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputClassNames.java +src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputCamelCaseDefined.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputSingleLineJavadocAndInvalidJavadocPosition.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnCanonicalConstructorsWithAnnotation.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnCompactConstructorsWithAnnotation.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnConstructorInRecord.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputRecordClassJavadocPosition.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputCorrectJavadocLeadingAsteriskAlignment.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputIncorrectJavadocLeadingAsteriskAlignment.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputIncorrectRequireEmptyLineBeforeBlockTagGroup.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputIncorrectJavadocParagraph.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/InputJavaDocTagContinuationIndentation.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc/InputInvalidJavadocPosition.java +src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc/InputInvalidJavadocPositionRecord.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundWhen.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaChild.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchOnStartOfTheLine.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputCatchParametersOnNewLine.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaAndChildOnTheSameLine.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSingleSwitchStatementWithoutCurly.java +src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchWrappingIndentation.java +src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputRecordComponentNameTwo.java +src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputPatternVariableNameEnhancedInstanceofTestDefault.java diff --git a/config/google-java-format/excluded/noncompilable-input-paths.txt b/config/google-java-format/excluded/noncompilable-input-paths.txt new file mode 100644 index 000000000000..f5968caa91ed --- /dev/null +++ b/config/google-java-format/excluded/noncompilable-input-paths.txt @@ -0,0 +1 @@ +src/it/resources-noncompilable/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine2.java diff --git a/config/google-java-format/suppressions/suppress-diff-gt-100-lte-500.txt b/config/google-java-format/suppressions/suppress-diff-gt-100-lte-500.txt new file mode 100644 index 000000000000..336558ae0222 --- /dev/null +++ b/config/google-java-format/suppressions/suppress-diff-gt-100-lte-500.txt @@ -0,0 +1,11 @@ +InputNoLineWrapping.java +InputOrderingAndSpacing1.java +InputClassWithChainedMethods3.java +InputClassWithChainedMethods2.java +InputParenPad.java +InputNewKeywordChildren.java +InputClassAnnotations.java +InputMethodsAndConstructorsAnnotations.java +InputModifierOrder.java +InputJavaDocTagContinuationIndentation.java +InputOneStatementPerLine2.java diff --git a/config/google-java-format/suppressions/suppress-diff-gt-500.txt b/config/google-java-format/suppressions/suppress-diff-gt-500.txt new file mode 100644 index 000000000000..7a291bbaa1f7 --- /dev/null +++ b/config/google-java-format/suppressions/suppress-diff-gt-500.txt @@ -0,0 +1 @@ +InputOneStatementPerLine.java diff --git a/config/google-java-format/suppressions/suppress-diff-lte-100.txt b/config/google-java-format/suppressions/suppress-diff-lte-100.txt new file mode 100644 index 000000000000..e87e764f1d62 --- /dev/null +++ b/config/google-java-format/suppressions/suppress-diff-lte-100.txt @@ -0,0 +1,7 @@ +InputTryCatchIfElse.java +InputVerticalWhitespace.java +InputClassWithChainedMethods.java +InputTextBlocksGeneralForm.java +InputCamelCaseDefined.java +InputInvalidJavadocPosition.java +InputSingleSwitchStatementWithoutCurly.java diff --git a/config/import-control-test.xml b/config/import-control-test.xml index 76c35a0f8bab..0f65d5c23bed 100644 --- a/config/import-control-test.xml +++ b/config/import-control-test.xml @@ -3,26 +3,91 @@ "-//Checkstyle//DTD ImportControl Configuration 1.4//EN" "https://checkstyle.org/dtds/import_control_1_4.dtd"> - + - + + + + + + + + + - - - - - + + - + + + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/import-control.xml b/config/import-control.xml index d22aee5b830f..e54a81d4b6d9 100644 --- a/config/import-control.xml +++ b/config/import-control.xml @@ -4,7 +4,7 @@ "https://checkstyle.org/dtds/import_control_1_4.dtd"> - + @@ -14,14 +14,13 @@ - - - + + @@ -49,20 +48,71 @@ - - + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - @@ -74,8 +124,12 @@ + + + + @@ -95,19 +149,30 @@ + + - + + + + + + + + + + @@ -118,12 +183,19 @@ + + + + + + + @@ -131,6 +203,7 @@ + @@ -140,6 +213,24 @@ + + + + + + + + + + + + + + + + + + @@ -147,21 +238,24 @@ + + + - - - + + + @@ -178,6 +272,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -185,6 +309,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/intellij-idea-inspection-scope.xml b/config/intellij-idea-inspection-scope.xml index 51e22e8b4da6..013e545ffce3 100644 --- a/config/intellij-idea-inspection-scope.xml +++ b/config/intellij-idea-inspection-scope.xml @@ -1,6 +1,6 @@ - + diff --git a/config/intellij-idea-inspections-misc.xml b/config/intellij-idea-inspections-misc.xml new file mode 100644 index 000000000000..91bac9a51366 --- /dev/null +++ b/config/intellij-idea-inspections-misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + diff --git a/config/intellij-idea-inspections.properties b/config/intellij-idea-inspections.properties index a10f016dcf15..5637396936f5 100644 --- a/config/intellij-idea-inspections.properties +++ b/config/intellij-idea-inspections.properties @@ -1,12 +1,27 @@ -# this file is used by .ci/idea_inspection.sh and .ci/idea_inspection.bat +# this file is used by .ci/idea-inspection.sh and .ci/idea-inspection.bat # Content should be the same as in TeamCity "Include / exclude patterns:" idea.exclude.patterns=.idea/**;\ + .ci/*.config;\ + .ci/checker-framework.groovy;\ + .ci/codenarc.groovy;\ + .ci/error-prone-check.groovy;\ + .ci/pitest-survival-check-xml.groovy;\ + .circleci/config.yml;\ target/**;\ src/test/resources/**;\ src/it/resources/**;\ - src/site/resources/styleguides/** + src/xdocs-examples/resources/**;\ + src/site/resources/styleguides/**;\ src/site/resources/js/google-analytics.js;\ src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ParseTreeBuilder.java;\ src/test/java/com/puppycrawl/tools/checkstyle/grammar/javadoc/ParseTreeBuilder.java;\ config/idea.properties;\ - config/intellij-idea-inspections.properties + config/intellij-idea-inspections.properties;\ + config/site-2.0.0.xsd;\ + .ci-temp/**;\ + .classpath;\ + .project;\ + .settings/**;\ + bin/**;\ + .mvn/**;\ + docs/GRAMMAR_UPDATES.md; diff --git a/config/intellij-idea-inspections.xml b/config/intellij-idea-inspections.xml index a7127e35ff9a..749b0a9ab879 100644 --- a/config/intellij-idea-inspections.xml +++ b/config/intellij-idea-inspections.xml @@ -1,2449 +1,2458 @@ - diff --git a/config/java-regexp.header b/config/java-regexp.header new file mode 100644 index 000000000000..3a68ba8be50c --- /dev/null +++ b/config/java-regexp.header @@ -0,0 +1,18 @@ +^/{95}$ +^/{2} checkstyle: Checks Java source code and other text files for adherence to a set of rules.$ +^/{2} Copyright \(C\) \d\d\d\d-\d\d\d\d the original author or authors.$ +^/{2}$ +^/{2} This library is free software; you can redistribute it and/or$ +^/{2} modify it under the terms of the GNU Lesser General Public$ +^/{2} License as published by the Free Software Foundation; either$ +^/{2} version \d.\d of the License, or \(at your option\) any later version.$ +^/{2}$ +^/{2} This library is distributed in the hope that it will be useful,$ +^/{2} but WITHOUT ANY WARRANTY; without even the implied warranty of$ +^/{2} MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU$ +^/{2} Lesser General Public License for more details.$ +^/{2}$ +^/{2} You should have received a copy of the GNU Lesser General Public$ +^/{2} License along with this library; if not, write to the Free Software$ +^/{2} Foundation, Inc., \d\d Temple Place, Suite \d\d\d, Boston, MA \d\d\d\d\d-\d\d\d\d USA$ +^/{95}$ diff --git a/config/java.header b/config/java.header index 709becf73dd7..646d81274532 100644 --- a/config/java.header +++ b/config/java.header @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,4 +15,4 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/config/java_regexp.header b/config/java_regexp.header deleted file mode 100644 index c481e3ff1be3..000000000000 --- a/config/java_regexp.header +++ /dev/null @@ -1,18 +0,0 @@ -^/{80}$ -^/{2} checkstyle: Checks Java source code for adherence to a set of rules.$ -^/{2} Copyright \(C\) \d\d\d\d-\d\d\d\d the original author or authors.$ -^/{2}$ -^/{2} This library is free software; you can redistribute it and/or$ -^/{2} modify it under the terms of the GNU Lesser General Public$ -^/{2} License as published by the Free Software Foundation; either$ -^/{2} version \d.\d of the License, or \(at your option\) any later version.$ -^/{2}$ -^/{2} This library is distributed in the hope that it will be useful,$ -^/{2} but WITHOUT ANY WARRANTY; without even the implied warranty of$ -^/{2} MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU$ -^/{2} Lesser General Public License for more details.$ -^/{2}$ -^/{2} You should have received a copy of the GNU Lesser General Public$ -^/{2} License along with this library; if not, write to the Free Software$ -^/{2} Foundation, Inc., \d\d Temple Place, Suite \d\d\d, Boston, MA \d\d\d\d\d-\d\d\d\d USA$ -^/{80}$ diff --git a/config/jsoref-spellchecker/exclude.pl b/config/jsoref-spellchecker/exclude.pl new file mode 100755 index 000000000000..f98dbd825fbf --- /dev/null +++ b/config/jsoref-spellchecker/exclude.pl @@ -0,0 +1,32 @@ +#!/usr/bin/perl +# This script takes null delimited files as input +# it drops paths that match the listed exclusions +# output is null delimited to match input +$/="\0"; +my @excludes=qw( + \.png$ + (^|/)images/ + ^src/it/resources/ + ^src/test/resources/ + ^src/site/resources/styleguides/ + ^src/test/resources-noncompilable/ + /messages.*_..\.properties$ + /releasenotes_old.*\.xml$ + /releasenotes\.xml$ + /.*_..\.translation[^/]*$ + ^cdg-pitest-licence.txt$ + ^.teamcity/ + ^config/projects-to-test/openjdk17-excluded\.files$ + ^config/projects-to-test/openjdk19-excluded\.files$ + ^config/projects-to-test/openjdk20-excluded\.files$ + ^config/projects-to-test/openjdk25-excluded\.files$ + ^config/jsoref-spellchecker/whitelist.words$ + ^config/checker-framework-suppressions/ + ^config/archunit-store/ +); +my $exclude = join "|", @excludes; +while (<>) { + chomp; + next if m{$exclude}; + print "$_$/"; +} diff --git a/config/jsoref-spellchecker/whitelist.words b/config/jsoref-spellchecker/whitelist.words new file mode 100644 index 000000000000..8d07f761d58b --- /dev/null +++ b/config/jsoref-spellchecker/whitelist.words @@ -0,0 +1,1600 @@ +aaaa +Aapt +aarch +abbreviationaswordinname +abcun +abstractcheck +abstractclassname +abstractfileset +abstractjavadoc +ABx +ACEM +Acheckstyle +acm +Aconfig +actionlint +addons +Adoptium +adr +AFBR +AFilter +aggregators +allchecks +allclasses +allowlegacy +alot +alundblad +amazonaws +amd +amitkumardeoghoria +androidx +annotationlocation +annotationonsameline +annotationusestyle +annotationutil +anoninner +anoninnerlength +antfile +antlib +antlr +ANTLRv +antrun +anttask +Aop +api +apidocs +apirefs +apos +APPLET +appveyor +APRV +Aqj +ARCHITEW +archunit +arget +Arial +arity +Arquillian +arraycopy +arraytrailingcomma +arraytypestyle +asda +ASF +Aspectj +Asrc +assertj +ASTNo +asttreestringprinter +atclause +atclauseorder +ATest +atid +atlassian +atn +attchar +attlist +attr +autoboxing +autobuild +autocomplete +autocrlf +autofix +Autoproxy +Autowire +Autowired +Autowiring +avoiddoublebraceinitialization +avoidescapedunicodecharacters +avoidinlineconditionals +avoidnestedblocks +avoidnoargumentsuperconstructorcall +avoidstarimport +avoidstaticimport +Awarns +aws +awt +azurewebsites +Backquote +backticks +BADN +badpackage +baeldung +baratali +Barowski +basedir +basefont +baz +bc +bdc +bdd +bdo +beanutils +beforeexecutionexclusionfilefilter +bestpractices +bew +bff +bitbucket +bjrke +bleh +Blic +blockandinlinetags +blockcomment +blockcommentposition +blockcommentstyle +blockindentation +blockquote +blog +blogspot +Bludov +BNOT +booleanexpressioncomplexity +bothfiles +Bpmn +breadcrumb +BSR +Bsubscribe +BTest +btnfrs +buf +bugdatabase +bugfixes +Bunsubscribe +bw +BXOR +bytecode +Cacheable +cachefile +cacio +caciocavallosilano +calledmethods +camelcase +casegroup +casesensitive +catchparametername +cba +cbeaff +CComments +cdata +cde +cdfd +Cdi +Cfg +Cfml +Cfoo +cfz +cgi +chainedpropertyutil +charset +CHDBEFIF +checkchmod +checkerframework +checksandfilessuppressionfilegeneratorauditlistener +checkstyle +checkstyleanttask +checkstylemeta +checkutil +chmod +chr +ci +cimg +Cinit +circleci +cirrusci +classannotations +classdataabstractioncoupling +classfanoutcomplexity +classloader +classmemberimpliedmodifier +classname +classpath +classtypeparametername +clazz +clemens +Clickable +Cloneable +clss +cmdline +cmp +cmt +CNAME +Cnt +cobertura +codacy +codeclimate +codeconventions +codecov +codehaus +codenarc +codeql +codeselectorpresentation +codestyle +colgroup +columnlimit +Combobox +commentsindentation +commerical +commitish +commonutil +Compat +compilermsgs +Comspace +concat +config +configurationloader +Connell's +constantname +constructorsdeclarationgrouping +Contextualizable +contextualization +contextualized +Contextualizing +corrosponds +courtlink +courtlinkkk +covariantequals +COVEREDRATIO +cpp +crlf +cron +crossplatform +csoff +cson +css +cstyle +csv +ctc +ctor +ctx +CTYPE +customimportorder +CVS +cyclomatic +cyclomaticcomplexity +cygpath +cygwin +cz +dalvik +Daniil +daniilyar +Dantlr +Darguments +DArray +Datasource +Datatables +datatransfer +DATETIME +daveho +davidwalsh +DBFF +Dcheckstyle +dcm +Dconfig +Dconnection +ddd +DDDL +Ddry +DEADBEEF +DECCHARS +declarationorder +declaredwhenneeded +Deconstruction +defau +defaultcomeslast +defaultlabelpresence +defaultlogger +delims +DENORMALIZER +Depedency +dependabot +deque +descendanttoken +descr +Deserializable +designforextension +destfile +Destructuring +detailast +detailnodetreestringprinter +devops +Dexec +dfa +DFFF +Dfile +dfn +Dfoo +Dforbiddenapis +Dgpg +Dhttp +Diachenko +diffplug +DIFFTOOL +dirname +Djacoco +Djdepend +Dlinkcheck +DMail +Dmaven +DMC +dnd +Dnew +doccheck +Dockter +doclet +doclint +doctype +documentationcomments +donotignoreexceptions +Dorekit +Dorg +DOTALL +doubletag +downloader +doxia +Dpi +Dpmd +Dpom +Dpush +Drewrite +dropbox +dropdown +Dskip +dsm +Dsonar +Dspotbugs +Dstrict +Dsurefire +Dtag +Dtest +Dubinin +Duser +dv +Dversion +Dxml +eb +EBFF +EBNF +ecj +eclemma +eclipsecommunityawards +Edad +edb +ededed +edef +edu +Eghj +Ei +ej +ejb +elasticsearch +elif +elist +Ellipsize +emacs +Emoji +emptyblock +emptycatchblock +emptyforinitializerpad +emptyforiteratorpad +emptylineseparator +emptystatement +emptytag +Emtpy +endline +enegger +ENMI +ent +enum +eol +eot +epl +equalsavoidnull +equalshashcode +equalsverifier +erial +ERRORLEVEL +errorprone +esac +Eslint +esslingen +esversion +etsy +euf +ev +Evt +exceptionoverrides +executablestatementcount +Exif +explicitinitialization +expr +Externalizable +fallsthrough +fallthrough +fallthru +Fannotation +favicon +Fblocks +FCBL +FCCD +Fchecks +Fcheckstyle +fchurn +Fcoding +Fcom +fd +FDCF +Fdesign +FDF +FEF +fenum +ffd +fff +FFFA +FFFB +FFFD +ffff +FFFFL +Fgoogle +Fheader +fht +fieldannotations +fieldset +filebasic +filechooser +filefilter +filelength +filepath +fileset +filesetcheck +filestructure +filesystem +filetab +filetabcharacter +filetext +Fimports +finalclass +finalizer +finallocalvariable +finalparameters +findbugs +Findentation +findstr +firefox +firstsentence +FIXME +Fjava +Fjavadoc +fluido +Fmain +Fmessages +Fmetrics +Fmodifier +FModule +Fnaming +forbiddenapis +Foreach +Fpuppycrawl +fq +freemarker +Fregexp +Fresources +Frob +fsc +Fsizes +Fsun +Ftl +Ftools +ftp +ftpclient +fullident +fullname +func +funmodifiablecollection +Fwhitespace +Fx +Fxq +gav +Gdrox +generalform +genericwhitespace +getenv +gg +gh +Ghj +gitattributes +github +githubusercontent +Gjs +globbing +GMetrics +gnupg +google +googleblog +googleecommon +googlegroups +googlesource +govstrangefolder +GPath +gpg +gpgv +gradle +gradlew +graphicsenv +Grenner +grep +grepped +groovyism +groupcdg +groupon +grp +GSo +gsoc +Gsp +GString +Gtk +gui +guieffect +gwt +gx +gz +hadoop +hamcrest +Haml +hardcoded +hashcode +hashtable +HASHTAG +hazelcast +hbase +hcoles +Headerjava +Hejl +HEXCHARS +hexliteralcase +hh +hiddenfield +hideutilityclassconstructor +hipparchus +hne +homepage +horizontalwhitespace +Hostname +hotspot +href +htaccess +htag +htdocs +html +HTMLJS +htmltags +htmlunit +http +httpcomponents +hurz +HXKS +hyperlink +hz +iae +icm +ico +icu +identifiernames +Idref +idx +ietf +Igno +IGNORETHIS +igorminar +Ilja +illegalcatch +illegalex +illegalidentifiername +illegalimport +illegalinstantiation +illegalthrows +illegaltoken +illegaltokentext +illegaltype +Ime +img +iml +impl +importcontrol +importcontrolloader +importcontroltest +importorder +importrule +imprt +Incompatabilities +indentcontinuationlines +Inet +infinispan +initializedfields +Inlined +inlinetags +innerassignment +Innerclass +INNERR +innertypelast +inplace +instanceof +Intelli +intellij +intercell +interfaceistype +interfacememberimpliedmodifier +interfacetypeparametername +interp +invalidformat +invalidinherit +invalidjavadocposition +ioe +ioffset +IPonr +isfalse +isindex +isrutf +isset +issuecomment +issuehunt +Itemtype +itemvalue +ith +itr +itsallcode +ivanov +ivysettings +iws +Izmailov +jacoco +Jakub +jarchitect +javaastvisitor +javac +JAVACCMD +JAVACMD +javadoc +javadocblocktaglocation +javadoccontentlocation +javadocdetailnodeparser +javadocleadingasteriskalign +javadocmethod +javadocmissingleadingasterisk +javadocmissingwhitespaceafterasterisk +javadocpackage +javadocparagraph +javadocpropertiesgenerator +javadocstyle +javadoctagcontinuationindentation +javadoctags +javadoctype +javadocvariable +Javaee +javaformat +javaguide +javamagazine +javamail +javancss +javap +javaparser +javarevisited +javascript +javase +javastrangefolder +javax +Jax +jb +JBoss +JButton +JCheck +JCombo +JComponent +jcp +jdbc +JDE +jdee +jdepend +jdk +jdt +jedit +jenkins +jep +jeremymanson +jessesquires +jetbrains +JFile +JFrame +jgit +jgrasp +jguru +jhu +jide +jidesoft +jira +jitpack +jkl +JLabel +Jlo +jls +JNDI +JNullness +jooq +JOption +Jpa +JPanel +Jpdl +jpeg +jpf +jpg +jprofiler +jq +jqno +jre +JScroll +Jscs +jsecurity +Jsf +jshiell +jshint +JSJ +jslint +jsni +json +jsoref +jsp +JSplit +jsr +JTable +JText +JToggle +JTool +jtree +junit +junitpioneer +jvm +jxr +kailasam +Kansara +kazgroup +kbd +kclee +KDoc +keyname +keyscan +konstantinos +Kordas +Kotlin +Kp +lambdabodylength +lambdaparametername +LBRACE +LBRACK +lcurly +Leanback +leftcurly +legacywithboth +len +lexer +lexing +lgpl +lhmap +LHSOf +libcore +liberapay +lifecycle +linebreak +linecolumn +linelength +linkcheck +linkplain +linksource +linux +Lisetskii +Ljava +lkuehne +LNOT +localctx +localfinalvariablename +localhost +localvariablename +Loggable +lombok +lookaround +Loughran +lparen +lte +lucene +lui +luiframework +LVL +madbean +magicnumber +mailhost +mailto +mainframemodel +Mancuso +mapfile +marazmatic +markdownlint +Massol +matchxpath +mavenbadge +maxdepth +maxmem +maxmethods +mdl +MDM +mebigfatguy +mega +membername +meminitial +metadata +methodcount +methodlength +methodname +methodparampad +methodsandconstructorsannotations +methodtypeparametername +MEZk +mfussenegger +MHTML +Micha +microsoft +mingw +minimalistic +Mipmap +misconfigured +missingctor +missingdeprecated +missingjavadocmethod +missingjavadocpackage +missingjavadoctype +missingnullcaseinswitch +missingoverride +missingperiod +missingswitchdefault +missingtag +mixin +mkdir +MKo +mkordas +mktemp +MLINKCHECK +moby +mockit +mockito +Modello +modifiedcontrolvariable +modifierorder +Mohanad +Mohnen +mojohaus +moks +mondeja +moradan +mozilla +MRELEASE +mstudman +MTAGLIST +multicharacter +multifileregexpheader +multiline +Multimap +multiplestringliterals +multiplevariabledeclarations +Multiset +multithreading +mutableexception +mutationtest +MVC +mvn +mvnd +mvnrepository +mvnw +MWRAPPER +Mycheckstyle +mycompany +mycompanychecks +mycustom +mycustomtag +myfile +myname +myproject +Mysql +mytag +NAMEFILE +nameofaffectedcheck +namespace +nanos +nbactions +nbia +nbsp +ncal +ncss +needbraces +NEGS +Nejmeh +neovim +NEQ +nestedfordepth +nestedifdepth +nestedtrydepth +netbeans +newdomain +newlineatendoffile +Nfc +NFF +Nfo +nformatter +Niederhauser +nikitasavinov +nio +nlow +NMCS +NMTOKEN +noarch +noarg +noarraytrailingcomma +noblank +nobr +noclone +nocode +nocodeinfile +nocstylearray +NODESET +noembed +noenumtrailingcomma +nofinalizer +noinspection +noinspectionreason +nojavadoc +nolinewrap +nonascii +noncompilable +nonconstantfieldnames +nondex +nonemptyatclausedescription +nonemptyblocks +NONFORMATTED +NONGROUP +NONJAVA +nonjavadoc +nonlegacy +nonnull +nonrequiredjavadoc +nonvalidating +noparentfile +NOPMD +noprofile +noreply +noscript +NOSONAR +nospace +Nothin +notjava +NOTNULL +nowarn +nowhitespaceafter +nowhitespacebefore +nowhitespacebeforecasedefaultcolon +nowildcard +nowrap +npath +npathcomplexity +npe +npm +nrmancuso +ntokens +NTU +nullcase +nullcheck +nullness +numberperline +numericliterals +nutsandbolts +nvim +nvuillam +nx +OAuth +objblock +oburn +OCP +octocat +ogg +OI +olddomain +olympe +onestatement +onestatementperline +onetoplevel +onetoplevelclass +onevariableperline +OOL +oopsla +OOQ +opencollective +openjdk +openrewrite +operatorwrap +opsummary +optimisation +optionalbracesusage +OQ +orderedproperties +orderingandspacing +orekit +ORELSEGET +orm +Osgi +oss +OSX +otechie +outertypefilename +outertypenumber +outter +ove +overloadmethodsdeclarationorder +overloadsplit +overridable +overridealwaysused +OVERRIDERS +packageannotation +packagecomment +packagedeclaration +packageinfo +packagename +packagenamesloader +packageobjectfactory +packagestatement +packge +packifc +packpub +Pageflow +pageview +Paikin +Papaioannou +paraception +parameterassignment +parametername +parameternumber +paramnum +Parcelable +parenpad +PARM +parrt +parsetreetablepresentation +Passembly +passphrase +pathcomplexity +patreon +patternvariableassignment +patternvariablename +Paulicke +paypal +pbludov +Pcheckstyle +pdf +Peclipse +Penable +perl +Perror +pgjdbc +Pgpg +Pgpgv +php +picocli +pid +pinentry +PIPESTATUS +pitest +pkga +pkghtml +pkginfo +pkx +PLHM +plugin +PMB +pmd +pmdruleset +PModel +png +Pno +poetix +Pointcut +POJO +Popup +Postgresql +powershell +prebuilts +prefs +PRESIZE +prettyprint +printf +println +PRINTSTACKTRACE +priva +PRMC +programpractice +Proguard +propertycachefile +propkey +PROTECTE +protonpack +Psevntu +PSHOME +PSMODULEP +Pstatic +pubconstr +pubifc +PUBLI +pubpub +pullrequest +puppycrawl +pw +pwd +px +py +qa +qalab +qaplug +qualitygates +Qube +qux +qw +qwe +QX +rawtypes +rb +RBRACE +rbrack +rcurly +rdiachenko +RDz +reactivex +README +Readonly +rebased +rebasing +recordcomponentname +recordcomponentnumber +recordtypeparametername +redundantimport +redundantmodifier +refactor +refactoring +refasterrules +refid +refreshenv +regex +regexp +regexpheader +regexpmultiline +regexponfilename +regexpsingleline +regexpsinglelinejava +relativized +releasenotes +RELi +remkop +reportyml +REPOURL +requireemptylinebeforeblocktaggroup +requirethis +resourceleak +Rethrown +returncount +returnsreceiver +reviewdog +revwalk +rfc +Rgb +rgba +rhs +rhysd +rickgiles +rightcurly +Rl +Rli +rnveach +robinraju +romani +romanivanovjr +rparen +rpmfind +rq +Rr +Rrridden +RRRR +Rsa +RSPEC +Rtl +ru +ruleset +rulesetfiles +Ruslan +rw +rx +sabaka +Saludo +Sameline +sariflogger +sarifweb +Savinov +saxonica +sbe +sbt +scache +Schneeberger +scm +scp +screenshot +Scriptblock +Scss +sdk +sdkman +sealedshouldhavepermitslist +selfexplanatory +Selkin +semaphoreci +semver +SEO +separatorwrap +SERIALVERSIONUID +servlet +severitymatchfilter +sevntu +shanegenschaw +shasum +shellcheck +shengchen +Shiell +sickboy +Simplifiable +simplifybooleanexpression +simplifybooleanreturn +singleline +singlelined +singlelinejavadoc +singlespaceseparator +sivakumar +Slawinski +slf +slist +SLL +SLo +Slurper +slurpersupport +Sms +smth +snyk +socio +Sohjiro +solr +someinner +somename +someoneelse +someuser +sonarcloud +sonarqube +sonarsource +sonatype +Sopov +sourcefile +sourceforge +sourcepath +sourcesets +spacebar +specialescape +spellchecker +spliterator +spotbugs +spotbugsreports +spotify +springframework +sqe +sql +src +ssh +ssl +stackexchange +stackoverflow +stackoverflowerror +stacktrace +standalone +staticanalysis +staticvariablename +stdin +Stdlib +stdout +stemp +stext +sthref +stmt +streamapi +strictfp +stringliteralequality +strkkk +STT +Studman +Styleable +styleguide +subdir +subelements +subext +subscope +sudo +suitebuilder +sukhodolsky +summaryjavadoc +summerofcode +superclasses +superclone +superfinalize +Superinterface +supertype +suppressioncommentfilter +suppressionexample +suppressionfilter +suppressionsinglefilter +suppressionsloader +suppressionsstringprinter +suppressionxpathfilter +suppressionxpathsinglefilter +suppresswarnings +suppresswarningsfilter +suppresswarningsholder +suppresswithnearbycommentfilter +suppresswithnearbytextfilter +suppresswithplaintextcommentfilter +suse +svg +sxpath +syntastic +Sys +sysextensions +sysprop +systemout +tac +Taglib +taglist +taskdef +tbody +tcr +td +teamcity +technotes +temurin +Testik +testmodules +textblocks +tfij +Tfo +tfoot +Thauvin +thead +thesummaryfragment +thetaphi +thomasjensen +thr +throwable +throwscount +Thymeleaf +tidelift +timeline +timezone +TKN +Tls +tmp +tmpdir +tngtech +toc +todo +todocomment +tokenizer +tokennizer +tokentype +tolist +Toolbar +toolongpackagetotestcoveragegooglesjavastylerule +TOSTRING +Touchscreen +trailingcomment +treemap +treeset +treetable +treewalker +trino +trinodb +tschneeberger +tstamp +tt +tta +ttf +tvf +tw +typecastparenpad +typename +typevariablenames +ub +uber +ubuntu +ucc +UElement +ufeff +ul +UMD +UML +uname +uncomment +uncommentedmain +Unconstructable +unicode +Uninstantiable +uninterned +uniq +uniqueproperties +Unitless +unnecessarynullcheckwithinstanceof +unnecessaryparentheses +unnecessarysemicolonafteroutertypedeclaration +unnecessarysemicolonaftertypememberdeclaration +unnecessarysemicoloninenumeration +unnecessarysemicolonintrywithresources +Unproxyable +unregister +unstale +unsubscribe +unusedcatchparametershouldbeunnamed +unusedimports +unusedlambdaparametershouldbeunnamed +unusedlocalvariable +upperell +upsss +urandom +uri +url +usebackq +userguide +username +usr +UTests +utf +Uth +UUID +UWF +uxxxx +validator +VALUEEEE +vararg +variabledeclarationusagedistance +Veach +Verdana +Versioning +verticalwhitespace +Vetrenko +Vfs +vh +viesure +visibilitymodifier +visualstudio +VK +Vladislav +Vladlis +vm +vnd +Vnen +vscode +Vtl +Vuillamy +Wadl +Wakelock +walkthrough +Warni +Weakento +webclient +Webflow +webjar +Weblogic +Webp +website +webtoolkit +Wellformedness +wget +whenshouldbeused +wherejavadocrequired +wheretobreak +whitelist +whitespaceafter +whitespacearound +wholename +Wifi +wiki +wikipedia +wiktionary +windowsservercore +withgoogle +wj +wnd +WOC +woff +wontfix +workaround +workflow +wq +writetag +writingchecks +writingfilefilters +writingfilters +writingjavadocchecks +writinglisteners +Wsdl +www +Wyq +xa +xabc +xar +xargs +XDcompile +xdeadbeef +xdoc +xdocspagetitle +Xep +Xerces +xf +xffffffff +xffffffffffffffff +xg +Xhenseval +XHTML +xm +Xmaxerrs +Xmaxwarns +xml +XMLHTTP +xmllogger +xmlmetareader +xmlns +xmlp +xmlstarlet +Xmx +Xor +xpath +xpathfilegenerator +xpathfilegeneratorastfilter +xpathfilegeneratorauditlistener +xpathfilterelement +xpathmapper +xpathquerygenerator +Xpkginfo +Xplugin +xright +xsd +Xshare +xsi +xsl +xslt +xsltproc +XSO +xwiki +XXXX +xxxxxx +XXXXXXXXXXXXXXXXXXXXXXXXXXXX +xy +XYzz +xzf +xzvf +yaml +yamllint +Yaroslavtsev +YC +yml +youtrack +youtu +youtube +Yoyodyne +yyyy +Yzz +Zbbh +zf +zh +zm +ZSH diff --git a/config/linkcheck-suppressions.txt b/config/linkcheck-suppressions.txt new file mode 100644 index 000000000000..b65cd085d143 --- /dev/null +++ b/config/linkcheck-suppressions.txt @@ -0,0 +1,1415 @@ +
    AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +AbstractNode.html#getDeclaredNamespaces(net.sf.saxon.om.NamespaceBinding%5B%5D): doesn't exist. +AbstractNode.html#getDeclaredNamespaces(net.sf.saxon.om.NamespaceBinding%5B%5D): doesn't exist. +AbstractNode.html#getDeclaredNamespaces(net.sf.saxon.om.NamespaceBinding%5B%5D): doesn't exist. +AbstractNode.html#getDeclaredNamespaces(net.sf.saxon.om.NamespaceBinding%5B%5D): doesn't exist. +AbstractNode.html#getDeclaredNamespaces(net.sf.saxon.om.NamespaceBinding%5B%5D): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +../ChecksAndFilesSuppressionFileGeneratorAuditListener.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.PropertyResolver,boolean,com.puppycrawl.tools.checkstyle.ThreadModeSettings): doesn't exist. +../ConfigurationLoader.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.PropertyResolver,boolean,com.puppycrawl.tools.checkstyle.ThreadModeSettings): doesn't exist. +../ConfigurationLoader.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.PropertyResolver,boolean,com.puppycrawl.tools.checkstyle.ThreadModeSettings): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.ThreadModeSettings): doesn't exist. +../DefaultConfiguration.html#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.ThreadModeSettings): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +../DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +../DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,com.puppycrawl.tools.checkstyle.AuditEventFormatter): doesn't exist. +../DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,com.puppycrawl.tools.checkstyle.AuditEventFormatter): doesn't exist. +../DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,com.puppycrawl.tools.checkstyle.AuditEventFormatter): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +../../DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(org.antlr.v4.runtime.CommonTokenStream): doesn't exist. +#%3Cinit%3E(org.antlr.v4.runtime.CommonTokenStream,int,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(int,java.lang.String,java.lang.Object...): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.Class,java.lang.String,java.lang.Object...): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +../MetadataGeneratorLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.ClassLoader): doesn't exist. +#%3Cinit%3E(java.util.Set,java.lang.ClassLoader): doesn't exist. +#%3Cinit%3E(java.util.Set,java.lang.ClassLoader,com.puppycrawl.tools.checkstyle.PackageObjectFactory.ModuleLoadOption): doesn't exist. +../PackageObjectFactory.html#%3Cinit%3E(java.util.Set,java.lang.ClassLoader,com.puppycrawl.tools.checkstyle.PackageObjectFactory.ModuleLoadOption): doesn't exist. +#%3Cinit%3E(java.util.Properties): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.Configuration,java.lang.String): doesn't exist. +../../PropertyCacheFile.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.Configuration,java.lang.String): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +../property_types.html#Pattern: doesn't exist. +../property_types.html#String: doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +../SarifLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +../../SarifLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(int,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileContents,java.lang.String,com.puppycrawl.tools.checkstyle.api.Violation,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../TreeWalkerAuditEvent.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileContents,java.lang.String,com.puppycrawl.tools.checkstyle.api.Violation,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../TreeWalkerAuditEvent.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileContents,java.lang.String,com.puppycrawl.tools.checkstyle.api.Violation,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../TreeWalkerAuditEvent.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileContents,java.lang.String,com.puppycrawl.tools.checkstyle.api.Violation,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +../XMLLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +../../XMLLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.util.Map): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +../XpathFileGeneratorAuditListener.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#beginTree.28com.puppycrawl.tools.checkstyle.api.DetailAST.29: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#finishTree.28com.puppycrawl.tools.checkstyle.api.DetailAST.29: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#getAcceptableTokens--: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#getDefaultTokens--: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#getRequiredTokens--: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#isCommentNodesRequired--: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#leaveToken.28com.puppycrawl.tools.checkstyle.api.DetailAST.29: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#setTokens-java.lang.String...-: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#visitToken.28com.puppycrawl.tools.checkstyle.api.DetailAST.29: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#visitToken-com.puppycrawl.tools.checkstyle.api.DetailAST-: doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.html#processFiltered-java.io.File-com.puppycrawl.tools.checkstyle.api.FileText-: doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.Object): doesn't exist. +#%3Cinit%3E(java.lang.Object,java.lang.String): doesn't exist. +#%3Cinit%3E(java.lang.Object,java.lang.String,com.puppycrawl.tools.checkstyle.api.Violation): doesn't exist. +../AuditEvent.html#%3Cinit%3E(java.lang.Object,java.lang.String,com.puppycrawl.tools.checkstyle.api.Violation): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.Throwable): doesn't exist. +#%3Cinit%3E(java.lang.String%5B%5D,int,int,int): doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/api/ExternalResourceHolder.html#getExternalResourceLocations--: doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileText): doesn't exist. +../FileContents.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileText): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileText): doesn't exist. +../FileText.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileText): doesn't exist. +#%3Cinit%3E(java.io.File,java.lang.String): doesn't exist. +#%3Cinit%3E(java.io.File,java.util.List): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +../../apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#DEPRECATED_BLOCK_TAG: doesn't exist. +../../apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#EXCEPTION_BLOCK_TAG: doesn't exist. +../../apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#PARAM_BLOCK_TAG: doesn't exist. +../../apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#RETURN_BLOCK_TAG: doesn't exist. +../../apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#THROWS_BLOCK_TAG: doesn't exist. +#%3Cinit%3E(int,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.SeverityLevel): doesn't exist. +../SeverityLevelCounter.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.SeverityLevel): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(int,int,int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +../Violation.html#%3Cinit%3E(int,int,int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +#%3Cinit%3E(int,int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +../Violation.html#%3Cinit%3E(int,int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +#%3Cinit%3E(int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +../Violation.html#%3Cinit%3E(int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +#%3Cinit%3E(int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +#%3Cinit%3E(int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +../Violation.html#%3Cinit%3E(int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +#%3Cinit%3E(int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,int,int,int,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST,boolean): doesn't exist. +../../checks/blocks/RightCurlyCheck.Details.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST,boolean): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/AbstractSuperCheck.MethodNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck.FieldFrame): doesn't exist. +../EqualsAvoidNullCheck.FieldFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck.FieldFrame): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/FinalLocalVariableCheck.FinalVariableCandidate.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.HiddenFieldCheck.FieldFrame,boolean,java.lang.String): doesn't exist. +../HiddenFieldCheck.FieldFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.HiddenFieldCheck.FieldFrame,boolean,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#isInContext(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D%5B%5D,java.util.BitSet): doesn't exist. +../../checks/coding/InnerAssignmentCheck.html#isInContext(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D%5B%5D,java.util.BitSet): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/RequireThisCheck.AbstractFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../RequireThisCheck.AbstractFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,java.lang.String): doesn't exist. +../RequireThisCheck.AnonymousClassFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,java.lang.String): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/RequireThisCheck.BlockFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../RequireThisCheck.BlockFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/RequireThisCheck.CatchFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../RequireThisCheck.CatchFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/RequireThisCheck.ClassFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../RequireThisCheck.ClassFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/RequireThisCheck.ConstructorFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../RequireThisCheck.ConstructorFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/RequireThisCheck.ForFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../RequireThisCheck.ForFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/RequireThisCheck.MethodFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../RequireThisCheck.MethodFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/RequireThisCheck.TryWithResourcesFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../RequireThisCheck.TryWithResourcesFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(boolean): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/UnusedCatchParameterShouldBeUnnamedCheck.CatchParameterDetails.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/UnusedLambdaParameterShouldBeUnnamedCheck.LambdaParameterDetails.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/UnusedLocalVariableCheck.TypeDeclDesc.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/UnusedLocalVariableCheck.VariableDesc.html#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/coding/UnusedLocalVariableCheck.VariableDesc.html#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/design/FinalClassCheck.ClassDesc.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/design/FinalClassCheck.TypeDeclarationDescription.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/design/HideUtilityClassConstructorCheck.Details.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.net.URI,java.lang.String,java.util.List,java.util.List): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(boolean,int,java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.AbstractImportControl,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +../AbstractImportControl.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.AbstractImportControl,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +../AbstractImportControl.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.AbstractImportControl,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +#%3Cinit%3E(boolean,boolean,boolean): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(boolean,boolean,java.lang.String,boolean): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String,boolean,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/imports/CustomImportOrderCheck.ImportDetails.html#%3Cinit%3E(java.lang.String,java.lang.String,boolean,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(java.lang.String,int,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl,java.lang.String,boolean): doesn't exist. +../FileImportControl.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl,java.lang.String,boolean): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#getGroupNumber(java.util.regex.Pattern%5B%5D,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl,java.lang.String,boolean,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +../PkgImportControl.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl,java.lang.String,boolean,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +../PkgImportControl.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl,java.lang.String,boolean,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +#%3Cinit%3E(java.lang.String,boolean,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +../PkgImportControl.html#%3Cinit%3E(java.lang.String,boolean,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +#%3Cinit%3E(boolean,boolean,java.lang.String,boolean,boolean): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck.Frame): doesn't exist. +../UnusedImportsCheck.Frame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck.Frame): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/AbstractExpressionHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../AbstractExpressionHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../AbstractExpressionHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +../../checks/indentation/AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +../AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/AnnotationArrayInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../AnnotationArrayInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../AnnotationArrayInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/ArrayInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ArrayInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ArrayInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/BlockParentHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../BlockParentHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../BlockParentHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/CaseHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../CaseHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../CaseHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/CatchHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../CatchHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../CatchHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/ClassDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ClassDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ClassDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +../DetailAstSet.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/DoWhileHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../DoWhileHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../DoWhileHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/ElseHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ElseHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ElseHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/FinallyHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../FinallyHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../FinallyHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/ForHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ForHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ForHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/IfHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../IfHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../IfHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/ImportHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ImportHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ImportHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,int...): doesn't exist. +../IndentLevel.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,int...): doesn't exist. +#%3Cinit%3E(int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/IndexHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../IndexHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../IndexHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/LabelHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../LabelHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../LabelHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/LambdaHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../LambdaHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../LambdaHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +../LineWrappingHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/MemberDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../MemberDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../MemberDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/MethodCallHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../MethodCallHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../MethodCallHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/MethodDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../MethodDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../MethodDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/NewHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../NewHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../NewHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/ObjectBlockHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ObjectBlockHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../ObjectBlockHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/PackageDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../PackageDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../PackageDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +../PrimordialHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/SlistHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../SlistHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../SlistHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/StaticInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../StaticInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../StaticInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/SwitchHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../SwitchHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../SwitchHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/SwitchRuleHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../SwitchRuleHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../SwitchRuleHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/SynchronizedHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../SynchronizedHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../SynchronizedHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/TryHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../TryHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../TryHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/WhileHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../WhileHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../WhileHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../../checks/indentation/YieldHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../YieldHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +../YieldHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.html#getAcceptableJavadocTokens--: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.html#getBlockCommentAst--: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.html#getDefaultJavadocTokens--: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.html#getRequiredJavadocTokens--: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.html#setJavadocTokens-java.lang.String...-: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.html#visitJavadocToken-com.puppycrawl.tools.checkstyle.api.DetailNode-: doesn't exist. +apidocs/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.html#visitToken-com.puppycrawl.tools.checkstyle.api.DetailAST-: doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,int,int,boolean,boolean,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(int,int,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.Token): doesn't exist. +../JavadocMethodCheck.ClassInfo.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.Token): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.ClassInfo): doesn't exist. +../../checks/javadoc/JavadocMethodCheck.ExceptionInfo.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.ClassInfo): doesn't exist. +../JavadocMethodCheck.ExceptionInfo.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.ClassInfo): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FullIdent): doesn't exist. +../../checks/javadoc/JavadocMethodCheck.Token.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FullIdent): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#getMultilineNoArgTags(java.util.regex.Matcher,java.lang.String%5B%5D,int,int): doesn't exist. +../JavadocMethodCheck.html#getMultilineNoArgTags(java.util.regex.Matcher,java.lang.String%5B%5D,int,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(int,int,java.lang.String): doesn't exist. +#%3Cinit%3E(int,int,java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagInfo.Type): doesn't exist. +../JavadocTagInfo.html#%3Cinit%3E(java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagInfo.Type): doesn't exist. +#%3Cinit%3E(java.util.Collection,java.util.Collection): doesn't exist. +../JavadocTags.html#%3Cinit%3E(java.util.Collection,java.util.Collection): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(int,int): doesn't exist. +#%3Cinit%3E(java.lang.String%5B%5D,int): doesn't exist. +#findChar(java.lang.String%5B%5D,char,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +../TagParser.html#findChar(java.lang.String%5B%5D,char,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +#getNextPoint(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +../TagParser.html#getNextPoint(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +#getTagId(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +../TagParser.html#getTagId(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +#isCommentTag(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +../TagParser.html#isCommentTag(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +#isTag(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +../TagParser.html#isTag(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +#parseTag(java.lang.String%5B%5D,int,int,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +../TagParser.html#parseTag(java.lang.String%5B%5D,int,int,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +#parseTags(java.lang.String%5B%5D,int): doesn't exist. +#skipHtmlComment(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +../TagParser.html#skipHtmlComment(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.api.LineColumn): doesn't exist. +../../checks/javadoc/utils/TagInfo.html#%3Cinit%3E(java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.api.LineColumn): doesn't exist. +#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/metrics/AbstractClassCouplingCheck.ClassContext.html#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(int): doesn't exist. +#%3Cinit%3E(boolean): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.math.BigInteger,java.math.BigInteger): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileContents): doesn't exist. +../../checks/regexp/CommentSuppressor.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileContents): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.regexp.DetectorOptions): doesn't exist. +../MultilineDetector.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.regexp.DetectorOptions): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.regexp.DetectorOptions): doesn't exist. +../SinglelineDetector.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.regexp.DetectorOptions): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/sizes/ExecutableStatementCountCheck.Context.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../checks/sizes/MethodCountCheck.MethodCounter.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#processNestedGenerics(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,int): doesn't exist. +../../checks/whitespace/GenericWhitespaceCheck.html#processNestedGenerics(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,int): doesn't exist. +#processSingleGeneric(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,int): doesn't exist. +../../checks/whitespace/GenericWhitespaceCheck.html#processSingleGeneric(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#isBlockCommentEnd(int%5B%5D,int): doesn't exist. +#isFirstInLine(int%5B%5D,int): doesn't exist. +#isSingleSpace(int%5B%5D,int): doesn't exist. +#isSpace(int%5B%5D,int): doesn't exist. +#isTextSeparatedCorrectlyFromPrevious(int%5B%5D,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(int): doesn't exist. +#%3Cinit%3E(java.lang.Integer,java.lang.Integer): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(java.util.regex.Pattern,java.util.regex.Pattern,java.util.regex.Pattern,java.lang.String,java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilter): doesn't exist. +../SuppressWithNearbyCommentFilter.Tag.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilter): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyTextFilter): doesn't exist. +../SuppressWithNearbyTextFilter.Suppression.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyTextFilter): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter.SuppressionType,com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter): doesn't exist. +../SuppressWithPlainTextCommentFilter.Suppression.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter.SuppressionType,com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter): doesn't exist. +../SuppressWithPlainTextCommentFilter.Suppression.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter.SuppressionType,com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(int,int,java.lang.String,com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter.TagType,com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter): doesn't exist. +../SuppressionCommentFilter.Tag.html#%3Cinit%3E(int,int,java.lang.String,com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter.TagType,com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter): doesn't exist. +../SuppressionCommentFilter.Tag.html#%3Cinit%3E(int,int,java.lang.String,com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter.TagType,com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(java.util.regex.Pattern,java.util.regex.Pattern,java.util.regex.Pattern,java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(org.antlr.v4.runtime.Lexer,org.antlr.v4.runtime.atn.ATN,org.antlr.v4.runtime.dfa.DFA%5B%5D,org.antlr.v4.runtime.atn.PredictionContextCache): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(org.antlr.v4.runtime.Token): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.Object,javax.swing.JTextArea,java.util.Collection): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,java.util.List): doesn't exist. +../../gui/CodeSelectorPresentation.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,java.util.List): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailNode,java.util.List): doesn't exist. +../../gui/CodeSelectorPresentation.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailNode,java.util.List): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.TreeTable): doesn't exist. +../ListToTreeSelectionModelWrapper.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.TreeTable): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../gui/ParseTreeTableModel.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#fireTreeStructureChanged(java.lang.Object,java.lang.Object%5B%5D,int%5B%5D,java.lang.Object...): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../gui/ParseTreeTablePresentation.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel): doesn't exist. +../TreeTable.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.TreeTable,javax.swing.tree.TreeModel): doesn't exist. +../TreeTableCellRenderer.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.TreeTable,javax.swing.tree.TreeModel): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel,javax.swing.JTree): doesn't exist. +../TreeTableModelAdapter.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel,javax.swing.JTree): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.meta.ModuleType,java.util.List,java.util.List): doesn't exist. +../ModuleDetails.html#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.meta.ModuleType,java.util.List,java.util.List): doesn't exist. +../ModuleDetails.html#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.meta.ModuleType,java.util.List,java.util.List): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#getDifference(int%5B%5D,int...): doesn't exist. +#getNodesOfSpecificType(com.puppycrawl.tools.checkstyle.api.DetailNode%5B%5D,int): doesn't exist. +../../site/SiteUtil.html#getNodesOfSpecificType(com.puppycrawl.tools.checkstyle.api.DetailNode%5B%5D,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.io.Writer,java.lang.String): doesn't exist. +#tableRows(int%5B%5D,boolean): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#endsWith(int%5B%5D,java.lang.String): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#isCodePointWhitespace(int%5B%5D,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#copyOfArray(T%5B%5D,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.xpath.AbstractNode,int,int): doesn't exist. +../AbstractElementNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.xpath.AbstractNode,int,int): doesn't exist. +#%3Cinit%3E(net.sf.saxon.om.TreeInfo): doesn't exist. +#getDeclaredNamespaces(net.sf.saxon.om.NamespaceBinding%5B%5D): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(java.lang.String,java.lang.String): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.api.DetailAST,int,int): doesn't exist. +../../xpath/ElementNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.api.DetailAST,int,int): doesn't exist. +../ElementNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.api.DetailAST,int,int): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +../../xpath/RootNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent,int): doesn't exist. +../xpath/XpathQueryGenerator.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent,int): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,int,int,com.puppycrawl.tools.checkstyle.api.FileText,int): doesn't exist. +../../xpath/XpathQueryGenerator.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,int,int,com.puppycrawl.tools.checkstyle.api.FileText,int): doesn't exist. +../../xpath/XpathQueryGenerator.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,int,int,com.puppycrawl.tools.checkstyle.api.FileText,int): doesn't exist. +#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,int,int,int,com.puppycrawl.tools.checkstyle.api.FileText,int): doesn't exist. +../../xpath/XpathQueryGenerator.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,int,int,int,com.puppycrawl.tools.checkstyle.api.FileText,int): doesn't exist. +../../xpath/XpathQueryGenerator.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,int,int,int,com.puppycrawl.tools.checkstyle.api.FileText,int): doesn't exist. +#%3Cinit%3E(): doesn't exist. +#%3Cinit%3E(net.sf.saxon.om.NodeInfo,com.puppycrawl.tools.checkstyle.xpath.iterators.DescendantIterator.StartWith): doesn't exist. +../DescendantIterator.html#%3Cinit%3E(net.sf.saxon.om.NodeInfo,com.puppycrawl.tools.checkstyle.xpath.iterators.DescendantIterator.StartWith): doesn't exist. +#%3Cinit%3E(net.sf.saxon.om.NodeInfo): doesn't exist. +#%3Cinit%3E(net.sf.saxon.om.NodeInfo): doesn't exist. +#%3Cinit%3E(net.sf.saxon.om.NodeInfo): doesn't exist. +#%3Cinit%3E(java.util.Collection): doesn't exist. +#%3Cinit%3E(java.io.Writer): doesn't exist. +#com.puppycrawl: doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.OutputStreamOptions.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.PatternArrayConverter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.PatternConverter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.RelaxedAccessModifierArrayConverter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.RelaxedStringArrayConverter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.ScopeConverter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.SeverityLevelConverter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.UriConverter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AbstractAutomaticBean.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AstTreeStringPrinter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/AuditEventDefaultFormatter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/Checker.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/ChecksAndFilesSuppressionFileGeneratorAuditListener.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/CheckstyleParserErrorStrategy.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/ConfigurationLoader.IgnoredModulesOptions.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/ConfigurationLoader.InternalLoader.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/ConfigurationLoader.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.PropertyResolver,boolean,com.puppycrawl.tools.checkstyle.ThreadModeSettings): doesn't exist. +com/puppycrawl/tools/checkstyle/DefaultConfiguration.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/DefaultConfiguration.html#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.ThreadModeSettings): doesn't exist. +com/puppycrawl/tools/checkstyle/DefaultContext.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions,com.puppycrawl.tools.checkstyle.AuditEventFormatter): doesn't exist. +com/puppycrawl/tools/checkstyle/DefaultLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/Definitions.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/DetailAstImpl.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavaAstVisitor.DetailAstPair.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavaAstVisitor.html#%3Cinit%3E(org.antlr.v4.runtime.CommonTokenStream): doesn't exist. +com/puppycrawl/tools/checkstyle/JavadocCommentsAstVisitor.html#%3Cinit%3E(org.antlr.v4.runtime.CommonTokenStream,int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/JavadocCommentsAstVisitor.TextAccumulator.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavaParser.CheckstyleErrorListener.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavaParser.Options.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavaParser.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.DescriptiveErrorListener.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.ParseErrorMessage.html#%3Cinit%3E(int,java.lang.String,java.lang.Object...): doesn't exist. +com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.ParseStatus.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.CliOptions.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/LocalizedMessage.Utf8Control.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/LocalizedMessage.html#%3Cinit%3E(java.lang.String,java.lang.Class,java.lang.String,java.lang.Object...): doesn't exist. +com/puppycrawl/tools/checkstyle/Main.CliOptions.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/Main.OnlyCheckstyleLoggersFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/Main.OutputFormat.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/Main.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/MetadataGeneratorLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/OsSpecificUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/PackageNamesLoader.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/PackageObjectFactory.ModuleLoadOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/PackageObjectFactory.html#%3Cinit%3E(java.lang.String,java.lang.ClassLoader): doesn't exist. +com/puppycrawl/tools/checkstyle/PackageObjectFactory.html#%3Cinit%3E(java.util.Set,java.lang.ClassLoader): doesn't exist. +com/puppycrawl/tools/checkstyle/PackageObjectFactory.html#%3Cinit%3E(java.util.Set,java.lang.ClassLoader,com.puppycrawl.tools.checkstyle.PackageObjectFactory.ModuleLoadOption): doesn't exist. +com/puppycrawl/tools/checkstyle/PropertiesExpander.html#%3Cinit%3E(java.util.Properties): doesn't exist. +com/puppycrawl/tools/checkstyle/PropertyCacheFile.ExternalResource.html#%3Cinit%3E(java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/PropertyCacheFile.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.Configuration,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/PropertyType.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/SarifLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/SarifLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/SarifLogger.RuleKey.html#%3Cinit%3E(java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/SuppressionsStringPrinter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/ThreadModeSettings.html#%3Cinit%3E(int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/TreeWalker.AstState.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/TreeWalker.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/TreeWalkerAuditEvent.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileContents,java.lang.String,com.puppycrawl.tools.checkstyle.api.Violation,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/XMLLogger.FileMessages.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/XMLLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/XMLLogger.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/XmlLoader.LoadExternalDtdFeatureProvider.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/XmlLoader.html#%3Cinit%3E(java.util.Map): doesn't exist. +com/puppycrawl/tools/checkstyle/XpathFileGeneratorAstFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/XpathFileGeneratorAuditListener.html#%3Cinit%3E(java.io.OutputStream,com.puppycrawl.tools.checkstyle.AbstractAutomaticBean.OutputStreamOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.Formatter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.FormatterType.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.Property.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AbstractCheck.FileContext.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AbstractCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.FileContext.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AuditEvent.html#%3Cinit%3E(java.lang.Object): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AuditEvent.html#%3Cinit%3E(java.lang.Object,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AuditEvent.html#%3Cinit%3E(java.lang.Object,java.lang.String,com.puppycrawl.tools.checkstyle.api.Violation): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AutomaticBean.OutputStreamOptions.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/AutomaticBean.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/BeforeExecutionFileFilterSet.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/CheckstyleException.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/api/CheckstyleException.html#%3Cinit%3E(java.lang.String,java.lang.Throwable): doesn't exist. +com/puppycrawl/tools/checkstyle/api/Comment.html#%3Cinit%3E(java.lang.String%5B%5D,int,int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/api/FileContents.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileText): doesn't exist. +com/puppycrawl/tools/checkstyle/api/FileText.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileText): doesn't exist. +com/puppycrawl/tools/checkstyle/api/FileText.html#%3Cinit%3E(java.io.File,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/api/FileText.html#%3Cinit%3E(java.io.File,java.util.List): doesn't exist. +com/puppycrawl/tools/checkstyle/api/FilterSet.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/FullIdent.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/JavadocCommentsTokenTypes.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/LineColumn.html#%3Cinit%3E(int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/api/Scope.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/SeverityLevel.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/SeverityLevelCounter.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.SeverityLevel): doesn't exist. +com/puppycrawl/tools/checkstyle/api/TokenTypes.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/api/Violation.html#%3Cinit%3E(int,int,int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/api/Violation.html#%3Cinit%3E(int,int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/api/Violation.html#%3Cinit%3E(int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/api/Violation.html#%3Cinit%3E(int,int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/api/Violation.html#%3Cinit%3E(int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,com.puppycrawl.tools.checkstyle.api.SeverityLevel,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/api/Violation.html#%3Cinit%3E(int,java.lang.String,java.lang.String,java.lang.Object%5B%5D,java.lang.String,java.lang.Class,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/ArrayTypeStyleCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/WhenShouldBeUsedCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/DescendantTokenCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/LineSeparatorOption.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/NoCodeInFileCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.SequencedProperties.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/OrderedPropertiesCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolder.Entry.html#%3Cinit%3E(java.lang.String,int,int,int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolder.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/TodoCommentCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/TranslationCheck.ResourceBundle.html#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/TranslationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/UncommentedMainCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.UniqueProperties.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/UpperEllCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/HexLiteralCaseCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationLocationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationOnSameLineCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleCheck.ClosingParensOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleCheck.ElementStyleOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleCheck.TrailingArrayCommaOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/AnnotationUseStyleCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/MissingDeprecatedCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/MissingOverrideCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/PackageAnnotationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/annotation/SuppressWarningsCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/AvoidNestedBlocksCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/BlockOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/EmptyBlockCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/LeftCurlyOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/NeedBracesCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.Details.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST,boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/blocks/RightCurlyOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.MethodNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/AbstractSuperCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/ArrayTrailingCommaCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/AvoidInlineConditionalsCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/AvoidNoArgumentSuperConstructorCallCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/ConstructorsDeclarationGroupingCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/CovariantEqualsCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.ScopeState.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/DefaultComesLastCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/EmptyStatementCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.FieldFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck.FieldFrame): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/EqualsHashCodeCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.FinalVariableCandidate.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.ScopeData.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.FieldFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.HiddenFieldCheck.FieldFrame,boolean,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/HiddenFieldCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/IllegalCatchCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/IllegalThrowsCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/InnerAssignmentCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/InnerAssignmentCheck.html#isInContext(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D%5B%5D,java.util.BitSet): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/MagicNumberCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/MissingCtorCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/MissingNullCaseInSwitchCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/MissingSwitchDefaultCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/MultipleStringLiteralsCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/NestedIfDepthCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/NestedTryDepthCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/NoArrayTrailingCommaCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/NoEnumTrailingCommaCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/NoFinalizerCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/OverloadMethodsDeclarationOrderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/PackageDeclarationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/ParameterAssignmentCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/PatternVariableAssignmentCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.AbstractFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.AnonymousClassFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.BlockFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.CatchFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.ClassFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.ConstructorFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.ForFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.FrameType.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.MethodFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.TryWithResourcesFrame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.AbstractFrame,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.Context.html#%3Cinit%3E(boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanExpressionCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/SimplifyBooleanReturnCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/StringLiteralEqualityCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/SuperCloneCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/SuperFinalizeCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryNullCheckWithInstanceOfCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnnecessarySemicolonAfterOuterTypeDeclarationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnnecessarySemicolonAfterTypeMemberDeclarationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnnecessarySemicolonInEnumerationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnnecessarySemicolonInTryWithResourcesCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedCatchParameterShouldBeUnnamedCheck.CatchParameterDetails.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedCatchParameterShouldBeUnnamedCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedLambdaParameterShouldBeUnnamedCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedLambdaParameterShouldBeUnnamedCheck.LambdaParameterDetails.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.TypeDeclDesc.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.VariableDesc.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.VariableDesc.html#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.VariableDesc.html#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/DesignForExtensionCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.ClassDesc.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.TypeDeclarationDescription.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheck.Details.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/HideUtilityClassConstructorCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/InnerTypeLastCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/InterfaceIsTypeCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/MutableExceptionCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/OneTopLevelClassCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/SealedShouldHavePermitsListCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/header/AbstractHeaderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/header/HeaderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/header/MultiFileRegexpHeaderCheck.HeaderFileMetadata.html#%3Cinit%3E(java.net.URI,java.lang.String,java.util.List,java.util.List): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/header/MultiFileRegexpHeaderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/header/MultiFileRegexpHeaderCheck.MatchResult.html#%3Cinit%3E(boolean,int,java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/header/RegexpHeaderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/AbstractImportControl.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.AbstractImportControl,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/AbstractImportRule.html#%3Cinit%3E(boolean,boolean,boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/AccessResult.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/AvoidStarImportCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/AvoidStaticImportCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/ClassImportRule.html#%3Cinit%3E(boolean,boolean,java.lang.String,boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.ImportDetails.html#%3Cinit%3E(java.lang.String,java.lang.String,boolean,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.RuleMatchForImport.html#%3Cinit%3E(java.lang.String,int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/FileImportControl.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl,java.lang.String,boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.html#getGroupNumber(java.util.regex.Pattern%5B%5D,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/MismatchStrategy.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl,java.lang.String,boolean,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/PkgImportControl.html#%3Cinit%3E(java.lang.String,boolean,com.puppycrawl.tools.checkstyle.checks.imports.MismatchStrategy): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/PkgImportRule.html#%3Cinit%3E(boolean,boolean,java.lang.String,boolean,boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/RedundantImportCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.Frame.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck.Frame): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/imports/UnusedImportsCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/AbstractExpressionHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/AbstractExpressionHandler.html#checkChildren(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,boolean,boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/AnnotationArrayInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/ArrayInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/BlockParentHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/CaseHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/CatchHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/ClassDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/DetailAstSet.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/DoWhileHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/ElseHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/FinallyHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/ForHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/IfHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/ImportHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentLevel,int...): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/IndentLevel.html#%3Cinit%3E(int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/IndexHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/LabelHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/LambdaHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.LineWrappingOptions.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/MemberDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/MethodCallHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/MethodDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/ObjectBlockHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/PackageDefHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/PrimordialHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/SlistHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/StaticInitHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/SwitchRuleHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/SynchronizedHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/WhileHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/indentation/YieldHandler.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck,com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.FileContext.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/AtclauseOrderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/HtmlTag.html#%3Cinit%3E(java.lang.String,int,int,boolean,boolean,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/InvalidJavadocPositionCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/InvalidJavadocTag.html#%3Cinit%3E(int,int,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocBlockTagLocationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocContentLocationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocContentLocationOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocLeadingAsteriskAlignCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.ClassInfo.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.Token): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.ExceptionInfo.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.ClassInfo): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.Token.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FullIdent): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.html#getMultilineNoArgTags(java.util.regex.Matcher,java.lang.String%5B%5D,int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMissingLeadingAsteriskCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMissingWhitespaceAfterAsteriskCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocPackageCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocParagraphCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocStyleCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTag.html#%3Cinit%3E(int,int,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTag.html#%3Cinit%3E(int,int,java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagContinuationIndentationCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.Type.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfo.html#%3Cinit%3E(java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagInfo.Type): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTags.html#%3Cinit%3E(java.util.Collection,java.util.Collection): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocVariableCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocPackageCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocTypeCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/RequireEmptyLineBeforeBlockTagGroupCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/SingleLineJavadocCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/SummaryJavadocCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.Point.html#%3Cinit%3E(int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#%3Cinit%3E(java.lang.String%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#findChar(java.lang.String%5B%5D,char,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#getNextPoint(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#getTagId(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#isCommentTag(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#isTag(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#parseTag(java.lang.String%5B%5D,int,int,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#parseTags(java.lang.String%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/TagParser.html#skipHtmlComment(java.lang.String%5B%5D,com.puppycrawl.tools.checkstyle.checks.javadoc.TagParser.Point): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/WriteTagCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/javadoc/utils/TagInfo.html#%3Cinit%3E(java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.api.LineColumn): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.ClassContext.html#%3Cinit%3E(java.lang.String,com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.html#%3Cinit%3E(int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheck.Context.html#%3Cinit%3E(boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/CyclomaticComplexityCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/JavaNCSSCheck.Counter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/JavaNCSSCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.TokenEnd.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.Values.html#%3Cinit%3E(java.math.BigInteger,java.math.BigInteger): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/modifier/ClassMemberImpliedModifierCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/modifier/ModifierOrderCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/AbbreviationAsWordInNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/AbstractAccessControlNameCheck.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/AbstractNameCheck.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/AccessModifierOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/CatchParameterNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/ClassTypeParameterNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/ConstantNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/IllegalIdentifierNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/InterfaceTypeParameterNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/LambdaParameterNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/LocalVariableNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/MemberNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/MethodTypeParameterNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/PackageNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/ParameterNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/PatternVariableNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/RecordComponentNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/RecordTypeParameterNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/StaticVariableNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/naming/TypeNameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/CommentSuppressor.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.FileContents): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.Builder.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/DetectorOptions.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/MultilineDetector.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.regexp.DetectorOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/NeverSuppress.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/RegexpCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/RegexpOnFilenameCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/regexp/SinglelineDetector.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.checks.regexp.DetectorOptions): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/AnonInnerLengthCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheck.Context.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/ExecutableStatementCountCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/FileLengthCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/LambdaBodyLengthCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/LineLengthCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.MethodCounter.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/MethodLengthCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/OuterTypeNumberCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/ParameterNumberCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/sizes/RecordComponentNumberCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/AbstractParenPadCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForInitializerPadCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyForIteratorPadCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/FileTabCharacterCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.html#processNestedGenerics(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/GenericWhitespaceCheck.html#processSingleGeneric(com.puppycrawl.tools.checkstyle.api.DetailAST,int%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/MethodParamPadCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/NoLineWrapCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceBeforeCaseDefaultColonCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceBeforeCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/PadOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/SeparatorWrapCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/SingleSpaceSeparatorCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/SingleSpaceSeparatorCheck.html#isBlockCommentEnd(int%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/SingleSpaceSeparatorCheck.html#isFirstInLine(int%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/SingleSpaceSeparatorCheck.html#isSingleSpace(int%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/SingleSpaceSeparatorCheck.html#isSpace(int%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/SingleSpaceSeparatorCheck.html#isTextSeparatedCorrectlyFromPrevious(int%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/TypecastParenPadCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAroundCheck.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/checks/whitespace/WrapOption.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filefilters/BeforeExecutionExclusionFileFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/CsvFilterElement.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/IntMatchFilterElement.html#%3Cinit%3E(int): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/IntRangeFilterElement.html#%3Cinit%3E(java.lang.Integer,java.lang.Integer): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.html#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressFilterElement.html#%3Cinit%3E(java.util.regex.Pattern,java.util.regex.Pattern,java.util.regex.Pattern,java.lang.String,java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressWarningsFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.Tag.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilter): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.Suppression.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyTextFilter): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyTextFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.Suppression.html#%3Cinit%3E(java.lang.String,int,com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter.SuppressionType,com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.SuppressionType.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.Tag.html#%3Cinit%3E(int,int,java.lang.String,com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter.TagType,com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.TagType.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressionFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressionSingleFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressionXpathSingleFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/SuppressionsLoader.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.html#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/filters/XpathFilterElement.html#%3Cinit%3E(java.util.regex.Pattern,java.util.regex.Pattern,java.util.regex.Pattern,java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/grammar/CrAwareLexerSimulator.html#%3Cinit%3E(org.antlr.v4.runtime.Lexer,org.antlr.v4.runtime.atn.ATN,org.antlr.v4.runtime.dfa.DFA%5B%5D,org.antlr.v4.runtime.atn.PredictionContextCache): doesn't exist. +com/puppycrawl/tools/checkstyle/grammar/JavadocCommentsLexerUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/grammar/JavadocCommentsParserUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/grammar/SimpleToken.html#%3Cinit%3E(org.antlr.v4.runtime.Token): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/BaseCellEditor.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/CodeSelector.html#%3Cinit%3E(java.lang.Object,javax.swing.JTextArea,java.util.Collection): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentation.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,java.util.List): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentation.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailNode,java.util.List): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/ListToTreeSelectionModelWrapper.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.TreeTable): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/Main.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/MainFrame.ExpandCollapseAction.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/MainFrame.FileSelectionAction.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/MainFrame.FindNodeByXpathAction.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/MainFrame.JavaFileFilter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/MainFrame.ReloadAction.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/MainFrame.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/MainFrameModel.ParseMode.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/MainFrameModel.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/ParseTreeTableModel.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/ParseTreeTableModel.html#fireTreeStructureChanged(java.lang.Object,java.lang.Object%5B%5D,int%5B%5D,java.lang.Object...): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentation.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/TreeTable.TreeTableCellEditor.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/TreeTable.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/TreeTableCellRenderer.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.TreeTable,javax.swing.tree.TreeModel): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.UpdatingTreeExpansionListener.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.UpdatingTreeModelListener.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/gui/TreeTableModelAdapter.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel,javax.swing.JTree): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/JavadocMetadataScraperUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/MetadataGeneratorUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/ModuleDetails.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/ModuleDetails.html#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,com.puppycrawl.tools.checkstyle.meta.ModuleType,java.util.List,java.util.List): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/ModulePropertyDetails.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/ModulePropertyDetails.html#%3Cinit%3E(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/ModuleType.html#%3Cinit%3E(java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/XmlMetaReader.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/meta/XmlMetaWriter.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/ClassAndPropertiesSettersJavadocScraper.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/ChecksXmlMacro.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/DescriptionMacro.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/ExampleMacro.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/JavadocScraperResultUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/ModuleJavadocParsingUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/NotesMacro.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/ParentModuleMacro.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/PropertiesMacro.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/SiteUtil.DescriptionExtractor.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/SiteUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/SiteUtil.html#getDifference(int%5B%5D,int...): doesn't exist. +com/puppycrawl/tools/checkstyle/site/SiteUtil.html#getNodesOfSpecificType(com.puppycrawl.tools.checkstyle.api.DetailNode%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/site/ViolationMessagesMacro.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/XdocsTemplateParser.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/site/XdocsTemplateSink.html#%3Cinit%3E(java.io.Writer,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/site/XdocsTemplateSink.html#tableRows(int%5B%5D,boolean): doesn't exist. +com/puppycrawl/tools/checkstyle/site/XdocsTemplateSinkFactory.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/AnnotationUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/BlockCommentPosition.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/ChainedPropertyUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/CheckUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/CodePointUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/CodePointUtil.html#endsWith(int%5B%5D,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/CommonUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/CommonUtil.html#isCodePointWhitespace(int%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/FilterUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/JavadocUtil.JavadocTagType.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/JavadocUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/ParserUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/ScopeUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/TokenUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/UnmodifiableCollectionUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/XpathUtil.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/AbstractElementNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.xpath.AbstractNode,int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/AbstractNode.html#%3Cinit%3E(net.sf.saxon.om.TreeInfo): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/AbstractNode.html#getDeclaredNamespaces(net.sf.saxon.om.NamespaceBinding%5B%5D): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/AbstractRootNode.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/AttributeNode.html#%3Cinit%3E(java.lang.String,java.lang.String): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/ElementNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.xpath.AbstractNode,com.puppycrawl.tools.checkstyle.api.DetailAST,int,int): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/RootNode.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent,int): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,int,int,com.puppycrawl.tools.checkstyle.api.FileText,int): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/XpathQueryGenerator.html#%3Cinit%3E(com.puppycrawl.tools.checkstyle.api.DetailAST,int,int,int,com.puppycrawl.tools.checkstyle.api.FileText,int): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.StartWith.html#%3Cinit%3E(): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/iterators/DescendantIterator.html#%3Cinit%3E(net.sf.saxon.om.NodeInfo,com.puppycrawl.tools.checkstyle.xpath.iterators.DescendantIterator.StartWith): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/iterators/FollowingIterator.html#%3Cinit%3E(net.sf.saxon.om.NodeInfo): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/iterators/PrecedingIterator.html#%3Cinit%3E(net.sf.saxon.om.NodeInfo): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseDescendantIterator.html#%3Cinit%3E(net.sf.saxon.om.NodeInfo): doesn't exist. +com/puppycrawl/tools/checkstyle/xpath/iterators/ReverseListIterator.html#%3Cinit%3E(java.util.Collection): doesn't exist. +com/puppycrawl/tools/checkstyle/utils/UnmodifiableCollectionUtil.html#copyOfArray(T%5B%5D,int): doesn't exist. +com/puppycrawl/tools/checkstyle/site/XdocsTemplateSink.CustomPrintWriter.html#%3Cinit%3E(java.io.Writer): doesn't exist. diff --git a/config/markdownlint.rb b/config/markdownlint.rb new file mode 100644 index 000000000000..d36c06965327 --- /dev/null +++ b/config/markdownlint.rb @@ -0,0 +1,12 @@ +# Enable all rules +all + +# The maximum allowed line length is 100 +rule 'MD013', :line_length => 100 + +# We do not use some parsers, our md files are for Github mostly, and it works fine with bare URLs +exclude_rule 'MD034' + +# This rule conflicts with Github templates. +# See https://github.com/checkstyle/checkstyle/issues/9285 for the details. +exclude_rule 'MD041' diff --git a/config/openrewrite-recipes-checkstyle.properties b/config/openrewrite-recipes-checkstyle.properties new file mode 100644 index 000000000000..27ab6d0235c4 --- /dev/null +++ b/config/openrewrite-recipes-checkstyle.properties @@ -0,0 +1,8 @@ +checkstyle.cache.file=${mvn.project.build.directory}/cachefile +checkstyle.header.file=config/java.header +checkstyle.importcontrol.file=config/import-control.xml +checkstyle.importcontroltest.file=config/import-control-test.xml +checkstyle.java.version=${mvn.java.version} +checkstyle.regexp.header.file=config/java-regexp.header +checkstyle.suppressions-xpath.file=config/suppressions-xpath.xml +checkstyle.suppressions.file=config/suppressions.xml diff --git a/config/org.eclipse.jdt.core.prefs b/config/org.eclipse.jdt.core.prefs index ae51e9e7af8b..d6a9f1e8a238 100644 --- a/config/org.eclipse.jdt.core.prefs +++ b/config/org.eclipse.jdt.core.prefs @@ -1,5 +1,8 @@ -org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=enabled +# The list of options supported by Eclipse compiler +# https://github.com/eclipse/eclipse.jdt.core/blame/master/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/impl/CompilerOptions.java + org.eclipse.jdt.core.compiler.problem.APILeak=error +org.eclipse.jdt.core.compiler.problem.annotatedTypeArgumentToUnannotated=error org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.comparingIdentical=error @@ -10,16 +13,21 @@ org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod= org.eclipse.jdt.core.compiler.problem.discouragedReference=error org.eclipse.jdt.core.compiler.problem.emptyStatement=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -#The severity is set to 'warning', since we need to suppress it in some cases. +# The severity is set to 'warning', since we need to suppress it in some cases. org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=warning org.eclipse.jdt.core.compiler.problem.fallthroughCase=error +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=error org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=error org.eclipse.jdt.core.compiler.problem.finalParameterBound=error org.eclipse.jdt.core.compiler.problem.forbiddenReference=error org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=error +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=error +org.eclipse.jdt.core.compiler.problem.incompatibleOwningContract=error org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=error org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=error +org.eclipse.jdt.core.compiler.problem.insufficientResourceAnalysis=error org.eclipse.jdt.core.compiler.problem.invalidJavadoc=error org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=error org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=error @@ -31,13 +39,9 @@ org.eclipse.jdt.core.compiler.problem.missingDefaultCase=error org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=error org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=enabled org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=error -#We don't document the tests. As we cannot exclude them, this check is muted. -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=enabled org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=protected org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=all_standard_tags -#We don't document the tests. As we cannot exclude them, this check is muted. -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=enabled org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=enabled org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=protected @@ -48,81 +52,96 @@ org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=error org.eclipse.jdt.core.compiler.problem.noEffectAssignment=error org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=error org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=error +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=error org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error org.eclipse.jdt.core.compiler.problem.nullReference=error +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=error -#Incompatible with visitToken and similar API. -org.eclipse.jdt.core.compiler.problem.overridingMethodWithoutSuperInvocation=ignore org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=error org.eclipse.jdt.core.compiler.problem.parameterAssignment=error +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=error org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=error -# rawTypeReference=warning to allow us suppress it in code for old code +# The option rawTypeReference is set to warning to allow us suppress it in code for old code org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=error org.eclipse.jdt.core.compiler.problem.redundantNullCheck=error org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=error org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=error org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=error +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=error org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=error org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=enabled -# uncheckedTypeOperation=warning to allow us suppress it in code for old code +org.eclipse.jdt.core.compiler.problem.tasks=enabled +org.eclipse.jdt.core.compiler.problem.terminalDeprecation=error +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +# The option uncheckedTypeOperation is set to warning to allow us suppress it in code for old code org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=error +org.eclipse.jdt.core.compiler.problem.uninternedIdentityComparison=enabled org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=error +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=enabled org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=error org.eclipse.jdt.core.compiler.problem.unnecessaryElse=error +org.eclipse.jdt.core.compiler.problem.unstableAutoModuleName=error org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=error org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled org.eclipse.jdt.core.compiler.problem.unusedImport=error org.eclipse.jdt.core.compiler.problem.unusedLabel=error +org.eclipse.jdt.core.compiler.problem.unusedLambdaParameter=error org.eclipse.jdt.core.compiler.problem.unusedLocal=error org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=error org.eclipse.jdt.core.compiler.problem.unusedParameter=error org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -#For an event handler it is not possible to remove unneeded parameter nor use it. -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -#For an event handler it is not possible to remove unneeded parameter nor use it. -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=error org.eclipse.jdt.core.compiler.problem.unusedTypeArgumentsForMethodInvocation=error org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=error org.eclipse.jdt.core.compiler.problem.unusedWarningToken=error org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=error -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=error -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.fieldHiding=error # Ignore section -# We are not ready to refactor code to use non-null validation, we will try later on -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nullanalysis=ignore -#We can not enforce this rule as we are library and we keep deprecated stuff for some time +# Requires us to box and unbox all conversions manually which seems unnecessary. +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +# We can not enforce this rule as we are library and we keep deprecated stuff for some time org.eclipse.jdt.core.compiler.problem.deprecation=ignore -#we will not put all String values to resources, it does not make sense in our project +# Preview features can be enabled be enabled only at source level 14, we are using 8 +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +# We don't document the tests. As we cannot exclude them, this check is muted. +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +# We don't document the tests. As we cannot exclude them, this check is muted. +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +# We will not put all String values to resources, it does not make sense in our project org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -#we should print errors on all throwables -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=disabled -#we shouldn't print errors on overriding methods that don't make use of exceptions -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -#We use checkstyle rule, special cases could be suppressed by configs out of code -org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore -#Requires us to box and unbox all conversions manually which seems unnecessary. -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -#Too much complaining about potential null code but tests and pitests don't show anything. +# Incompatible with visitToken and similar API. +org.eclipse.jdt.core.compiler.problem.overridingMethodWithoutSuperInvocation=ignore +# Too much complaining about potential null code but tests and pitests don't show anything. org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -#Complains about any resource that leaves a method that isn't closed first. +# Complains about any resource that leaves a method that isn't closed first. org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -#Too many false positives for methods that should be static but would cause issues. +# Too many false positives for methods that should be static but would cause issues. org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -#Checkstyle doesn't mind synthetic methods. +# We should print all errors +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarningsNotFullyAnalysed=disabled +# Checkstyle doesn't mind synthetic methods. org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -#We have another check that ensures fields have this when necessary. -#This asks for this on all fields. -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -#IntelliJ requires the type casts while this wants it removed. +# IntelliJ requires the type casts while this wants it removed. org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +# We have another check that ensures fields have this when necessary. +# This asks for this on all fields. +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +# We should print errors on all throwables +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=disabled +# We shouldn't print errors on overriding methods that don't make use of exceptions +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +# We use checkstyle rule, special cases could be suppressed by configs out of code +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore +# For an event handler it is not possible to remove unneeded parameter nor use it. +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +# For an event handler it is not possible to remove unneeded parameter nor use it. +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled diff --git a/config/pitest-suppressions/pitest-ant-suppressions.xml b/config/pitest-suppressions/pitest-ant-suppressions.xml new file mode 100644 index 000000000000..f32c811de669 --- /dev/null +++ b/config/pitest-suppressions/pitest-ant-suppressions.xml @@ -0,0 +1,101 @@ + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + createOverridingProperties + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTask::getLocation + + properties + "'", exc, getLocation()); + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + createOverridingProperties + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/util/Map$Entry::getValue + final String value = String.valueOf(entry.getValue()); + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + createOverridingProperties + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/util/Properties::setProperty + returnValue.setProperty(entry.getKey(), value); + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + createOverridingProperties + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + throw new BuildException("Error loading Properties file '" + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + createRootModule + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Package::getName + Checker.class.getPackage().getName() + ".", moduleClassLoader); + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + execute + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Package::getImplementationVersion + CheckstyleAntTask.class.getPackage().getImplementationVersion(), + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + execute + org.pitest.mutationtest.engine.gregor.mutators.experimental.ArgumentPropagationMutator + replaced call to java/util/Objects::toString with argument + final String version = Objects.toString( + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + getListeners + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/util/List::size + final int formatterCount = Math.max(1, formatters.size()); + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + processFiles + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + throw new BuildException("Unable to process files: " + files, exc); + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + retrieveAllScannedFiles + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Integer::valueOf + logIndex, fileNames.length, scanner.getBasedir()), Project.MSG_VERBOSE); + + + + CheckstyleAntTask.java + com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask + scanPath + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + log(pathIndex + ") Scanning path " + path, Project.MSG_VERBOSE); + + diff --git a/config/pitest-suppressions/pitest-api-suppressions.xml b/config/pitest-suppressions/pitest-api-suppressions.xml new file mode 100644 index 000000000000..c67b147cbda0 --- /dev/null +++ b/config/pitest-suppressions/pitest-api-suppressions.xml @@ -0,0 +1,47 @@ + + + + AbstractCheck.java + com.puppycrawl.tools.checkstyle.api.AbstractCheck + log + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/api/AbstractCheck::getSeverityLevel + getSeverityLevel(), + + + + AbstractFileSetCheck.java + com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck + log + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheck::getSeverityLevel + getSeverityLevel(), + + + + AbstractViolationReporter.java + com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter + setSeverity + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable severityLevel + severityLevel = SeverityLevel.getInstance(severity); + + + + FileText.java + com.puppycrawl.tools.checkstyle.api.FileText + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable charset + charset = null; + + + + Violation.java + com.puppycrawl.tools.checkstyle.api.Violation + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable args + this.args = null; + + diff --git a/config/pitest-suppressions/pitest-coding-1-suppressions.xml b/config/pitest-suppressions/pitest-coding-1-suppressions.xml new file mode 100644 index 000000000000..4bb57192e56c --- /dev/null +++ b/config/pitest-suppressions/pitest-coding-1-suppressions.xml @@ -0,0 +1,3 @@ + + + diff --git a/config/pitest-suppressions/pitest-coding-2-suppressions.xml b/config/pitest-suppressions/pitest-coding-2-suppressions.xml new file mode 100644 index 000000000000..4d82be322e81 --- /dev/null +++ b/config/pitest-suppressions/pitest-coding-2-suppressions.xml @@ -0,0 +1,38 @@ + + + + UnusedLocalVariableCheck.java + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheck + getBlockContainingLocalAnonInnerClass + org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator + negated conditional + if (currentAst.getType() == TokenTypes.LAMBDA) { + + + + UnusedLocalVariableCheck.java + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheck + getBlockContainingLocalAnonInnerClass + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + if (currentAst.getType() == TokenTypes.LAMBDA) { + + + + UnusedLocalVariableCheck.java + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheck + isInsideLocalAnonInnerClass + org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator + negated conditional + if (currentAst.getType() == TokenTypes.SLIST) { + + + + UnusedLocalVariableCheck.java + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheck + isInsideLocalAnonInnerClass + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + if (currentAst.getType() == TokenTypes.SLIST) { + + diff --git a/config/pitest-suppressions/pitest-common-suppressions.xml b/config/pitest-suppressions/pitest-common-suppressions.xml new file mode 100644 index 000000000000..24645d9899dd --- /dev/null +++ b/config/pitest-suppressions/pitest-common-suppressions.xml @@ -0,0 +1,325 @@ + + + + JavadocCommentsLexerUtil.java + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsLexerUtil + <init> + org.pitest.mutationtest.engine.gregor.mutators.ConstructorCallMutator + removed call to java/lang/IllegalStateException::<init> + throw new IllegalStateException("Utility class"); + + + + JavadocCommentsLexerUtil.java + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsLexerUtil + getUnclosedTagNameTokens + org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator + changed conditional boundary + && openingTag.getTokenIndex() < closingTag.getTokenIndex()) { + + + + JavadocCommentsLexerUtil.java + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsLexerUtil + getUnclosedTagNameTokens + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/util/Deque::isEmpty + while (!unmatchedOpen.isEmpty()) { + + + + JavadocCommentsLexerUtil.java + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsLexerUtil + getUnclosedTagNameTokens + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + while (!unmatchedOpen.isEmpty()) { + + + + JavadocCommentsLexerUtil.java + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsLexerUtil + isOpenTagName + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + return previousToken == null + + + + JavadocCommentsParserUtil.java + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsParserUtil + <init> + org.pitest.mutationtest.engine.gregor.mutators.ConstructorCallMutator + removed call to java/lang/IllegalStateException::<init> + throw new IllegalStateException("Utility class"); + + + + LocalizedMessage.java + com.puppycrawl.tools.checkstyle.LocalizedMessage + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable args + this.args = null; + + + SarifLogger.java + com.puppycrawl.tools.checkstyle.SarifLogger + renderSeverityLevel + org.pitest.mutationtest.engine.gregor.mutators.ConstructorCallMutator + removed call to java/lang/IncompatibleClassChangeError::<init> + return switch (severityLevel) { + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + <init> + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to org/antlr/v4/runtime/Token::getTokenIndex + setTokenIndex(token.getTokenIndex()); + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + <init> + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/grammar/SimpleToken::setTokenIndex + setTokenIndex(token.getTokenIndex()); + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + && getCharPositionInLine() == other.getCharPositionInLine() + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + && getLine() == other.getLine() + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + && getStartIndex() == other.getStartIndex() + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + && getStopIndex() == other.getStopIndex(); + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + && getText().equals(other.getText()) + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + && getTokenIndex() == other.getTokenIndex() + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_ELSE + removed conditional - replaced equality check with false + if (getClass() != obj.getClass()) { + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_ELSE + removed conditional - replaced equality check with false + if (obj == null) { + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.returns.BooleanTrueReturnValsMutator + replaced boolean return with true for com/puppycrawl/tools/checkstyle/grammar/SimpleToken::equals + return false; + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + return getType() == other.getType() + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + equals + org.pitest.mutationtest.engine.gregor.mutators.returns.BooleanFalseReturnValsMutator + replaced boolean return with false for com/puppycrawl/tools/checkstyle/grammar/SimpleToken::equals + return true; + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/grammar/SimpleToken::getCharPositionInLine + getCharPositionInLine(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Integer::valueOf + getCharPositionInLine(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/grammar/SimpleToken::getLine + getLine(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Integer::valueOf + getLine(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/grammar/SimpleToken::getStartIndex + getStartIndex(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Integer::valueOf + getStartIndex(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/grammar/SimpleToken::getStopIndex + getStopIndex() + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Integer::valueOf + getStopIndex() + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/grammar/SimpleToken::getText + getText(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/grammar/SimpleToken::getTokenIndex + getTokenIndex(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Integer::valueOf + getTokenIndex(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/grammar/SimpleToken::getType + getType(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/Integer::valueOf + getType(), + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/util/Objects::hash + return Objects.hash( + + + + SimpleToken.java + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + hashCode + org.pitest.mutationtest.engine.gregor.mutators.returns.PrimitiveReturnsMutator + replaced int return with 0 for com/puppycrawl/tools/checkstyle/grammar/SimpleToken::hashCode + return Objects.hash( + + diff --git a/config/pitest-suppressions/pitest-filters-suppressions.xml b/config/pitest-suppressions/pitest-filters-suppressions.xml new file mode 100644 index 000000000000..84d3beb5bd82 --- /dev/null +++ b/config/pitest-suppressions/pitest-filters-suppressions.xml @@ -0,0 +1,137 @@ + + + + SuppressFilterElement.java + com.puppycrawl.tools.checkstyle.filters.SuppressFilterElement + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable columnFilter + columnFilter = null; + + + + SuppressFilterElement.java + com.puppycrawl.tools.checkstyle.filters.SuppressFilterElement + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable columnsCsv + columnsCsv = null; + + + + SuppressFilterElement.java + com.puppycrawl.tools.checkstyle.filters.SuppressFilterElement + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable lineFilter + lineFilter = null; + + + + SuppressFilterElement.java + com.puppycrawl.tools.checkstyle.filters.SuppressFilterElement + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable linesCsv + linesCsv = null; + + + + SuppressWithNearbyCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilter + accept + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter::getFileContents + if (getFileContents() != currentContents) { + + + + SuppressWithNearbyCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilter$Tag + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable tagIdRegexp + tagIdRegexp = null; + + + + SuppressWithNearbyCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilter$Tag + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable tagMessageRegexp + tagMessageRegexp = null; + + + + SuppressWithNearbyCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilter$Tag + toString + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + return "Tag[text='" + text + '\'' + + + + SuppressWithPlainTextCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter$Suppression + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable eventIdRegexp + eventIdRegexp = null; + + + + SuppressWithPlainTextCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilter$Suppression + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable eventMessageRegexp + eventMessageRegexp = null; + + + + SuppressionCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter$Tag + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable tagIdRegexp + tagIdRegexp = null; + + + + SuppressionCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter$Tag + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable tagMessageRegexp + tagMessageRegexp = null; + + + + SuppressionCommentFilter.java + com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter$Tag + toString + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + return "Tag[text='" + text + '\'' + + + + XpathFilterElement.java + com.puppycrawl.tools.checkstyle.filters.XpathFilterElement + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable xpathExpression + xpathExpression = null; + + + + XpathFilterElement.java + com.puppycrawl.tools.checkstyle.filters.XpathFilterElement + isXpathQueryMatching + org.pitest.mutationtest.engine.gregor.mutators.experimental.NakedReceiverMutator + replaced call to java/util/stream/Stream::map with receiver + .stream().map(AbstractNode.class::cast) + + diff --git a/config/pitest-suppressions/pitest-header-suppressions.xml b/config/pitest-suppressions/pitest-header-suppressions.xml new file mode 100644 index 000000000000..2dcc3b66b88e --- /dev/null +++ b/config/pitest-suppressions/pitest-header-suppressions.xml @@ -0,0 +1,4 @@ + + + + diff --git a/config/pitest-suppressions/pitest-imports-suppressions.xml b/config/pitest-suppressions/pitest-imports-suppressions.xml new file mode 100644 index 000000000000..bda6908599f5 --- /dev/null +++ b/config/pitest-suppressions/pitest-imports-suppressions.xml @@ -0,0 +1,74 @@ + + + + ImportControlCheck.java + com.puppycrawl.tools.checkstyle.checks.imports.ImportControlCheck + setFile + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + throw new IllegalArgumentException(UNABLE_TO_LOAD + uri, exc); + + + + ImportControlLoader.java + com.puppycrawl.tools.checkstyle.checks.imports.ImportControlLoader + load + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + throw new CheckstyleException("unable to read " + uri, exc); + + + + ImportControlLoader.java + com.puppycrawl.tools.checkstyle.checks.imports.ImportControlLoader + loadUri + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + throw new CheckstyleException("syntax error in url " + uri, exc); + + + + ImportControlLoader.java + com.puppycrawl.tools.checkstyle.checks.imports.ImportControlLoader + loadUri + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + throw new CheckstyleException("unable to find " + uri, exc); + + + + ImportOrderCheck.java + com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck + visitToken + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/lang/String::valueOf + throw new IllegalStateException( + + + + PkgImportControl.java + com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable patternForExactMatch + patternForExactMatch = null; + + + + PkgImportControl.java + com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable patternForPartialMatch + patternForPartialMatch = null; + + + + PkgImportControl.java + com.puppycrawl.tools.checkstyle.checks.imports.PkgImportControl + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable regex + this.regex = false; + + diff --git a/config/pitest-suppressions/pitest-indentation-suppressions.xml b/config/pitest-suppressions/pitest-indentation-suppressions.xml new file mode 100644 index 000000000000..ed5f3ba7cbbd --- /dev/null +++ b/config/pitest-suppressions/pitest-indentation-suppressions.xml @@ -0,0 +1,182 @@ + + + + AbstractExpressionHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler + getFirstAstNode + org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator + changed conditional boundary + && curNode.getColumnNo() < realStart.getColumnNo()) { + + + + AbstractExpressionHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler + getFirstToken + org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator + changed conditional boundary + if (toTest.getColumnNo() < first.getColumnNo()) { + + + + CommentsIndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck + findPreviousStatement + org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator + negated conditional + if (root.getFirstChild().getType() == TokenTypes.LITERAL_NEW) { + + + + CommentsIndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck + findPreviousStatement + org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator + changed conditional boundary + if (root.getLineNo() >= comment.getLineNo()) { + + + + CommentsIndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck + findTokenWhichBeginsTheLine + org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator + negated conditional + if (isUsingOfObjectReferenceToInvokeMethod(root)) { + + + + CommentsIndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck + getPrevStatementWhenCommentIsUnderCase + org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator + negated conditional + if (isUsingOfObjectReferenceToInvokeMethod(blockBody)) { + + + + CommentsIndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck + isUsingOfObjectReferenceToInvokeMethod + org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator + negated conditional + && root.getFirstChild().getFirstChild().getFirstChild().getNextSibling() != null; + + + + CommentsIndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck + isUsingOfObjectReferenceToInvokeMethod + org.pitest.mutationtest.engine.gregor.mutators.returns.BooleanTrueReturnValsMutator + replaced boolean return with true for com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheck::isUsingOfObjectReferenceToInvokeMethod + return root.getFirstChild().getFirstChild().getFirstChild() != null + + + + HandlerFactory.java + com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory + <init> + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory::register + register(TokenTypes.INDEX_OP, IndexHandler.class); + + + + HandlerFactory.java + com.puppycrawl.tools.checkstyle.checks.indentation.HandlerFactory + clearCreatedHandlers + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to java/util/Map::clear + createdHandlers.clear(); + + + + IndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck + beginTree + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/HandlerFactory::clearCreatedHandlers + handlerFactory.clearCreatedHandlers(); + + + + IndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck + beginTree + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to java/util/Deque::clear + handlers.clear(); + + + + IndentationCheck.java + com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck + beginTree + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/PrimordialHandler::checkIndentation + primordialHandler.checkIndentation(); + + + + MethodDefHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.MethodDefHandler + getMethodDefLineStart + org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator + changed conditional boundary + if (node.getLineNo() < lineStart) { + + + + SwitchHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.SwitchHandler + checkIndentation + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler::checkSwitchExpr + checkSwitchExpr(); + + + + SwitchHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.SwitchHandler + checkSwitchExpr + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/SwitchHandler::checkExpressionSubtree + checkExpressionSubtree( + + + + SynchronizedHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.SynchronizedHandler + checkIndentation + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/SynchronizedHandler::checkSynchronizedExpr + checkSynchronizedExpr(); + + + + SynchronizedHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.SynchronizedHandler + checkIndentation + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/SynchronizedHandler::checkWrappingIndentation + checkWrappingIndentation(getMainAst(), + + + + SynchronizedHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.SynchronizedHandler + checkSynchronizedExpr + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/SynchronizedHandler::checkExpressionSubtree + checkExpressionSubtree(syncAst, expected, false, false); + + + + TryHandler.java + com.puppycrawl.tools.checkstyle.checks.indentation.TryHandler + checkIndentation + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler::checkTryResParen + checkTryResParen(getTryResLparen(), "lparen"); + + diff --git a/config/pitest-suppressions/pitest-java-ast-visitor-suppressions.xml b/config/pitest-suppressions/pitest-java-ast-visitor-suppressions.xml new file mode 100644 index 000000000000..93462d60ebeb --- /dev/null +++ b/config/pitest-suppressions/pitest-java-ast-visitor-suppressions.xml @@ -0,0 +1,47 @@ + + + + JavadocCommentsAstVisitor.java + com.puppycrawl.tools.checkstyle.JavadocCommentsAstVisitor + createImaginary + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + if (tokenType == JavadocCommentsTokenTypes.JAVADOC_CONTENT) { + + + + JavadocCommentsAstVisitor.java + com.puppycrawl.tools.checkstyle.JavadocCommentsAstVisitor + createImaginary + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocNodeImpl::setColumnNumber + node.setColumnNumber(javadocColumnNumber); + + + + JavadocCommentsAstVisitor.java + com.puppycrawl.tools.checkstyle.JavadocCommentsAstVisitor + processChildren + org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/JavadocCommentsAstVisitor$TextAccumulator::flushTo + accumulator.flushTo(parent); + + + + JavadocCommentsAstVisitor.java + com.puppycrawl.tools.checkstyle.JavadocCommentsAstVisitor + visitBlockTag + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + if (tag instanceof ParserRuleContext context) { + + + + JavadocCommentsAstVisitor.java + com.puppycrawl.tools.checkstyle.JavadocCommentsAstVisitor + visitInlineTag + org.pitest.mutationtest.engine.gregor.mutators.RemoveConditionalMutator_EQUAL_IF + removed conditional - replaced equality check with true + if (tagContent instanceof ParserRuleContext context) { + + diff --git a/config/pitest-suppressions/pitest-javadoc-suppressions.xml b/config/pitest-suppressions/pitest-javadoc-suppressions.xml new file mode 100644 index 000000000000..4bb57192e56c --- /dev/null +++ b/config/pitest-suppressions/pitest-javadoc-suppressions.xml @@ -0,0 +1,3 @@ + + + diff --git a/config/pitest-suppressions/pitest-main-suppressions.xml b/config/pitest-suppressions/pitest-main-suppressions.xml new file mode 100644 index 000000000000..37b75a0bf30b --- /dev/null +++ b/config/pitest-suppressions/pitest-main-suppressions.xml @@ -0,0 +1,20 @@ + + + + Main.java + com.puppycrawl.tools.checkstyle.Main + runCheckstyle + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to com/puppycrawl/tools/checkstyle/Main::getOutputStreamOptions + getOutputStreamOptions(options.outputPath)); + + + + Main.java + com.puppycrawl.tools.checkstyle.Main$CliOptions + getExclusions + org.pitest.mutationtest.engine.gregor.mutators.experimental.NakedReceiverMutator + replaced call to java/util/stream/Stream::map with receiver + .map(Pattern::quote) + + diff --git a/config/pitest-suppressions/pitest-packagenamesloader-suppressions.xml b/config/pitest-suppressions/pitest-packagenamesloader-suppressions.xml new file mode 100644 index 000000000000..4bb57192e56c --- /dev/null +++ b/config/pitest-suppressions/pitest-packagenamesloader-suppressions.xml @@ -0,0 +1,3 @@ + + + diff --git a/config/pitest-suppressions/pitest-tree-walker-suppressions.xml b/config/pitest-suppressions/pitest-tree-walker-suppressions.xml new file mode 100644 index 000000000000..4bd4b4caa2c4 --- /dev/null +++ b/config/pitest-suppressions/pitest-tree-walker-suppressions.xml @@ -0,0 +1,29 @@ + + + + TreeWalker.java + com.puppycrawl.tools.checkstyle.TreeWalker + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable javaParseExceptionSeverity + private SeverityLevel javaParseExceptionSeverity = SeverityLevel.ERROR; + + + + TreeWalker.java + com.puppycrawl.tools.checkstyle.TreeWalker + createNewCheckSortedSet + org.pitest.mutationtest.engine.gregor.mutators.experimental.NakedReceiverMutator + replaced call to java/util/Comparator::thenComparing with receiver + .thenComparing(AbstractCheck::getId, + + + + TreeWalker.java + com.puppycrawl.tools.checkstyle.TreeWalker + createNewCheckSortedSet + org.pitest.mutationtest.engine.gregor.mutators.NonVoidMethodCallMutator + removed call to java/util/Comparator::naturalOrder + Comparator.nullsLast(Comparator.naturalOrder())) + + diff --git a/config/pitest-suppressions/pitest-utils-suppressions.xml b/config/pitest-suppressions/pitest-utils-suppressions.xml new file mode 100644 index 000000000000..4bb57192e56c --- /dev/null +++ b/config/pitest-suppressions/pitest-utils-suppressions.xml @@ -0,0 +1,3 @@ + + + diff --git a/config/pitest-suppressions/pitest-xpath-suppressions.xml b/config/pitest-suppressions/pitest-xpath-suppressions.xml new file mode 100644 index 000000000000..ace4e55b78a4 --- /dev/null +++ b/config/pitest-suppressions/pitest-xpath-suppressions.xml @@ -0,0 +1,29 @@ + + + + FollowingIterator.java + com.puppycrawl.tools.checkstyle.xpath.iterators.FollowingIterator + next + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable siblingEnum + siblingEnum = null; + + + + PrecedingIterator.java + com.puppycrawl.tools.checkstyle.xpath.iterators.PrecedingIterator + next + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable previousSiblingEnum + previousSiblingEnum = null; + + + + ReverseListIterator.java + com.puppycrawl.tools.checkstyle.xpath.iterators.ReverseListIterator + <init> + org.pitest.mutationtest.engine.gregor.mutators.experimental.MemberVariableMutator + Removed assignment to member variable items + this.items = null; + + diff --git a/config/pmd-main.xml b/config/pmd-main.xml index e1837f89dc26..17023c952bcf 100644 --- a/config/pmd-main.xml +++ b/config/pmd-main.xml @@ -4,66 +4,76 @@ 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"> - - PMD ruleset for Checkstyle main code - - .*/src/it/.* - .*/src/test/.* - + + PMD ruleset for Checkstyle main code + + .*/src/it/.* + .*/src/test/.* + .*/src/xdocs-examples/.* + - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/pmd-test.xml b/config/pmd-test.xml index d27264bbddaf..73e648ce545b 100644 --- a/config/pmd-test.xml +++ b/config/pmd-test.xml @@ -4,213 +4,232 @@ 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"> - - PMD ruleset for Checkstyle tests - - .*/src/main/.* + + PMD ruleset for Checkstyle tests + + .*/src/main/.* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + + + + + + + - - - - - - + + + + + + + + - - - - - - - + + + + + + + + + + + + + + - - - - - - - - - - - - - + + + + + + - - - - - - - - - - - - - - - - - - + + + - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/config/pmd.xml b/config/pmd.xml index 9723a5fec295..ad73a605c970 100644 --- a/config/pmd.xml +++ b/config/pmd.xml @@ -9,41 +9,107 @@ - - - - - - + + + + + + + + - + - + + + + + + + value="//ClassDeclaration + [@SimpleName='Main' or @SimpleName='Main$CliOptions' + or @SimpleName='JavadocPropertiesGenerator']"/> + + + + + + + + + + + + + + + + + + + + + @@ -52,18 +118,13 @@ + value="//ClassDeclaration[@SimpleName='RequireThisCheck']"/> - - - - @@ -82,48 +143,55 @@ - - - - - - - - + + + + + + + + + | //ClassDeclaration[@SimpleName='HandlerFactory'] + //MethodDeclaration[@Name='getHandler'] + | //ClassDeclaration[@SimpleName='JavaAstVisitor'] + //MethodDeclaration[@Name='visitWildCardTypeArgument']"/> - + + value="//ClassDeclaration[@SimpleName='AbstractFileSetCheck' + or @SimpleName='AbstractCheck' or @SimpleName='AbstractJavadocCheck' + or @SimpleName='AbstractNode' + or @SimpleName='AbstractViolationReporter'] + | //ClassDeclaration[@SimpleName='AbstractRootNode'] + //MethodDeclaration[@Name='getParent' or @Name='getDepth']"/> @@ -144,30 +212,38 @@ + value="//ClassDeclaration[@SimpleName='Main' or @SimpleName='Tag']"/> - - - - - + + + + + + + + + + + + + - - - - - + @@ -177,12 +253,17 @@ + + + + @@ -190,21 +271,40 @@ - + - + + + + + + + + + + - @@ -220,21 +320,21 @@ a runtime exception. JavadocMethodCheck: Exception type is not predictable. --> - - + + @@ -243,97 +343,77 @@ - + + + value="//ClassDeclaration[@SimpleName='HandlerFactory' + or @SimpleName='SiteUtil' or @SimpleName='Checker' or @SimpleName='JavaAstVisitor' + or @SimpleName='Main' or @SimpleName='TreeWalker' or @SimpleName='CheckstyleAntTask' + or @SimpleName='TranslationCheck' or @SimpleName='JavadocMethodCheck' + or @SimpleName='JavadocCommentsAstVisitor']"/> + - - - - - - - - - + | //ClassDeclaration[@SimpleName='PropertiesMacro'] + //MethodDeclaration[@Name='getDefaultValue'] + | //ClassDeclaration[@SimpleName='SiteUtil'] + //MethodDeclaration[@Name='getDefaultValue'] + | //ClassDeclaration[@SimpleName='DescriptionExtractor'] + //MethodDeclaration[@Name='getDescriptionFromJavadoc'] + | //ClassDeclaration[@SimpleName='JavadocTokenTypes' + or @SimpleName='TokenTypes' or @SimpleName='RequireThisCheck' + or @SimpleName='JavadocMethodCheck' or @SimpleName='JavaAstVisitor' + or @SimpleName='SiteUtil' or @SimpleName='JavadocCommentsAstVisitor']"/> @@ -341,53 +421,65 @@ + value="//ClassDeclaration[@SimpleName='Checker'] + | //ClassDeclaration[@SimpleName='Main'] + | //ClassDeclaration[@SimpleName='ImportOrderCheck']"/> - + - + + + + value="//ClassDeclaration[@SimpleName='JavaAstVisitor' + or @SimpleName='SiteUtil' or @SimpleName='JavadocCommentsAstVisitor']"/> - + - - + + value="//ClassDeclaration[@SimpleName='Violation']"/> - + - + + value="//ClassDeclaration[@SimpleName='Main' + or @SimpleName='Checker' or @SimpleName='CheckstyleAntTask' + or @SimpleName='TranslationCheck' + or @SimpleName='AbstractAutomaticBean' + or @SimpleName='SiteUtil' + or @SimpleName='MetadataGeneratorUtil']"/> - + - + + + value="//ClassDeclaration[@SimpleName='XdocsPagesTest'] + //MethodDeclaration[@Name='getModulePropertyExpectedValue'] + | //ClassDeclaration[@SimpleName='SiteUtil'] + //MethodDeclaration[@Name='getDefaultValue'] + | //ClassDeclaration[@SimpleName='DescriptionExtractor'] + //MethodDeclaration[@Name='getDescriptionFromJavadoc']"/> - + - - + + @@ -401,8 +493,8 @@ overloads a synchronized method, so it should have synchronized modifier. --> + value="//ClassDeclaration[@SimpleName='UniqueProperties' + or @SimpleName='SequencedProperties']//MethodDeclaration[@Name='keys' or @Name='put']"/> @@ -412,4 +504,94 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/projects-to-test/openjdk-17-projects-to-test-on.config b/config/projects-to-test/openjdk-17-projects-to-test-on.config new file mode 100644 index 000000000000..8ed4f352c6b5 --- /dev/null +++ b/config/projects-to-test/openjdk-17-projects-to-test-on.config @@ -0,0 +1,8 @@ +# List of GIT repositories to clone / pull for checking with Checkstyle +# File format: REPO_NAME|[local|git|hg]|URL|[COMMIT_ID]|[EXCLUDE FOLDERS] +# Please note that bash comments works in this file +# +# This file has been created to alleviate confusion in the contribution +# repository's projects-to-test-on.properties file; these projects +# must be used with special configurations. +openjdk17|git|https://github.com/openjdk/jdk17.git|master|| diff --git a/config/projects-to-test/openjdk-19-projects-to-test-on.config b/config/projects-to-test/openjdk-19-projects-to-test-on.config new file mode 100644 index 000000000000..f4c3101076f2 --- /dev/null +++ b/config/projects-to-test/openjdk-19-projects-to-test-on.config @@ -0,0 +1,8 @@ +# List of GIT repositories to clone / pull for checking with Checkstyle +# File format: REPO_NAME|[local|git|hg]|URL|[COMMIT_ID]|[EXCLUDE FOLDERS] +# Please note that bash comments works in this file +# +# This file has been created to alleviate confusion in the contribution +# repository's projects-to-test-on.properties file; these projects +# must be used with special configurations. +openjdk19|git|https://github.com/openjdk/jdk19u.git|master|| diff --git a/config/projects-to-test/openjdk-20-projects-to-test-on.config b/config/projects-to-test/openjdk-20-projects-to-test-on.config new file mode 100644 index 000000000000..b7cceb937310 --- /dev/null +++ b/config/projects-to-test/openjdk-20-projects-to-test-on.config @@ -0,0 +1,8 @@ +# List of GIT repositories to clone / pull for checking with Checkstyle +# File format: REPO_NAME|[local|git|hg]|URL|[COMMIT_ID]|[EXCLUDE FOLDERS] +# Please note that bash comments works in this file +# +# This file has been created to alleviate confusion in the contribution +# repository's projects-to-test-on.properties file; these projects +# must be used with special configurations. +openjdk20|git|https://github.com/openjdk/jdk20u.git|master|| diff --git a/config/projects-to-test/openjdk-25-projects-to-test-on.config b/config/projects-to-test/openjdk-25-projects-to-test-on.config new file mode 100644 index 000000000000..799728e4d48a --- /dev/null +++ b/config/projects-to-test/openjdk-25-projects-to-test-on.config @@ -0,0 +1,8 @@ +# List of GIT repositories to clone / pull for checking with Checkstyle +# File format: REPO_NAME|[local|git|hg]|URL|[COMMIT_ID]|[EXCLUDE FOLDERS] +# Please note that bash comments works in this file +# +# This file has been created to alleviate confusion in the contribution +# repository's projects-to-test-on.properties file; these projects +# must be used with special configurations. +openjdk25|git|https://github.com/openjdk/jdk25u.git|master|| diff --git a/config/projects-to-test/openjdk17-excluded.files b/config/projects-to-test/openjdk17-excluded.files new file mode 100644 index 000000000000..c6b1f2494411 --- /dev/null +++ b/config/projects-to-test/openjdk17-excluded.files @@ -0,0 +1,509 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/projects-to-test/openjdk19-excluded.files b/config/projects-to-test/openjdk19-excluded.files new file mode 100644 index 000000000000..06a99e78a18f --- /dev/null +++ b/config/projects-to-test/openjdk19-excluded.files @@ -0,0 +1,559 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/projects-to-test/openjdk20-excluded.files b/config/projects-to-test/openjdk20-excluded.files new file mode 100644 index 000000000000..f15a4180622e --- /dev/null +++ b/config/projects-to-test/openjdk20-excluded.files @@ -0,0 +1,538 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/projects-to-test/openjdk25-excluded.files b/config/projects-to-test/openjdk25-excluded.files new file mode 100644 index 000000000000..5562655e7206 --- /dev/null +++ b/config/projects-to-test/openjdk25-excluded.files @@ -0,0 +1,758 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/projects-to-test/projects-for-no-exception-javadoc.config b/config/projects-to-test/projects-for-no-exception-javadoc.config new file mode 100644 index 000000000000..7d4b9eccb550 --- /dev/null +++ b/config/projects-to-test/projects-for-no-exception-javadoc.config @@ -0,0 +1,19 @@ +# List of GIT repositories to clone / pull for checking with Checkstyle +# File format: REPO_NAME|[local|git|hg]|URL|[COMMIT_ID]|[EXCLUDE FOLDERS] +# Please note that bash comments works in this file + +guava|git|https://github.com/google/guava|v28.2|| + +#infinispan|git|https://github.com/infinispan/infinispan|7.2.5.Final|| +#protonpack|git|https://github.com/poetix/protonpack|protonpack-1.7|| +#jOOL|git|https://github.com/jOOQ/jOOL|version-0.9.7|| +#lucene-solr|git|https://github.com/apache/lucene-solr|releases/lucene-solr/5.4.0|| + +#tapestry-5|git|https://github.com/apache/tapestry-5|5.4.0|**/archetype-resources/**/*| +#storm|git|https://github.com/apache/storm|v0.9.6|| +#cassandra|git|https://github.com/apache/cassandra|cassandra-3.2|| + +#apache-commons|git|https://github.com/apache/commons-lang|LANG_3_4|| +#hadoop|git|https://github.com/apache/hadoop|release-2.6.3|| +#scouter|git|https://github.com/scouter-project/scouter|v0.4.4|| +#groovy|git|https://github.com/apache/groovy|GROOVY_2_4_5|| diff --git a/config/release-settings.xml b/config/release-settings.xml new file mode 100644 index 000000000000..5e3f9c9abadf --- /dev/null +++ b/config/release-settings.xml @@ -0,0 +1,24 @@ + + + + central + SONATYPE_USER + SONATYPE_PWD + + + + + + + gpg + + GPG_PASSPHRASE + GPG_KEYNAME + + + + diff --git a/config/sevntu-suppressions.xml b/config/sevntu-suppressions.xml new file mode 100644 index 000000000000..3faafc2b61a0 --- /dev/null +++ b/config/sevntu-suppressions.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/sevntu_suppressions.xml b/config/sevntu_suppressions.xml deleted file mode 100644 index a8b8089664e2..000000000000 --- a/config/sevntu_suppressions.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/config/signatures-test.txt b/config/signatures-test.txt new file mode 100644 index 000000000000..003cbdf2dc98 --- /dev/null +++ b/config/signatures-test.txt @@ -0,0 +1,6 @@ +com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport#verify(com.puppycrawl.tools.checkstyle.api.Configuration, java.lang.String, java.lang.String[]) @ Use inline config parser instead. +java.nio.file.Files#createTempFile(java.lang.String,java.lang.String,java.nio.file.attribute.FileAttribute[]) @ Use of this method is forbidden, please use @TempDir for better temporary directory control +java.io.File#createTempFile(java.lang.String,java.lang.String,java.io.File) @ Use of this method is forbidden, please use @TempDir for better temporary directory control +java.io.File#createTempFile(java.lang.String,java.lang.String) @ Use of this method is forbidden, please use @TempDir for better temporary directory control +java.nio.file.Files#createTempDirectory(java.lang.String,java.nio.file.attribute.FileAttribute[]) @ Use of this method is forbidden, please use @TempDir for better temporary directory control +java.nio.file.Files#createTempFile(java.nio.file.Path,java.lang.String,java.lang.String,java.nio.file.attribute.FileAttribute[]) @ Use of this method is forbidden, please use @TempDir for better temporary directory control diff --git a/config/signatures.txt b/config/signatures.txt new file mode 100644 index 000000000000..95071d4d7981 --- /dev/null +++ b/config/signatures.txt @@ -0,0 +1,6 @@ +com.puppycrawl.tools.checkstyle.DefaultConfiguration#getAttributeNames() @ Usage of deprecated API is forbidden. Please use DefaultConfiguration.getPropertyNames() instead. +com.puppycrawl.tools.checkstyle.DefaultConfiguration#getAttribute(java.lang.String) @ Usage of deprecated API is forbidden. Please use DefaultConfiguration.getProperty(String name) instead. +com.puppycrawl.tools.checkstyle.DefaultConfiguration#addAttribute(java.lang.String,java.lang.String) @ Usage of deprecated API is forbidden. Please use DefaultConfiguration.addProperty(String name, String value) instead. +com.puppycrawl.tools.checkstyle.api.AbstractCheck#log(int,int,java.lang.String,java.lang.Object[]) @ Use of this log method is forbidden, please use AbstractCheck#log(DetailAST ast, String key, Object... args) +com.puppycrawl.tools.checkstyle.api.AbstractCheck#log(int,java.lang.String,java.lang.Object[]) @ Use of this log method is forbidden, please use AbstractCheck#log(DetailAST ast, String key, Object... args) +java.net.URI#toString() @ This method can return garbage for non-ascii data, please use URI#toASCIIString() diff --git a/config/site-2.0.0.xsd b/config/site-2.0.0.xsd new file mode 100644 index 000000000000..4aacce42054f --- /dev/null +++ b/config/site-2.0.0.xsd @@ -0,0 +1,561 @@ + + + + + + + + + + 1.0.0+ + + The <code>&lt;site&gt;</code> + element is the root of the site decoration descriptor. + + + + + + 1.0.0+ + + The <code>&lt;site&gt;</code> + element is the root of the site decoration descriptor. + + + + + + 1.0.0+ + + Banner logo on the masthead of the site to the left. + + + + + + 1.0.0+ + + Banner logo on the masthead of the site to the right. + + + + + + 1.0.0+ + + Modify the date published display properties. + + + + + + 1.0.0+ + + Modify the version published display properties. + + + + + + 1.8.0+ + + The base url to edit Doxia document sources. + In general, <code>${project.scm.url}</code> value should do the job. + + + + + + 1.0.0+ + Powered by logos list. + + + + + + + + + + 1.0.0+ + + The artifact containing the skin for the site. + + + + + + 1.0.0+ + The main site content. + + + + + 1.0.0+ + + Custom configuration for use with customized Velocity templates. + Data from this field are + accessible in Velocity template from <code>$site.custom</code> + variable as DOM content. + Example: <code>$site.custom.getChild( 'customElement' ).getValue()</code> + + + + + + + + + + + + 1.0.0+ + The full name of the project site. + + + + + 1.6.0+ + + Whether to inherit configuration from a parent project site descriptor + (<code>merge</code>) + or not (<code>override</code>). + + + + + + 2.0.0+ + + Whether this "site.xml" should inherit from a parent "site.xml". + If set to "true" it fails the build + in case a parent site descriptor cannot be retrieved. + It does not necessarily need to be the direct parent + but just a site descriptor anywhere in the parent hierarchy. + + + + + + + 1.0.0+ + + Banner logo on the masthead of the site. + + + + + + 2.0.0+ + The image for the link. + + + + + + 1.0.0+ + The name to display for the link. + + + + + 1.0.0+ + The href to use for the link. + + + + + 1.0.1+ + + Where the new document will be displayed when the user follows a link, + i.e. _blank opens the new document in a new window. + + + + + + + 2.0.0+ + An image. + + + + 2.0.0+ + The source location. + + + + + 2.0.0+ + + Where to place the image relative to the displayed name (left or right). + + + + + + 2.0.0+ + The alternative text to use. + + + + + 2.0.0+ + The width to use. + + + + + 2.0.0+ + The height to use. + + + + + 2.0.0+ + The style to use. + + + + + + 1.0.0+ + The main content. + + + + + 1.7.0+ + + Additional content (like JavaScript) to include in the + HEAD block of the generated pages. + + + + + + 1.0.0+ + + A list of links to display in the navigation. + + + + + + + + + + + 1.0.0+ + + A list of breadcrumbs to display in the navigation. + + + + + + + + + + + 1.0.0+ + + A list of menus to include in the navigation. + + + + + + 1.7.0+ + + If present, the contained text will be used instead of the generated copyright text. + + + + + + + + 1.0.0+ + A link in the navigation. + + + + + 2.0.0+ + The image for the link. + + + + + + 1.0.0+ + The name to display for the link. + + + + + 1.0.0+ + The href to use for the link. + + + + + 1.0.1+ + + Where the new document will be displayed when the user follows a link, + i.e. _blank opens the new document in a new window. + + + + + + + 1.0.0+ + A menu in the navigation. + + + + + 2.0.0+ + The image for the menu. + + + + + 1.0.0+ + A list of menu item. + + + + + + 1.0.0+ + The name to display for the menu. + + + + + 1.0.0+ + + The way in which the menu is inherited. Can be one of : + <code>top</code>, <code>bottom</code>. + + + + + + 1.0.0+ + + If this is a reference, setting to + <code>true</code> means that it will be populated + in the site, whereas if it is <code>false</code>, + it is populated in the parent and then inherited. + + + + + + 1.0.0+ + + Mark this menu as reference to a pre-defined menu: + <code>reports</code>, <code>modules</code> + or <code>parent</code>. It will be populated at runtime + with corresponding pre-defined content. + + + + + + + 1.0.0+ + A menu item. + + + + + 1.0.0+ + A list of menu item. + + + + + 2.0.0+ + The image for the link. + + + + + + 1.0.0+ + + Whether to collapse children elements of an item menu (by default). + + + + + + 1.0.0+ + + A reference to a pre-defined menu item, such as a report (specified by the report goal + name). Any elements explicitly given override those from the pre-defined reference. + + + + + + 1.0.0+ + The name to display for the link. + + + + + 1.0.0+ + The href to use for the link. + + + + + 1.0.1+ + + Where the new document will be displayed when the user follows a link, + i.e. _blank opens the new document in a new window. + + + + + + + 1.0.0+ + + Modify display properties for date published. + + + + + 1.0.0+ + + Where to place the date published + (left, right, navigation-top, navigation-bottom, bottom). + + + + + + 1.0.0+ + Date format to use. + + + + + 1.8.1+ + + The timezone to use. Use <code>system</code> for + the default locale for this instance + of the Java Virtual Machine. + Refer to <code>java.util.TimeZone</code> for details. + + + + + + + 1.0.0+ + Power by logo on the navigation. + + + + + 2.0.0+ + The image for the link. + + + + + + 1.0.0+ + The name to display for the link. + + + + + 1.0.0+ + The href to use for the link. + + + + + 1.0.1+ + + Where the new document will be displayed when the user follows a link, + i.e. _blank opens the new document in a new window. + + + + + + + 1.0.0+ + + Modify display properties for version published. + + + + + 1.0.0+ + + Where to place the version published + (left, right, navigation-top, navigation-bottom, bottom). + + + + + + + 1.0.0+ + A skin artifact declaration. + + + + + 1.0.0+ + The skin group ID. + + + + + 1.0.0+ + The skin artifact ID. + + + + + 1.0.0+ + The skin version. + + + + + diff --git a/config/spotbugs-exclude.xml b/config/spotbugs-exclude.xml index 696a40e04d39..a918fecbb3d3 100644 --- a/config/spotbugs-exclude.xml +++ b/config/spotbugs-exclude.xml @@ -1,248 +1,461 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/spotless/import.order b/config/spotless/import.order new file mode 100644 index 000000000000..81fcd2e191bb --- /dev/null +++ b/config/spotless/import.order @@ -0,0 +1,4 @@ +3= +2=org +1=javax +0=java diff --git a/config/spotless/licence.header b/config/spotless/licence.header new file mode 100644 index 000000000000..7efb6a0b49d0 --- /dev/null +++ b/config/spotless/licence.header @@ -0,0 +1,19 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-$YEAR the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + diff --git a/config/suppressions-xpath.xml b/config/suppressions-xpath.xml index 01a72f9ac3e2..f198f30c0ef9 100644 --- a/config/suppressions-xpath.xml +++ b/config/suppressions-xpath.xml @@ -5,18 +5,510 @@ "https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd"> - - + + + + + + + + - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/suppressions.xml b/config/suppressions.xml index e9c7591e1783..d1a4c7f88871 100644 --- a/config/suppressions.xml +++ b/config/suppressions.xml @@ -5,106 +5,171 @@ "https://checkstyle.org/dtds/suppressions_1_2.dtd"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/version-number-rules.xml b/config/version-number-rules.xml index 72a4282dc519..03952f02b57f 100644 --- a/config/version-number-rules.xml +++ b/config/version-number-rules.xml @@ -5,38 +5,26 @@ xsi:schemaLocation="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0 https://mojo.codehaus.org/versions-maven-plugin/xsd/rule-2.0.0.xsd"> - - - .*[-_\.](alpha|Alpha|ALPHA|beta|Beta|BETA|rc|RC|M|EA)[-_\.]?[0-9]?.* - - - - - - .*-android - - - - - - 20030911 - - - - - - .* - - - - - - .* - - - + + + .*[-_\.](alpha|Alpha|ALPHA|beta|Beta|BETA|rc|RC|M|EA)[-_\.]?[0-9]?.* + + + + + + .*-android + + + + + + .* + + + diff --git a/config/yamllint.yaml b/config/yamllint.yaml new file mode 100644 index 000000000000..b497025aa7fb --- /dev/null +++ b/config/yamllint.yaml @@ -0,0 +1,37 @@ +--- + +yaml-files: + - '*.yaml' + - '*.yml' + +rules: + braces: enable + brackets: + min-spaces-inside: 1 + max-spaces-inside: 1 + colons: enable + commas: enable + comments: enable + comments-indentation: enable + # We have no use for yaml directives, and we do not have single yaml files + # with multiple documents in them, so we do not need doc start or end. + document-start: disable + document-end: disable + + empty-lines: enable + empty-values: enable + hyphens: enable + indentation: enable + key-duplicates: enable + # alphabetical keys are not always the best way to organize them + key-ordering: disable + line-length: + max: 100 + new-line-at-end-of-file: enable + new-lines: enable + octal-values: enable + # we do not need such strict format + quoted-strings: disable + trailing-spaces: enable + truthy: + allowed-values: [ 'true', 'false', 'on' ] diff --git a/docs/AuditListener.png.md b/docs/AuditListener.png.md new file mode 100644 index 000000000000..88667d50086d --- /dev/null +++ b/docs/AuditListener.png.md @@ -0,0 +1,32 @@ +```mermaid +classDiagram +direction TB + class DefaultLogger { + } + + class AuditListener { + +auditStarted(event: AuditEvent) : void + +auditFinished(event: AuditEvent) : void + +fileStarted(event: AuditEvent) : void + +fileFinished(event: AuditEvent) : void + +addError(event: AuditEvent) : void + +addException(event: AuditEvent, throwable: Throwable) : void + } + + class AuditEvent { + +getFileName() : String + +getLine() : int + +getMessage() : String + +getColumn() : int + +getSeverityLevel() : SeverityLevel + +getSourceName() : String + +getLocalizedMessage() : LocalizedMessage + } + + AuditListener <|-- DefaultLogger + DefaultLogger --> AuditEvent + + class DefaultLogger:::Sky + class AuditListener:::Sky + class AuditEvent:::Sky +``` diff --git a/docs/BEGINNING_DEVELOPMENT.md b/docs/BEGINNING_DEVELOPMENT.md new file mode 100644 index 000000000000..f666709ec428 --- /dev/null +++ b/docs/BEGINNING_DEVELOPMENT.md @@ -0,0 +1,262 @@ +# Beginning Development Guide + +![](https://raw.githubusercontent.com/checkstyle/resources/master/img/checkstyle-logos/checkstyle-logo-260x99.png) + +--------------------------------- + +**This guide is for developers who want to contribute to Checkstyle. It will guide you through +everything you need to do to complete your first pull request.** + +## Prerequisites + +This guide assumes that you have some basic knowledge of +the command line for your operating system. + +You must have the following installed on your local machine: + +- [Java 21](https://docs.oracle.com/en/java/javase/21/install/overview-jdk-installation.html) +- [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) + +## Forking the repository + +You must fork the repository to your own GitHub account. This will allow you to make +changes to the code and submit a pull request to the main repository. + +Navigate to https://github.com/checkstyle/checkstyle/fork and click the "Create fork" button. It is +recommended to NOT rename the forked repository, and the rest of this guide assumes that +you have not renamed the forked repository. + +## Setting up your local repository + +Clone the repository to your local machine using the following command. You must +Replace `MY_USERNAME` with your GitHub username. + +```bash +git@github.com:MY_USERNAME/checkstyle.git +``` + +Navigate to the root directory of the project and run the following command: + +```bash +git remote add upstream https://github.com/checkstyle/checkstyle +```` + +This allows you to pull changes from the main repository into your local repository. + +## Building the project + +To build the project, navigate to the root directory of the project and run the following command: + +```bash +mvn clean verify +``` + +This will build the project and run all the tests. Congratulations, you have +successfully built the project! + +## Setting up your IDE + +You can use any IDE to work on the project, here are some guides to help you set up your IDE: + +- [IntelliJ](https://checkstyle.org/idea.html) +- [Eclipse](https://checkstyle.org/eclipse.html) +- [Netbeans](https://checkstyle.org/netbeans.html) + +Using an IDE is not required, but it is recommended. + +## Selecting an issue + +- Browse through issues with the + https://github.com/checkstyle/checkstyle/labels/good%20first%20issue label. +- Read the issue description and comments to understand the problem. +- Look at some previous pull requests to help to understand what you will need to do. +- Make a comment on the issue to let others know that you are working on it. + +## Working on the issue + +For this section of the guide, we will assume that you are working on an issue with the +number `1234`. + +Create a new branch for your work using the following command: + +```bash +git checkout -b issue-1234 +``` + +Make your changes to the code as described in the issue. +Commit your changes using the following command: + +```bash +git add . +git commit -m "Issue #1234: Fixing the issue" +``` + +Run `mvn clean verify` to ensure that your changes have not broken the build and that all tests +are still passing. If the build does not succeed, carefully read the error messages and try to +fix the issue. If you are unable to fix the issue, reach out in our +[Contributors Chat](https://app.element.io/#/room/#checkstyle_checkstyle:gitter.im) or in the +[Google Group Forum](https://groups.google.com/g/checkstyle-devel) for help. + +Push your changes to your forked repository using the following command: + +```bash +git push origin issue-1234 +``` + +At this point, you have made your changes and pushed them to your forked repository. Now, you +need to create a pull request. + +## Creating a pull request + +- Navigate to https://github.com/checkstyle/checkstyle/pulls +- You will see a "Compare & pull request" button. Click it. +- Please read the pull request template and fill in the details as requested. +- Click the "Create pull request" button. +- Check back in about an hour to check if your pull request has passed our automated checks + and builds. If it has not, you will need to make the necessary changes and push them to your + forked repository. + +DO NOT: + +- open a pull request without an attached issue +- open and close pull requests to trigger checks +- open and close pull requests due to struggles with `git` + +## Reviewing your pull request + +You should be the first person to review your pull request! Make sure to leave any comments on +things you might not understand, need help with, or just want to call out. Your pull request +will be reviewed by the maintainers of the project. They will look at your code +and provide feedback. You may need to make changes to your code based on the feedback. + +## Making changes to your pull request + +This is an area that trips a lot of people up. There is a lot of ways to make changes to your pull +request, but we will discuss what we believe is the easiest way. + +Make the changes to your code on your local machine. +Commit your changes using the following command: + +```bash +git add . +git commit -m "Issue #1234: Fixing the issue" +``` + +We typically require a single commit for each pull request. This +(and lots of other `git` operations) can be done via interactive rebase. You can read more about +this concept at https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History. Here is an example +of what you will need to do: + +```bash +git rebase -i HEAD~3 +``` + +`3` is the number of commits that you want to deal with in the interactive rebase. This will open +up a text editor with a list of commits. You will need to change the word `pick` to `fixup` for all +the commits that you want to squash into your first commit. + +Here is an example of what the file will look like when it opens: + +```bash +pick 1a2b3c4d Issue #4242: Some other issue +pick 5e6f7g8h Issue #1234: Fixing the issue +pick 9i0j1k2l Issue #1234: Fixing the issue + +# Rebase a25806399..9i0j1k2l onto 9i0j1k2l (3 commands) +# +# Commands: +# p, pick = use commit +# r, reword = use commit, but edit the commit message +# e, edit = use commit, but stop for amending +# s, squash = use commit, but meld into previous commit +# f, fixup [-C | -c] = like "squash" but keep only the previous +# commit's log message, unless -C is used, in which case +# keep only this commit's message; -c is same as -C but +# opens the editor +``` + +You want to change the word `pick` to `fixup` for the commits that you want to squash into the +first commit. Here is what the file will look like after you have made the changes: + +```bash +pick 1a2b3c4d Issue #4242: Some other issue +pick 5e6f7g8h Issue #1234: Fixing the issue +fixup 9i0j1k2l Issue #1234: Fixing the issue + +# Rebase a25806399..9i0j1k2l onto 9i0j1k2l (3 commands) +# +# Commands: +# p, pick = use commit +# r, reword = use commit, but edit the commit message +# e, edit = use commit, but stop for amending +# s, squash = use commit, but meld into previous commit +# f, fixup [-C | -c] = like "squash" but keep only the previous +# commit's log message, unless -C is used, in which case +# keep only this commit's message; -c is same as -C but +# opens the editor +``` + +Now, save the file and close the text editor. This will squash the commits into one commit. + +Run `mvn clean verify` on your local before pushing to make sure that your changes have not +broken the build and that all tests are still passing, as above. + +Push your changes to your forked repository using the following command: + +```bash +git push origin issue-1234 --force +``` + +Note that you MUST force push your changes to your forked repository. This is because you have +rewritten your commit history and you need to force push to overwrite the commit history on your +forked repository. + +## Rebasing on the latest changes in the main repository + +If your pull request has been open for a while, you may need to rebase your changes on the latest +changes in the main repository. This is to ensure that your changes can be merged into the main +repository without any conflicts. + +Fetch the latest changes from the main repository using the following command: + +```bash +git checkout master +git pull upstream master +``` + +You can optionally push the latest changes to the master branch of your forked repository: + +```bash +git push origin master +``` + +Rebase your changes on the latest changes in the main repository using the following command: + +```bash +git checkout issue-1234 +git rebase master +``` + +Push your changes to your forked repository using the following command: + +```bash +git push origin issue-1234 --force +``` + +## Dealing with merge conflicts + +If you have merge conflicts when you rebase your changes on the latest changes in the main +repository, you will need to resolve the conflicts. This can be a bit tricky, but here is a +guide to help you through it: + +- Run `git status` to see which files have conflicts. +- Open the files with conflicts in your IDE or text editor. +- Look for the `<<<<<<<`, `=======`, and `>>>>>>>` markers. These markers show you where the + conflicts are. +- Resolve the conflicts by editing the files. You will need to remove the `<<<<<<<`, `=======`, and + `>>>>>>>` markers and make the necessary changes to the code. +- Run `git add .` to stage the changes. +- Run `git rebase --continue` to continue the rebase process. +- Run `mvn clean verify` to ensure that your changes have not broken the build and that all tests + are still passing. +- Run `git push origin issue-1234 --force` to push your changes to your forked repository. diff --git a/docs/Filter.png.md b/docs/Filter.png.md new file mode 100644 index 000000000000..b876bc90b65a --- /dev/null +++ b/docs/Filter.png.md @@ -0,0 +1,25 @@ +```mermaid +classDiagram + direction TB + + class Filter { + + accept(event: AuditEvent): boolean + } + + class FilterSet { + + accept(event: AuditEvent): boolean + + - filters: Set + + addFilter(filter: Filter): void + + removeFilter(filter: Filter): void + + clear(): void + } + + <> Filter + Filter <|.. FilterSet + + class Filter:::Sky + class FilterSet:::Sky + +classDef Sky fill:#E2EBFF,stroke:#374D7C,stroke-width:1px,color:#374D7C +``` diff --git a/docs/GRAMMAR_UPDATES.md b/docs/GRAMMAR_UPDATES.md new file mode 100644 index 000000000000..42b1ceeedf90 --- /dev/null +++ b/docs/GRAMMAR_UPDATES.md @@ -0,0 +1,240 @@ +# Java Grammar Update Process + +This document outlines the procedures for updating the Java grammar and +integrating new language features into Checkstyle. + +## Prerequisites + +There are some tools and concepts that you should be familiar with before +updating the Java grammar: + +- [ANTLR4](https://www.antlr.org/) +- Basic knowledge of lexers and parsers +- [Java Language Specification (JLS)](https://docs.oracle.com/javase/specs/jls/se22/html/index.html) +- [EBNF](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) + +## Basics + +A few basics to understand: + +- **Lexer**: A lexer is a program that performs lexical analysis. It takes the + input text and converts it into tokens. Our lexer grammar is + defined [here](https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/com/puppycrawl/tools/checkstyle/grammar/java/JavaLanguageLexer.g4). +- **Parser**: A parser is a program that performs syntax analysis. It takes the + tokens generated by the lexer and constructs a parse tree. Our parser grammar + is + defined [here](https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/com/puppycrawl/tools/checkstyle/grammar/java/JavaLanguageParser.g4). +- **Parse Tree**: A parse tree is a tree representation of the syntactic structure + of the source code. It is generated by the parser. We do not use the parse tree + directly in Checkstyle, but we use the parser to generate the parse tree and + then visit the parse tree to build our Abstract Syntax Tree (AST). +- **Abstract Syntax Tree (AST)**: An AST is a tree representation of the + syntactic structure of the source code. We build our AST by visiting the parse + tree generated by the parser. We use the AST to perform static analysis. +- **Token**: A token is a single element of the source code. For example, a + keyword, an identifier, a literal, etc. We define tokens in our lexer grammar. +- **Token Type**: A token type is a category of tokens. For example, `IDENT` + is a token type that includes all identifiers in the source code. We define + token types in our lexer grammar. +- **Parser Rule**: A parser rule is a rule that defines the syntax of the + programming language. For example, a class declaration. +- **Parser Rule Context**: A parser rule context is a context in which a parser + rule is applied, and contains information about the source code that matches + the parser rule. We use parser rule contexts to build our AST. +- **Visitor**: A visitor is a design pattern that allows us to separate the + algorithm from the object structure. We use a visitor to traverse the parse + tree and build our AST. +- **JavaAstVisitor**: A visitor that we use to traverse the parse tree and build + our AST. We define our + visitors [here](https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/JavaAstVisitor.java). + +## Java Grammar Update Procedure + +Let's walk through an example of updating the Java grammar to support a new language feature. We +will use the `when` +expression as an example: https://openjdk.org/jeps/441. + +### Review the JEP and JLS + +It is good to first take some time to read the JEP to understand the new language feature. +The JEP provides detailed information about the goals and motivations behind the new feature, +And help us to come up with good testing strategies. + +It is also important to review the Java Language Specification (JLS) to understand the syntax +and semantics of the new language feature. The JLS provides the formal definition of the Java +programming language and is the ultimate reference for language features. + +The JLS defines the `when` expression as follows (surrounding context provided for clarity): + +```txt +SwitchBlock: + { SwitchRule {SwitchRule} } + { {SwitchBlockStatementGroup} {SwitchLabel :} } + +SwitchRule: + SwitchLabel -> Expression ; + SwitchLabel -> Block + SwitchLabel -> ThrowStatement + +SwitchBlockStatementGroup: + SwitchLabel : {SwitchLabel :} BlockStatements + +SwitchLabel: + case CaseConstant {, CaseConstant} + case null [, default] + case CasePattern {, CasePattern} [Guard] + default + +CaseConstant: + ConditionalExpression + +CasePattern: + Pattern + +Guard: + when Expression +``` + +### Identify New Tokens and Update Lexer Grammar + +Not every new language feature requires new tokens. But in the case of the `when` expression, +we need to introduce a new token to represent the `when` keyword. This requires an update +to the lexer grammar. + +```antlr +LITERAL_WHEN : 'when' ; +``` + +Notes: + +- We preface literal tokens with `LITERAL_` to distinguish them from other tokens. +- Lexer rules are written in uppercase by convention. + +We will also need to add a +new [TokenType](https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java) +in this case. However, we may not need to always add a token type for every new lexer token, it +depends on the use case. An example would be the `LCURLY` (left curly) token, which is used to +represent the `{`. This token is also a `SLIST` (statement list) in certain contexts. This greatly +eases static analysis, since we do not need to differentiate between the two tokens by checking +their context in checks. Token "reuse" is a common pattern, and helps to avoid code duplication and +having an unnecessarily large number of token types. + +### Update Parser Grammar + +Next, we need to update the parser grammar to understand in what contexts the new tokens should +appear. We need to add a new parser rule for the `when` expression. The `when` expression is +used in the context of a guard in a switch statement or switch expression. We need to update +the `guard` rule to recognize the `when` expression. + +```antlr +guardedPattern + : primaryPattern guard expression + ; + +// we use the `LAND` token to represent the logical `&&` operator +guard: ( LAND | LITERAL_WHEN ); +``` + +Notes: + +- Parser rules are written in lower camel case by convention. +- It is important to consider how many subrules are needed to represent the new language feature. + Due to the recursive nature of parsing, Stackoverflow errors can occur if the grammar is too + complex with too many subrules. +- It is good + to try to strike a balance between the number of subrules, the complexity of the grammar, and the + complexity of JavaAstVisitor to ease maintenance. + +### Update JavaAstVisitor + +Now, our lexer recognizes the `when` keyword, and our parser recognizes the `when` expression. We +have updated +TokenTypes to include `LITERAL_WHEN`. At this point, we are able to parse the new syntax, however, +the new tokens +will not appear in the AST unless we update the JavaAstVisitor. This is because our ANTLR grammar +provides us with a parse tree, which we traverse using the JavaAstVisitor to build our AST. + +```java +@Override +public DetailAstImpl visitGuardedPattern(JavaLanguageParser.GuardedPatternContext ctx) { + // since the `guard` rule is a terminal rule, we need to create a new AST node for it + final DetailAstImpl guardAstNode = flattenedTree(ctx.guard()); + // we add the children of the `primaryPattern` and `expression` rules to the AST node + guardAstNode.addChild(visit(ctx.primaryPattern())); + guardAstNode.addChild(visit(ctx.expression())); + return guardAstNode; +} +``` + +Above is an example of the transformation of the `guardedPattern` rule in the JavaAstVisitor. We +create a new AST node for the `guard` rule, and add the children of the `primaryPattern` and +`expression` rules to the AST node. This is a simplified example, and the actual implementation +may vary depending on the complexity of the rule. + +Notes: + +- When we visit a parser rule context, we have access to all the parse tree elements that + correspond to that rule. We can use this information to build our AST. +- The structure of the AST should be carefully considered; we want to ease static analysis by + providing a clear and concise representation of the source code. We can review existing AST + nodes within other contexts to get an idea of how to structure the AST; however, there is no + strict rules regarding this topic. This part of the process relies heavily on heuristics and + experience. +- In many cases, we can consider the ASTs yielded by visiting the subrule of a given rule to be + the children of the AST node for that rule. This is a common pattern in the JavaAstVisitor; if + we did not visit the subrule, the AST would not get built. + +### Update Tests + +Finally, we need to update our tests to ensure that the new language feature is correctly parsed and +analyzed. You +can find our AST +tests [here](https://github.com/checkstyle/checkstyle/tree/master/src/test/java/com/puppycrawl/tools/checkstyle/grammar). + +Notes: + +- We typically separate tests into directories based on the language level. +- We test the content of the AST only, we generally do not test the actual parse tree. + +## Additional Considerations + +### DetailAstPair + +The `DetailAstPair` class is used to represent a pair of AST nodes. It is used in +the `JavaAstVisitor` to +represent the nested parent-child relationship between AST nodes, especially where there is +recursive nesting of only two to three types of tokens. An example of this is the `qualifiedName` +rule, where the parent node is a `DOT` token and the child nodes are `IDENT` tokens. We use +`DetailAstPair` to represent this relationship in the JavaAstVisitor#visitQualifiedName method. + +### Imaginary Tokens + +We often create "Imaginary tokens" to represent the structure of the source code. These tokens are +not directly generated by the lexer (or parser in most cases) but are used to represent the +structure of the source code in the AST, and ease the process of static analysis. An example of this +is the `EXPR` token; no such token is generated by the lexer, but it is used to represent +expressions in the AST to make it easy for checks to find and analyze expressions. + +Notes: + +- Imaginary tokens are not always necessary, and should be used judiciously. +- Imaginary tokens take on the column and line number of the first child token in the AST. + +### Why we don't use the parse tree directly + +ANTLR generates a parse tree that represents the syntactic structure of the source code. We could +use this parse tree directly to perform static analysis. However, we use the parse tree to build our +AST because it provides a more structured representation of the source code that is easier to +analyze. The AST is designed specifically for static analysis and provides a more convenient +interface for writing checks; it abstracts away the details of the parse tree and provides a +simplified view of the source code. + +### Performance Regressions + +When updating the grammar, we should be mindful of the performance impact of our changes. For that, +we have a CI job that compares the performance of the changes against a baseline. Make sure to +check the results of the performance regression tests after making changes to the grammar. You can +find the tests +[here](https://github.com/checkstyle/checkstyle/blob/master/.ci/check-performance-regression.sh) and +the CI job +[here](https://github.com/checkstyle/checkstyle/blob/master/.github/workflows/check-performance-regression.yml). diff --git a/docs/NEW_LANGUAGE_FEATURE_INTEGRATION_PROCESS.md b/docs/NEW_LANGUAGE_FEATURE_INTEGRATION_PROCESS.md new file mode 100644 index 000000000000..5bb85126908b --- /dev/null +++ b/docs/NEW_LANGUAGE_FEATURE_INTEGRATION_PROCESS.md @@ -0,0 +1,176 @@ +# New Language Feature Check Integration Process + +The ability to parse new language features must be implemented and +merged before following this document. + +Updating check modules and creating new checks to support new language features aligns Checkstyle +with current best practices in the Java community and contributes to +the project's ongoing evolution. This document outlines the procedures +for integrating new language features into Checkstyle, +by updating existing checks and creating new ones. + +--- + +## 1. Analyze Current Check Support for This Java Version + +### 1.1 Review Java Enhancement Proposals (JEPS) + +Review Java Enhancement Proposals (JEPS) related to the new feature. +JEPS provide detailed information about the goals +and motivations behind new language features. +This information can help us understand the feature better and figure out +which checks are most likely to be impacted or what new checks might be needed. +Key concepts to consider: + +- **Problem identification**: Understand what problem the new feature solves to build + insights about which checks are more likely to be impacted. + +- **Impact on Readability**: Assess whether the new feature enhances code readability. + Not all new features will necessarily improve readability, but if this one does, + Checkstyle can promote its use to enhance clarity and reduce verbosity. + +**Examples**: + +- **Check updates**: For unnamed variables (`_`), the JEP guides us to recognize the new role of + the underscore for unnamed variables and avoid flagging the non-use of such variables. + Consequently, we updated `UnusedLocalVariableCheck` to ensure it does not + incorrectly violate unnamed variables. + +- **New checks**: Pattern Matching for `instanceof`, where the newer pattern matching feature + provides a more concise and type-safe alternative to traditional casting. + Ideally, we would consider creating a check + to suggest the use of this new feature if we see the typical `if X instanceof Y` + followed by a typecasting pattern. + +### 1.2 Consider Similar and Related Tokens + +Identify existing tokens that are similar to the new language feature tokens. +This comparison helps to determine which existing checks may be relevant +and require updates to support the new token. Additionally, +we should consider the impact that a new child token may have +on existing checks. By examining the acceptable tokens of existing checks and +comparing them with the new tokens, you can determine which checks are likely to be impacted. + +**Examples**: + +- **Check updates**: When the `RECORD_DEF` token was introduced, + it was reasonable to look at all checks that had `CLASS_DEF` in their acceptable tokens. + +- **Check updates**: When the `TEXT_BLOCK_CONTENT` token was introduced, + it was reasonable to look at all checks that had `STRING_LITERAL` in their acceptable tokens. + +- **Check updates**: When switch expressions were introduced, it was reasonable to look at all + checks that deals with expressions because `LITERAL_SWITCH` may now fall under `EXPR` token. + This requires analyzing the impact of this new child token on existing checks, + such as `InnerAssignmentCheck` + +- **New checks**: When the `ENUM_DEF` token was introduced, + we examined checks that used `ARRAY_INIT` tokens and found that checks + like `NoArrayTrailingComma` were similar. However, it was determined that a new check, + `NoEnumTrailingComma`, was needed to handle enums. + We recommend creating separate checks because they handle different tokens + with distinct specifics, making configuration easier for users and allowing for + more tailored behavior. + +### 1.3 Frequently Impacted Checks + +Certain checks are most likely to be impacted by new language features. +We should analyze the impact on the following frequently affected checks: + +- [IllegalToken](https://checkstyle.org/checks/coding/illegaltoken.html): This check violates the + usage of specified tokens. Since new language features often introduce new tokens, + it's important to review this check. + +- [IllegalTokenText](https://checkstyle.org/checks/coding/illegaltokentext.html): + This check identifies and restricts customizable text patterns in the code. + New language features can provide programmers new ways to add custom text to + the code which would need to be scanned. + +- [Indentation](https://checkstyle.org/checks/misc/indentation.html#Indentation): + As new language features are introduced, it's important to ensure that they + follow proper indentation rules and that this check works as expected when executed on them. + +- [Whitespace](https://checkstyle.org/checks/whitespace/index.html): + This check impacts almost all language constructs by ensuring proper + use of whitespace before, after, or around them. As new language features + introduce new constructs, it's important to review and update this check. + +### 1.4 Discover Similar Checks + +Look for existing checks that address concepts +similar to those introduced by the new language feature. +These checks serve as references for designing and implementing new checks. + +**Examples**: + +- **Identifiers and Naming Conventions**: If the new feature introduces + new tokens involving identifiers, explore existing checks related to naming conventions. + We can create a new similar check to enforce naming conventions for the new feature. + +- **Sizes**: If we have a check that enforces a limit on the number of parameters + a method can have, we created a similar check for the number of record components + to ensure that records do not have an excessive number of components. + +### 1.5 Review Other Static Analysis Tools + +Examining how other static analysis tools handle new language features +can provide valuable insights into best practices and potential pitfalls. +A list to a few of the popular ones: + +- [IntelliJ Inspections](https://www.jetbrains.com/help/idea/code-inspection.html) +- [PMD](https://pmd.github.io/) +- [SonarQube](https://www.sonarqube.org/) + +**Examples**: + +- **Check updates**: IntelliJ IDEA introduced an inspection rule for Java 17 or higher to detect + redundant `strictfp` modifiers. This resulted in the analysis of `RedundantModifierCheck` + to verify if we needed to update it. + +- **New check**: Sonar introduced a [new rule](https://rules.sonarsource.com/java/tag/java21/RSPEC-6916/) + to suggest the use of `when` instead of a single if statement inside + a pattern match body. This resulted in the creation + of a new check `WhenShouldBeUsed` to enforce the use of this new feature. + +### 1.6 Real Usage Examples in Large Projects + +Review real usage examples of the new language feature in large projects. +This helps to identify potential issues and ensures that the checks +are aligned with practical use cases. +A list of representative projects can be found +[here](https://github.com/checkstyle/contribution/tree/master/checkstyle-tester) +in projects files. + +### 1.7 Good Source of Best Practices + +Identify a reliable source of best practices related to the new language feature. +This could include official language documentation and community-driven style guides +such as: + +- [Oracle Java Magazine](https://blogs.oracle.com/javamagazine/) +- [JetBrains blogs](https://blog.jetbrains.com/) +- [Stackoverflow](https://stackoverflow.com/) + +--- + +## 2. How to Create Tracker Issue + +The tracker issue should document and share the results of the analysis +conducted according to the outlined procedures in this document. +It should include sections for each step of the analysis with the result +of all the actions done. These tracker issues should be created for each +new language feature, demonstrating the team's due diligence +in integrating the feature into Checkstyle. +See [#14961](https://github.com/checkstyle/checkstyle/issues/14961) and +[#14942](https://github.com/checkstyle/checkstyle/issues/14942) for reference. + +--- + +## 3. How to Open Child Issues + +Using the findings from the tracker issue, open child issues for each check that needs +to be updated or for a new check related to the new language feature. +This issue should be linked to the tracker issue of this feature. +It is good to follow the bug report template to aid in demonstrating the need for check updates. +See [#14963](https://github.com/checkstyle/checkstyle/issues/14963) and +[#14985](https://github.com/checkstyle/checkstyle/issues/14985) for reference. diff --git a/docs/TestingTechniques.md b/docs/TestingTechniques.md new file mode 100644 index 000000000000..f29b4091cb8c --- /dev/null +++ b/docs/TestingTechniques.md @@ -0,0 +1,171 @@ +# Checkstyle's testing techniques + +----------- +[The video walkthrough of this page with an example](https://youtu.be/CoMKo1X5daU?si=N9dvNW_sE83gHXKS) + +## Test Driven Development (TDD) + +**TDD** is one of the encouraged ways to efficiently make new implementations for Checkstyle. + +With **TDD**, you create the test prior the implementation that it will test. Created test then +serves as a door to the module's source code, which we can access by using the debug tool and +reproduce its execution piece by piece. + +**TDD** in turn provides a precise experiment field for bringing new implementation to the module, +allowing to develop with respect to that test's results. + +## Where Checkstyle's tests are located + +The directory with tests that we need are located in +`src/test/java/com/puppycrawl/tools/checkstyle/,,,`. What follows after is the +relative path of the module that the needed tests belong to. + +- Tests are organized into module data collection files. Each such collection file stores all + of the tests for certain module +- Name format for such collection files is: `[ModuleClassName]Test` where `[...]` indicates you + paste your own option inside + +## Test structure + +Each method with `test` prefix in module data collection files represents distinct test. Such test +methods come in the following common structure: + +```text +@Test +public void test[NameOfTest]() throws Exception { + final String[] expected = { + ... + } + verifyWithInlineConfigParser( + getPath("InputFile.java"), expected); +} +``` + +### Let's go over each essential part of the test method structure + +### 1. Input file + +Input files are files that are being tested by the test. + +All input files are located in same `src/test` +directory, but in `resources` or`resources-noncompilable` folders. + +- At this moment, Checkstyle uses jdk 17 as its operating version, and all input files that can + be compiled at jdk 17 or older go to `resources`, while those input files that require newer + versions of jdk to compile go to `resources-noncompilable`. + +Input files are named in the following format: `Input[ModuleName][FileNickname].java` + +- **Ex.** the input file name with a nickname of "Class" for AnnotationLocation check + would be: `InputAnnotationLocationClass.java` +- Although you can put anything for `[FileNickname]`, it is encouraged + that nickname is the same or at least has resemblance to the test's name it belongs to. + +### 2. Expected violations + +- The String array, `String[] expected`, contains the violation messages that we *expect* to + receive from the test. +- These are not always the violation messages that are guaranteed + to come out of test, but rather the violation messages that test *should* give if we assume + that all necessary implementation for that test's module is correctly in effect. +- The format for expected violation message element in `expected` array is:\ + `"lineNumber:columnNumber: " + ` + +### 3. Verification + +Once input file and expected violations are properly connected to the test, it's time for the +verify method (usually `verifyWithInlineConfigParser()`) to attempt to use Checkstyle to analyze +input file, get *actual* violations that it detects with current implementation, and at the end +compare actual results with the expected. If actual results differ from the expected, the test +fails, and explains where exactly was the inconsistency. + +## Input file structure and Behavior Driven Development + +Checkstyle input files have the following abstract structure: + +```text +/* +... +config +... +*/ + +package [inputPathPackage] + ... + +public class InputFileName { + ... + ... + ... // violation, '...' + ... +} +``` + +This structure manifests the concept of **Behavior Driven Development (BDD)**. **BDD** simulates +the results of **before**, **during**, and **after** states of execution in an illustrative way. +This makes it easier for developers to access and be aware of source's status on each phase of +execution. + +### For input files, these states are implemented in 3 parts + +#### Config (Before) + +Enclosed in block comments `/* ... */` at beginning of file, config represents the **before** +state of the input file as it shows the settings used for the module to run on the code. + +There are various types/formats of configs such as `property`, `XML`, and `java`. However, in +regular tests, the `property` format is required to be used at all times, unless there is an +exception such as when module has no properties (because property config requires at least some +property to be defined), then `XML` format is used. `Java` config format is the last resort if +others don't help, being defined outside the input file in the test method and thus violating the +BDD. + +The `property`config format has the following layout: + +```text +/* +ModuleName +propertyName = propertyValue +otherPropertyName = (default)otherPropertyDefaultValue +... +lastPropertyName = lastPropertyValue + +*/ +``` + +**Note:** Although not shown here, it is encouraged to leave **2** blank lines at the end of +the config before closing comment block to avoid having to change consequent violation lines when +new property is added. + +#### Tested Code (During) + +Next after config comes the rest of the Java source code that serves the **during** state of +input file's BDD. This is the intended piece to be tested and to be covered by the running test's +scope. + +#### Violation marking (After) + +The final part represents the **after** state of input file by showing the intended results of the +test using specific `// violation` comment marking on same lines of code that intend to cause the +violation. + +The format of violation comment is: `// violation, 'violation message'` where violation message +has to belong to any of the module's existing violation message options, but not necessarily +be entirely written out between the quotes but at least just some part. + +## Conclusion + +Once you have the test set up properly, you now have the handy tool for accurately analyzing +the module by using test to access the module's source in real time. + +- To do so, place breakpoint anywhere in the module's source and run test method with debug. + This will get you to that point of module's source in debug mode. + +This **Test Driven Development** technique with collaboration of debug fits well for solving +various module problems from corresponding issues that give you already prepared information for +creating the input file and the test to solve that problem. + +To watch the live moment on applying TDD to solve module's problem, you can take a look at the +[2nd part of video tutorial](https://youtu.be/VnenZbbh1WU?si=wjNjKpMm9WyqQX1C) mentioned at the +beginning of this page. diff --git a/mvnw b/mvnw new file mode 100755 index 000000000000..d0d0f6b5e0d0 --- /dev/null +++ b/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } +END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" \ No newline at end of file diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 000000000000..249bdf382222 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml index 6a9b517ea35b..c3c6fbb8fd0d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,6 +1,6 @@ - + 4.0.0 @@ -12,7 +12,7 @@ com.puppycrawl.tools checkstyle - 8.31-SNAPSHOT + 12.1.3-SNAPSHOT jar checkstyle @@ -24,8 +24,8 @@ 2001 - LGPL-2.1+ - http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt + LGPL-2.1-or-later + https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt @@ -51,25 +51,39 @@ developer + + strkkk + Andrei Paikin + + developer + + + + nrmancuso + Nick Mancuso + + former project admin, developer + + sabaka Ilja Dubinin - developer + former developer MEZk Andrei Selkin - developer + former developer Vladlis Vladislav Lisetskii - developer + former developer @@ -157,13 +171,6 @@ - - checkstyle-announce - https://groups.google.com/forum/#!forum/checkstyle-announce - mailto:checkstyle-announce%2Bsubscribe@googlegroups.com - mailto:checkstyle-announce%2Bunsubscribe@googlegroups.com - privilege of admins - checkstyle https://groups.google.com/forum/#!forum/checkstyle @@ -189,49 +196,121 @@ GitHub Issues https://github.com/checkstyle/checkstyle/issues - - travis - https://travis-ci.org/checkstyle/checkstyle - - UTF-8 UTF-8 + ${project.version} - 4.8-1 - 3.8.2 - 3.1.12.2 - 3.13.0 - 6.21.0 - 0.8.5 - 2.0.5 - 9.9.1-6 - 3.1.1 - 1.37.1 + 4.13.2 + 3.21.0 + 4.9.8.1 + 3.28.0 + 7.18.0 + 0.8.14 + 5.2.0 + 1.7.32 + 12.9 + 3.6.0 + 1.44.1 - 8.29 + 10.4 - 2.7 - 1.8 - 1.4.9 + 2.19.1 + 3.14.1 + true + 1.0.0-SNAPSHOT + 17 + 21 + ${java.version} + 1.21.1 10 + HTML,XML 50000 4 - 0.10 + 1.2.3 + 1.0.6 **/test/resources/**/*,**/it/resources/**/* - 5.6.0 + 6.0.1 + 3.10 + 1.2.0 + 3.52.0 + 2.44.0 + 0.26.0 + 1.12.0 + + -Xep:AmbiguousJsonCreator:ERROR + -Xep:AssertJNullnessAssertion:ERROR + -Xep:AutowiredConstructor:ERROR + -Xep:CanonicalAnnotationSyntax:ERROR + -Xep:CollectorMutability:ERROR + -Xep:ConstantNaming:ERROR + -Xep:DefaultCharset:ERROR + -Xep:DirectReturn:ERROR + -Xep:EmptyMethod:ERROR + -Xep:EnumOrdinal:ERROR + -Xep:ExplicitArgumentEnumeration:ERROR + -Xep:ExplicitEnumOrdering:ERROR + -Xep:FormatStringConcatenation:ERROR + -Xep:IdentityConversion:ERROR + -Xep:ImmutablesSortedSetComparator:ERROR + -Xep:IsInstanceLambdaUsage:ERROR + -Xep:LexicographicalAnnotationAttributeListing:ERROR + -Xep:LexicographicalAnnotationListing:ERROR + -Xep:MockitoMockClassReference:ERROR + -Xep:MockitoStubbing:ERROR + -Xep:NestedOptionals:ERROR + -Xep:OptionalOrElseGet:ERROR + -Xep:PrimitiveComparison:ERROR + -Xep:RedundantStringConversion:ERROR + -Xep:RedundantStringEscape:ERROR + -Xep:ReferenceEquality:ERROR + -Xep:Slf4jLogStatement:ERROR + -Xep:StreamResourceLeak:ERROR + -Xep:StringJoin:ERROR + -Xep:StringJoining:ERROR + -Xep:TimeZoneUsage:ERROR + -Xep:TruthAssertExpected:ERROR + -Xep:TypeParameterUnusedInFormals:ERROR + -Xep:UnusedMethod:ERROR + -Xep:VoidUsed:ERROR + + -Xep:EqualsGetClass:WARN + -Xep:InlineFormatString:WARN + -Xep:JdkObsolete:WARN + -Xep:StatementSwitchToExpressionSwitch:WARN + -Xep:StringSplitter:WARN + -Xep:EffectivelyPrivate:WARN + + -Xep:JUnitClassModifiers:OFF + + -Xep:JUnitMethodDeclaration:OFF + + -Xep:JUnitValueSource:OFF + + -Xep:StaticImport:OFF + + -Xep:InvalidBlockTag:OFF + + -Xep:OperatorPrecedence:OFF + + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + info.picocli picocli - 4.2.0 - - - antlr - antlr - 2.7.7 + 4.7.7 org.antlr @@ -241,101 +320,119 @@ commons-beanutils commons-beanutils - 1.9.4 + 1.11.0 + + + commons-logging + commons-logging + + com.google.guava guava - 28.2-jre + 33.5.0-jre + + + org.checkerframework + checker-qual + + org.apache.ant ant - 1.10.7 + 1.10.15 provided + + org.reflections + reflections + 0.10.2 + org.junit.jupiter junit-jupiter-api - ${junit.version} test org.junit.jupiter junit-jupiter-engine - ${junit.version} test org.itsallcode junit5-system-extensions - 1.1.0 + 1.2.2 test org.junit-pioneer junit-pioneer - 0.5.4 + 2.3.0 test - - org.junit.vintage - junit-vintage-engine - ${junit.version} + com.tngtech.archunit + archunit-junit5 + 1.4.1 test - com.google.truth - truth - 1.0.1 + com.github.caciocavallosilano + cacio-tta + 1.18 test + + + com.jidesoft + jide-oss + + - - com.github.stefanbirkner - system-rules - 1.19.0 + com.google.truth + truth + 1.4.4 test nl.jqno.equalsverifier equalsverifier - 3.1.12 - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} + 4.2.2 test - - org.powermock - powermock-module-junit4 - ${powermock.version} + org.mockito + mockito-inline + ${mockito.version} test commons-io commons-io - 2.6 + 2.21.0 test org.eclipse.jgit org.eclipse.jgit - 5.6.1.202002131546-r + 7.4.0.202509020913-r test + + org.slf4j + slf4j-api + ${slf4j.version} + runtime + org.slf4j slf4j-simple - 1.7.30 - test + ${slf4j.version} + runtime org.jacoco @@ -344,6 +441,12 @@ runtime test + + de.thetaphi + forbiddenapis + ${forbiddenapis.version} + test + net.sf.saxon Saxon-HE @@ -353,6 +456,47 @@ com.ibm.icu icu4j + + xml-apis + xml-apis + + + org.slf4j + slf4j-api + + + + + org.checkerframework + checker-qual + ${checkerframework.version} + + + org.apache.maven.doxia + doxia-core + ${doxia.version} + + + + commons-codec + commons-codec + + + com.google.collections + google-collections + + + + + org.apache.maven.doxia + doxia-module-xdoc + ${doxia.version} + + + com.google.collections + google-collections + @@ -369,21 +513,24 @@ - + org.apache.maven.plugins maven-antrun-plugin - 1.8 + 3.2.0 + org.apache.maven.plugins maven-assembly-plugin - 3.2.0 + 3.7.1 + org.apache.maven.plugins maven-dependency-plugin - 3.1.1 + 3.9.0 maven-release-plugin @@ -395,23 +542,28 @@ org.codehaus.mojo exec-maven-plugin - 1.6.0 + 3.6.2 org.codehaus.mojo sonar-maven-plugin - 3.7.0.1746 + 3.9.1.2184 org.apache.maven.plugins maven-shade-plugin - 3.2.2 + 3.6.1 org.pitest pitest-maven ${pitest.plugin.version} + + com.groupcdg.pitest + pitest-accelerator-junit5 + ${pitest.accelerator.junit5.plugin.version} + org.pitest pitest-junit5-plugin @@ -422,19 +574,55 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.1.1 + 3.12.0 + + + com.puppycrawl.tools.checkstyle.grammar.java: + com.puppycrawl.tools.checkstyle.grammar.javadoc: + ${java.version} + private true + true + -missing true noinspection X + + noinspectionreason + X + + + propertySince + X + + + com.diffplug.spotless + spotless-maven-plugin + 3.0.0 + + + + + + config/spotless/import.order + + + config/spotless/licence.header + + + + true + + + org.apache.maven.plugins maven-pmd-plugin @@ -454,6 +642,7 @@ src/it/resources src/test/resources + src/xdocs-examples/resources target/generated-sources/antlr target/generated-sources/antlr/com/puppycrawl/tools/checkstyle/grammar/javadoc @@ -492,6 +681,13 @@ Low config/spotbugs-exclude.xml target/spotbugsreports + + + com.mebigfatguy.sb-contrib + sb-contrib + 7.6.15 + + @@ -518,19 +714,6 @@ - - - org.codehaus.mojo - antlr-maven-plugin - [1.0,) - - generate - - - - - - org.antlr @@ -546,19 +729,6 @@ - - - org.codehaus.mojo - exec-maven-plugin - [1.0,) - - java - - - - - - org.apache.maven.plugins @@ -589,54 +759,63 @@ + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.1 + + + attach-sources + + test-jar + jar + + + + + - - org.apache.maven.plugins - maven-checkstyle-plugin - ${maven.checkstyle.plugin.version} - - - com.github.sevntu-checkstyle - sevntu-checks - ${maven.sevntu.checkstyle.plugin.version} - - - com.puppycrawl.tools - checkstyle - ${maven.sevntu-checkstyle-check.checkstyle.version} - - - + com.diffplug.spotless + spotless-maven-plugin + + + org.codehaus.plexus + plexus-component-metadata + 2.2.0 + + + + generate-metadata + + + + + + org.gaul + modernizer-maven-plugin + 3.2.0 + + ${java.version} + false + + + java/util/Optional.get:.* + + java/io/File.* + java/nio/file/Paths.get:.* + + - sevntu-checkstyle-check + modernizer verify - - - ${project.basedir}/config/checkstyle_sevntu_checks.xml - - true - false - false - true - 0 - error - project.basedir=${project.basedir} - - ${project.basedir}/src - - - **/it/resources/**/*,**/it/resources-noncompilable/**/*, - ,**/test/resources/**/*,**/test/resources-noncompilable/**/* - - - check + modernizer @@ -645,13 +824,13 @@ org.apache.maven.plugins maven-clean-plugin - 3.1.0 + 3.5.0 org.codehaus.mojo tidy-maven-plugin - 1.1.0 + 1.4.0 validate @@ -666,16 +845,16 @@ org.apache.maven.plugins maven-resources-plugin - 3.1.0 + 3.3.1 - copy-resources + copy-dtd-resources pre-site copy-resources - ${basedir}/target/site/dtds + ${project.basedir}/target/site/dtds src/main/resources/com/puppycrawl/tools/checkstyle @@ -694,63 +873,43 @@ + + copy-xsd-resources + pre-site + + copy-resources + + + ${project.basedir}/target/site/xsds + + + config + + configuration*.xsd + checkstyle-report-*.xsd + + + + + org.apache.maven.plugins maven-compiler-plugin - 3.8.1 + ${maven.compiler.plugin.version} - ${java.version} - ${java.version} + + -Xpkginfo:always + - org.apache.maven.plugins maven-install-plugin - 2.5.2 + 3.1.4 @@ -782,7 +941,7 @@ org.apache.maven.plugins maven-deploy-plugin - 2.8.2 + 3.1.4 org.codehaus.mojo @@ -790,7 +949,7 @@ ${maven.versions.plugin.version} false - file://${basedir}/config/version-number-rules.xml + file://${project.basedir}/config/version-number-rules.xml xml html @@ -822,18 +981,6 @@ report - - - - com/puppycrawl/tools/checkstyle/grammar/*.class - com/puppycrawl/tools/checkstyle/grammar/javadoc/*.class - - com/puppycrawl/tools/checkstyle/JavadocDetailNodeParser$JavadocParserErrorStrategy.class - - - com/puppycrawl/tools/checkstyle/gui/*.class - - default-check @@ -845,18 +992,30 @@ CLASS + + + com.puppycrawl.tools.checkstyle.api.AutomaticBean* + + + com.puppycrawl.tools.checkstyle.site.* - com.puppycrawl.tools.checkstyle.grammar.GeneratedJavaRecognizer + com.puppycrawl.tools.checkstyle.grammar.java.JavaLanguageParser* + + + com.puppycrawl.tools.checkstyle.grammar.java.JavaLanguageLexer - com.puppycrawl.tools.checkstyle.grammar.GeneratedJavaLexer - com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocParser* + com.puppycrawl.tools.checkstyle.CheckstyleParserErrorStrategy - com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocLexer - com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.JavadocParserErrorStrategy + com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocCommentsParser* + com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocCommentsLexer + com.puppycrawl.tools.checkstyle.JavadocCommentsAstVisitor + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsParserUtil + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsLexerUtil + com.puppycrawl.tools.checkstyle.grammar.SimpleToken com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck @@ -864,17 +1023,28 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.RegularClass - com.puppycrawl.tools.checkstyle.gui.BaseCellEditor* + com.puppycrawl.tools.checkstyle.gui.BaseCellEditor com.puppycrawl.tools.checkstyle.gui.CodeSelector - com.puppycrawl.tools.checkstyle.gui.TreeTable* - com.puppycrawl.tools.checkstyle.gui.ListToTreeSelectionModelWrapper* + com.puppycrawl.tools.checkstyle.gui.ListToTreeSelectionModelWrapper + + com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel + com.puppycrawl.tools.checkstyle.gui.TreeTable + + com.puppycrawl.tools.checkstyle.gui.TreeTable.TreeTableCellEditor + + com.puppycrawl.tools.checkstyle.gui.TreeTableCellRenderer + com.puppycrawl.tools.checkstyle.gui.TreeTableModelAdapter + + com.puppycrawl.tools.checkstyle.gui.TreeTableModelAdapter.UpdatingTreeModelListener - com.puppycrawl.tools.checkstyle.gui.Main* - com.puppycrawl.tools.checkstyle.gui.MainFrame* - com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel* - com.puppycrawl.tools.checkstyle.gui.TreeTableCellRenderer* - com.puppycrawl.tools.checkstyle.gui.TreeTableModelAdapter* + + com.puppycrawl.tools.checkstyle.meta.MetadataGeneratorUtil + com.puppycrawl.tools.checkstyle.meta.ModuleDetails* + com.puppycrawl.tools.checkstyle.meta.JavadocMetadataScraperUtil* + com.puppycrawl.tools.checkstyle.meta.XmlMeta* + + com.puppycrawl.tools.checkstyle.utils.OsSpecificUtil @@ -889,79 +1059,78 @@ + CLASS - - com.puppycrawl.tools.checkstyle.grammar.GeneratedJavaRecognizer - + com.puppycrawl.tools.checkstyle.meta.MetadataGeneratorUtil LINE COVEREDRATIO - 0.96 + 0.85 BRANCH COVEREDRATIO - 0.73 + 0.80 CLASS - com.puppycrawl.tools.checkstyle.grammar.GeneratedJavaLexer + com.puppycrawl.tools.checkstyle.gui.BaseCellEditor LINE COVEREDRATIO - 0.96 + 0.76 BRANCH COVEREDRATIO - 0.79 + 0.75 CLASS - - com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocParser - + com.puppycrawl.tools.checkstyle.gui.CodeSelector LINE COVEREDRATIO - 0.54 + 0.91 BRANCH COVEREDRATIO - 0.44 + 0.50 CLASS - com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocLexer + + com.puppycrawl.tools.checkstyle.gui.ListToTreeSelectionModelWrapper + LINE COVEREDRATIO - 0.84 + 0.74 BRANCH COVEREDRATIO - 0.64 + 0.35 @@ -969,39 +1138,91 @@ CLASS - com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser.JavadocParserErrorStrategy + com.puppycrawl.tools.checkstyle.gui.ParseTreeTableModel LINE COVEREDRATIO - 0.50 + 0.91 BRANCH COVEREDRATIO - 1.00 + 0.83 CLASS - - com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck - + com.puppycrawl.tools.checkstyle.gui.TreeTable LINE COVEREDRATIO - 0.98 + 0.89 BRANCH COVEREDRATIO - 0.94 + 0.54 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.gui.TreeTable.TreeTableCellEditor + + + + LINE + COVEREDRATIO + 0.06 + + + BRANCH + COVEREDRATIO + 0.00 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.gui.TreeTableCellRenderer + + + + LINE + COVEREDRATIO + 0.46 + + + BRANCH + COVEREDRATIO + 0.20 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.gui.TreeTableModelAdapter + + + + LINE + COVEREDRATIO + 0.86 + + + BRANCH + COVEREDRATIO + 1.00 @@ -1009,41 +1230,302 @@ CLASS - com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.RegularClass + com.puppycrawl.tools.checkstyle.gui.TreeTableModelAdapter.UpdatingTreeModelListener LINE COVEREDRATIO - 0.70 + 0.45 BRANCH COVEREDRATIO - 0.00 + 1.00 - - - + + CLASS + + + com.puppycrawl.tools.checkstyle.grammar.java.JavaLanguageParser + + + + + LINE + COVEREDRATIO + 0.80 + + + BRANCH + COVEREDRATIO + 0.71 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.grammar.java.JavaLanguageLexer + + + + LINE + COVEREDRATIO + 0.80 + + + BRANCH + COVEREDRATIO + 0.75 + + + + + CLASS + + + com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocCommentsParser + + + + + LINE + COVEREDRATIO + 0.57 + + + BRANCH + COVEREDRATIO + 0.48 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocCommentsLexer + + + + LINE + COVEREDRATIO + 0.80 + + + BRANCH + COVEREDRATIO + 0.64 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.JavadocCommentsAstVisitor + + + + LINE + COVEREDRATIO + 0.97 + + + BRANCH + COVEREDRATIO + 0.97 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.grammar.SimpleToken + + + + LINE + COVEREDRATIO + 0.88 + + + BRANCH + COVEREDRATIO + 0.70 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsLexerUtil + + + + LINE + COVEREDRATIO + 0.90 + + + BRANCH + COVEREDRATIO + 0.92 + + + + + CLASS + + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsParserUtil + + + + LINE + COVEREDRATIO + 0.50 + + + BRANCH + COVEREDRATIO + 0.50 + + + + + CLASS + + + com.puppycrawl.tools.checkstyle.CheckstyleParserErrorStrategy + + + + + LINE + COVEREDRATIO + 0.50 + + + BRANCH + COVEREDRATIO + 1.00 + + + + + CLASS + + + com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck + + + + + LINE + COVEREDRATIO + 0.98 + + + BRANCH + COVEREDRATIO + 0.94 + + + + + CLASS + + + com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.RegularClass + + + + + LINE + COVEREDRATIO + 0.70 + + + BRANCH + COVEREDRATIO + 0.00 + + + + + + CLASS + + + com.puppycrawl.tools.checkstyle.meta.JavadocMetadataScraperUtil + + + + + BRANCH + COVEREDRATIO + 0.90 + + + + + CLASS + + + com.puppycrawl.tools.checkstyle.meta.XmlMetaWriter + + + + + LINE + COVEREDRATIO + 0.91 + + + BRANCH + COVEREDRATIO + 0.75 + + + + + CLASS + + + com.puppycrawl.tools.checkstyle.meta.XmlMetaReader + + + + + LINE + COVEREDRATIO + 0.95 + + + BRANCH + COVEREDRATIO + 0.93 + + + + + + - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.8 - true - - - sonatype-nexus-staging - https://oss.sonatype.org/ - true - + org.sonatype.central + central-publishing-maven-plugin + 0.9.0 + true + + central + true + @@ -1051,7 +1533,6 @@ maven-site-plugin ${maven.site.plugin.version} - ${basedir}/src/xdocs true @@ -1059,7 +1540,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.0.0-M3 + 3.6.2 enforce-versions @@ -1069,11 +1550,20 @@ - 1.8 + ${java.version} - 3.0.1 + 3.6.3 + + + + org.apache.maven.doxia:doxia-core + org.apache.commons* + org.apache.httpcomponents* + org.codehaus.plexus* + + - - - org.codehaus.mojo - antlr-maven-plugin - 2.2 - - - ${basedir}/src/main/resources/com/puppycrawl/tools/checkstyle/grammar - - java.g - - - - - generate - - - - - org.antlr antlr4-maven-plugin ${antlr4.version} - false + true false - ${basedir}/src/main/resources/ + ${project.basedir}/src/main/resources/ ${project.build.directory}/generated-sources/antlr/ com/puppycrawl/tools/checkstyle/grammar/javadoc/*.g4 + com/puppycrawl/tools/checkstyle/grammar/java/*.g4 @@ -1143,7 +1614,7 @@ org.codehaus.mojo build-helper-maven-plugin - 3.0.0 + 3.6.1 add-source @@ -1164,6 +1635,7 @@ add-test-source + ${checkstyle.skipCompileInputResources} src/test/resources @@ -1188,18 +1660,44 @@ add-test-source + ${checkstyle.skipCompileInputResources} src/it/resources - + + add-xdocs-examples-source + process-resources + + add-test-source + + + + src/xdocs-examples/java + + + + + add-xdocs-examples-resource + process-resources + + add-test-source + + + ${checkstyle.skipCompileInputResources} + + src/xdocs-examples/resources + + + + org.apache.maven.plugins maven-failsafe-plugin - 2.22.2 + 3.5.4 com/google/**/*.java @@ -1226,11 +1724,35 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.2 + 3.5.4 + -Dfile.encoding=UTF-8 ${surefire.options} ${project.build.directory}/jacoco.exec + + com.github.caciocavallosilano.cacio.ctc.CTCToolkit + false + + com.github.caciocavallosilano.cacio.ctc.CTCGraphicsEnvironment + + + --add-exports=java.desktop/java.awt=ALL-UNNAMED + --add-exports=java.desktop/java.awt.peer=ALL-UNNAMED + --add-exports=java.desktop/sun.awt.image=ALL-UNNAMED + --add-exports=java.desktop/sun.java2d=ALL-UNNAMED + --add-exports=java.desktop/java.awt.dnd.peer=ALL-UNNAMED + --add-exports=java.desktop/sun.awt=ALL-UNNAMED + --add-exports=java.desktop/sun.awt.event=ALL-UNNAMED + --add-exports=java.desktop/sun.awt.datatransfer=ALL-UNNAMED + --add-exports=java.base/sun.security.action=ALL-UNNAMED + --add-opens=java.base/java.util=ALL-UNNAMED + --add-opens=java.desktop/java.awt=ALL-UNNAMED + --add-opens=java.desktop/sun.java2d=ALL-UNNAMED + --add-opens=java.base/java.lang.reflect=ALL-UNNAMED + -XX:+EnableDynamicAgentLoading + -Xshare:off + src/test/resources-noncompilable @@ -1255,35 +1777,34 @@ - - + - - - org.apache.ant - ant-nodeps - 1.8.1 - - org.apache.maven.plugins maven-jar-plugin - 3.2.0 + 3.4.2 true true + + ${project.groupId}.${project.artifactId} + + + **/Input*.* + **/Expected*.* + @@ -1294,6 +1815,12 @@ + + + org.apache.maven.plugins + maven-source-plugin + + org.apache.maven.plugins maven-eclipse-plugin @@ -1332,24 +1859,67 @@ org.codehaus.mojo xml-maven-plugin - 1.0.2 + 1.2.0 validate + check-format strict + + false + + + . + + **/*.xml + **/*.xsd + **/*.xml.vm + + + + .git/** + + src/site/xdoc/** + + target/** + .ci-temp/** + + src/test/resources/** + src/xdocs-examples/resources/** + + src/site/xdoc/releasenotes.xml + src/site/xdoc/releasenotes_old*.xml + src/main/resources/com/puppycrawl/tools/checkstyle/meta/** + + + config + archunit-store/** + codenarc-rules.groovy.txt + google-java-format/** + intellij-idea-inspections.properties + java-regexp.header java.header - java_regexp.header + jsoref-spellchecker/** + markdownlint.rb + openrewrite-recipes-checkstyle.properties org.eclipse.jdt.core.prefs - intellij-idea-inspections.properties + projects-to-test/** + signatures-test.txt + signatures.txt + spotless/import.order + spotless/licence.header + yamllint.yaml + + linkcheck-suppressions.txt @@ -1362,7 +1932,7 @@ site.xml - .ci/travis/decoration-1.0.0.xsd + config/site-2.0.0.xsd true @@ -1383,6 +1953,15 @@ google_checks.xml sun_checks.xml + config/configuration-1-3.xsd + + + true + src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger + + *.xml + + config/checkstyle-report-1.0.0.xsd @@ -1394,7 +1973,7 @@ de.thetaphi forbiddenapis - 2.7 + ${forbiddenapis.version} ${java.version} false @@ -1404,33 +1983,145 @@ jdk-system-out jdk-non-portable - - - **/Main.class - **/MainTest.class - **/Main$CliOptions.class - **/JavadocPropertiesGenerator.class - - **/GeneratedJavaLexer.class - **/JavadocParser.class - **/Input* - - **/XpathFileGeneratorAuditListenerTest.class - + forbiddenapis-main + verify check + + + + ${project.basedir}/config/signatures.txt + + + + **/Main.class + **/Main$CliOptions.class + **/JavadocPropertiesGenerator.class + + **/JavadocCommentsParser.class + + **/RegexpCheck.class + + **/NoCodeInFileCheck.class + + **/AbstractJavadocCheck.class + **/AtclauseOrderCheck.class + **/JavadocBlockTagLocationCheck.class + **/JavadocLeadingAsteriskAlignCheck.class + **/JavadocMethodCheck.class + **/JavadocMissingLeadingAsteriskCheck.class + **/JavadocMissingWhitespaceAfterAsteriskCheck.class + **/JavadocParagraphCheck.class + **/JavadocStyleCheck.class + **/JavadocTagContinuationIndentationCheck.class + **/JavadocTypeCheck.class + **/MissingDeprecatedCheck.class + **/NonEmptyAtclauseDescriptionCheck.class + **/RequireEmptyLineBeforeBlockTagGroupCheck.class + **/SingleLineJavadocCheck.class + **/SummaryJavadocCheck.class + **/WriteTagCheck.class + **/JavadocMetadataScraperUtil.class + + + + + forbiddenapis-test + verify + testCheck + + + ${project.basedir}/config/signatures-test.txt + + + **/Example* + **/Input* + + **/MainTest.class + + **/XpathFileGeneratorAuditListenerTest.class + **/AllChecksTest.class + + **/DefaultConfigurationTest.class + + **/MetadataGeneratorUtilTest.class + + + **/UniquePropertiesCheckTest.class + **/OrderedPropertiesCheckTest.class + + + **/RegexpMultilineCheckTest.class + **/RegexpCheckTest.class + + + **/SuppressWithPlainTextCommentFilterTest.class + **/NewlineAtEndOfFileCheckTest.class + + + **/IndentationCheckTest.class + + + **/NoCodeInFileCheckTest.class + + + **/RegexpOnFilenameCheckTest.class + + + **/OneStatementPerLineCheckTest.class + + + **/AbstractModuleTestSupport.class + + + **/EmptyLineSeparatorCheckTest.class + + + **/HeaderCheckTest.class + + **/RegexpHeaderCheckTest.class + + **/MultiFileRegexpHeaderCheckTest.class + + edu.illinois nondex-maven-plugin - 1.1.1 + 2.2.1 + + + + com.groupon.maven.plugin.json + json-schema-validator + ${json-schema-validator.version} + + + verify + + validate + + + + + + + ${project.basedir}/src/test/resources/com/puppycrawl/tools/checkstyle/sariflogger + https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json + + **/*.sarif + + + + @@ -1438,11 +2129,13 @@ + org.apache.maven.plugins maven-project-info-reports-plugin - 3.0.0 + 3.9.0 + org.apache.maven.plugins maven-javadoc-plugin @@ -1466,28 +2159,34 @@ org.apache.maven.plugins maven-surefire-report-plugin - 2.22.2 + 3.5.4 + + + + report-only + + + org.apache.maven.plugins maven-jxr-plugin - 3.0.0 + 3.6.0 org.codehaus.mojo jdepend-maven-plugin - 2.0 + 2.1 org.codehaus.mojo taglist-maven-plugin - 2.4 + 3.2.1 - - true + **/*/checks/TodoCommentCheck.java @@ -1508,15 +2207,6 @@ - - org.codehaus.sonar-plugins - maven-report - 0.1 - - https://sonarcloud.io - - - org.apache.maven.plugins maven-pmd-plugin @@ -1594,19 +2284,21 @@ https://paypal.com/ http://www.mojohaus.org/exec-maven-plugin + http://www.mojohaus.org/versions-maven-plugin + http://www.mojohaus.org/xml-maven-plugin - https://travis-ci.org/ - https://travis-ci.org/checkstyle/checkstyle https://coveralls.io/r/checkstyle/checkstyle - + https://github.com/* + http://jeremymanson.blogspot.com/* + https://javarevisited.blogspot.com/* + https://webtoolkit.googleblog.com/* https://help.github.com/* http://search.maven.org/* - + http://sonar-plugins.codehaus.org/maven-report http://www.mojohaus.org/sonar-maven-plugin/sonar-maven-plugin @@ -1614,19 +2306,20 @@ http://mojo.codehaus.org/antlr-maven-plugin - - http://mojo.codehaus.org/jdepend-maven-plugin + + + https://www.mojohaus.org/jdepend-maven-plugin/jdepend-maven-plugin + http://mojo.codehaus.org/taglist-maven-plugin - http://www.antlr.org/antlr4-maven-plugin + https://www.antlr.org/antlr4-maven-plugin/ - http://maven.apache.org/plugins/maven-release-plugin/ - + https://maven.apache.org/plugins/maven-release-plugin/ + http://jacoco-maven-plugin/ @@ -1636,20 +2329,18 @@ https://twitter.com/checkstyle_java/ - - https://flattr.com/submit/ - - https://button.flattr.com/flattr-badge-large.png http://tide.olympe.in/* http://dl.acm.org/* https://git-scm.com + + https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.28 https://plus.google.com/+CheckstyleJava + this link does not look like permanent, it is better to keep the existing link --> https://marketplace.atlassian.com/apps/1214095/checkstyles-for-bitbucket-server @@ -1659,12 +2350,57 @@ https://wiki.jenkins.io/display/JENKINS/Checkstyle+Plugin https://gradle.org + https://www.codacy.com/ https://docs.gradle.org/current/userguide/checkstyle_plugin.html https://www.w3.org/TR/* + + https://maven.apache.org/* + + https://bitbucket.org/atlassian/bamboo-checkstyle-plugin + + https://www.manning.com/books/java-development-with-ant + + https://opencollective.com/* + + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + https://liberapay.com/checkstyle/ + + https://www.jarchitect.com + + http://maven.apache.org/plugins/maven-release-plugin/ + http://maven.apache.org/plugins/maven-deploy-plugin/ + http://maven.apache.org/plugins/maven-eclipse-plugin/ + http://maven.apache.org/plugins/maven-install-plugin/ + http://maven.apache.org/plugins/maven-linkcheck-plugin/ + http://www.mojohaus.org/build-helper-maven-plugin/ + + https://www.mojohaus.org/exec-maven-plugin + + https://www.eclipse.org/legal/epl-v20.html + + https://www.ej-technologies.com/* + https://stackoverflow.com/questions/* + + https://docs.github.com/en/rest/checks + https://www.ietf.org/rfc/rfc4627.txt + https://liberapay.com/assets/widgets/donate.svg + https://maven-doccheck.sourceforge.net/ + http://jdee.sourceforge.net/ + https://qalab.sourceforge.net/ + https://codeclimate.com + https://saxon.sourceforge.net/saxon7.1/expressions.html + https://www.baeldung.com/* + https://medium.com/* + + https://checkstyle.sourceforge.io/version/6.18 + + https://bugs.eclipse.org/ @@ -1681,7 +2417,6 @@ true true - true true true true @@ -1690,121 +2425,811 @@ true true true + true + true + + + + + + com.groupon.maven.plugin.json + json-schema-validator + ${json-schema-validator.version} + + + none + + + + + + + + + + sevntu + + false + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + ant-phase-verify + none + + + + ant-phase-verify-sevntu + verify + + run + + + + + + + + + + + + com.puppycrawl.tools + checkstyle + ${maven.sevntu-checkstyle-check.checkstyle.version} + + + com.github.sevntu-checkstyle + sevntu-checks + ${maven.sevntu.checkstyle.plugin.version} + + + + + + + + + + + assembly + + true + true + + + + + + + org.apache.maven.plugins + maven-site-plugin + ${maven.site.plugin.version} + + + gen-site + prepare-package + + site + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + false + true + all + + + com.puppycrawl.tools.checkstyle.Main + + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + config/assembly-bin.xml + config/assembly-src.xml + + gnu + + + + make-bundle + package + + single + + + + + + + + com.groupon.maven.plugin.json + json-schema-validator + ${json-schema-validator.version} + + + none + + + + + + + + + + sonar + + + + org.codehaus.mojo + sonar-maven-plugin + + + + + + + error-prone-compile + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + + default-compile + compile + + compile + + + true + + + + error-prone-compile + compile + + compile + + + false + + -Xpkginfo:always + -XDcompilePolicy=simple + --should-stop=ifError=FLOW + + -Xplugin:ErrorProne ${error-prone.configuration-args} + + + + + com.google.errorprone + error_prone_core + ${error-prone.version} + + + tech.picnic.error-prone-support + error-prone-contrib + ${error-prone-support.version} + + + + + + + + + + + + error-prone-test-compile + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + + default-testCompile + test-compile + + testCompile + + + true + + + + error-prone-test-compile + test-compile + + testCompile + + + false + + --should-stop=ifError=FLOW + -Xpkginfo:always + -XDcompilePolicy=simple + + -Xplugin:ErrorProne \ + -XepExcludedPaths:.*[\\/]resources[\\/].* \ + ${error-prone.configuration-args} + + + + + com.google.errorprone + error_prone_core + ${error-prone.version} + + + tech.picnic.error-prone-support + error-prone-contrib + ${error-prone-support.version} + + + + + + + + + + + + + gpgv2 + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.2.8 + + + --pinentry-mode + loopback + + + + + + + + + + checker-nullness-optional-interning + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + true + true + 1024m + 8192m + + 10000 + 10000 + + + + org.checkerframework + checker + ${checkerframework.version} + + + + org.checkerframework.checker.nullness.NullnessChecker + org.checkerframework.checker.optional.OptionalChecker + org.checkerframework.checker.interning.InterningChecker + + + + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + + + + + true + + + + org.checkerframework + checker + ${checkerframework.version} + + + + + + checker-methods-resource-fenum + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + true + true + 1024m + 8192m + + 10000 + 10000 + + + + org.checkerframework + checker + ${checkerframework.version} + + + + org.checkerframework.checker.calledmethods.CalledMethodsChecker + org.checkerframework.checker.resourceleak.ResourceLeakChecker + org.checkerframework.checker.fenum.FenumChecker + + + + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + + + + + true + + + + org.checkerframework + checker + ${checkerframework.version} + + + + + + checker-lock-tainting + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + true + true + 1024m + 8192m + + 10000 + 10000 + + + + org.checkerframework + checker + ${checkerframework.version} + + + + org.checkerframework.checker.lock.LockChecker + org.checkerframework.checker.tainting.TaintingChecker + + + + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + + + + + true + + + + org.checkerframework + checker + ${checkerframework.version} + + + + + + checker-index + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + true + true + 1024m + 8192m + + 10000 + 10000 + + + + org.checkerframework + checker + ${checkerframework.version} + + + + org.checkerframework.checker.index.IndexChecker + + + + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + + + + + true + + + org.checkerframework + checker + ${checkerframework.version} + + - - - assembly - - true - true - true - true - true - true - true - true - true - true - true - - true - - + checker-formatter - org.apache.maven.plugins - maven-site-plugin - ${maven.site.plugin.version} - - - gen-site - prepare-package - - site - - - + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + true + true + 1024m + 8192m + + 10000 + 10000 + + + + org.checkerframework + checker + ${checkerframework.version} + + + + org.checkerframework.checker.i18nformatter.I18nFormatterChecker + + + + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + + + + true + + + + org.checkerframework + checker + ${checkerframework.version} + + + - + + checker-signature-gui-units-init + + org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - true - all - - - com.puppycrawl.tools.checkstyle.Main - - - - - + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + true + true + 1024m + 8192m + + 10000 + 10000 + + + + org.checkerframework + checker + ${checkerframework.version} + + + + org.checkerframework.checker.signature.SignatureChecker + org.checkerframework.checker.guieffect.GuiEffectChecker + org.checkerframework.checker.units.UnitsChecker + org.checkerframework.common.initializedfields.InitializedFieldsChecker + + + + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + + + + true + + + + org.checkerframework + checker + ${checkerframework.version} + + + - + + checker-regex-property-key-compiler-message + + - maven-assembly-plugin + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} - - config/assembly-bin.xml - config/assembly-src.xml - - gnu + + true + true + 1024m + 8192m + + 10000 + 10000 + + + + org.checkerframework + checker + ${checkerframework.version} + + + + org.checkerframework.checker.regex.RegexChecker + org.checkerframework.checker.propkey.PropertyKeyChecker + org.checkerframework.checker.compilermsgs.CompilerMessagesChecker + + + + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + - - - make-bundle - package - - single - - - - + + + true + + + + org.checkerframework + checker + ${checkerframework.version} + + - sonar + checker-purity-value-returns - org.codehaus.mojo - sonar-maven-plugin + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + + + true + true + 1024m + 8192m + + 10000 + 10000 + + + + org.checkerframework + checker + ${checkerframework.version} + + + + org.checkerframework.framework.util.PurityChecker + org.checkerframework.common.value.ValueChecker + org.checkerframework.common.returnsreceiver.ReturnsReceiverChecker + + + + -Awarns + -J--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + -J--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + -J--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + + true + + + + org.checkerframework + checker + ${checkerframework.version} + + + pitest-misc - true true @@ -1817,18 +3242,35 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.ArrayTypeStyleCheck* + com.puppycrawl.tools.checkstyle.internal.annotation.* com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck* @@ -1836,6 +3278,7 @@ com.puppycrawl.tools.checkstyle.checks.FinalParametersCheck* com.puppycrawl.tools.checkstyle.checks.LineSeparatorOption* com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck* + com.puppycrawl.tools.checkstyle.checks.NoCodeInFileCheck* com.puppycrawl.tools.checkstyle.checks.OrderedPropertiesCheck* com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheck* com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolder* @@ -1845,6 +3288,7 @@ com.puppycrawl.tools.checkstyle.checks.UncommentedMainCheck* com.puppycrawl.tools.checkstyle.checks.UniquePropertiesCheck* com.puppycrawl.tools.checkstyle.checks.UpperEllCheck* + com.puppycrawl.tools.checkstyle.checks.HexLiteralCaseCheck* com.puppycrawl.tools.checkstyle.checks.ArrayTypeStyleCheckTest @@ -1854,6 +3298,7 @@ com.puppycrawl.tools.checkstyle.checks.DescendantTokenCheckTest com.puppycrawl.tools.checkstyle.checks.FinalParametersCheckTest com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheckTest + com.puppycrawl.tools.checkstyle.checks.NoCodeInFileCheckTest com.puppycrawl.tools.checkstyle.checks.OrderedPropertiesCheckTest com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheckTest com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolderTest @@ -1863,9 +3308,17 @@ com.puppycrawl.tools.checkstyle.checks.UncommentedMainCheckTest com.puppycrawl.tools.checkstyle.checks.UniquePropertiesCheckTest com.puppycrawl.tools.checkstyle.checks.UpperEllCheckTest + com.puppycrawl.tools.checkstyle.checks.HexLiteralCaseCheckTest com.puppycrawl.tools.checkstyle.filters.SuppressWarningsFilterTest + + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + org.apache.commons.logging + + + +funmodifiablecollection + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.annotation.* @@ -1925,6 +3394,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -1933,7 +3403,6 @@ pitest-blocks - true true @@ -1946,15 +3415,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.blocks.* @@ -1970,15 +3455,15 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} - pitest-coding + pitest-coding-1 - true true @@ -1991,22 +3476,285 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS + INCREMENTS + + + INVERT_NEGS + MATH + NEGATE_CONDITIONALS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF + VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS + + + com.puppycrawl.tools.checkstyle.checks.coding.AbstractSuperCheck* + com.puppycrawl.tools.checkstyle.checks.coding.ArrayTrailingCommaCheck* + com.puppycrawl.tools.checkstyle.checks.coding.AvoidDoubleBraceInitializationCheck* + com.puppycrawl.tools.checkstyle.checks.coding.AvoidInlineConditionalsCheck* + com.puppycrawl.tools.checkstyle.checks.coding.AvoidNoArgumentSuperConstructorCallCheck* + com.puppycrawl.tools.checkstyle.checks.coding.ConstructorsDeclarationGroupingCheck* + com.puppycrawl.tools.checkstyle.checks.coding.CovariantEqualsCheck* + com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheck* + com.puppycrawl.tools.checkstyle.checks.coding.DefaultComesLastCheck* + com.puppycrawl.tools.checkstyle.checks.coding.EmptyStatementCheck* + com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck* + com.puppycrawl.tools.checkstyle.checks.coding.EqualsHashCodeCheck* + com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck* + com.puppycrawl.tools.checkstyle.checks.coding.IllegalThrowsCheck* + com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenCheck* + com.puppycrawl.tools.checkstyle.checks.coding.VariableDeclarationUsageDistanceCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryNullCheckWithInstanceOfCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck* + com.puppycrawl.tools.checkstyle.checks.coding.SuperCloneCheck* + com.puppycrawl.tools.checkstyle.checks.coding.SuperFinalizeCheck* + com.puppycrawl.tools.checkstyle.checks.coding.PackageDeclarationCheck* + com.puppycrawl.tools.checkstyle.checks.coding.ParameterAssignmentCheck* + com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck* + com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanExpressionCheck* + com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanReturnCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnusedCatchParameterShouldBeUnnamedCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLambdaParameterShouldBeUnnamedCheck* + com.puppycrawl.tools.checkstyle.checks.coding.PatternVariableAssignmentCheck* + + + com.puppycrawl.tools.checkstyle.checks.coding.ArrayTrailingCommaCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.AvoidDoubleBraceInitializationCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.AvoidInlineConditionalsCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.AvoidNoArgumentSuperConstructorCallCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.ConstructorsDeclarationGroupingCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.CovariantEqualsCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.DefaultComesLastCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.EmptyStatementCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.EqualsHashCodeCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.ExplicitInitializationCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.FallThroughCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.IllegalThrowsCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.VariableDeclarationUsageDistanceCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryNullCheckWithInstanceOfCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.SuperCloneCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.SuperFinalizeCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.PackageDeclarationCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.ParameterAssignmentCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanExpressionCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanReturnCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnusedCatchParameterShouldBeUnnamedCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLambdaParameterShouldBeUnnamedCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.PatternVariableAssignmentCheckTest + + + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + + + +funmodifiablecollection + + + *.Input* + + 100 + 98 + ${pitest.plugin.timeout.factor} + ${pitest.plugin.timeout.constant} + ${pitest.plugin.threads} + ${pitest.plugin.output.formats} + + + + + + + pitest-coding-2 + + true + + + + + org.pitest + pitest-maven + ${pitest.plugin.version} + + + CONDITIONALS_BOUNDARY + CONSTRUCTOR_CALLS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - - - RETURN_VALS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF + VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS + + + com.puppycrawl.tools.checkstyle.checks.coding.FinalLocalVariableCheck* + com.puppycrawl.tools.checkstyle.checks.coding.HiddenFieldCheck* + com.puppycrawl.tools.checkstyle.checks.coding.IllegalInstantiationCheck* + com.puppycrawl.tools.checkstyle.checks.coding.InnerAssignmentCheck* + com.puppycrawl.tools.checkstyle.checks.coding.MagicNumberCheck* + com.puppycrawl.tools.checkstyle.checks.coding.MatchXpathCheck* + com.puppycrawl.tools.checkstyle.checks.coding.MissingCtorCheck* + com.puppycrawl.tools.checkstyle.checks.coding.MissingNullCaseInSwitchCheck* + com.puppycrawl.tools.checkstyle.checks.coding.MissingSwitchDefaultCheck* + com.puppycrawl.tools.checkstyle.checks.coding.ModifiedControlVariableCheck* + com.puppycrawl.tools.checkstyle.checks.coding.MultipleStringLiteralsCheck* + com.puppycrawl.tools.checkstyle.checks.coding.MultipleVariableDeclarationsCheck* + com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck* + com.puppycrawl.tools.checkstyle.checks.coding.NestedIfDepthCheck* + com.puppycrawl.tools.checkstyle.checks.coding.NestedTryDepthCheck* + com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenTextCheck* + com.puppycrawl.tools.checkstyle.checks.coding.IllegalTypeCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInTryWithResourcesCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheck* + com.puppycrawl.tools.checkstyle.checks.coding.OneStatementPerLineCheck* + com.puppycrawl.tools.checkstyle.checks.coding.FallThroughCheck* + com.puppycrawl.tools.checkstyle.checks.coding.NoArrayTrailingCommaCheck* + com.puppycrawl.tools.checkstyle.checks.coding.NoCloneCheck* + com.puppycrawl.tools.checkstyle.checks.coding.NoEnumTrailingCommaCheck* + com.puppycrawl.tools.checkstyle.checks.coding.NoFinalizerCheck* + com.puppycrawl.tools.checkstyle.checks.coding.OverloadMethodsDeclarationOrderCheck* + com.puppycrawl.tools.checkstyle.checks.coding.StringLiteralEqualityCheck* + com.puppycrawl.tools.checkstyle.checks.coding.ExplicitInitializationCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonAfterOuterTypeDeclarationCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonAfterTypeMemberDeclarationCheck* + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInEnumerationCheck* + com.puppycrawl.tools.checkstyle.checks.coding.WhenShouldBeUsedCheck* + + + com.puppycrawl.tools.checkstyle.checks.coding.FinalLocalVariableCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.HiddenFieldCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.IllegalInstantiationCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.InnerAssignmentCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.MagicNumberCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.MatchXpathCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.MissingCtorCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.MissingNullCaseInSwitchCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.MissingSwitchDefaultCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.ModifiedControlVariableCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.MultipleStringLiteralsCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.MultipleVariableDeclarationsCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.NestedIfDepthCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.NestedTryDepthCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenTextCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.IllegalTypeCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInTryWithResourcesCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.OneStatementPerLineCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.FallThroughCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.NoArrayTrailingCommaCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.NoCloneCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.NoEnumTrailingCommaCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.NoFinalizerCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.OverloadMethodsDeclarationOrderCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.StringLiteralEqualityCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.ExplicitInitializationCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonAfterOuterTypeDeclarationCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonAfterTypeMemberDeclarationCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInEnumerationCheckTest + com.puppycrawl.tools.checkstyle.checks.coding.WhenShouldBeUsedCheckTest + + + *.Input* + + + +funmodifiablecollection + + 100 + 98 + ${pitest.plugin.timeout.factor} + ${pitest.plugin.timeout.constant} + ${pitest.plugin.threads} + ${pitest.plugin.output.formats} + + + + + + + pitest-coding-require-this-check + + true + + + + + org.pitest + pitest-maven + ${pitest.plugin.version} + + + CONDITIONALS_BOUNDARY + CONSTRUCTOR_CALLS + INCREMENTS + + + INVERT_NEGS + MATH + NEGATE_CONDITIONALS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS - com.puppycrawl.tools.checkstyle.checks.coding.* + com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck* - com.puppycrawl.tools.checkstyle.checks.coding.* + com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheckTest *.Input* @@ -2016,6 +3764,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2024,7 +3773,6 @@ pitest-design - true true @@ -2037,15 +3785,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.design.* @@ -2061,6 +3825,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2069,7 +3834,6 @@ pitest-header - true true @@ -2082,15 +3846,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.header.* @@ -2101,11 +3881,12 @@ *.Input* - 98 + 100 97 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2114,7 +3895,6 @@ pitest-imports - true true @@ -2127,34 +3907,48 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.imports.* + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil com.puppycrawl.tools.checkstyle.checks.imports.* - - - loadUri - *.Input* 100 - 97 + 98 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2163,7 +3957,6 @@ pitest-indentation - true true @@ -2182,8 +3975,7 @@ MATH NEGATE_CONDITIONALS - - RETURN_VALS + TRUE_RETURNS VOID_METHOD_CALLS @@ -2201,6 +3993,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2209,7 +4002,6 @@ pitest-javadoc - true true @@ -2222,16 +4014,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - - - RETURN_VALS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF + VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS TRUE_RETURNS - VOID_METHOD_CALLS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.javadoc.* @@ -2239,6 +4046,9 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.* + + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + *.Input* @@ -2252,10 +4062,11 @@ destroy 100 - 97 + 96 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2264,7 +4075,6 @@ pitest-metrics - true true @@ -2277,15 +4087,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.metrics.* @@ -2301,6 +4127,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2309,7 +4136,6 @@ pitest-modifier - true true @@ -2322,15 +4148,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.modifier.* @@ -2346,6 +4188,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2354,7 +4197,6 @@ pitest-naming - true true @@ -2367,15 +4209,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.naming.* @@ -2391,6 +4249,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2399,7 +4258,6 @@ pitest-regexp - true true @@ -2412,15 +4270,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.regexp.* @@ -2436,6 +4310,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2444,7 +4319,6 @@ pitest-sizes - true true @@ -2457,15 +4331,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.sizes.* @@ -2481,6 +4371,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2489,7 +4380,6 @@ pitest-whitespace - true true @@ -2502,15 +4392,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.checks.whitespace.* @@ -2526,16 +4432,16 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} - + pitest-ant - true true @@ -2548,15 +4454,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.ant.* @@ -2567,11 +4489,12 @@ *.Input* - 99 - 96 + 100 + 92 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2580,7 +4503,6 @@ pitest-packagenamesloader - true true @@ -2593,15 +4515,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.PackageNamesLoader* @@ -2610,10 +4548,11 @@ com.puppycrawl.tools.checkstyle.PackageNamesLoaderTest 100 - 100 + 90 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2622,7 +4561,6 @@ pitest-common - true true @@ -2635,59 +4573,126 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS + com.puppycrawl.tools.checkstyle.AbstractAutomaticBean* com.puppycrawl.tools.checkstyle.AuditEventDefaultFormatter* com.puppycrawl.tools.checkstyle.ConfigurationLoader* com.puppycrawl.tools.checkstyle.DefaultConfiguration* com.puppycrawl.tools.checkstyle.DefaultContext* com.puppycrawl.tools.checkstyle.DefaultLogger* com.puppycrawl.tools.checkstyle.Definitions* + com.puppycrawl.tools.checkstyle.LocalizedMessage* com.puppycrawl.tools.checkstyle.XMLLogger* + com.puppycrawl.tools.checkstyle.SarifLogger* + com.puppycrawl.tools.checkstyle.MetadataGeneratorLogger* com.puppycrawl.tools.checkstyle.PackageObjectFactory* com.puppycrawl.tools.checkstyle.PropertiesExpander* com.puppycrawl.tools.checkstyle.PropertyCacheFile* com.puppycrawl.tools.checkstyle.Checker* com.puppycrawl.tools.checkstyle.ThreadModeSettings* + com.puppycrawl.tools.checkstyle.grammar.CrAwareLexerSimulator* + com.puppycrawl.tools.checkstyle.grammar.SimpleToken* + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsLexerUtil* + com.puppycrawl.tools.checkstyle.grammar.JavadocCommentsParserUtil* + com.puppycrawl.tools.checkstyle.grammar.CompositeLexerContextCache* - com.puppycrawl.tools.checkstyle.AuditEventFormatter - com.puppycrawl.tools.checkstyle.FileStatefulCheck - com.puppycrawl.tools.checkstyle.ModuleFactory - com.puppycrawl.tools.checkstyle.PropertyResolver - com.puppycrawl.tools.checkstyle.StatelessCheck - com.puppycrawl.tools.checkstyle.TreeWalkerFilter - com.puppycrawl.tools.checkstyle.GlobalStatefulCheck - com.puppycrawl.tools.checkstyle.grammar.CommentListener + com.puppycrawl.tools.checkstyle.AuditEventFormatter* + com.puppycrawl.tools.checkstyle.XdocsPropertyType* + com.puppycrawl.tools.checkstyle.PropertyType* + com.puppycrawl.tools.checkstyle.FileStatefulCheck* + com.puppycrawl.tools.checkstyle.ModuleFactory* + com.puppycrawl.tools.checkstyle.PropertyResolver* + com.puppycrawl.tools.checkstyle.StatelessCheck* + com.puppycrawl.tools.checkstyle.TreeWalkerFilter* + com.puppycrawl.tools.checkstyle.GlobalStatefulCheck* + com.puppycrawl.tools.checkstyle.grammar.CommentListener* + com.puppycrawl.tools.checkstyle.ChecksAndFilesSuppressionFileGeneratorAuditListener* + com.puppycrawl.tools.checkstyle.AbstractAutomaticBeanTest com.puppycrawl.tools.checkstyle.AuditEventDefaultFormatterTest + com.puppycrawl.tools.checkstyle.XdocsPropertyTypeTest com.puppycrawl.tools.checkstyle.ConfigurationLoaderTest com.puppycrawl.tools.checkstyle.DefaultConfigurationTest com.puppycrawl.tools.checkstyle.DefaultLoggerTest com.puppycrawl.tools.checkstyle.DefinitionsTest + com.puppycrawl.tools.checkstyle.LocalizedMessageTest com.puppycrawl.tools.checkstyle.XMLLoggerTest + com.puppycrawl.tools.checkstyle.SarifLoggerTest + com.puppycrawl.tools.checkstyle.MetadataGeneratorLoggerTest com.puppycrawl.tools.checkstyle.PackageObjectFactoryTest com.puppycrawl.tools.checkstyle.PropertiesExpanderTest com.puppycrawl.tools.checkstyle.PropertyCacheFileTest com.puppycrawl.tools.checkstyle.CheckerTest com.puppycrawl.tools.checkstyle.ThreadModeSettingsTest + com.puppycrawl.tools.checkstyle.grammar.CrAwareLexerTest + com.puppycrawl.tools.checkstyle.grammar.javadoc.JavadocCommentsAstRegressionTest + + com.puppycrawl.tools.checkstyle.grammar.java21.Java21AstRegressionTest com.puppycrawl.tools.checkstyle.filefilters.BeforeExecutionExclusionFileFilterTest + com.puppycrawl.tools.checkstyle.checks.TranslationCheckTest + + com.puppycrawl.tools.checkstyle.meta.MetadataGeneratorUtilTest + + com.puppycrawl.tools.checkstyle.checks.naming.ParameterNameCheckTest + + com.puppycrawl.tools.checkstyle.checks.coding.IllegalTypeCheckTest + + com.sun.checkstyle.test.chapter5comments.rule52documentationcomments.InvalidJavadocPositionTest + com.puppycrawl.tools.checkstyle.ChecksAndFilesSuppressionFileGeneratorAuditListenerTest + + com.puppycrawl.tools.checkstyle.MainTest + + org.apache.commons.logging + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + + + + lazyLoad + + initStringBuilderWithOptimalBuffer + + replaceVersionString + + printVersionString + + + +funmodifiablecollection + 99 - 95 + 96 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2696,7 +4701,6 @@ pitest-common-2 - true true @@ -2709,15 +4713,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.DetailAstImpl* @@ -2730,25 +4750,34 @@ com.puppycrawl.tools.checkstyle.JavadocPropertiesGeneratorTest com.puppycrawl.tools.checkstyle.XmlLoaderTest com.puppycrawl.tools.checkstyle.JavaParserTest + com.puppycrawl.tools.checkstyle.MainTest + com.puppycrawl.tools.checkstyle.utils.CheckUtilTest com.puppycrawl.tools.checkstyle.filters.SuppressionsLoaderTest com.puppycrawl.tools.checkstyle.ConfigurationLoaderTest - + setFeaturesBySystemProperty + + +funmodifiablecollection + - + com.puppycrawl.tools.checkstyle.XmlLoader$LoadExternalDtdFeatureProvider + + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + 100 - 100 + 96 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2757,7 +4786,6 @@ pitest-main - true true @@ -2770,15 +4798,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.Main* @@ -2786,11 +4830,17 @@ com.puppycrawl.tools.checkstyle.MainTest - 100 - 98 + + + getVersionString + printVersionToSystemOutput + + 99 + 99 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2799,7 +4849,6 @@ pitest-tree-walker - true true @@ -2812,15 +4861,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser* @@ -2829,6 +4894,7 @@ com.puppycrawl.tools.checkstyle.SuppressionsStringPrinter* com.puppycrawl.tools.checkstyle.TreeWalker* com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent* + com.puppycrawl.tools.checkstyle.CheckstyleParserErrorStrategy* com.puppycrawl.tools.checkstyle.DetailNodeTreeStringPrinterTest @@ -2872,18 +4938,27 @@ destroy - org.antlr.v4.runtime.BailErrorStrategy + + + org.antlr.v4.runtime.atn.ParserATNSimulator + 100 - 99 + 98 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2892,7 +4967,6 @@ pitest-api - true true @@ -2905,22 +4979,56 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.api.* com.puppycrawl.tools.checkstyle.api.* + + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheckTest + + com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheckTest + com.puppycrawl.tools.checkstyle.checks.sizes.LineLengthCheckTest + com.puppycrawl.tools.checkstyle.checks.javadoc.NonEmptyAtclauseDescriptionCheckTest + com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTypeCheckTest + org.checkstyle.suppressionxpathfilter.XpathRegressionUnusedLocalVariableTest + com.puppycrawl.tools.checkstyle.checks.javadoc.SummaryJavadocCheckTest + org.checkstyle.suppressionxpathfilter.javadoc.XpathRegressionJavadocMethodTest + com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheckTest + com.puppycrawl.tools.checkstyle.filters.SuppressWithPlainTextCommentFilterTest + com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheckTest + com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheckTest + com.puppycrawl.tools.checkstyle.checks.modifier.InterfaceMemberImpliedModifierCheckTest + + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + *.Input* @@ -2934,10 +5042,11 @@ destroy 100 - 100 + 97 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2946,7 +5055,6 @@ pitest-filters - true true @@ -2959,15 +5067,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.filefilters.* @@ -2977,14 +5101,21 @@ com.puppycrawl.tools.checkstyle.filefilters.* com.puppycrawl.tools.checkstyle.filters.* + + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + + + +funmodifiablecollection + *.Input* 100 - 100 + 94 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -2993,7 +5124,6 @@ pitest-utils - true true @@ -3006,16 +5136,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - - - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.utils.* @@ -3024,11 +5169,17 @@ isFileExists + + com.puppycrawl.tools.checkstyle.utils.OsSpecificUtil + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + com.puppycrawl.tools.checkstyle.utils.* com.puppycrawl.tools.checkstyle.AstTreeStringPrinterTest + + com.puppycrawl.tools.checkstyle.ConfigurationLoaderTest com.puppycrawl.tools.checkstyle.DetailNodeTreeStringPrinterTest @@ -3038,21 +5189,102 @@ com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheckTest + + com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheckTest + + + com.puppycrawl.tools.checkstyle.checks.whitespace.SingleSpaceSeparatorCheckTest + + + + com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocStyleCheckTest + com.puppycrawl.tools.checkstyle.checks.javadoc.SingleLineJavadocCheckTest com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheckTest + + + com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheckTest + + + + com.puppycrawl.tools.checkstyle.checks.coding.MagicNumberCheckTest + + + com.puppycrawl.tools.checkstyle.checks.coding.MultipleStringLiteralsCheckTest + + + com.puppycrawl.tools.checkstyle.checks.coding.IllegalThrowsCheckTest + + + com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheckTest + + + com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheckTest + + + com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheckTest + + + com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheckTest + + + com.puppycrawl.tools.checkstyle.checks.javadoc.InvalidJavadocPositionCheckTest + + + com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocMethodCheckTest + + + com.puppycrawl.tools.checkstyle.checks.coding.CovariantEqualsCheckTest + + + com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonAfterOuterTypeDeclarationCheckTest + + + com.puppycrawl.tools.checkstyle.checks.annotation.MissingOverrideCheckTest + + + com.puppycrawl.tools.checkstyle.checks.coding.IllegalTypeCheckTest + + + com.puppycrawl.tools.checkstyle.xpath.XpathMapperTest + + + com.puppycrawl.tools.checkstyle.xpath.ElementNodeTest + + + com.puppycrawl.tools.checkstyle.checks.javadoc.WriteTagCheckTest + + + com.puppycrawl.tools.checkstyle.checks.FinalParametersCheckTest + + + com.puppycrawl.tools.checkstyle.checks.coding.MissingSwitchDefaultCheckTest + + + + com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocParagraphCheckTest + + + + com.puppycrawl.tools.checkstyle.meta.MetadataGeneratorUtilTest + + + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + *.Input* - 99 - 100 + 100 + 96 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -3061,7 +5293,6 @@ pitest-gui - true true @@ -3080,7 +5311,6 @@ MATH NEGATE_CONDITIONALS REMOVE_CONDITIONALS - RETURN_VALS TRUE_RETURNS VOID_METHOD_CALLS @@ -3098,6 +5328,7 @@ ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} @@ -3107,9 +5338,9 @@ eclipse-compiler - org.eclipse.jdt - org.eclipse.jdt.annotation - 2.2.400 + org.eclipse.jdt + org.eclipse.jdt.annotation + 2.4.0 @@ -3122,6 +5353,7 @@ test + ${next.java.version} @@ -3131,7 +5363,6 @@ pitest-xpath - true true @@ -3144,15 +5375,31 @@ CONDITIONALS_BOUNDARY CONSTRUCTOR_CALLS - FALSE_RETURNS INCREMENTS + + INVERT_NEGS MATH NEGATE_CONDITIONALS - REMOVE_CONDITIONALS - RETURN_VALS - TRUE_RETURNS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS com.puppycrawl.tools.checkstyle.xpath.* @@ -3163,16 +5410,155 @@ com.puppycrawl.tools.checkstyle.xpath.* com.puppycrawl.tools.checkstyle.XpathFileGeneratorAuditListenerTest com.puppycrawl.tools.checkstyle.XpathFileGeneratorAstFilterTest + com.puppycrawl.tools.checkstyle.filters.* + + com.puppycrawl.tools.checkstyle.utils.UnmodifiableCollectionUtil + + + +funmodifiablecollection + *.Input* 100 - 96 + 98 + ${pitest.plugin.timeout.factor} + ${pitest.plugin.timeout.constant} + ${pitest.plugin.threads} + ${pitest.plugin.output.formats} + + + + + + + pitest-java-ast-visitor + + true + + + + + org.pitest + pitest-maven + ${pitest.plugin.version} + + + CONDITIONALS_BOUNDARY + CONSTRUCTOR_CALLS + INCREMENTS + + + INVERT_NEGS + MATH + NEGATE_CONDITIONALS + NON_VOID_METHOD_CALLS + REMOVE_CONDITIONALS_EQUAL_ELSE + REMOVE_CONDITIONALS_EQUAL_IF + REMOVE_CONDITIONALS_ORDER_ELSE + REMOVE_CONDITIONALS_ORDER_IF + VOID_METHOD_CALLS + EXPERIMENTAL_ARGUMENT_PROPAGATION + EXPERIMENTAL_BIG_DECIMAL + EXPERIMENTAL_BIG_INTEGER + EXPERIMENTAL_MEMBER_VARIABLE + EXPERIMENTAL_NAKED_RECEIVER + REMOVE_INCREMENTS + EXPERIMENTAL_SWITCH + REMOVE_SWITCH + FALSE_RETURNS + TRUE_RETURNS + EMPTY_RETURNS + NULL_RETURNS + PRIMITIVE_RETURNS + + + com.puppycrawl.tools.checkstyle.JavaAstVisitor* + com.puppycrawl.tools.checkstyle.JavadocCommentsAstVisitor* + + + com.puppycrawl.tools.checkstyle.checks.javadoc.* + com.puppycrawl.tools.checkstyle.grammar.* + com.puppycrawl.tools.checkstyle.JavaAstVisitorTest + + + *.Input* + + 100 + 99 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} + ${pitest.plugin.output.formats} + + + + + + + checkstyle-autofix + + + + + org.openrewrite.maven + rewrite-maven-plugin + 6.23.0 + + true + true + + org.checkstyle.AllAutoFixes + + + **.ci-temp** + **/resources-noncompilable/** + **src/it/resources** + **src/test/resources** + **xdocs-examples** + + + **/*.xml + **/*.yml + **/*.groovy + **/resources/** + **/resources-noncompilable/** + + + + com.puppycrawl.tools + checkstyle-openrewrite-recipes + ${checkstyle.openrewrite.version} + + + org.openrewrite.recipe + rewrite-migrate-java + 3.21.2 + + + org.openrewrite.recipe + rewrite-static-analysis + 2.21.0 + + + org.openrewrite.recipe + rewrite-rewrite + 0.15.0 + + + + + + + + spotless-autofix + + + + com.diffplug.spotless + spotless-maven-plugin diff --git a/release.sh b/release.sh deleted file mode 100755 index 5d9b1e58afef..000000000000 --- a/release.sh +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/env bash -set -e - -echo "Make sure you prepared your PC for automative deployment" -echo "Release process: https://github.com/checkstyle/checkstyle/wiki/How-to-make-a-release" - -RELEASE=$(xmlstarlet sel -N pom=http://maven.apache.org/POM/4.0.0 \ - -t -m pom:project -v pom:version pom.xml | sed "s/-SNAPSHOT//") -PREV_RELEASE=$(git describe --abbrev=0 $(git rev-list --tags --max-count=1) | sed "s/checkstyle-//") - -echo "PREVIOUS RELEASE version:"$PREV_RELEASE -echo "RELEASE version:"$RELEASE - -if [[ ! -f ~/.m2/token-checkstyle.txt ]]; then - echo "File ~/.m2/token-checkstyle.txt with Github token is not found" - exit 1 -fi -if [[ -z $RELEASE ]]; then - echo "Problem to calculate release version." - exit 1 -fi -if [[ -z $PREV_RELEASE ]]; then - echo "Problem to calculate previous release version." - exit 1 -fi -if [[ $(grep "
    " src/xdocs/releasenotes.xml \ - | cat | wc -l) -eq 0 ]]; then - echo "src/xdocs/releasenotes.xml do not have section for $RELEASE" - exit 1 -fi - -SKIP_TEST="-DskipTests -DskipITs" -SKIP_CHECKSTYLE="-Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true" -SKIP_OTHERS="-Dpmd.skip=true -Dspotbugs.skip=true -Djacoco.skip=true -Dxml.skip=true" - -echo "Version bump in pom.xml (release:prepare) ..." -mvn -e -Pgpg release:prepare -B -Darguments="$SKIP_TEST $SKIP_CHECKSTYLE $SKIP_OTHERS" - -echo "Deployment of jars to maven central (release:perform) ..." -mvn -e -Pgpg release:perform -Darguments="$SKIP_CHECKSTYLE" - -echo "Go to folder where site was build and sources are already at required tag" -cd target/checkout - -echo "Generating web site" -mvn -e site - -echo "Generating uber jar ...(no clean to keep site resources just in case)" -mvn -e -Passembly package - -echo "Come back repo folder" -cd ../../ - -############################## - -NEW_RELEASE=$(git describe --abbrev=0 | cut -d '-' -f 2) -PREV_RELEASE=$(git describe --abbrev=0 --tags \ - `git rev-list --tags --skip=1 --max-count=1` \ - | cut -d '-' -f 2) -FUTURE_RELEASE=$(xmlstarlet sel -N pom=http://maven.apache.org/POM/4.0.0 \ - -t -m pom:project -v pom:version pom.xml | sed "s/-SNAPSHOT//") -TKN=$(cat ~/.m2/token-checkstyle.txt) - -echo "Updating Github tag page" -curl -i -H "Authorization: token $TKN" \ - -d "{ \"tag_name\": \"checkstyle-$NEW_RELEASE\", \ - \"target_commitish\": \"master\", \ - \"name\": \"\", \ - \"body\": \"https://checkstyle.org/releasenotes.html#Release_$NEW_RELEASE\", \ - \"draft\": false, \"prerelease\": false }" \ - -X POST https://api.github.com/repos/checkstyle/checkstyle/releases - -echo "Publishing 'all' jar to Github" -RELEASE_ID=$(curl -s -X GET \ - https://api.github.com/repos/checkstyle/checkstyle/releases/tags/checkstyle-$NEW_RELEASE \ - | jq ".id") -curl -i -H "Authorization: token $TKN" \ - -H "Content-Type: application/zip" \ - --data-binary @"target/checkout/target/checkstyle-$NEW_RELEASE-all.jar" \ - -X POST https://uploads.github.com/repos/checkstyle/checkstyle/releases/$RELEASE_ID/assets?name=checkstyle-$NEW_RELEASE-all.jar - -echo "Close previous milestone at github" -MILESTONE_ID=$(curl -s \ - -X GET https://api.github.com/repos/checkstyle/checkstyle/milestones?state=open \ - | jq ".[0] | .number") -curl -i -H "Authorization: token $TKN" \ - -d "{ \"state\": \"closed\" }" \ - -X PATCH https://api.github.com/repos/checkstyle/checkstyle/milestones/$MILESTONE_ID - - -echo "Creation of new milestone ..." -LAST_SUNDAY_DAY=$(cal -d $(date -d "next month" +"%Y-%m") \ - | awk '/^ *[0-9]/ { d=$1 } END { print d }') -LAST_SUNDAY_DATETIME=$(date -d "next month" +"%Y-%m")"-$LAST_SUNDAY_DAY""T08:00:00Z" -echo $LAST_SUNDAY_DATETIME -curl -i -H "Authorization: token $TKN" \ - -d "{ \"title\": \"$FUTURE_RELEASE\", \ - \"state\": \"open\", \ - \"description\": \"\", \ - \"due_on\": \"$LAST_SUNDAY_DATETIME\" \ - }" \ - -X POST https://api.github.com/repos/checkstyle/checkstyle/milestones - -echo "Creation of issue in eclipse-cs repo ..." -curl -i -H "Authorization: token $TKN" \ - -d "{ \"title\": \"upgrade to checkstyle $NEW_RELEASE\", \ - \"body\": \"https://checkstyle.org/releasenotes.html#Release_$NEW_RELEASE\" \ - }" \ - -X POST https://api.github.com/repos/checkstyle/eclipse-cs/issues - -echo "Creation of issue in sonar-checkstyle repo ..." -curl -i -H "Authorization: token $TKN" \ - -d "{ \"title\": \"upgrade to checkstyle $NEW_RELEASE\", \ - \"body\": \"https://checkstyle.org/releasenotes.html#Release_$NEW_RELEASE\" \ - }" \ - -X POST https://api.github.com/repos/checkstyle/sonar-checkstyle/issues - -############################## - -echo "Switch to checkstyle.github.io repository" -if [ -d "../checkstyle.github.io" ] ; then - cd ../checkstyle.github.io -else - cd ../ - echo "Clone by ssh only to avoid passwords on push ..." - git clone git@github.com:checkstyle/checkstyle.github.io.git - cd checkstyle.github.io -fi -git rm -rf * -git checkout HEAD -- CNAME -cp -R ../checkstyle/target/checkout/target/site/* . -git add . -git commit -m "release $RELEASE" -echo "Push site content to remote ..." -echo "We do force to avoid history changes, we do not need history as github.io shows only HEAD." -git push origin --force diff --git a/rewrite.yml b/rewrite.yml new file mode 100644 index 000000000000..8139c1e90626 --- /dev/null +++ b/rewrite.yml @@ -0,0 +1,53 @@ +--- +type: specs.openrewrite.org/v1beta/recipe +name: org.checkstyle.AllAutoFixes +displayName: Auto Fixes +description: List of auto fixes from different providers. +recipeList: + - org.checkstyle.autofix.CheckstyleAutoFix: + violationReportPath: "target/cs_errors.xml" + configurationPath: "config/checkstyle-checks.xml" + propertiesPath: "config/openrewrite-recipes-checkstyle.properties" + - org.openrewrite.java.RemoveUnusedImports + - org.openrewrite.java.format.NormalizeFormat + - org.openrewrite.java.format.NormalizeLineBreaks + - org.openrewrite.java.format.RemoveTrailingWhitespace + - org.openrewrite.java.migrate.UpgradeToJava17 + - org.openrewrite.java.recipes.JavaRecipeBestPractices + - org.openrewrite.java.recipes.RecipeTestingBestPractices + - org.openrewrite.maven.BestPractices + - org.openrewrite.staticanalysis.BufferedWriterCreationRecipes + - org.openrewrite.staticanalysis.EqualsAvoidsNull + - org.openrewrite.staticanalysis.InlineVariable + - org.openrewrite.staticanalysis.JavaApiBestPractices + - org.openrewrite.staticanalysis.LowercasePackage + - org.openrewrite.staticanalysis.MissingOverrideAnnotation + - org.openrewrite.staticanalysis.ModifierOrder + - org.openrewrite.staticanalysis.NoFinalizer + - org.openrewrite.staticanalysis.NoToStringOnStringType + - org.openrewrite.staticanalysis.RemoveUnusedLocalVariables + - org.openrewrite.staticanalysis.RemoveUnusedPrivateFields + - org.openrewrite.staticanalysis.RemoveUnusedPrivateMethods + - org.openrewrite.staticanalysis.ReplaceLambdaWithMethodReference + - org.openrewrite.staticanalysis.SimplifyTernaryRecipes + - org.openrewrite.staticanalysis.URLEqualsHashCodeRecipes + - org.openrewrite.staticanalysis.UnnecessaryCloseInTryWithResources + - org.openrewrite.staticanalysis.UnnecessaryExplicitTypeArguments + - org.openrewrite.staticanalysis.UnnecessaryParentheses + - org.openrewrite.staticanalysis.UnnecessaryReturnAsLastStatement + - org.openrewrite.staticanalysis.UseLambdaForFunctionalInterface + - tech.picnic.errorprone.refasterrules.BigDecimalRulesRecipes + - tech.picnic.errorprone.refasterrules.CharSequenceRulesRecipes + - tech.picnic.errorprone.refasterrules.ClassRulesRecipes + - tech.picnic.errorprone.refasterrules.CollectionRulesRecipes + - tech.picnic.errorprone.refasterrules.ComparatorRulesRecipes + - tech.picnic.errorprone.refasterrules.FileRulesRecipes + - tech.picnic.errorprone.refasterrules.MapRulesRecipes + - tech.picnic.errorprone.refasterrules.MicrometerRulesRecipes + - tech.picnic.errorprone.refasterrules.MockitoRulesRecipes + - tech.picnic.errorprone.refasterrules.PatternRulesRecipes + - tech.picnic.errorprone.refasterrules.PreconditionsRulesRecipes + - tech.picnic.errorprone.refasterrules.PrimitiveRulesRecipes + - tech.picnic.errorprone.refasterrules.StreamRulesRecipes + - tech.picnic.errorprone.refasterrules.TimeRulesRecipes +--- diff --git a/shippable.yml b/shippable.yml deleted file mode 100644 index 6a24cd4fb3b8..000000000000 --- a/shippable.yml +++ /dev/null @@ -1,60 +0,0 @@ -language: java - -jdk: - - openjdk8 - -env: - matrix: - # we skip openjdk till we find way to install "hg" to shippable image - #- CMD="./.ci/shippable.sh no-exception-openjdk7-openjdk8" - - CMD="./.ci/shippable.sh no-exception-openjdk9-lucene-and-others" - - CMD="./.ci/shippable.sh no-exception-cassandra-storm-tapestry" - - CMD="./.ci/shippable.sh no-exception-hadoop-apache-groovy-scouter" - - CMD="./.ci/shippable.sh no-exception-only-javadoc" - -branches: - only: - - master - -build: - cache: true - cache_dir_list: - - /root/.m2 - - /root/groovy-2.4.7 - - pre_ci_boot: - # This version should match version defined in "Node Pools" in Shippable UI - image_name: drydock/u16javall - image_tag: v7.2.4 - - ci: - # we skip PRs and commits that are not for Issues, as pitest is too time consuming - - | - set -e - pwd - ls -la - if [ ! -d /root/groovy-2.4.7 ]; then - wget https://dl.bintray.com/groovy/maven/apache-groovy-binary-2.4.7.zip - unzip apache-groovy-binary-2.4.7.zip -d /root/ - fi - # load custom PATH - export PATH=/root/groovy-2.4.7/bin:$PATH - SKIP_FILES1="appveyor.yml|codeship-*|buddy.yml|circleci|.travis.yml" - SKIP_FILES2="|wercker.yml|wercker.sh|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md" - SKIP_FILES3="|release.sh|RIGHTS.antlr|intellij-idea-inspections.xml" - SKIP_FILES4="|org.eclipse.jdt.core.prefs" - SKIP_FILES5="|Jenkinsfile" - SKIP_FILES=$SKIP_FILES1$SKIP_FILES2$SKIP_FILES3$SKIP_FILES4$SKIP_FILES5 - export RUN_JOB=1 - source ./.ci/common.sh - # should_run_job will change RUN_JOB variable - should_run_job "recheck" $SKIP_FILES - if [[ $RUN_JOB == 1 ]]; - then - echo "eval of CMD is starting" - echo "CMD=$CMD" - eval $CMD - echo "eval of CMD is completed" - else - echo "Build is skipped" - fi diff --git a/src/it/java/com/google/checkstyle/test/base/AbstractGoogleModuleTestSupport.java b/src/it/java/com/google/checkstyle/test/base/AbstractGoogleModuleTestSupport.java index 04c4b6509543..dac8672d63c0 100644 --- a/src/it/java/com/google/checkstyle/test/base/AbstractGoogleModuleTestSupport.java +++ b/src/it/java/com/google/checkstyle/test/base/AbstractGoogleModuleTestSupport.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,19 +15,17 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package com.google.checkstyle.test.base; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; +import java.util.Properties; import java.util.Set; import org.checkstyle.base.AbstractItModuleTestSupport; import com.puppycrawl.tools.checkstyle.ConfigurationLoader; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.PropertiesExpander; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; @@ -44,17 +42,20 @@ public abstract class AbstractGoogleModuleTestSupport extends AbstractItModuleTe static { try { + final Properties properties = new Properties(); + properties.setProperty("org.checkstyle.google.severity", "error"); + final PropertiesExpander expander = new PropertiesExpander(properties); CONFIGURATION = ConfigurationLoader.loadConfiguration(XML_NAME, - new PropertiesExpander(System.getProperties())); + expander); } - catch (CheckstyleException ex) { - throw new IllegalStateException(ex); + catch (CheckstyleException exc) { + throw new IllegalStateException(exc); } try { CHECKSTYLE_MODULES = CheckUtil.getCheckstyleModules(); } - catch (IOException ex) { - throw new IllegalStateException(ex); + catch (IOException exc) { + throw new IllegalStateException(exc); } } @@ -76,76 +77,13 @@ protected ModuleCreationOption findModuleCreationOption(String moduleName) { return moduleCreationOption; } - @Override - protected DefaultConfiguration createModuleConfig(Class clazz) { - return new DefaultConfiguration(clazz.getName()); - } - /** - * Returns {@link Configuration} instance for the given module name. - * This implementation uses {@link #getModuleConfig(String, String)} method inside. - * @param moduleName module name. - * @return {@link Configuration} instance for the given module name. + * Performs verification of the file with the given file path against the whole config. + * + * @param filePath file path to verify. + * @throws Exception if exception occurs during verification process. */ - protected static Configuration getModuleConfig(String moduleName) { - return getModuleConfig(moduleName, null); + protected void verifyWithWholeConfig(String filePath) throws Exception { + verifyWithItConfig(CONFIGURATION, filePath); } - - /** - * Returns {@link Configuration} instance for the given module name. - * This implementation uses {@link #getModuleConfig(String)} method inside. - * @param moduleName module name. - * @param moduleId module id. - * @return {@link Configuration} instance for the given module name. - */ - protected static Configuration getModuleConfig(String moduleName, String moduleId) { - final Configuration result; - final List configs = getModuleConfigs(moduleName); - if (configs.size() == 1) { - result = configs.get(0); - } - else if (configs.isEmpty()) { - throw new IllegalStateException("no instances of the Module was found: " + moduleName); - } - else if (moduleId == null) { - throw new IllegalStateException("multiple instances of the same Module are detected"); - } - else { - result = configs.stream().filter(conf -> { - try { - return conf.getAttribute("id").equals(moduleId); - } - catch (CheckstyleException ex) { - throw new IllegalStateException("problem to get ID attribute from " + conf, ex); - } - }) - .findFirst() - .orElseThrow(() -> new IllegalStateException("problem with module config")); - } - - return result; - } - - /** - * Returns a list of all {@link Configuration} instances for the given module name. - * @param moduleName module name. - * @return {@link Configuration} instance for the given module name. - */ - protected static List getModuleConfigs(String moduleName) { - final List result = new ArrayList<>(); - for (Configuration currentConfig : CONFIGURATION.getChildren()) { - if ("TreeWalker".equals(currentConfig.getName())) { - for (Configuration moduleConfig : currentConfig.getChildren()) { - if (moduleName.equals(moduleConfig.getName())) { - result.add(moduleConfig); - } - } - } - else if (moduleName.equals(currentConfig.getName())) { - result.add(currentConfig); - } - } - return result; - } - } diff --git a/src/it/java/com/google/checkstyle/test/base/AbstractIndentationTestSupport.java b/src/it/java/com/google/checkstyle/test/base/AbstractIndentationTestSupport.java index e0cd41637030..bb50eeaec4dd 100644 --- a/src/it/java/com/google/checkstyle/test/base/AbstractIndentationTestSupport.java +++ b/src/it/java/com/google/checkstyle/test/base/AbstractIndentationTestSupport.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,15 +15,14 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package com.google.checkstyle.test.base; import java.io.BufferedReader; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -60,12 +59,21 @@ protected Integer[] getLinesWithWarn(String fileName) throws IOException { return getLinesWithWarnAndCheckComments(fileName, TAB_WIDTH); } + /** + * Returns line numbers for lines with 'warn' comments. + * + * @param aFileName file name. + * @param tabWidth tab width. + * @return array of line numbers containing 'warn' comments ('warn'). + * @throws IOException while reading the file for checking lines. + * @throws IllegalStateException if file has incorrect indentation in comment or + * comment is inconsistent or if file has no indentation comment. + */ private static Integer[] getLinesWithWarnAndCheckComments(String aFileName, final int tabWidth) throws IOException { final List result = new ArrayList<>(); - try (BufferedReader br = Files.newBufferedReader( - Paths.get(aFileName), StandardCharsets.UTF_8)) { + try (BufferedReader br = Files.newBufferedReader(Path.of(aFileName))) { int lineNumber = 1; for (String line = br.readLine(); line != null; line = br.readLine()) { final Matcher match = LINE_WITH_COMMENT_REGEX.matcher(line); @@ -109,44 +117,63 @@ else if (NONEMPTY_LINE_REGEX.matcher(line).matches()) { return result.toArray(new Integer[0]); } + /** + * Returns amount of indentation from the comment. + * + * @param comment the indentation comment to be checked. + * @return amount of indentation in comment. + */ private static int getIndentFromComment(String comment) { final Matcher match = GET_INDENT_FROM_COMMENT_REGEX.matcher(comment); match.matches(); return Integer.parseInt(match.group(1)); } + /** + * Checks if comment is a warn comment (ends with "warn") or not. + * + * @param comment the comment to be checked. + * @return true if comment ends with " warn" else returns false. + */ private static boolean isWarnComment(String comment) { return comment.endsWith(" warn"); } + /** + * Checks if a comment of comment type is consistent or not. + * + * @param comment the comment to be checked. + * @return true if comment is consistent based on expected indent level, actual indent level + * and if comment is a warn comment else it returns false. + * @throws IllegalArgumentException if comment type is unknown and cannot determine consistency. + * @throws IllegalStateException if cannot determine that comment is consistent(default case). + */ private static boolean isCommentConsistent(String comment) { final int indentInComment = getIndentFromComment(comment); final boolean isWarnComment = isWarnComment(comment); - - final boolean result; final CommentType type = getCommentType(comment); - switch (type) { - case MULTILEVEL: - result = isMultiLevelCommentConsistent(comment, indentInComment, isWarnComment); - break; - - case SINGLE_LEVEL: - result = isSingleLevelCommentConsistent(comment, indentInComment, isWarnComment); - break; - - case NON_STRICT_LEVEL: - result = isNonStrictCommentConsistent(comment, indentInComment, isWarnComment); - break; - - case UNKNOWN: - throw new IllegalArgumentException("Cannot determine comment consistent"); - - default: - throw new IllegalStateException("Cannot determine comment is consistent"); - } - return result; + return switch (type) { + case MULTILEVEL -> + isMultiLevelCommentConsistent(comment, indentInComment, isWarnComment); + case SINGLE_LEVEL -> + isSingleLevelCommentConsistent(comment, indentInComment, isWarnComment); + case NON_STRICT_LEVEL -> + isNonStrictCommentConsistent(comment, indentInComment, isWarnComment); + case UNKNOWN -> + throw new IllegalArgumentException("Cannot determine comment consistent"); + default -> + throw new IllegalStateException("Cannot determine comment is consistent"); + }; } + /** + * Checks if a Non Strict Comment is consistent or not. + * + * @param comment the comment to be checked. + * @param indentInComment the actual indentation in that comment. + * @param isWarnComment if comment is Warn comment or not. + * @return true if Non Strict comment is consistent else returns false. + */ private static boolean isNonStrictCommentConsistent(String comment, int indentInComment, boolean isWarnComment) { final Matcher nonStrictLevelMatch = NON_STRICT_LEVEL_COMMENT_REGEX.matcher(comment); @@ -157,6 +184,14 @@ private static boolean isNonStrictCommentConsistent(String comment, || indentInComment < expectedMinimalIndent && isWarnComment; } + /** + * Checks if a Single Level comment is consistent or not. + * + * @param comment the comment to be checked. + * @param indentInComment the actual indentation in that comment. + * @param isWarnComment if comment is Warn comment or not. + * @return true if Single Level comment is consistent or not else returns false. + */ private static boolean isSingleLevelCommentConsistent(String comment, int indentInComment, boolean isWarnComment) { final Matcher singleLevelMatch = SINGLE_LEVEL_COMMENT_REGEX.matcher(comment); @@ -167,6 +202,14 @@ private static boolean isSingleLevelCommentConsistent(String comment, || expectedLevel != indentInComment && isWarnComment; } + /** + * Checks if a Multi-Level comment is consistent or not. + * + * @param comment the comment to be checked. + * @param indentInComment the actual indentation in that comment. + * @param isWarnComment if comment is Warn comment or not. + * @return true if Multi-Level comment is consistent or not else returns false. + */ private static boolean isMultiLevelCommentConsistent(String comment, int indentInComment, boolean isWarnComment) { final Matcher multilevelMatch = MULTILEVEL_COMMENT_REGEX.matcher(comment); @@ -180,6 +223,14 @@ private static boolean isMultiLevelCommentConsistent(String comment, || !containsActualLevel && isWarnComment; } + /** + * Returns the type of Comment by matching with specific regex for each type. + * Possible types include {@link CommentType#MULTILEVEL}, {@link CommentType#SINGLE_LEVEL}, + * {@link CommentType#NON_STRICT_LEVEL}, and {@link CommentType#UNKNOWN}. + * + * @param comment the comment whose type is to be returned. + * @return {@link CommentType} instance for the given comment. + */ private static CommentType getCommentType(String comment) { CommentType result = CommentType.UNKNOWN; final Matcher multilevelMatch = MULTILEVEL_COMMENT_REGEX.matcher(comment); @@ -201,6 +252,13 @@ private static CommentType getCommentType(String comment) { return result; } + /** + * Returns starting position of a Line. + * + * @param line the line whose starting position is required. + * @param tabWidth tab width (passed value is 4 to this method). + * @return starting position of given line. + */ private static int getLineStart(String line, final int tabWidth) { int lineStart = 0; for (int index = 0; index < line.length(); ++index) { diff --git a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule21filename/FileNameTest.java b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule21filename/FileNameTest.java new file mode 100644 index 000000000000..c0960d1a73c8 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule21filename/FileNameTest.java @@ -0,0 +1,48 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter2filebasic.rule21filename; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class FileNameTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter2filebasic/rule21filename"; + } + + @Test + public void testOuterTypeFilename1() throws Exception { + verifyWithWholeConfig(getPath("InputFileName1.java")); + } + + @Test + public void testOuterTypeFilename2() throws Exception { + verifyWithWholeConfig(getPath("InputFileName2.java")); + } + + @Test + public void testOuterTypeFilename3() throws Exception { + verifyWithWholeConfig(getPath("InputFileName3.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule21filename/OuterTypeFilenameTest.java b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule21filename/OuterTypeFilenameTest.java deleted file mode 100644 index e0a68f3b188e..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule21filename/OuterTypeFilenameTest.java +++ /dev/null @@ -1,73 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter2filebasic.rule21filename; - -import static com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheck.MSG_KEY; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class OuterTypeFilenameTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter2filebasic/rule21filename"; - } - - @Test - public void testOuterTypeFilename1() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("OuterTypeFilename"); - final String filePath = getPath("InputOuterTypeFilename1.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testOuterTypeFilename2() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("OuterTypeFilename"); - final String filePath = getPath("InputOuterTypeFilename2.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testOuterTypeFilename3() throws Exception { - final String[] expected = { - "3: " + getCheckMessage(OuterTypeFilenameCheck.class, MSG_KEY), - }; - - final Configuration checkConfig = getModuleConfig("OuterTypeFilename"); - final String filePath = getPath("InputOuterTypeFilename3.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule231filetab/FileTabCharacterTest.java b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule231filetab/FileTabCharacterTest.java deleted file mode 100644 index 74efc1dc900e..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule231filetab/FileTabCharacterTest.java +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter2filebasic.rule231filetab; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck; - -public class FileTabCharacterTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter2filebasic/rule231filetab"; - } - - @Test - public void testFileTab() throws Exception { - final String[] expected = { - "8:25: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - "51:5: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - "121:35: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - "122:64: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - "130:9: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - "131:10: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - "132:1: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - "133:3: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - "134:3: " + getCheckMessage(FileTabCharacterCheck.class, "containsTab"), - }; - - final Configuration checkConfig = getModuleConfig("FileTabCharacter"); - final String filePath = getPath("InputFileTabCharacter.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule231filetab/WhitespaceCharactersTest.java b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule231filetab/WhitespaceCharactersTest.java new file mode 100644 index 000000000000..ef630458edb1 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule231filetab/WhitespaceCharactersTest.java @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter2filebasic.rule231filetab; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class WhitespaceCharactersTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter2filebasic/rule231filetab"; + } + + @Test + public void testFileTab() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceCharacters.java")); + } + + @Test + public void testFileTabFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceCharacters.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/IllegalTokenTextTest.java b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/IllegalTokenTextTest.java deleted file mode 100644 index 7ebb21810b8c..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/IllegalTokenTextTest.java +++ /dev/null @@ -1,109 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter2filebasic.rule232specialescape; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class IllegalTokenTextTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter2filebasic/rule232specialescape"; - } - - @Test - public void testIllegalTokens() throws Exception { - final String message = "Consider using special escape sequence instead of octal value or " - + "Unicode escaped value."; - - final String[] expected = { - "18:27: " + message, - "19:27: " + message, - "22:25: " + message, - "23:25: " + message, - "25:16: " + message, - "43:21: " + message, - "44:21: " + message, - "45:21: " + message, - "46:21: " + message, - "47:21: " + message, - "48:21: " + message, - "49:21: " + message, - "54:21: " + message, - "55:21: " + message, - "56:21: " + message, - "57:21: " + message, - "58:21: " + message, - "59:21: " + message, - "60:21: " + message, - "61:21: " + message, - "69:31: " + message, - "70:31: " + message, - "73:29: " + message, - "74:29: " + message, - "76:20: " + message, - "94:25: " + message, - "95:25: " + message, - "96:25: " + message, - "97:25: " + message, - "98:25: " + message, - "99:25: " + message, - "100:25: " + message, - "105:25: " + message, - "106:25: " + message, - "107:25: " + message, - "108:25: " + message, - "109:25: " + message, - "110:25: " + message, - "111:25: " + message, - "112:25: " + message, - "119:35: " + message, - "120:35: " + message, - "123:33: " + message, - "124:33: " + message, - "126:24: " + message, - "144:29: " + message, - "145:29: " + message, - "146:29: " + message, - "147:29: " + message, - "148:29: " + message, - "149:29: " + message, - "150:29: " + message, - "155:29: " + message, - "156:29: " + message, - "157:29: " + message, - "158:29: " + message, - "159:29: " + message, - "160:29: " + message, - "161:29: " + message, - "162:29: " + message, - }; - - final Configuration checkConfig = getModuleConfig("IllegalTokenText"); - final String filePath = getPath("InputIllegalTokenText.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/SpecialEscapeSequencesTest.java b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/SpecialEscapeSequencesTest.java new file mode 100644 index 000000000000..7204d777b8da --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/SpecialEscapeSequencesTest.java @@ -0,0 +1,54 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter2filebasic.rule232specialescape; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class SpecialEscapeSequencesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter2filebasic/rule232specialescape"; + } + + @Test + public void testIllegalTokens() throws Exception { + verifyWithWholeConfig(getPath("InputSpecialEscapeSequences.java")); + } + + @Test + public void testIllegalTokensInTextBlockForOctalValues() throws Exception { + verifyWithWholeConfig( + getPath("InputSpecialEscapeSequencesInTextBlockForOctalValues.java")); + } + + @Test + public void testIllegalTokensInTextBlockForUnicodeValues() throws Exception { + verifyWithWholeConfig( + getPath("InputSpecialEscapeSequencesInTextBlockForUnicodeValues.java")); + } + + @Test + public void testIllegalTokensEscapedForEscapedS() throws Exception { + verifyWithWholeConfig(getPath("InputSpecialEscapeSequencesForEscapedS.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule233nonascii/AvoidEscapedUnicodeCharactersTest.java b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule233nonascii/AvoidEscapedUnicodeCharactersTest.java deleted file mode 100644 index 88d8cbba71e8..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule233nonascii/AvoidEscapedUnicodeCharactersTest.java +++ /dev/null @@ -1,55 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter2filebasic.rule233nonascii; - -import static com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck.MSG_KEY; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck; - -public class AvoidEscapedUnicodeCharactersTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter2filebasic/rule233nonascii"; - } - - @Test - public void testUnicodeEscapes() throws Exception { - final String[] expected = { - "5: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), - "15: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), - "25: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), - "33: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), - "35: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), - "36: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), - }; - - final Configuration checkConfig = getModuleConfig("AvoidEscapedUnicodeCharacters"); - final String filePath = getPath("InputAvoidEscapedUnicodeCharacters.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule233nonascii/NonAsciiCharactersTest.java b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule233nonascii/NonAsciiCharactersTest.java new file mode 100644 index 000000000000..998c8fda7583 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter2filebasic/rule233nonascii/NonAsciiCharactersTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter2filebasic.rule233nonascii; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class NonAsciiCharactersTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter2filebasic/rule233nonascii"; + } + + @Test + public void testUnicodeEscapes() throws Exception { + verifyWithWholeConfig(getPath("InputNonAsciiCharacters.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule32packagestate/LineLengthTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule32packagestate/LineLengthTest.java deleted file mode 100644 index fa25db4902f8..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule32packagestate/LineLengthTest.java +++ /dev/null @@ -1,55 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter3filestructure.rule32packagestate; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.sizes.LineLengthCheck; - -public class LineLengthTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter3filestructure/rule32packagestate"; - } - - @Test - public void testLineLength() throws Exception { - final String[] expected = { - "5: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 112), - "29: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 183), - "46: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 131), - "47: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 124), - "48: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 113), - "50: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 116), - "53: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 131), - "57: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 116), - }; - - final Configuration checkConfig = getModuleConfig("LineLength"); - final String filePath = getPath("InputLineLength.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule32packagestatement/PackageStatementTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule32packagestatement/PackageStatementTest.java new file mode 100644 index 000000000000..f418961fa897 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule32packagestatement/PackageStatementTest.java @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter3filestructure.rule32packagestatement; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class PackageStatementTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter3filestructure/rule32packagestatement"; + } + + @Test + public void testPackageStatement() throws Exception { + verifyWithWholeConfig(getPath("InputPackageStatement.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/AvoidStarImportTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/AvoidStarImportTest.java deleted file mode 100644 index 8bb817dd73ea..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/AvoidStarImportTest.java +++ /dev/null @@ -1,50 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter3filestructure.rule331nowildcard; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class AvoidStarImportTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter3filestructure/rule331nowildcard"; - } - - @Test - public void testStarImport() throws Exception { - final String[] expected = { - "3: Using the '.*' form of import should be avoided - java.io.*.", - "4: Using the '.*' form of import should be avoided - java.lang.*.", - "18: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", - "19: Using the '.*' form of import should be avoided - javax.swing.WindowConstants.*.", - }; - - final Configuration checkConfig = getModuleConfig("AvoidStarImport"); - final String filePath = getPath("InputAvoidStarImport.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/NoWildcardImportsTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/NoWildcardImportsTest.java new file mode 100644 index 000000000000..f0da474b08db --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/NoWildcardImportsTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter3filestructure.rule331nowildcard; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class NoWildcardImportsTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter3filestructure/rule331nowildcard"; + } + + @Test + public void testStarImport() throws Exception { + verifyWithWholeConfig(getPath("InputNoWildcardImports.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/NoLineWrapTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/NoLineWrapTest.java deleted file mode 100644 index 86685b8e02f7..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/NoLineWrapTest.java +++ /dev/null @@ -1,78 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter3filestructure.rule332nolinewrap; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.sizes.LineLengthCheck; -import com.puppycrawl.tools.checkstyle.checks.whitespace.NoLineWrapCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class NoLineWrapTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap"; - } - - @Test - public void testBadLineWrap() throws Exception { - final String[] expected = { - "1: " + getCheckMessage(NoLineWrapCheck.class, "no.line.wrap", "package"), - "6: " + getCheckMessage(NoLineWrapCheck.class, "no.line.wrap", "import"), - "10: " + getCheckMessage(NoLineWrapCheck.class, "no.line.wrap", "import"), - }; - - final Configuration checkConfig = getModuleConfig("NoLineWrap"); - final String filePath = getPath("InputNoLineWrapBad.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testGoodLineWrap() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("NoLineWrap"); - final String filePath = getPath("InputNoLineWrapGood.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void goodLineLength() throws Exception { - final int maxLineLength = 100; - final String[] expected = { - "5: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", maxLineLength, 112), - "29: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", maxLineLength, 113), - }; - - final Configuration checkConfig = getModuleConfig("LineLength"); - final String filePath = getPath("InputLineLength.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/NoLineWrappingTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/NoLineWrappingTest.java new file mode 100644 index 000000000000..a83ed51028c6 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/NoLineWrappingTest.java @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter3filestructure.rule332nolinewrap; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class NoLineWrappingTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap"; + } + + @Test + public void testBadLineWrap() throws Exception { + verifyWithWholeConfig(getPath("InputNoLineWrapping.java")); + } + + @Test + public void testBadLineWrapFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNoLineWrapping.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/CustomImportOrderTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/CustomImportOrderTest.java deleted file mode 100644 index e6de9a03ef09..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/CustomImportOrderTest.java +++ /dev/null @@ -1,203 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class CustomImportOrderTest extends AbstractGoogleModuleTestSupport { - - /** Shortcuts to make code more compact. */ - private static final String MSG_LINE_SEPARATOR = CustomImportOrderCheck.MSG_LINE_SEPARATOR; - private static final String MSG_SEPARATED_IN_GROUP = - CustomImportOrderCheck.MSG_SEPARATED_IN_GROUP; - private static final String MSG_LEX = CustomImportOrderCheck.MSG_LEX; - private static final String MSG_NONGROUP_EXPECTED = - CustomImportOrderCheck.MSG_NONGROUP_EXPECTED; - - private static final String STATIC = CustomImportOrderCheck.STATIC_RULE_GROUP; - - private final Class clazz = CustomImportOrderCheck.class; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing"; - } - - @Test - public void testCustomImport1() throws Exception { - final String[] expected = { - "4: " + getCheckMessage(clazz, MSG_LEX, "java.awt.Button.ABORT", - "java.io.File.createTempFile"), - "6: " + getCheckMessage(clazz, MSG_LINE_SEPARATOR, "java.awt.Button"), - "8: " + getCheckMessage(clazz, MSG_LEX, "java.awt.Dialog", "java.awt.Frame"), - "12: " + getCheckMessage(clazz, MSG_LEX, "java.io.File", "javax.swing.JTable"), - "13: " + getCheckMessage(clazz, MSG_LEX, "java.io.IOException", "javax.swing.JTable"), - "14: " + getCheckMessage(clazz, MSG_LEX, "java.io.InputStream", "javax.swing.JTable"), - "15: " + getCheckMessage(clazz, MSG_LEX, "java.io.Reader", "javax.swing.JTable"), - "17: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "com.google.common.base.Ascii"), - "17: " + getCheckMessage(clazz, MSG_LEX, "com.google.common.base.Ascii", - "javax.swing.JTable"), - }; - - final Configuration checkConfig = getModuleConfig("CustomImportOrder"); - final String filePath = getPath("InputCustomImportOrder1.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testCustomImport2() throws Exception { - final String[] expected = { - "4: " + getCheckMessage(clazz, MSG_LEX, "java.awt.Button.ABORT", - "java.io.File.createTempFile"), - "9: " + getCheckMessage(clazz, MSG_LEX, "java.util.*", "java.util.StringTokenizer"), - "11: " + getCheckMessage(clazz, MSG_LEX, "java.util.concurrent.*", - "java.util.concurrent.AbstractExecutorService"), - "13: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "com.google.checkstyle.test.chapter2filebasic.rule21filename.*"), - "13: " + getCheckMessage(clazz, MSG_LEX, - "com.google.checkstyle.test.chapter2filebasic.rule21filename.*", - "java.util.concurrent.AbstractExecutorService"), - "14: " + getCheckMessage(clazz, MSG_LEX, - "com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.*", - "java.util.concurrent.AbstractExecutorService"), - "16: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "com.google.common.reflect.*"), - "16: " + getCheckMessage(clazz, MSG_LEX, "com.google.common.reflect.*", - "java.util.concurrent.AbstractExecutorService"), - }; - - final Configuration checkConfig = getModuleConfig("CustomImportOrder"); - final String filePath = getPath("InputCustomImportOrder2.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testCustomImport3() throws Exception { - final String[] expected = { - "4: " + getCheckMessage(clazz, MSG_LINE_SEPARATOR, "java.awt.Dialog"), - "5: " + getCheckMessage(clazz, MSG_NONGROUP_EXPECTED, STATIC, - "javax.swing.WindowConstants.*"), - "7: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "com.google.checkstyle.test.chapter2filebasic.rule21filename.*"), - "7: " + getCheckMessage(clazz, MSG_LEX, - "com.google.checkstyle.test.chapter2filebasic.rule21filename.*", "java.awt.Dialog"), - "8: " + getCheckMessage(clazz, MSG_LEX, "com.google.common.reflect.*", - "java.awt.Dialog"), - "9: " + getCheckMessage(clazz, MSG_LEX, - "com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.*", - "java.awt.Dialog"), - "11: " + getCheckMessage(clazz, MSG_NONGROUP_EXPECTED, STATIC, - "java.io.File.createTempFile"), - "13: " + getCheckMessage(clazz, MSG_LEX, "java.util.*", "java.util.StringTokenizer"), - "15: " + getCheckMessage(clazz, MSG_LEX, "java.util.concurrent.*", - "java.util.concurrent.AbstractExecutorService"), - }; - - final Configuration checkConfig = getModuleConfig("CustomImportOrder"); - final String filePath = getPath("InputCustomImportOrder3.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testCustomImport4() throws Exception { - final String[] expected = { - "7: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "javax.swing.WindowConstants.*"), - "15: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "java.util.StringTokenizer"), - "17: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "java.util.concurrent.AbstractExecutorService"), - }; - - final Configuration checkConfig = getModuleConfig("CustomImportOrder"); - final String filePath = getPath("InputCustomImportOrder4.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testCustomImport5() throws Exception { - final String[] expected = { - "9: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "javax.swing.WindowConstants.*"), - "13: " + getCheckMessage(clazz, MSG_LINE_SEPARATOR, - "com.google.checkstyle.test.chapter2filebasic.rule21filename.*"), - "17: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "com.google.common.reflect.*"), - "21: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "java.util.StringTokenizer"), - "25: " + getCheckMessage(clazz, MSG_SEPARATED_IN_GROUP, - "java.util.concurrent.AbstractExecutorService"), - }; - - final Configuration checkConfig = getModuleConfig("CustomImportOrder"); - final String filePath = getPath("InputCustomImportOrder5.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testValid() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("CustomImportOrder"); - final String filePath = getPath("InputCustomImportOrderValid.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testValid2() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("CustomImportOrder"); - final String filePath = getPath("InputCustomImportOrderValid2.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testValidGoogleStyleOrderOfImports() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("CustomImportOrder"); - final String filePath = getPath("InputCustomImportOrderNoImports.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/OrderingAndSpacingTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/OrderingAndSpacingTest.java new file mode 100644 index 000000000000..f0480d40d275 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/OrderingAndSpacingTest.java @@ -0,0 +1,112 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class OrderingAndSpacingTest extends AbstractGoogleModuleTestSupport { + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing"; + } + + @Test + public void testCustomImport1() throws Exception { + verifyWithWholeConfig(getPath("InputOrderingAndSpacing1.java")); + } + + @Test + public void testCustomImport1Formatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOrderingAndSpacing1.java")); + } + + @Test + public void testCustomImport2() throws Exception { + verifyWithWholeConfig(getPath("InputOrderingAndSpacing2.java")); + } + + @Test + public void testCustomImport2Formatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOrderingAndSpacing2.java")); + } + + @Test + public void testCustomImport3() throws Exception { + verifyWithWholeConfig(getPath("InputOrderingAndSpacing3.java")); + } + + @Test + public void testCustomImport3Formatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOrderingAndSpacing3.java")); + } + + @Test + public void testCustomImport4() throws Exception { + verifyWithWholeConfig(getPath("InputOrderingAndSpacing4.java")); + } + + @Test + public void testCustomImport4Formatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOrderingAndSpacing4.java")); + } + + @Test + public void testCustomImport5() throws Exception { + verifyWithWholeConfig(getPath("InputOrderingAndSpacing5.java")); + } + + @Test + public void testCustomImport5Formatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOrderingAndSpacing5.java")); + } + + @Test + public void testValid() throws Exception { + verifyWithWholeConfig(getPath("InputOrderingAndSpacingValid.java")); + } + + @Test + public void testValidFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOrderingAndSpacingValid.java")); + } + + @Test + public void testValid2() throws Exception { + verifyWithWholeConfig(getPath("InputOrderingAndSpacingValid2.java")); + } + + @Test + public void testValid2Formatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOrderingAndSpacingValid2.java")); + } + + @Test + public void testValidGoogleStyleOrderOfImports() throws Exception { + verifyWithWholeConfig(getPath("InputOrderingAndSpacingNoImports.java")); + } + + @Test + public void testValidGoogleStyleOrderOfImportsFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOrderingAndSpacingNoImports.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/ExactlyOneTopLevelClassDeclarationTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/ExactlyOneTopLevelClassDeclarationTest.java new file mode 100644 index 000000000000..f6f5d555bb7d --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/ExactlyOneTopLevelClassDeclarationTest.java @@ -0,0 +1,53 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter3filestructure.rule341onetoplevel; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ExactlyOneTopLevelClassDeclarationTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel"; + } + + @Test + public void testBad() throws Exception { + verifyWithWholeConfig(getPath("InputOneTopLevelClassBasic.java")); + } + + @Test + public void testGood() throws Exception { + verifyWithWholeConfig(getPath("InputOneTopLevelClassGood.java")); + } + + @Test + public void testBad1() throws Exception { + verifyWithWholeConfig(getPath("InputOneTopLevelClassBad1.java")); + } + + @Test + public void testBad2() throws Exception { + verifyWithWholeConfig(getPath("InputOneTopLevelClassBad2.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/OneTopLevelClassTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/OneTopLevelClassTest.java deleted file mode 100644 index fa26849b129a..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/OneTopLevelClassTest.java +++ /dev/null @@ -1,101 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter3filestructure.rule341onetoplevel; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.design.OneTopLevelClassCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class OneTopLevelClassTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel"; - } - - @Test - public void testBad() throws Exception { - final Class clazz = OneTopLevelClassCheck.class; - final String messageKey = "one.top.level.class"; - - final String[] expected = { - "25: " + getCheckMessage(clazz, messageKey, "NoSuperClone"), - "33: " + getCheckMessage(clazz, messageKey, "InnerClone"), - "50: " + getCheckMessage(clazz, messageKey, "CloneWithTypeArguments"), - "55: " + getCheckMessage(clazz, messageKey, "CloneWithTypeArgumentsAndNoSuper"), - "60: " + getCheckMessage(clazz, messageKey, "MyClassWithGenericSuperMethod"), - "77: " + getCheckMessage(clazz, messageKey, "AnotherClass"), - }; - - final Configuration checkConfig = getModuleConfig("OneTopLevelClass"); - final String filePath = getPath("InputOneTopLevelClassBasic.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testGood() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("OneTopLevelClass"); - final String filePath = getPath("InputOneTopLevelClassGood.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testBad1() throws Exception { - final Class clazz = OneTopLevelClassCheck.class; - final String messageKey = "one.top.level.class"; - - final String[] expected = { - "4: " + getCheckMessage(clazz, messageKey, "FooEnum"), - }; - - final Configuration checkConfig = getModuleConfig("OneTopLevelClass"); - final String filePath = getPath("InputOneTopLevelClassBad1.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testBad2() throws Exception { - final Class clazz = OneTopLevelClassCheck.class; - final String messageKey = "one.top.level.class"; - - final String[] expected = { - "5: " + getCheckMessage(clazz, messageKey, "FooIn"), - "7: " + getCheckMessage(clazz, messageKey, "FooClass"), - }; - - final Configuration checkConfig = getModuleConfig("OneTopLevelClass"); - final String filePath = getPath("InputOneTopLevelClassBad2.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/OverloadMethodsDeclarationOrderTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/OverloadMethodsDeclarationOrderTest.java deleted file mode 100644 index 3b509051c7e1..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/OverloadMethodsDeclarationOrderTest.java +++ /dev/null @@ -1,55 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter3filestructure.rule3421overloadsplit; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.coding.OverloadMethodsDeclarationOrderCheck; - -public class OverloadMethodsDeclarationOrderTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit"; - } - - @Test - public void testOverloadMethods() throws Exception { - final Class clazz = - OverloadMethodsDeclarationOrderCheck.class; - final String messageKey = "overload.methods.declaration"; - - final String[] expected = { - "26: " + getCheckMessage(clazz, messageKey, 15), - "54: " + getCheckMessage(clazz, messageKey, 43), - "66: " + getCheckMessage(clazz, messageKey, 64), - "109: " + getCheckMessage(clazz, messageKey, 98), - }; - - final Configuration checkConfig = getModuleConfig("OverloadMethodsDeclarationOrder"); - final String filePath = getPath("InputOverloadMethodsDeclarationOrder.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/OverloadsNeverSplitTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/OverloadsNeverSplitTest.java new file mode 100644 index 000000000000..ab74e9c0df4a --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/OverloadsNeverSplitTest.java @@ -0,0 +1,42 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter3filestructure.rule3421overloadsplit; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class OverloadsNeverSplitTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit"; + } + + @Test + public void testOverloadConstructors() throws Exception { + verifyWithWholeConfig(getPath("InputOverloadsNeverSplit.java")); + } + + @Test + public void testOverloadConstructorsRecords() throws Exception { + verifyWithWholeConfig(getPath("InputOverloadsNeverSplitRecords.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/EmptyLineSeparatorTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/EmptyLineSeparatorTest.java deleted file mode 100644 index d1ebbf3ddd04..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/EmptyLineSeparatorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter3filestructure.rule3sourcefile; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyLineSeparatorCheck; - -public class EmptyLineSeparatorTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter3filestructure/rule3sourcefile"; - } - - @Test - public void testEmptyLineSeparator() throws Exception { - final Class clazz = EmptyLineSeparatorCheck.class; - final String messageKey = "empty.line.separator"; - - final String[] expected = { - "19: " + getCheckMessage(clazz, messageKey, "package"), - "20: " + getCheckMessage(clazz, messageKey, "import"), - "33: " + getCheckMessage(clazz, messageKey, "CLASS_DEF"), - "37: " + getCheckMessage(clazz, messageKey, "STATIC_INIT"), - "66: " + getCheckMessage(clazz, messageKey, "METHOD_DEF"), - "75: " + getCheckMessage(clazz, messageKey, "INTERFACE_DEF"), - "82: " + getCheckMessage(clazz, messageKey, "INSTANCE_INIT"), - "113: " + getCheckMessage(clazz, messageKey, "CLASS_DEF"), - "119: " + getCheckMessage(clazz, messageKey, "VARIABLE_DEF"), - }; - - final Configuration checkConfig = getModuleConfig("EmptyLineSeparator"); - final String filePath = getPath("InputEmptyLineSeparator.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/SourceFileStructureTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/SourceFileStructureTest.java new file mode 100644 index 000000000000..a5e3472de770 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/SourceFileStructureTest.java @@ -0,0 +1,47 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter3filestructure.rule3sourcefile; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class SourceFileStructureTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter3filestructure/rule3sourcefile"; + } + + @Test + public void testEmptyLineSeparator() throws Exception { + verifyWithWholeConfig(getPath("InputSourceFileStructure.java")); + } + + @Test + public void testEmptyLineSeparatorFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedSourceFileStructure.java")); + } + + @Test + public void testEmptyLineSeparatorPackageInfo() throws Exception { + verifyWithWholeConfig(getPath("package-info.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/PackageStatementTest.java b/src/it/java/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/PackageStatementTest.java new file mode 100644 index 000000000000..50c5816543fa --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/PackageStatementTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class PackageStatementTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter3filestructure/" + + "toolongpackagetotestcoveragegooglesjavastylerule"; + } + + @Test + public void testPackageStatement() throws Exception { + verifyWithWholeConfig(getPath("InputPackageStatementLongName.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule411bracesareused/NeedBracesTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule411bracesareused/NeedBracesTest.java deleted file mode 100644 index 62b75cee9314..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule411bracesareused/NeedBracesTest.java +++ /dev/null @@ -1,88 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule411bracesareused; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.blocks.NeedBracesCheck; - -public class NeedBracesTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule411bracesareused"; - } - - @Test - public void testNeedBraces() throws Exception { - final Class clazz = NeedBracesCheck.class; - final String messageKey = "needBraces"; - - final String[] expected = { - "29: " + getCheckMessage(clazz, messageKey, "do"), - "41: " + getCheckMessage(clazz, messageKey, "while"), - "42: " + getCheckMessage(clazz, messageKey, "while"), - "44: " + getCheckMessage(clazz, messageKey, "while"), - "45: " + getCheckMessage(clazz, messageKey, "if"), - "58: " + getCheckMessage(clazz, messageKey, "for"), - "59: " + getCheckMessage(clazz, messageKey, "for"), - "61: " + getCheckMessage(clazz, messageKey, "for"), - "63: " + getCheckMessage(clazz, messageKey, "if"), - "82: " + getCheckMessage(clazz, messageKey, "if"), - "83: " + getCheckMessage(clazz, messageKey, "if"), - "85: " + getCheckMessage(clazz, messageKey, "if"), - "87: " + getCheckMessage(clazz, messageKey, "else"), - "89: " + getCheckMessage(clazz, messageKey, "if"), - "97: " + getCheckMessage(clazz, messageKey, "else"), - "99: " + getCheckMessage(clazz, messageKey, "if"), - "100: " + getCheckMessage(clazz, messageKey, "if"), - "126: " + getCheckMessage(clazz, messageKey, "while"), - "129: " + getCheckMessage(clazz, messageKey, "do"), - "135: " + getCheckMessage(clazz, messageKey, "if"), - "138: " + getCheckMessage(clazz, messageKey, "if"), - "139: " + getCheckMessage(clazz, messageKey, "else"), - "144: " + getCheckMessage(clazz, messageKey, "for"), - "147: " + getCheckMessage(clazz, messageKey, "for"), - "157: " + getCheckMessage(clazz, messageKey, "while"), - "160: " + getCheckMessage(clazz, messageKey, "do"), - "166: " + getCheckMessage(clazz, messageKey, "if"), - "169: " + getCheckMessage(clazz, messageKey, "if"), - "170: " + getCheckMessage(clazz, messageKey, "else"), - "175: " + getCheckMessage(clazz, messageKey, "for"), - "178: " + getCheckMessage(clazz, messageKey, "for"), - "189: " + getCheckMessage(clazz, messageKey, "while"), - "192: " + getCheckMessage(clazz, messageKey, "do"), - "198: " + getCheckMessage(clazz, messageKey, "if"), - "201: " + getCheckMessage(clazz, messageKey, "if"), - "202: " + getCheckMessage(clazz, messageKey, "else"), - "207: " + getCheckMessage(clazz, messageKey, "for"), - "210: " + getCheckMessage(clazz, messageKey, "for"), - }; - - final Configuration checkConfig = getModuleConfig("NeedBraces"); - final String filePath = getPath("InputNeedBraces.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule411optionalbracesusage/UseOfOptionalBracesTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule411optionalbracesusage/UseOfOptionalBracesTest.java new file mode 100644 index 000000000000..27b14b507814 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule411optionalbracesusage/UseOfOptionalBracesTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule411optionalbracesusage; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class UseOfOptionalBracesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule411optionalbracesusage"; + } + + @Test + public void testNeedBraces() throws Exception { + verifyWithWholeConfig(getPath("InputUseOfOptionalBraces.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/LeftCurlyTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/LeftCurlyTest.java deleted file mode 100644 index fd6783f51ebc..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/LeftCurlyTest.java +++ /dev/null @@ -1,100 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; - -import static com.puppycrawl.tools.checkstyle.checks.blocks.LeftCurlyCheck.MSG_KEY_LINE_PREVIOUS; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.blocks.LeftCurlyCheck; - -public class LeftCurlyTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks"; - } - - @Test - public void testLeftCurlyBraces() throws Exception { - final String[] expected = { - "4:1: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 1), - "7:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "13:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "26:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "43:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "61:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "97:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - }; - - final Configuration checkConfig = getModuleConfig("LeftCurly"); - final String filePath = getPath("InputLeftCurlyBraces.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testLeftCurlyAnnotations() throws Exception { - final String[] expected = { - "10:1: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 1), - "14:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "21:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "27:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "50:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - }; - - final Configuration checkConfig = getModuleConfig("LeftCurly"); - final String filePath = getPath("InputLeftCurlyAnnotations.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testLeftCurlyMethods() throws Exception { - final String[] expected = { - "4:1: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 1), - "9:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "16:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "19:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "23:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "31:1: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 1), - "33:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "38:9: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 9), - "41:9: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 9), - "45:9: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 9), - "57:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "61:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "69:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "72:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - "76:5: " + getCheckMessage(LeftCurlyCheck.class, MSG_KEY_LINE_PREVIOUS, "{", 5), - }; - - final Configuration checkConfig = getModuleConfig("LeftCurly"); - final String filePath = getPath("InputLeftCurlyMethod.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/NonemptyBlocksKrStyleTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/NonemptyBlocksKrStyleTest.java new file mode 100644 index 000000000000..fab8e5d55f3f --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/NonemptyBlocksKrStyleTest.java @@ -0,0 +1,143 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class NonemptyBlocksKrStyleTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks"; + } + + @Test + public void testLeftAndRightCurlyBraces() throws Exception { + verifyWithWholeConfig(getPath("InputNonemptyBlocksLeftRightCurly.java")); + } + + @Test + public void testLeftAndRightCurlyBracesFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNonemptyBlocksLeftRightCurly.java")); + } + + @Test + public void testLeftCurlyAnnotations() throws Exception { + verifyWithWholeConfig(getPath("InputLeftCurlyAnnotations.java")); + } + + @Test + public void testLeftCurlyAnnotationsFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedLeftCurlyAnnotations.java")); + } + + @Test + public void testLeftCurlyMethods() throws Exception { + verifyWithWholeConfig(getPath("InputLeftCurlyMethod.java")); + } + + @Test + public void testLeftCurlyMethodsFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedLeftCurlyMethod.java")); + } + + @Test + public void testRightCurly() throws Exception { + verifyWithWholeConfig(getPath("InputRightCurly.java")); + } + + @Test + public void testRightCurlyFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedRightCurly.java")); + } + + @Test + public void testRightCurlyLiteralDoDefault() throws Exception { + verifyWithWholeConfig(getPath("InputRightCurlyDoWhile.java")); + } + + @Test + public void testRightCurlyLiteralDoDefaultFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedRightCurlyDoWhile.java")); + } + + @Test + public void testRightCurlyOther() throws Exception { + verifyWithWholeConfig(getPath("InputRightCurlyOther.java")); + } + + @Test + public void testRightCurlyOtherFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedRightCurlyOther.java")); + } + + @Test + public void testRightCurlyLiteralDo() throws Exception { + verifyWithWholeConfig(getPath("InputRightCurlyDoWhile2.java")); + } + + @Test + public void testRightCurlyLiteralDoFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedRightCurlyDoWhile2.java")); + } + + @Test + public void testRightCurlySwitch() throws Exception { + verifyWithWholeConfig(getPath("InputRightCurlySwitchCase.java")); + } + + @Test + public void testRightCurlySwitchFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedRightCurlySwitchCase.java")); + } + + @Test + public void testRightCurlySwitchCases() throws Exception { + verifyWithWholeConfig(getPath("InputRightCurlySwitchCasesBlocks.java")); + } + + @Test + public void testRightCurlySwitchCasesFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedRightCurlySwitchCasesBlocks.java")); + } + + @Test + public void testTryCatchIfElse() throws Exception { + verifyWithWholeConfig(getPath("InputTryCatchIfElse.java")); + } + + @Test + public void testTryCatchIfElseFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedTryCatchIfElse.java")); + } + + @Test + public void testTryCatchIfElse2() throws Exception { + verifyWithWholeConfig(getPath("InputTryCatchIfElse2.java")); + } + + @Test + public void testTryCatchIfElse2Formatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedTryCatchIfElse2.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/RightCurlyTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/RightCurlyTest.java deleted file mode 100644 index 93f6d7cd65f1..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/RightCurlyTest.java +++ /dev/null @@ -1,129 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; - -import static com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck.MSG_KEY_LINE_ALONE; -import static com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck.MSG_KEY_LINE_BREAK_BEFORE; -import static com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck.MSG_KEY_LINE_SAME; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class RightCurlyTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks"; - } - - @Test - public void testRightCurlyAlone() throws Exception { - final String[] expected = { - "20:17: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_SAME, "}", 17), - "32:13: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_SAME, "}", 13), - "79:27: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_BREAK_BEFORE, "}", 27), - }; - - final Configuration checkConfig = getModuleConfig("RightCurly", "RightCurlySame"); - final String filePath = getPath("InputRightCurlyOther.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testRightCurlySame() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("RightCurly", "RightCurlySame"); - final String filePath = getPath("InputRightCurlySame.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testRightCurlySameAndLiteralDoDefault() throws Exception { - final String[] expected = { - "62:9: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_SAME, "}", 9), - "67:13: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_SAME, "}", 13), - "83:9: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_SAME, "}", 9), - }; - - final Configuration checkConfig = getModuleConfig("RightCurly", "RightCurlySame"); - final String filePath = getPath("InputRightCurlyDoWhile.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testRightCurlyAloneOther() throws Exception { - final String[] expected = { - "72:5: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 5), - "97:5: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 5), - "97:6: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 6), - "108:5: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 5), - "108:6: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 6), - "122:5: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 5), - "122:6: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 6), - "125:57: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 57), - "148:39: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 39), - "150:61: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 61), - "153:28: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 28), - "163:16: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 16), - "165:30: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 30), - "168:16: " + getCheckMessage(RightCurlyCheck.class, MSG_KEY_LINE_ALONE, "}", 16), - }; - - final Configuration checkConfig = getModuleConfig("RightCurly", "RightCurlyAlone"); - final String filePath = getPath("InputRightCurlyOtherAlone.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testRightCurlyAloneSame() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("RightCurly", "RightCurlyAlone"); - final String filePath = getPath("InputRightCurlySame.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testRightCurlyAloneSameAndLiteralDo() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("RightCurly", "RightCurlyAlone"); - final String filePath = getPath("InputRightCurlyDoWhileAlone.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyBlockTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyBlockTest.java deleted file mode 100644 index 85a6ce1c0ce0..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyBlockTest.java +++ /dev/null @@ -1,95 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.blocks.EmptyBlockCheck; - -public class EmptyBlockTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule413emptyblocks"; - } - - @Test - public void testEmptyBlock() throws Exception { - final String[] expected = { - "19:21: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "22:34: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "26:21: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "28:20: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "switch"), - "68:25: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "71:38: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "75:25: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "77:24: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "switch"), - "98:29: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "101:42: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "105:29: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "107:28: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "switch"), - "126:16: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "172:28: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "173:14: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "175:21: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "179:14: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "181:21: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "182:26: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "195:20: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "241:32: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "242:18: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "244:25: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "248:18: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "250:25: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "251:30: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "264:24: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "310:36: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "311:22: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "313:29: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "317:22: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "else"), - "319:29: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - "320:34: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "if"), - }; - - final Configuration checkConfig = getModuleConfig("EmptyBlock"); - final String filePath = getPath("InputEmptyBlockBasic.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testEmptyBlockCatch() throws Exception { - final String[] expected = { - "29:17: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "finally"), - "50:21: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "finally"), - "72:21: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "finally"), - }; - - final Configuration checkConfig = getModuleConfig("EmptyBlock"); - final String filePath = getPath("InputEmptyBlock.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyBlocksMayBeConciseTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyBlocksMayBeConciseTest.java new file mode 100644 index 000000000000..41e21e5002ec --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyBlocksMayBeConciseTest.java @@ -0,0 +1,72 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class EmptyBlocksMayBeConciseTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule413emptyblocks"; + } + + @Test + public void testEmptyBlocksAndCatchBlocks() throws Exception { + verifyWithWholeConfig(getPath("InputEmptyBlocksAndCatchBlocks.java")); + } + + @Test + public void testEmptyBlocksAndCatchBlocksFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedEmptyBlocksAndCatchBlocks.java")); + } + + @Test + public void testEmptyFinallyBlocks() throws Exception { + verifyWithWholeConfig(getPath("InputEmptyFinallyBlocks.java")); + } + + @Test + public void testEmptyCatchBlockNoViolations() throws Exception { + verifyWithWholeConfig(getPath("InputEmptyBlocksAndCatchBlocksNoViolations.java")); + } + + @Test + public void testEmptyCatchBlockViolationsByComment() throws Exception { + verifyWithWholeConfig(getPath("InputEmptyCatchBlockViolationsByComment.java")); + } + + @Test + public void testEmptyCatchBlockViolationsByVariableName() throws Exception { + verifyWithWholeConfig(getPath("InputEmptyCatchBlockViolationsByVariableName.java")); + } + + @Test + public void testEmptyCatchEmptyComment() throws Exception { + verifyWithWholeConfig(getPath("InputEmptyCatchEmptyComment.java")); + } + + @Test + public void testFormattedEmptyCatchEmptyComment() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedEmptyCatchEmptyComment.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyCatchBlockTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyCatchBlockTest.java deleted file mode 100644 index be6ce325bb11..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/EmptyCatchBlockTest.java +++ /dev/null @@ -1,94 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.blocks.EmptyCatchBlockCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class EmptyCatchBlockTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule413emptyblocks"; - } - - @Test - public void testEmptyBlockCatch() throws Exception { - final String[] expected = { - "28: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - "49: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - "71: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - "79: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - "83: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - }; - - final Configuration checkConfig = getModuleConfig("EmptyCatchBlock"); - final String filePath = getPath("InputEmptyBlockCatch.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testNoViolations() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("EmptyCatchBlock"); - final String filePath = getPath("InputEmptyCatchBlockNoViolations.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testViolationsByComment() throws Exception { - final String[] expected = { - "19: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - "27: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - }; - - final Configuration checkConfig = getModuleConfig("EmptyCatchBlock"); - final String filePath = getPath("InputEmptyCatchBlockViolationsByComment.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testViolationsByVariableName() throws Exception { - final String[] expected = { - "19: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - "35: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - "51: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - "58: " + getCheckMessage(EmptyCatchBlockCheck.class, "catch.block.empty"), - }; - - final Configuration checkConfig = getModuleConfig("EmptyCatchBlock"); - final String filePath = getPath("InputEmptyCatchBlockViolationsByVariableName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/BlockIndentation2SpacesTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/BlockIndentation2SpacesTest.java new file mode 100644 index 000000000000..b64689e52cab --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/BlockIndentation2SpacesTest.java @@ -0,0 +1,103 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractIndentationTestSupport; + +public class BlockIndentation2SpacesTest extends AbstractIndentationTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule42blockindentation"; + } + + @Test + public void testCorrectClass() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectClass.java")); + } + + @Test + public void testCorrectField() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectFieldAndParameter.java")); + } + + @Test + public void testCorrectFor() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectForAndParameter.java")); + } + + @Test + public void testCorrectIf() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectIfAndParameter.java")); + } + + @Test + public void testCorrectNewKeyword() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectNewChildren.java")); + } + + @Test + public void testCorrect() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrect.java")); + } + + @Test + public void testCorrectReturn() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectReturnAndParameter.java")); + } + + @Test + public void testCorrectWhile() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectWhileDoWhileAndParameter.java")); + } + + @Test + public void testCorrectChained() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedClassWithChainedMethods3.java")); + } + + @Test + public void testWarnChained() throws Exception { + verifyWithWholeConfig(getPath("InputClassWithChainedMethods3.java")); + } + + @Test + public void testCorrectAnnotationArrayInit() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectAnnotationArrayInit.java")); + } + + @Test + public void testCodeBlocks() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCodeBlocks.java")); + } + + @Test + public void testCodeBlocksFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedIndentationCodeBlocks.java")); + } + + @Test + public void testFastMatcher() throws Exception { + verifyWithWholeConfig(getPath("InputFastMatcher.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule43onestatement/OneStatementPerLineTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule43onestatement/OneStatementPerLineTest.java index 6c704943b712..49efab6e5dc3 100644 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule43onestatement/OneStatementPerLineTest.java +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule43onestatement/OneStatementPerLineTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,17 +15,13 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package com.google.checkstyle.test.chapter4formatting.rule43onestatement; -import java.io.File; - import org.junit.jupiter.api.Test; import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.coding.OneStatementPerLineCheck; public class OneStatementPerLineTest extends AbstractGoogleModuleTestSupport { @@ -36,61 +32,22 @@ protected String getPackageLocation() { @Test public void testOneStatement() throws Exception { - final String msg = getCheckMessage(OneStatementPerLineCheck.class, - "multiple.statements.line"); - - final String[] expected = { - "6:59: " + msg, - "50:21: " + msg, - "52:21: " + msg, - "54:42: " + msg, - "57:25: " + msg, - "58:35: " + msg, - "68:14: " + msg, - "95:25: " + msg, - "97:25: " + msg, - "99:46: " + msg, - "102:29: " + msg, - "103:39: " + msg, - "111:15: " + msg, - "123:23: " + msg, - "138:59: " + msg, - "170:19: " + msg, - "188:15: " + msg, - "196:15: " + msg, - "208:6: " + msg, - "217:22: " + msg, - "307:39: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("OneStatementPerLine"); - final String filePath = getPath("InputOneStatementPerLine.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + verifyWithWholeConfig(getPath("InputOneStatementPerLine.java")); } @Test - public void testOneStatementNonCompilableInput() throws Exception { - final String msg = getCheckMessage(OneStatementPerLineCheck.class, - "multiple.statements.line"); - - final String[] expected = { - "32:6: " + msg, - "37:58: " + msg, - "38:58: " + msg, - "38:74: " + msg, - "39:50: " + msg, - "43:85: " + msg, - }; + public void testOneStatementFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOneStatementPerLine.java")); + } - final Configuration checkConfig = getModuleConfig("OneStatementPerLine"); - final String filePath = new File("src/test/resources-noncompilable/" - + "com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/" - + "InputOneStatementPerLine.java").getCanonicalPath(); + @Test + public void testOneStatementInput() throws Exception { + verifyWithWholeConfig(getNonCompilablePath("InputOneStatementPerLine2.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testOneStatementInputFormatted() throws Exception { + verifyWithWholeConfig(getNonCompilablePath("InputFormattedOneStatementPerLine2.java")); } } diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/ColumnLimit100Test.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/ColumnLimit100Test.java new file mode 100644 index 000000000000..eb7e72810b9b --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/ColumnLimit100Test.java @@ -0,0 +1,62 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ColumnLimit100Test extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule44columnlimit"; + } + + @Test + public void testLineLength() throws Exception { + verifyWithWholeConfig(getPath("InputColumnLimit.java")); + } + + @Test + public void testLineLengthFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedColumnLimit.java")); + } + + @Test + public void testTextBlockLineLimit() throws Exception { + verifyWithWholeConfig(getPath("InputTextBlockColumnLimit.java")); + } + + @Test + public void testFormattedTextBlockLineLimit() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedTextBlockColumnLimit.java")); + } + + @Test + public void testTextBlockLineLimitEdgeCase() throws Exception { + verifyWithWholeConfig(getPath("InputColumnLimitEdgeCase.java")); + } + + @Test + public void testFormattedTextBlockLineLimitEdgeCase() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedColumnLimitEdgeCase.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/LineLengthTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/LineLengthTest.java deleted file mode 100644 index 58f3c522aeaf..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/LineLengthTest.java +++ /dev/null @@ -1,49 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.sizes.LineLengthCheck; - -public class LineLengthTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule44columnlimit"; - } - - @Test - public void testLineLength() throws Exception { - final String[] expected = { - "5: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 112), - "29: " + getCheckMessage(LineLengthCheck.class, "maxLineLen", 100, 113), - }; - - final Configuration checkConfig = getModuleConfig("LineLength"); - final String filePath = getPath("InputLineLength.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/MethodParamPadTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/MethodParamPadTest.java deleted file mode 100644 index 9ff8928492d9..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/MethodParamPadTest.java +++ /dev/null @@ -1,55 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.MethodParamPadCheck; - -public class MethodParamPadTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule451wheretobreak"; - } - - @Test - public void testOperatorWrap() throws Exception { - final Class clazz = MethodParamPadCheck.class; - final String messageKeyPrevious = "line.previous"; - final String messageKeyPreceded = "ws.preceded"; - - final String[] expected = { - "83:9: " + getCheckMessage(clazz, messageKeyPrevious, "("), - "128:13: " + getCheckMessage(clazz, messageKeyPrevious, "("), - "130:9: " + getCheckMessage(clazz, messageKeyPrevious, "("), - "353:15: " + getCheckMessage(clazz, messageKeyPreceded, "("), - "358:13: " + getCheckMessage(clazz, messageKeyPrevious, "("), - }; - final Configuration checkConfig = getModuleConfig("MethodParamPad"); - final String filePath = getPath("InputMethodParamPad.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/OperatorWrapTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/OperatorWrapTest.java deleted file mode 100644 index 85d5896710c7..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/OperatorWrapTest.java +++ /dev/null @@ -1,69 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.OperatorWrapCheck; - -public class OperatorWrapTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule451wheretobreak"; - } - - @Test - public void testOperatorWrap() throws Exception { - final Class clazz = OperatorWrapCheck.class; - final String messageKey = "line.new"; - - final String[] expected = { - "11:27: " + getCheckMessage(clazz, messageKey, "+"), - "12:28: " + getCheckMessage(clazz, messageKey, "-"), - "20:27: " + getCheckMessage(clazz, messageKey, "&&"), - "62:42: " + getCheckMessage(clazz, messageKey, "?"), - "66:27: " + getCheckMessage(clazz, messageKey, "!="), - "72:30: " + getCheckMessage(clazz, messageKey, "=="), - "78:27: " + getCheckMessage(clazz, messageKey, ">"), - "84:35: " + getCheckMessage(clazz, messageKey, "||"), - "107:46: " + getCheckMessage(clazz, messageKey, "?"), - "111:31: " + getCheckMessage(clazz, messageKey, "!="), - "117:34: " + getCheckMessage(clazz, messageKey, "=="), - "123:31: " + getCheckMessage(clazz, messageKey, ">"), - "129:39: " + getCheckMessage(clazz, messageKey, "||"), - "153:46: " + getCheckMessage(clazz, messageKey, "?"), - "157:31: " + getCheckMessage(clazz, messageKey, "!="), - "163:34: " + getCheckMessage(clazz, messageKey, "=="), - "169:31: " + getCheckMessage(clazz, messageKey, ">"), - "175:39: " + getCheckMessage(clazz, messageKey, "||"), - "194:38: " + getCheckMessage(clazz, messageKey, "?"), - }; - - final Configuration checkConfig = getModuleConfig("OperatorWrap"); - final String filePath = getPath("InputOperatorWrap.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/SeparatorWrapTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/SeparatorWrapTest.java deleted file mode 100644 index 61df2e9b324c..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/SeparatorWrapTest.java +++ /dev/null @@ -1,103 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; - -import static com.puppycrawl.tools.checkstyle.checks.whitespace.SeparatorWrapCheck.MSG_LINE_NEW; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.SeparatorWrapCheck; - -public class SeparatorWrapTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule451wheretobreak"; - } - - @Test - public void testSeparatorWrapDot() throws Exception { - final String[] expected = { - "28:30: " + getCheckMessage(SeparatorWrapCheck.class, "line.new", "."), - }; - - final Configuration checkConfig = getModuleConfig("SeparatorWrap", "SeparatorWrapDot"); - final String filePath = getPath("InputSeparatorWrap.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testSeparatorWrapComma() throws Exception { - final String[] expected = { - "31:17: " + getCheckMessage(SeparatorWrapCheck.class, "line.previous", ","), - }; - - final Configuration checkConfig = getModuleConfig("SeparatorWrap", "SeparatorWrapComma"); - final String filePath = getPath("InputSeparatorWrapComma.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testSeparatorWrapMethodRef() throws Exception { - final String[] expected = { - "17:49: " + getCheckMessage(SeparatorWrapCheck.class, MSG_LINE_NEW, "::"), - }; - - final Configuration checkConfig = getModuleConfig("SeparatorWrap", - "SeparatorWrapMethodRef"); - final String filePath = getPath("InputSeparatorWrapMethodRef.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testEllipsis() throws Exception { - final String[] expected = { - "11:13: " + getCheckMessage(SeparatorWrapCheck.class, "line.previous", "..."), - }; - - final Configuration checkConfig = getModuleConfig("SeparatorWrap", "SeparatorWrapEllipsis"); - final String filePath = getPath("InputSeparatorWrapEllipsis.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testArrayDeclarator() throws Exception { - final String[] expected = { - "9:13: " + getCheckMessage(SeparatorWrapCheck.class, "line.previous", "["), - }; - final Configuration checkConfig = getModuleConfig("SeparatorWrap", - "SeparatorWrapArrayDeclarator"); - final String filePath = getPath("InputSeparatorWrapArrayDeclarator.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/WhereToBreakTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/WhereToBreakTest.java new file mode 100644 index 000000000000..36f57c8a6699 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/WhereToBreakTest.java @@ -0,0 +1,142 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class WhereToBreakTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule451wheretobreak"; + } + + @Test + public void testOperatorWrap() throws Exception { + verifyWithWholeConfig(getPath("InputOperatorWrap.java")); + } + + @Test + public void testOperatorWrapFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOperatorWrap.java")); + } + + @Test + public void testMethodParamPad() throws Exception { + verifyWithWholeConfig(getPath("InputMethodParamPad.java")); + } + + @Test + public void testMethodParamPadFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedMethodParamPad.java")); + } + + @Test + public void testSeparatorWrapDot() throws Exception { + verifyWithWholeConfig(getPath("InputSeparatorWrap.java")); + } + + @Test + public void testSeparatorWrapDotFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedSeparatorWrap.java")); + } + + @Test + public void testSeparatorWrapComma() throws Exception { + verifyWithWholeConfig(getPath("InputSeparatorWrapComma.java")); + } + + @Test + public void testSeparatorWrapCommaFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedSeparatorWrapComma.java")); + } + + @Test + public void testSeparatorWrapMethodRef() throws Exception { + verifyWithWholeConfig(getPath("InputSeparatorWrapMethodRef.java")); + } + + @Test + public void testSeparatorWrapMethodRefFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedSeparatorWrapMethodRef.java")); + } + + @Test + public void testEllipsis() throws Exception { + verifyWithWholeConfig(getPath("InputSeparatorWrapEllipsis.java")); + } + + @Test + public void testEllipsisFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedSeparatorWrapEllipsis.java")); + } + + @Test + public void testArrayDeclarator() throws Exception { + verifyWithWholeConfig(getPath("InputSeparatorWrapArrayDeclarator.java")); + } + + @Test + public void testArrayDeclaratorFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedSeparatorWrapArrayDeclarator.java")); + } + + @Test + public void testLambdaBodyWrap() throws Exception { + verifyWithWholeConfig(getPath("InputLambdaBodyWrap.java")); + } + + @Test + public void testLambdaBodyWrapFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedLambdaBodyWrap.java")); + } + + @Test + public void testIllegalLineBreakAroundLambda() throws Exception { + verifyWithWholeConfig(getPath("InputIllegalLineBreakAroundLambda.java")); + } + + @Test + public void testFormattedIllegalLineBreakAroundLambda() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedIllegalLineBreakAroundLambda.java")); + } + + @Test + public void testNoWrappingAfterRecordName1() throws Exception { + verifyWithWholeConfig(getPath("InputNoWrappingAfterRecordName.java")); + } + + @Test + public void testNoWrappingAfterRecordNameFormatted1() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNoWrappingAfterRecordName.java")); + } + + @Test + public void testNoWrappingAfterRecordName2() throws Exception { + verifyWithWholeConfig(getPath("InputNoWrappingAfterRecordName2.java")); + } + + @Test + public void testNoWrappingAfterRecordNameFormatted2() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNoWrappingAfterRecordName2.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/IndentContinuationLinesAtLeast4SpacesTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/IndentContinuationLinesAtLeast4SpacesTest.java new file mode 100644 index 000000000000..edf5625e10ea --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/IndentContinuationLinesAtLeast4SpacesTest.java @@ -0,0 +1,92 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractIndentationTestSupport; + +public class IndentContinuationLinesAtLeast4SpacesTest extends AbstractIndentationTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines"; + } + + @Test + public void testCorrectClass() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectClass.java")); + } + + @Test + public void testCorrectField() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectFieldAndParameter.java")); + } + + @Test + public void testCorrectFor() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectForAndParameter.java")); + } + + @Test + public void testCorrectIf() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectIfAndParameter.java")); + } + + @Test + public void testCorrectNewKeyword() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectNewChildren.java")); + } + + @Test + public void testCorrect() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrect.java")); + } + + @Test + public void testCorrectReturn() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectReturnAndParameter.java")); + } + + @Test + public void testCorrectWhile() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectWhileDoWhileAndParameter.java")); + } + + @Test + public void testCorrectChained() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedClassWithChainedMethods2.java")); + } + + @Test + public void testWarnChained() throws Exception { + verifyWithWholeConfig(getPath("InputClassWithChainedMethods2.java")); + } + + @Test + public void testCorrectAnnotationArrayInit() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectAnnotationArrayInit.java")); + } + + @Test + public void testFastMatcher() throws Exception { + verifyWithWholeConfig(getPath("InputFastMatcher.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/EmptyLineSeparatorTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/EmptyLineSeparatorTest.java deleted file mode 100644 index 6910e494e473..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/EmptyLineSeparatorTest.java +++ /dev/null @@ -1,59 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule461verticalwhitespace; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyLineSeparatorCheck; - -public class EmptyLineSeparatorTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace"; - } - - @Test - public void testEmptyLineSeparator() throws Exception { - final Class clazz = EmptyLineSeparatorCheck.class; - final String messageKey = "empty.line.separator"; - - final String[] expected = { - "19: " + getCheckMessage(clazz, messageKey, "package"), - "20: " + getCheckMessage(clazz, messageKey, "import"), - "33: " + getCheckMessage(clazz, messageKey, "CLASS_DEF"), - "37: " + getCheckMessage(clazz, messageKey, "STATIC_INIT"), - "66: " + getCheckMessage(clazz, messageKey, "METHOD_DEF"), - "75: " + getCheckMessage(clazz, messageKey, "INTERFACE_DEF"), - "82: " + getCheckMessage(clazz, messageKey, "INSTANCE_INIT"), - "113: " + getCheckMessage(clazz, messageKey, "CLASS_DEF"), - "119: " + getCheckMessage(clazz, messageKey, "VARIABLE_DEF"), - }; - - final Configuration checkConfig = getModuleConfig("EmptyLineSeparator"); - final String filePath = getPath("InputEmptyLineSeparator.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/VerticalWhitespaceTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/VerticalWhitespaceTest.java new file mode 100644 index 000000000000..12f6e0c9ae7a --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/VerticalWhitespaceTest.java @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule461verticalwhitespace; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class VerticalWhitespaceTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace"; + } + + @Test + public void testEmptyLineSeparator() throws Exception { + verifyWithWholeConfig(getPath("InputVerticalWhitespace.java")); + } + + @Test + public void testEmptyLineSeparatorFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedVerticalWhitespace.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/GenericWhitespaceTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/GenericWhitespaceTest.java deleted file mode 100644 index bd23619c872e..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/GenericWhitespaceTest.java +++ /dev/null @@ -1,121 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class GenericWhitespaceTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace"; - } - - @Test - public void testWhitespaceAroundGenerics() throws Exception { - final String msgPreceded = "ws.preceded"; - final String msgFollowed = "ws.followed"; - final Configuration checkConfig = getModuleConfig("GenericWhitespace"); - final Map messages = checkConfig.getMessages(); - - final String[] expected = { - "12:17: " + getCheckMessage(messages, msgFollowed, "<"), - "12:17: " + getCheckMessage(messages, msgPreceded, "<"), - "12:37: " + getCheckMessage(messages, msgFollowed, "<"), - "12:37: " + getCheckMessage(messages, msgPreceded, "<"), - "12:48: " + getCheckMessage(messages, msgFollowed, ">"), - "12:48: " + getCheckMessage(messages, msgPreceded, ">"), - "12:50: " + getCheckMessage(messages, msgPreceded, ">"), - "14:33: " + getCheckMessage(messages, msgFollowed, "<"), - "14:33: " + getCheckMessage(messages, msgPreceded, "<"), - "14:46: " + getCheckMessage(messages, msgPreceded, ">"), - "15:33: " + getCheckMessage(messages, msgFollowed, "<"), - "15:33: " + getCheckMessage(messages, msgPreceded, "<"), - "15:46: " + getCheckMessage(messages, msgPreceded, ">"), - "20:39: " + getCheckMessage(messages, msgFollowed, "<"), - "20:39: " + getCheckMessage(messages, msgPreceded, "<"), - "20:62: " + getCheckMessage(messages, msgPreceded, ">"), - }; - - final String filePath = getPath("InputWhitespaceAroundGenerics.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testGenericWhitespace() throws Exception { - final String msgPreceded = "ws.preceded"; - final String msgFollowed = "ws.followed"; - final String msgNotPreceded = "ws.notPreceded"; - final String msgIllegalFollow = "ws.illegalFollow"; - final Configuration checkConfig = getModuleConfig("GenericWhitespace"); - final Map messages = checkConfig.getMessages(); - - final String[] expected = { - "16:14: " + getCheckMessage(messages, msgFollowed, "<"), - "16:14: " + getCheckMessage(messages, msgPreceded, "<"), - "16:24: " + getCheckMessage(messages, msgPreceded, ">"), - "16:44: " + getCheckMessage(messages, msgFollowed, "<"), - "16:44: " + getCheckMessage(messages, msgPreceded, "<"), - "16:54: " + getCheckMessage(messages, msgPreceded, ">"), - "17:14: " + getCheckMessage(messages, msgFollowed, "<"), - "17:14: " + getCheckMessage(messages, msgPreceded, "<"), - "17:21: " + getCheckMessage(messages, msgFollowed, "<"), - "17:21: " + getCheckMessage(messages, msgPreceded, "<"), - "17:31: " + getCheckMessage(messages, msgFollowed, ">"), - "17:31: " + getCheckMessage(messages, msgPreceded, ">"), - "17:33: " + getCheckMessage(messages, msgPreceded, ">"), - "17:53: " + getCheckMessage(messages, msgFollowed, "<"), - "17:53: " + getCheckMessage(messages, msgPreceded, "<"), - "17:60: " + getCheckMessage(messages, msgFollowed, "<"), - "17:60: " + getCheckMessage(messages, msgPreceded, "<"), - "17:70: " + getCheckMessage(messages, msgFollowed, ">"), - "17:70: " + getCheckMessage(messages, msgPreceded, ">"), - "17:72: " + getCheckMessage(messages, msgPreceded, ">"), - "30:18: " + getCheckMessage(messages, msgNotPreceded, "<"), - "30:20: " + getCheckMessage(messages, msgIllegalFollow, ">"), - "42:22: " + getCheckMessage(messages, msgPreceded, "<"), - "42:29: " + getCheckMessage(messages, msgFollowed, ">"), - "60:59: " + getCheckMessage(messages, msgNotPreceded, "&"), - "63:59: " + getCheckMessage(messages, msgFollowed, ">"), - }; - - final String filePath = getPath("InputGenericWhitespace.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void genericEndsTheLine() throws Exception { - final Configuration checkConfig = getModuleConfig("GenericWhitespace"); - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - verify(checkConfig, getPath("InputGenericWhitespaceEndsTheLine.java"), - expected); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/HorizontalWhitespaceTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/HorizontalWhitespaceTest.java new file mode 100644 index 000000000000..0669d66579d2 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/HorizontalWhitespaceTest.java @@ -0,0 +1,222 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class HorizontalWhitespaceTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace"; + } + + @Test + public void testWhitespaceAroundBasic() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceAroundBasic.java")); + } + + @Test + public void testWhitespaceAroundBasicFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceAroundBasic.java")); + } + + @Test + public void testWhitespaceAroundEmptyTypesCycles() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceAroundEmptyTypesAndCycles.java")); + } + + @Test + public void testWhitespaceAroundEmptyTypesCyclesFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceAroundEmptyTypesAndCycles.java")); + } + + @Test + public void testWhitespaceAfterBad() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceAfterBad.java")); + } + + @Test + public void testWhitespaceAfterBadFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceAfterBad.java")); + } + + @Test + public void testWhitespaceAfterGood() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceAfterGood.java")); + } + + @Test + public void testWhitespaceAfterGoodFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceAfterGood.java")); + } + + @Test + public void testParenPad() throws Exception { + verifyWithWholeConfig(getPath("InputParenPad.java")); + } + + @Test + public void testParenPadFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedParenPad.java")); + } + + @Test + public void testNoWhitespaceBeforeEmptyForLoop() throws Exception { + verifyWithWholeConfig(getPath("InputNoWhitespaceBeforeEmptyForLoop.java")); + } + + @Test + public void testNoWhitespaceBeforeEmptyForLoopFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNoWhitespaceBeforeEmptyForLoop.java")); + } + + @Test + public void testNoWhitespaceBeforeColonOfLabel() throws Exception { + verifyWithWholeConfig(getPath("InputNoWhitespaceBeforeColonOfLabel.java")); + } + + @Test + public void testNoWhitespaceBeforeColonOfLabelFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNoWhitespaceBeforeColonOfLabel.java")); + } + + @Test + public void testNoWhitespaceBeforeAnnotations() throws Exception { + verifyWithWholeConfig(getPath("InputNoWhitespaceBeforeAnnotations.java")); + } + + @Test + public void testNoWhitespaceBeforeAnnotationsFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNoWhitespaceBeforeAnnotations.java")); + } + + @Test + public void testNoWhitespaceBeforeEllipsis() throws Exception { + verifyWithWholeConfig(getPath("InputNoWhitespaceBeforeEllipsis.java")); + } + + @Test + public void testNoWhitespaceBeforeEllipsisFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNoWhitespaceBeforeEllipsis.java")); + } + + @Test + public void testNoWhitespaceBeforeCaseDefaultColon() throws Exception { + verifyWithWholeConfig(getPath("InputNoWhitespaceBeforeCaseDefaultColon.java")); + } + + @Test + public void testNoWhitespaceBeforeCaseDefaultColonFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNoWhitespaceBeforeCaseDefaultColon.java")); + } + + @Test + public void testMethodParamPad() throws Exception { + verifyWithWholeConfig(getPath("InputMethodParamPad2.java")); + } + + @Test + public void testMethodParamPadFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedMethodParamPad2.java")); + } + + @Test + public void testWhitespaceAroundGenerics() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceAroundGenerics.java")); + } + + @Test + public void testWhitespaceAroundGenericsFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceAroundGenerics.java")); + } + + @Test + public void testGenericWhitespace() throws Exception { + verifyWithWholeConfig(getPath("InputGenericWhitespace.java")); + } + + @Test + public void testGenericWhitespaceFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedGenericWhitespace.java")); + } + + @Test + public void genericEndsTheLine() throws Exception { + verifyWithWholeConfig(getPath("InputGenericWhitespaceEndsTheLine.java")); + } + + @Test + public void genericEndsTheLineFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedGenericWhitespaceEndsTheLine.java")); + } + + @Test + public void testWhitespaceAroundWhen() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceAroundWhen.java")); + } + + @Test + public void testWhitespaceInsideArrayInitializer() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceInsideArrayInitializer.java")); + } + + @Test + public void testWhitespaceInsideArrayInitializerFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceInsideArrayInitializer.java")); + } + + @Test + public void testWhitespaceAroundWhenFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceAroundWhen.java")); + } + + @Test + public void testWhitespaceAroundArrow() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceAroundArrow.java")); + } + + @Test + public void testFormattedWhitespaceAroundArrow() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceAroundArrow.java")); + } + + @Test + public void testWhitespaceAfterDoubleSlashes() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceAfterDoubleSlashes.java")); + } + + @Test + public void testWhitespaceAfterDoubleSlashesFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceAfterDoubleSlashes.java")); + } + + @Test + public void testWhitespaceBeforeLeftCurlyOfEmptyBlocks() throws Exception { + verifyWithWholeConfig(getPath("InputWhitespaceBeforeLeftCurlyOfEmptyBlock.java")); + } + + @Test + public void testWhitespaceBeforeLeftCurlyOfEmptyBlocksFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedWhitespaceBeforeLeftCurlyOfEmptyBlock.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/MethodParamPadTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/MethodParamPadTest.java deleted file mode 100644 index d70338888e4a..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/MethodParamPadTest.java +++ /dev/null @@ -1,57 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.MethodParamPadCheck; - -public class MethodParamPadTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace"; - } - - @Test - public void testOperatorWrap() throws Exception { - final Class clazz = MethodParamPadCheck.class; - final String messageKeyPreceded = "ws.preceded"; - - final String[] expected = { - "11:32: " + getCheckMessage(clazz, messageKeyPreceded, "("), - "13:15: " + getCheckMessage(clazz, messageKeyPreceded, "("), - "20:24: " + getCheckMessage(clazz, messageKeyPreceded, "("), - "29:39: " + getCheckMessage(clazz, messageKeyPreceded, "("), - "35:16: " + getCheckMessage(clazz, messageKeyPreceded, "("), - "41:21: " + getCheckMessage(clazz, messageKeyPreceded, "("), - "47:18: " + getCheckMessage(clazz, messageKeyPreceded, "("), - "52:36: " + getCheckMessage(clazz, messageKeyPreceded, "("), - }; - final Configuration checkConfig = getModuleConfig("MethodParamPad"); - final String filePath = getPath("InputMethodParamPad.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/NoWhitespaceBeforeTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/NoWhitespaceBeforeTest.java deleted file mode 100644 index 795f53decf53..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/NoWhitespaceBeforeTest.java +++ /dev/null @@ -1,52 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceBeforeCheck; - -public class NoWhitespaceBeforeTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace"; - } - - @Test - public void testEmptyForLoop() throws Exception { - final Class clazz = NoWhitespaceBeforeCheck.class; - final String messageKeyPreceded = "ws.preceded"; - - final String[] expected = { - "12:24: " + getCheckMessage(clazz, messageKeyPreceded, ";"), - "18:32: " + getCheckMessage(clazz, messageKeyPreceded, ";"), - }; - final Configuration checkConfig = getModuleConfig("NoWhitespaceBefore"); - final String filePath = getPath("InputNoWhitespaceBeforeEmptyForLoop.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} - diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/ParenPadTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/ParenPadTest.java deleted file mode 100644 index 74dfc35a45b4..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/ParenPadTest.java +++ /dev/null @@ -1,170 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.ParenPadCheck; - -public class ParenPadTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace"; - } - - @Test - public void testMethodParen() throws Exception { - final Class clazz = ParenPadCheck.class; - final String messageKeyPreceded = "ws.preceded"; - final String messageKeyFollowed = "ws.followed"; - - final String[] expected = { - "44:26: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "44:28: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "45:17: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "48:26: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "49:18: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "49:20: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "52:26: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "53:20: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "54:17: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "54:51: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "54:53: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "57:25: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "58:21: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "59:23: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "60:25: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "60:50: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "60:56: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "61:28: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "62:42: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "63:40: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "65:42: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "78:27: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "78:29: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "79:20: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "82:34: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "83:18: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "83:20: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "86:30: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "87:36: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "88:50: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "88:52: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "88:54: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "90:39: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "91:33: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "92:36: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "93:31: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "94:61: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "94:63: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "94:70: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "95:35: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "96:48: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "97:43: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "99:45: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "112:16: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "113:22: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "113:24: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "113:32: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "114:25: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "114:27: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "114:35: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "114:51: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "115:25: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "115:27: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "115:36: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "115:54: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "115:56: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "119:16: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "119:23: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "123:29: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "123:45: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "126:21: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "126:23: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "130:18: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "130:20: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "139:9: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "139:21: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "145:32: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "145:47: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "153:33: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "154:49: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "155:35: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "155:47: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "159:25: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "159:36: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "160:12: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "160:28: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "160:49: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "160:51: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "163:31: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "163:36: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "163:47: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "163:61: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "166:40: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "167:24: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "167:51: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "173:37: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "174:49: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "175:20: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "175:49: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "185:16: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "185:36: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "186:19: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "186:39: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "190:29: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "190:45: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "191:12: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "191:39: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "192:22: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "192:40: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "200:80: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "200:84: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "201:20: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "202:24: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "203:20: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "203:25: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "206:13: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "206:23: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "206:31: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "207:17: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "207:47: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "210:36: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "210:73: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "210:81: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "210:83: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "211:36: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "212:48: " + getCheckMessage(clazz, messageKeyFollowed, "("), - "212:52: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "212:54: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "220:37: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - "221:61: " + getCheckMessage(clazz, messageKeyPreceded, ")"), - }; - final Configuration checkConfig = getModuleConfig("ParenPad"); - final String filePath = getPath("InputParenPad.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/WhitespaceAroundTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/WhitespaceAroundTest.java deleted file mode 100644 index 2031453015b8..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/WhitespaceAroundTest.java +++ /dev/null @@ -1,86 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class WhitespaceAroundTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace"; - } - - @Test - public void testWhitespaceAroundBasic() throws Exception { - final Configuration checkConfig = getModuleConfig("WhitespaceAround"); - final String msgPreceded = "ws.notPreceded"; - final String msgFollowed = "ws.notFollowed"; - final Map messages = checkConfig.getMessages(); - - final String[] expected = { - "10:22: " + getCheckMessage(messages, msgPreceded, "="), - "12:23: " + getCheckMessage(messages, msgFollowed, "="), - "20:14: " + getCheckMessage(messages, msgPreceded, "="), - "21:10: " + getCheckMessage(messages, msgPreceded, "="), - "22:11: " + getCheckMessage(messages, msgFollowed, "+="), - "23:11: " + getCheckMessage(messages, msgFollowed, "-="), - "31:9: " + getCheckMessage(messages, msgFollowed, "synchronized"), - "33:13: " + getCheckMessage(messages, msgFollowed, "{"), - "35:36: " + getCheckMessage(messages, msgFollowed, "{"), - "52:9: " + getCheckMessage(messages, msgFollowed, "if"), - "70:13: " + getCheckMessage(messages, msgFollowed, "return"), - "92:24: " + getCheckMessage(messages, msgFollowed, "=="), - "98:22: " + getCheckMessage(messages, msgPreceded, "*"), - "113:18: " + getCheckMessage(messages, msgPreceded, "%"), - "114:19: " + getCheckMessage(messages, msgFollowed, "%"), - "115:18: " + getCheckMessage(messages, msgPreceded, "%"), - "117:18: " + getCheckMessage(messages, msgPreceded, "/"), - "118:19: " + getCheckMessage(messages, msgFollowed, "/"), - "147:9: " + getCheckMessage(messages, msgFollowed, "assert"), - "150:20: " + getCheckMessage(messages, msgPreceded, ":"), - "249:14: " + getCheckMessage(messages, msgPreceded, "->"), - "250:15: " + getCheckMessage(messages, msgFollowed, "->"), - }; - - final String filePath = getPath("InputWhitespaceAroundBasic.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testWhitespaceAroundEmptyTypesCycles() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("WhitespaceAround"); - final String filePath = getPath("InputWhitespaceAroundEmptyTypesAndCycles.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/MultipleVariableDeclarationsTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/MultipleVariableDeclarationsTest.java deleted file mode 100644 index a7916b1f7fbf..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/MultipleVariableDeclarationsTest.java +++ /dev/null @@ -1,72 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule4821onevariableperline; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.coding.MultipleVariableDeclarationsCheck; - -public class MultipleVariableDeclarationsTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline"; - } - - @Test - public void testMultipleVariableDeclarations() throws Exception { - final String msgComma = getCheckMessage(MultipleVariableDeclarationsCheck.class, - "multiple.variable.declarations.comma"); - final String msg = getCheckMessage(MultipleVariableDeclarationsCheck.class, - "multiple.variable.declarations"); - - final String[] expected = { - "5:5: " + msgComma, - "6:5: " + msg, - "9:9: " + msgComma, - "10:9: " + msg, - "14:5: " + msg, - "17:5: " + msg, - "31:9: " + msgComma, - "32:9: " + msg, - "35:13: " + msgComma, - "36:13: " + msg, - "40:9: " + msg, - "43:9: " + msg, - "57:13: " + msgComma, - "58:13: " + msg, - "61:17: " + msgComma, - "62:17: " + msg, - "66:13: " + msg, - "69:13: " + msg, - "86:5: " + msgComma, - "89:5: " + msgComma, - }; - - final Configuration checkConfig = getModuleConfig("MultipleVariableDeclarations"); - final String filePath = getPath("InputMultipleVariableDeclarations.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/OneVariablePerDeclarationTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/OneVariablePerDeclarationTest.java new file mode 100644 index 000000000000..b7a495a68625 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/OneVariablePerDeclarationTest.java @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4821onevariableperline; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class OneVariablePerDeclarationTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline"; + } + + @Test + public void testMultipleVariableDeclarations() throws Exception { + verifyWithWholeConfig(getPath("InputOneVariablePerDeclaration.java")); + } + + @Test + public void testMultipleVariableDeclarationsFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedOneVariablePerDeclaration.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4822declaredwhenneeded/DeclaredWhenNeededTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4822declaredwhenneeded/DeclaredWhenNeededTest.java new file mode 100644 index 000000000000..86e0f69bebcf --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4822declaredwhenneeded/DeclaredWhenNeededTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4822declaredwhenneeded; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class DeclaredWhenNeededTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4822declaredwhenneeded"; + } + + @Test + public void testVariableDeclarationUsageDistance() throws Exception { + verifyWithWholeConfig(getPath("InputDeclaredWhenNeeded.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4822variabledistance/VariableDeclarationUsageDistanceTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4822variabledistance/VariableDeclarationUsageDistanceTest.java deleted file mode 100644 index 8fcc632e9738..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4822variabledistance/VariableDeclarationUsageDistanceTest.java +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule4822variabledistance; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.coding.VariableDeclarationUsageDistanceCheck; - -public class VariableDeclarationUsageDistanceTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule4822variabledistance"; - } - - @Test - public void testArrayTypeStyle() throws Exception { - final String msgExt = "variable.declaration.usage.distance.extend"; - final Class clazz = - VariableDeclarationUsageDistanceCheck.class; - - final String[] expected = { - "71: " + getCheckMessage(clazz, msgExt, "count", 4, 3), - "219: " + getCheckMessage(clazz, msgExt, "t", 5, 3), - "483: " + getCheckMessage(clazz, msgExt, "myOption", 7, 3), - "495: " + getCheckMessage(clazz, msgExt, "myOption", 6, 3), - }; - - final Configuration checkConfig = - getModuleConfig("VariableDeclarationUsageDistance"); - final String filePath = getPath("InputVariableDeclarationUsageDistanceCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4832nocstylearray/ArrayTypeStyleTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4832nocstylearray/ArrayTypeStyleTest.java deleted file mode 100644 index 69e32b3bcb5f..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4832nocstylearray/ArrayTypeStyleTest.java +++ /dev/null @@ -1,58 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule4832nocstylearray; - -import static com.puppycrawl.tools.checkstyle.checks.ArrayTypeStyleCheck.MSG_KEY; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.ArrayTypeStyleCheck; - -public class ArrayTypeStyleTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule4832nocstylearray"; - } - - @Test - public void testArrayTypeStyle() throws Exception { - final String[] expected = { - "9:23: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - "15:44: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - "21:20: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - "22:23: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - "41:33: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - "46:36: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - "52:27: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - "62:16: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - "63:19: " + getCheckMessage(ArrayTypeStyleCheck.class, MSG_KEY), - }; - - final Configuration checkConfig = getModuleConfig("ArrayTypeStyle"); - final String filePath = getPath("InputArrayTypeStyle.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4832nocstylearray/NoCstyleArrayDeclarationsTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4832nocstylearray/NoCstyleArrayDeclarationsTest.java new file mode 100644 index 000000000000..a14c706cf452 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4832nocstylearray/NoCstyleArrayDeclarationsTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4832nocstylearray; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class NoCstyleArrayDeclarationsTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4832nocstylearray"; + } + + @Test + public void testArrayTypeStyle() throws Exception { + verifyWithWholeConfig(getPath("InputNoCstyleArrays.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4841indentation/IndentationTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4841indentation/IndentationTest.java index 0aa2ddba4265..1b8f747c3d09 100644 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4841indentation/IndentationTest.java +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4841indentation/IndentationTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,19 +15,13 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package com.google.checkstyle.test.chapter4formatting.rule4841indentation; -import static com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck.MSG_CHILD_ERROR; -import static com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck.MSG_ERROR; - import org.junit.jupiter.api.Test; import com.google.checkstyle.test.base.AbstractIndentationTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; public class IndentationTest extends AbstractIndentationTestSupport { @@ -38,106 +32,171 @@ protected String getPackageLocation() { @Test public void testCorrectClass() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + verifyWithWholeConfig(getPath("InputIndentationCorrectClass.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("InputIndentationCorrectClass.java"); + @Test + public void testCorrectField() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectFieldAndParameter.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testCorrectFor() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectForAndParameter.java")); } @Test - public void testCorrectField() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + public void testCorrectIf() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectIfAndParameter.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("InputIndentationCorrectFieldAndParameter.java"); + @Test + public void testCorrectNewKeyword() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectNewChildren.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testCorrect() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrect.java")); } @Test - public void testCorrectFor() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + public void testCorrectReturn() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectReturnAndParameter.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("InputIndentationCorrectForAndParameter.java"); + @Test + public void testCorrectWhile() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectWhileDoWhileAndParameter.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testCorrectChained() throws Exception { + verifyWithWholeConfig(getPath("InputClassWithChainedMethodsCorrect.java")); } @Test - public void testCorrectIf() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + public void testWarnChained() throws Exception { + verifyWithWholeConfig(getPath("InputClassWithChainedMethods.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("InputIndentationCorrectIfAndParameter.java"); + @Test + public void testWarnChainedFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedClassWithChainedMethods.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testCorrectAnnotationArrayInit() throws Exception { + verifyWithWholeConfig(getPath("InputIndentationCorrectAnnotationArrayInit.java")); } @Test - public void testCorrect() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + public void testFastMatcher() throws Exception { + verifyWithWholeConfig(getPath("InputFastMatcher.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("InputIndentationCorrect.java"); + @Test + public void testSwitchOnTheStartOfTheLine() throws Exception { + verifyWithWholeConfig(getPath("InputSwitchOnStartOfTheLine.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testFormattedSwitchOnTheStartOfTheLine() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedSwitchOnStartOfTheLine.java")); } @Test - public void testCorrectReturn() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + public void testSingleSwitchStatementWithoutCurly() throws Exception { + verifyWithWholeConfig(getPath("InputSingleSwitchStatementWithoutCurly.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("InputIndentationCorrectReturnAndParameter.java"); + @Test + public void testFormattedSingleSwitchStatementWithoutCurly() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedSingleSwitchStatementWithoutCurly.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testSwitchWrappingIndentation() throws Exception { + verifyWithWholeConfig(getPath("InputSwitchWrappingIndentation.java")); } @Test - public void testCorrectWhile() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + public void testFormattedSwitchWrappingIndentation() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedSwitchWrappingIndentation.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("InputIndentationCorrectWhileDoWhileAndParameter.java"); + @Test + public void testMultilineParameters() throws Exception { + verifyWithWholeConfig(getPath("InputCatchParametersOnNewLine.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testFormattedMultilineParameters() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedCatchParametersOnNewLine.java")); } @Test - public void testCorrectChained() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; + public void testNewKeywordChildren() throws Exception { + verifyWithWholeConfig(getPath("InputNewKeywordChildren.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("ClassWithChainedMethodsCorrect.java"); + @Test + public void testFormattedNewKeywordChildren() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedNewKeywordChildren.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testLambdaChild() throws Exception { + verifyWithWholeConfig(getPath("InputLambdaChild.java")); } @Test - public void testWarnChained() throws Exception { - final String[] expected = { - "18: " + getCheckMessage(IndentationCheck.class, MSG_CHILD_ERROR, "method call", 4, 8), - "23: " + getCheckMessage(IndentationCheck.class, MSG_ERROR, ".", 4, 8), - "24: " + getCheckMessage(IndentationCheck.class, MSG_ERROR, ".", 4, 8), - "27: " + getCheckMessage(IndentationCheck.class, MSG_ERROR, "new", 4, 8), - }; + public void testFormattedLambdaChild() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedLambdaChild.java")); + } - final Configuration checkConfig = getModuleConfig("Indentation"); - final String filePath = getPath("ClassWithChainedMethods.java"); + @Test + public void testLambdaAndChildOnTheSameLine() throws Exception { + verifyWithWholeConfig(getPath("InputLambdaAndChildOnTheSameLine.java")); + } - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); + @Test + public void testFormattedLambdaAndChildOnTheSameLine() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedLambdaAndChildOnTheSameLine.java")); } + @Test + public void testAnnotationArrayInitMultiline1() throws Exception { + verifyWithWholeConfig(getPath("InputAnnotationArrayInitMultiline.java")); + } + + @Test + public void testFormattedAnnotationArrayInitMultiline1() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedAnnotationArrayInitMultiline.java")); + } + + @Test + public void testAnnotationArrayInitMultiline2() throws Exception { + verifyWithWholeConfig(getPath("InputAnnotationArrayInitMultiline2.java")); + } + + @Test + public void testFormattedAnnotationArrayInitMultiline2() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedAnnotationArrayInitMultiline2.java")); + } + + @Test + public void testLineBreakAfterLeftCurlyOfBlockInSwitch() throws Exception { + verifyWithWholeConfig(getPath("InputLineBreakAfterLeftCurlyOfBlockInSwitch.java")); + } + + @Test + public void testFormattedLineBreakAfterLeftCurlyOfBlockInSwitch() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedLineBreakAfterLeftCurlyOfBlockInSwitch.java")); + } } diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/FallThroughCommentedTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/FallThroughCommentedTest.java new file mode 100644 index 000000000000..f39e629013d0 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/FallThroughCommentedTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4842fallthrough; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class FallThroughCommentedTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4842fallthrough"; + } + + @Test + public void testFallThrough() throws Exception { + verifyWithWholeConfig(getPath("InputFallThrough.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/FallThroughTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/FallThroughTest.java deleted file mode 100644 index 82f66ac79758..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/FallThroughTest.java +++ /dev/null @@ -1,65 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule4842fallthrough; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.coding.FallThroughCheck; - -public class FallThroughTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule4842fallthrough"; - } - - @Test - public void testFallThrough() throws Exception { - final String msg = getCheckMessage(FallThroughCheck.class, "fall.through"); - - final String[] expected = { - "14:13: " + msg, - "38:13: " + msg, - "47:13: " + msg, - "53:13: " + msg, - "70:13: " + msg, - "87:13: " + msg, - "123:13: " + msg, - "179:11: " + msg, - "369:11: " + msg, - "372:11: " + msg, - "374:41: " + msg, - "440:15: " + msg, - "442:15: " + msg, - "444:15: " + msg, - "446:15: " + msg, - "448:15: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("FallThrough"); - final String filePath = getPath("InputFallThrough.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4843defaultcasepresent/MissingSwitchDefaultTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4843defaultcasepresent/MissingSwitchDefaultTest.java deleted file mode 100644 index 995c43894a07..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4843defaultcasepresent/MissingSwitchDefaultTest.java +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule4843defaultcasepresent; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.coding.MissingSwitchDefaultCheck; - -public class MissingSwitchDefaultTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule4843defaultcasepresent"; - } - - @Test - public void testMissingSwitchDefault() throws Exception { - final String msg = getCheckMessage(MissingSwitchDefaultCheck.class, - "missing.switch.default"); - - final String[] expected = { - "11: " + msg, - "19: " + msg, - "23: " + msg, - "31: " + msg, - "38: " + msg, - "42: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("MissingSwitchDefault"); - final String filePath = getPath("InputMissingSwitchDefault.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4843defaultlabelpresence/PresenceOfTheDefaultLabelTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4843defaultlabelpresence/PresenceOfTheDefaultLabelTest.java new file mode 100644 index 000000000000..9baee3310448 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4843defaultlabelpresence/PresenceOfTheDefaultLabelTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4843defaultlabelpresence; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class PresenceOfTheDefaultLabelTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4843defaultlabelpresence"; + } + + @Test + public void testPresenceOfDefaultLabel() throws Exception { + verifyWithWholeConfig(getPath("InputPresenceOfDefaultLabel.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/ClassAnnotationsTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/ClassAnnotationsTest.java new file mode 100644 index 000000000000..38dca6603b8c --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/ClassAnnotationsTest.java @@ -0,0 +1,92 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ClassAnnotationsTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4852classannotations"; + } + + @Test + public void testAnnotation() throws Exception { + final String filePath = getPath("InputClassAnnotations.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testAnnotationFormatted() throws Exception { + final String filePath = getPath("InputFormattedClassAnnotations.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testAnnotation2() throws Exception { + final String filePath = getPath("InputClassAnnotation2.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testAnnotation2Formatted() throws Exception { + final String filePath = getPath("InputFormattedClassAnnotation2.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testPackageAnnotation() throws Exception { + final String filePath = getPath("package-info.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testPackageAnnotation2() throws Exception { + final String filePath = getPath("sample1/package-info.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testPackageAnnotation3() throws Exception { + final String filePath = getPath("sample2/package-info.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testPackageAnnotation4() throws Exception { + final String filePath = getPath("sample3/package-info.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testPackageAnnotation5() throws Exception { + final String filePath = getPath("sample4/package-info.java"); + verifyWithWholeConfig(filePath); + } + + @Test + public void testPackageAnnotation6() throws Exception { + final String filePath = getPath("sample5/package-info.java"); + verifyWithWholeConfig(filePath); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/MethodsAndConstructorsAnnotationsTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/MethodsAndConstructorsAnnotationsTest.java new file mode 100644 index 000000000000..6c1a6c1b3942 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/MethodsAndConstructorsAnnotationsTest.java @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4853methodsandconstructorsannotations; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class MethodsAndConstructorsAnnotationsTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/" + + "rule4853methodsandconstructorsannotations"; + } + + @Test + public void testAnnotation() throws Exception { + verifyWithWholeConfig(getPath("InputMethodsAndConstructorsAnnotations.java")); + } + + @Test + public void testAnnotationFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedMethodsAndConstructorsAnnotations.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/FieldAnnotationsTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/FieldAnnotationsTest.java new file mode 100644 index 000000000000..5380fd9a7f5e --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/FieldAnnotationsTest.java @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4854fieldannotations; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class FieldAnnotationsTest extends AbstractGoogleModuleTestSupport { + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations"; + } + + @Test + public void testAnnotations() throws Exception { + verifyWithWholeConfig(getPath("InputFieldAnnotations.java")); + } + + @Test + public void testAnnotationsFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedFieldAnnotations.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule485annotations/AnnotationLocationTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule485annotations/AnnotationLocationTest.java deleted file mode 100644 index d5fd8bdfb7e2..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule485annotations/AnnotationLocationTest.java +++ /dev/null @@ -1,83 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule485annotations; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationLocationCheck; - -public class AnnotationLocationTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule485annotations"; - } - - @Test - public void testAnnotation() throws Exception { - final Class clazz = AnnotationLocationCheck.class; - getCheckMessage(clazz, "annotation.location.alone"); - final Configuration checkConfig = getModuleConfig("AnnotationLocation", - "AnnotationLocationMostCases"); - - final String msgLocationAlone = "annotation.location.alone"; - final String msgLocation = "annotation.location"; - final String[] expected = { - "3: " + getCheckMessage(clazz, msgLocationAlone, "MyAnnotation1"), - "20: " + getCheckMessage(clazz, msgLocation, "MyAnnotation1", "8", "4"), - "27: " + getCheckMessage(clazz, msgLocation, "MyAnnotation2", "7", "4"), - "31: " + getCheckMessage(clazz, msgLocation, "MyAnnotation2", "8", "4"), - "32: " + getCheckMessage(clazz, msgLocation, "MyAnnotation3", "6", "4"), - "33: " + getCheckMessage(clazz, msgLocation, "MyAnnotation4", "10", "4"), - "54: " + getCheckMessage(clazz, msgLocation, "MyAnnotation2", "12", "8"), - "58: " + getCheckMessage(clazz, msgLocation, "MyAnnotation2", "12", "8"), - "78: " + getCheckMessage(clazz, msgLocation, "MyAnnotation2", "11", "8"), - "81: " + getCheckMessage(clazz, msgLocation, "MyAnnotation2", "10", "8"), - "90: " + getCheckMessage(clazz, msgLocation, "MyAnnotation2", "1", "0"), - "93: " + getCheckMessage(clazz, msgLocationAlone, "MyAnnotationWithParam"), - }; - - final String filePath = getPath("InputAnnotationLocation.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testAnnotationVariables() throws Exception { - final Class clazz = AnnotationLocationCheck.class; - getCheckMessage(clazz, "annotation.location.alone"); - final Configuration checkConfig = getModuleConfig("AnnotationLocation", - "AnnotationLocationVariables"); - - final String msgLocation = "annotation.location"; - final String[] expected = { - "63: " + getCheckMessage(clazz, msgLocation, "MyAnnotation2", "7", "4"), - }; - - final String filePath = getPath("InputAnnotationLocationVariables.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/BlockCommentStyleTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/BlockCommentStyleTest.java new file mode 100644 index 000000000000..97c2697d5ed6 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/BlockCommentStyleTest.java @@ -0,0 +1,74 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class BlockCommentStyleTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle"; + } + + @Test + public void testCommentIsAtTheEndOfBlock() throws Exception { + verifyWithWholeConfig(getPath("InputCommentsIndentationCommentIsAtTheEndOfBlock.java")); + } + + @Test + public void testCommentIsAtTheEndOfBlockFormatted() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedCommentsIndentationCommentIsAtTheEndOfBlock.java")); + } + + @Test + public void testCommentIsInsideSwitchBlock() throws Exception { + verifyWithWholeConfig(getPath("InputCommentsIndentationInSwitchBlock.java")); + } + + @Test + public void testCommentIsInsideSwitchBlockFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedCommentsIndentationInSwitchBlock.java")); + } + + @Test + public void testCommentIsInsideEmptyBlock() throws Exception { + verifyWithWholeConfig(getPath("InputCommentsIndentationInEmptyBlock.java")); + } + + @Test + public void testCommentIsInsideEmptyBlockFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedCommentsIndentationInEmptyBlock.java")); + } + + @Test + public void testSurroundingCode() throws Exception { + verifyWithWholeConfig(getPath("InputCommentsIndentationSurroundingCode.java")); + } + + @Test + public void testSurroundingCodeFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedCommentsIndentationSurroundingCode.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/CommentsIndentationTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/CommentsIndentationTest.java deleted file mode 100644 index bfcfa366fac2..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/CommentsIndentationTest.java +++ /dev/null @@ -1,203 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck; - -public class CommentsIndentationTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle"; - } - - @Test - public void testCommentIsAtTheEndOfBlock() throws Exception { - final String[] expected = { - "18: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 17, 25, 8), - "33: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 35, 5, 4), - "37: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 36, 0, 8), - "47: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 46, 15, 12), - "49: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 45, 10, 8), - "54: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 53, 13, 8), - "74: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 70, 18, 8), - "88: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 85, 31, 8), - "100: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 98, 21, 8), - "115: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 116, 29, 12), - "138: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 131, 26, 8), - "164: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 161, 33, 8), - "174: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 173, 21, 8), - "186: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 184, 34, 8), - "208: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 206, 26, 8), - "214: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 213, 0, 8), - "228: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 225, 12, 8), - "234: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 233, 0, 8), - "248: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 245, 12, 8), - "255: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 252, 0, 8), - "265: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 264, 14, 8), - "271: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 269, 9, 8), - "277: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 276, 9, 8), - "316: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 315, 9, 8), - "322: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 323, 0, 4), - "336: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 333, 0, 8), - "355: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 352, 9, 8), - }; - - final Configuration checkConfig = getModuleConfig("CommentsIndentation"); - final String filePath = - getPath("InputCommentsIndentationCommentIsAtTheEndOfBlock.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testCommentIsInsideSwitchBlock() throws Exception { - final String[] expected = { - "19: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.block", - 20, 12, 16), - "25: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "24, 26", 19, "16, 12"), - "31: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "30, 32", 19, "16, 12"), - "48: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 49, 6, 16), - "55: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 56, 8, 12), - "59: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 58, 22, 16), - "68: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "65, 69", 14, "12, 16"), - "88: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 89, 24, 20), - "113: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "112, 114", 15, "17, 12"), - "125: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 126, 8, 12), - "138: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 139, 4, 8), - "157: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "156, 158", 18, "16, 12"), - "200: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "199, 201", 4, "12, 12"), - "203: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "202, 206", 22, "16, 12"), - "204: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "202, 206", 20, "16, 12"), - "205: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "202, 206", 17, "16, 12"), - "229: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - "228, 230", 6, "12, 12"), - }; - - final Configuration checkConfig = getModuleConfig("CommentsIndentation"); - final String filePath = - getPath("InputCommentsIndentationInSwitchBlock.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testCommentIsInsideEmptyBlock() throws Exception { - final String[] expected = { - "9: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 12, 19, 31), - "10: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.block", - 12, 23, 31), - "33: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 34, 0, 8), - "57: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 58, 0, 8), - "71: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 72, 0, 8), - }; - - final Configuration checkConfig = getModuleConfig("CommentsIndentation"); - final String filePath = - getPath("InputCommentsIndentationInEmptyBlock.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testSurroundingCode() throws Exception { - final String[] expected = { - "13: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 14, 14, 12), - "23: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.block", - 24, 16, 12), - "25: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.block", - 27, 16, 12), - "28: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.block", - 31, 16, 12), - "50: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 53, 27, 36), - "51: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.block", - 53, 23, 36), - "90: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 91, 14, 8), - "98: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 100, 13, 8), - "108: " + getCheckMessage(CommentsIndentationCheck.class, "comments.indentation.single", - 109, 33, 8), - }; - - final Configuration checkConfig = getModuleConfig("CommentsIndentation"); - final String filePath = - getPath("InputCommentsIndentationSurroundingCode.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4862todocomments/TodoCommentTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4862todocomments/TodoCommentTest.java new file mode 100644 index 000000000000..c0a1e69adcb2 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule4862todocomments/TodoCommentTest.java @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule4862todocomments; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class TodoCommentTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule4862todocomments"; + } + + @Test + public void testTodoCommentAllVariants() throws Exception { + verifyWithWholeConfig(getPath("InputTodoCommentAllVariants.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule487modifiers/ModifierOrderTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule487modifiers/ModifierOrderTest.java deleted file mode 100644 index 849312acd401..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule487modifiers/ModifierOrderTest.java +++ /dev/null @@ -1,105 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule487modifiers; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.modifier.ModifierOrderCheck; - -public class ModifierOrderTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule487modifiers"; - } - - @Test - public void testModifierOrder() throws Exception { - final Class clazz = ModifierOrderCheck.class; - final String msgMod = "mod.order"; - final String msgAnnotation = "annotation.order"; - - final String[] expected = { - "3:10: " + getCheckMessage(clazz, msgMod, "abstract"), - "5:15: " + getCheckMessage(clazz, msgMod, "private"), - "7:14: " + getCheckMessage(clazz, msgMod, "public"), - "15:14: " + getCheckMessage(clazz, msgMod, "private"), - "25:13: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "30:13: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "40:34: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation4"), - "46:14: " + getCheckMessage(clazz, msgMod, "protected"), - "48:18: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "50:40: " + getCheckMessage(clazz, msgMod, "final"), - "52:29: " + getCheckMessage(clazz, msgMod, "static"), - "54:18: " + getCheckMessage(clazz, msgMod, "final"), - "56:49: " + getCheckMessage(clazz, msgMod, "private"), - "58:20: " + getCheckMessage(clazz, msgMod, "synchronized"), - "60:29: " + getCheckMessage(clazz, msgMod, "protected"), - "62:14: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "80:11: " + getCheckMessage(clazz, msgMod, "private"), - "96:15: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "98:12: " + getCheckMessage(clazz, msgMod, "protected"), - "102:12: " + getCheckMessage(clazz, msgMod, "synchronized"), - "104:12: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "106:19: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "108:18: " + getCheckMessage(clazz, msgMod, "static"), - "110:25: " + getCheckMessage(clazz, msgMod, "private"), - "137:19: " + getCheckMessage(clazz, msgMod, "private"), - "139:18: " + getCheckMessage(clazz, msgMod, "public"), - "143:19: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "145:22: " + getCheckMessage(clazz, msgMod, "protected"), - "147:16: " + getCheckMessage(clazz, msgMod, "synchronized"), - "149:16: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "151:16: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "153:29: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "155:22: " + getCheckMessage(clazz, msgMod, "private"), - "168:23: " + getCheckMessage(clazz, msgMod, "private"), - "170:22: " + getCheckMessage(clazz, msgMod, "public"), - "172:23: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "174:23: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "176:26: " + getCheckMessage(clazz, msgMod, "protected"), - "178:20: " + getCheckMessage(clazz, msgMod, "synchronized"), - "182:20: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "184:33: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "186:26: " + getCheckMessage(clazz, msgMod, "private"), - "197:19: " + getCheckMessage(clazz, msgMod, "private"), - "199:18: " + getCheckMessage(clazz, msgMod, "public"), - "203:18: " + getCheckMessage(clazz, msgMod, "protected"), - "205:22: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "207:37: " + getCheckMessage(clazz, msgMod, "final"), - "209:33: " + getCheckMessage(clazz, msgMod, "final"), - "211:22: " + getCheckMessage(clazz, msgMod, "final"), - "213:46: " + getCheckMessage(clazz, msgMod, "private"), - "215:24: " + getCheckMessage(clazz, msgMod, "synchronized"), - "217:33: " + getCheckMessage(clazz, msgMod, "protected"), - "219:18: " + getCheckMessage(clazz, msgAnnotation, "@MyAnnotation2"), - "245:14: " + getCheckMessage(clazz, msgMod, "default"), - }; - - final Configuration checkConfig = getModuleConfig("ModifierOrder"); - final String filePath = getPath("InputModifierOrder.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule487modifiers/ModifiersTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule487modifiers/ModifiersTest.java new file mode 100644 index 000000000000..85a034925259 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule487modifiers/ModifiersTest.java @@ -0,0 +1,62 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule487modifiers; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ModifiersTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule487modifiers"; + } + + @Test + public void testModifierOrder() throws Exception { + verifyWithWholeConfig(getPath("InputModifierOrder.java")); + } + + @Test + public void testModifierOrderFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedModifierOrder.java")); + } + + @Test + public void testModifierOrderSealed() throws Exception { + verifyWithWholeConfig(getPath("InputModifierOrderSealed.java")); + } + + @Test + public void testModifierOrderSealedFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedModifierOrderSealed.java")); + } + + @Test + public void testModifierOrderNonSealed() throws Exception { + verifyWithWholeConfig(getPath("InputModifierOrderNonSealed.java")); + } + + @Test + public void testModifierOrderNonSealedFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedModifierOrderNonSealed.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/NumericLiteralsTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/NumericLiteralsTest.java new file mode 100644 index 000000000000..966873cb1ffb --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/NumericLiteralsTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule488numericliterals; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class NumericLiteralsTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule488numericliterals"; + } + + @Test + public void testUpperEll() throws Exception { + verifyWithWholeConfig(getPath("InputNumericLiterals.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/UpperEllTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/UpperEllTest.java deleted file mode 100644 index 60676a9ffb63..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/UpperEllTest.java +++ /dev/null @@ -1,70 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter4formatting.rule488numericliterals; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class UpperEllTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter4formatting/rule488numericliterals"; - } - - @Test - public void testUpperEll() throws Exception { - final String[] expected = { - "6:33: Should use uppercase 'L'.", - "12:25: Should use uppercase 'L'.", - "14:30: Should use uppercase 'L'.", - "17:16: Should use uppercase 'L'.", - "21:27: Should use uppercase 'L'.", - "22:20: Should use uppercase 'L'.", - "25:13: Should use uppercase 'L'.", - "34:44: Should use uppercase 'L'.", - "40:29: Should use uppercase 'L'.", - "42:34: Should use uppercase 'L'.", - "45:20: Should use uppercase 'L'.", - "50:31: Should use uppercase 'L'.", - "51:24: Should use uppercase 'L'.", - "56:21: Should use uppercase 'L'.", - "65:45: Should use uppercase 'L'.", - "71:37: Should use uppercase 'L'.", - "73:42: Should use uppercase 'L'.", - "76:28: Should use uppercase 'L'.", - "80:39: Should use uppercase 'L'.", - "81:32: Should use uppercase 'L'.", - "84:25: Should use uppercase 'L'.", - "97:43: Should use uppercase 'L'.", - "99:27: Should use uppercase 'L'.", - "100:20: Should use uppercase 'L'.", - }; - - final Configuration checkConfig = getModuleConfig("UpperEll"); - final String filePath = getPath("InputUpperEll.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule489textblocks/TextBlocksTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule489textblocks/TextBlocksTest.java new file mode 100644 index 000000000000..f1e99eaa600a --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule489textblocks/TextBlocksTest.java @@ -0,0 +1,52 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule489textblocks; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class TextBlocksTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter4formatting/rule489textblocks"; + } + + @Test + public void testTextBlocksGeneralForm() throws Exception { + verifyWithWholeConfig(getPath("InputTextBlocksGeneralForm.java")); + } + + @Test + public void testFormattedTextBlocksGeneralForm() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedTextBlocksGeneralForm.java")); + } + + @Test + public void testTextBlocksIndentation() throws Exception { + verifyWithWholeConfig(getPath("InputTextBlocksIndentation.java")); + } + + @Test + public void testFormattedTextBlocksIndentation() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedTextBlocksIndentation.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule51identifiernames/CatchParameterNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule51identifiernames/CatchParameterNameTest.java deleted file mode 100644 index 42c629400758..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule51identifiernames/CatchParameterNameTest.java +++ /dev/null @@ -1,58 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule51identifiernames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class CatchParameterNameTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule51identifiernames"; - } - - @Test - public void testCatchParameterName() throws Exception { - final String msgKey = "name.invalidPattern"; - final Configuration checkConfig = getModuleConfig("CatchParameterName"); - final String format = checkConfig.getAttribute("format"); - final Map messages = checkConfig.getMessages(); - - final String[] expected = { - "47:28: " + getCheckMessage(messages, msgKey, "iException", format), - "50:28: " + getCheckMessage(messages, msgKey, "ex_1", format), - "53:28: " + getCheckMessage(messages, msgKey, "eX", format), - "56:28: " + getCheckMessage(messages, msgKey, "eXX", format), - "59:28: " + getCheckMessage(messages, msgKey, "x_y_z", format), - "62:28: " + getCheckMessage(messages, msgKey, "Ex", format), - }; - - final String filePath = getPath("InputCatchParameterName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule51identifiernames/RulesCommonToAllIdentifiersTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule51identifiernames/RulesCommonToAllIdentifiersTest.java new file mode 100644 index 000000000000..f18339c5095c --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule51identifiernames/RulesCommonToAllIdentifiersTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule51identifiernames; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class RulesCommonToAllIdentifiersTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming/rule51identifiernames"; + } + + @Test + public void testCatchParameterName() throws Exception { + verifyWithWholeConfig(getPath("InputCatchParameterName.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule521packagenames/PackageNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule521packagenames/PackageNameTest.java deleted file mode 100644 index 8f35726a0f5c..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule521packagenames/PackageNameTest.java +++ /dev/null @@ -1,107 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule521packagenames; - -import java.io.File; -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class PackageNameTest extends AbstractGoogleModuleTestSupport { - - private static final String MSG_KEY = "name.invalidPattern"; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming"; - } - - private String getPath(String packageName, String fileName) throws IOException { - return getPath("rule521" + packageName + File.separator + fileName); - } - - @Test - public void testGoodPackageName() throws Exception { - final Configuration checkConfig = getModuleConfig("PackageName"); - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final String filePath = getPath("packagenames", "InputPackageNameGood.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testBadPackageName() throws Exception { - final String packagePath = - "com.google.checkstyle.test.chapter5naming.rule521packageNamesCamelCase"; - final Configuration checkConfig = getModuleConfig("PackageName"); - final String format = checkConfig.getAttribute("format"); - final String msg = getCheckMessage(checkConfig.getMessages(), MSG_KEY, packagePath, format); - - final String[] expected = { - "1:9: " + msg, - }; - - final String filePath = getPath("packageNamesCamelCase", "InputPackageNameBad.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testBadPackageName2() throws Exception { - final String packagePath = "com.google.checkstyle.test.chapter5naming.rule521_packagenames"; - final Configuration checkConfig = getModuleConfig("PackageName"); - final String format = checkConfig.getAttribute("format"); - final String msg = getCheckMessage(checkConfig.getMessages(), MSG_KEY, packagePath, format); - - final String[] expected = { - "1:9: " + msg, - }; - - final String filePath = getPath("_packagenames", "InputBadPackageName2.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testBadPackageName3() throws Exception { - final String packagePath = "com.google.checkstyle.test.chapter5naming.rule521$packagenames"; - final Configuration checkConfig = getModuleConfig("PackageName"); - final String format = checkConfig.getAttribute("format"); - final String msg = getCheckMessage(checkConfig.getMessages(), MSG_KEY, packagePath, format); - - final String[] expected = { - "1:9: " + msg, - }; - - final String filePath = getPath("$packagenames", "InputPackageBadName3.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule521packagenames/PackageNamesTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule521packagenames/PackageNamesTest.java new file mode 100644 index 000000000000..6d99b9a2d99c --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule521packagenames/PackageNamesTest.java @@ -0,0 +1,60 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule521packagenames; + +import java.io.File; +import java.io.IOException; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class PackageNamesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming"; + } + + private String getPath(String packageName, String fileName) throws IOException { + return getPath("rule521" + packageName + File.separator + fileName); + } + + @Test + public void testGoodPackageName() throws Exception { + verifyWithWholeConfig(getPath("packagenames", "InputPackageNameGood.java")); + } + + @Test + public void testBadPackageName() throws Exception { + verifyWithWholeConfig(getPath("packageNamesCamelCase", "InputPackageNameBad.java")); + } + + @Test + public void testBadPackageName2() throws Exception { + verifyWithWholeConfig(getPath("_packagenames", "InputBadPackageName2.java")); + } + + @Test + public void testBadPackageName3() throws Exception { + verifyWithWholeConfig(getPath("$packagenames", "InputPackageBadName3.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule522classnames/ClassNamesTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule522classnames/ClassNamesTest.java new file mode 100644 index 000000000000..adf1dccad5b4 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule522classnames/ClassNamesTest.java @@ -0,0 +1,47 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule522classnames; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ClassNamesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming/rule522classnames"; + } + + @Test + public void testClassNames() throws Exception { + verifyWithWholeConfig(getPath("InputClassNames.java")); + } + + @Test + public void testClassNamesFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedClassNames.java")); + } + + @Test + public void testClassNamesWithUnderscore() throws Exception { + verifyWithWholeConfig(getPath("InputClassNamesWithUnderscore.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule522typenames/TypeNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule522typenames/TypeNameTest.java deleted file mode 100644 index b64a3cd46168..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule522typenames/TypeNameTest.java +++ /dev/null @@ -1,82 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule522typenames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class TypeNameTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule522typenames"; - } - - @Test - public void testTypeName() throws Exception { - final Configuration checkConfig = getModuleConfig("TypeName"); - final String msgKey = "name.invalidPattern"; - final String format = "^[A-Z][a-zA-Z0-9]*$"; - final Map messages = checkConfig.getMessages(); - - final String[] expected = { - "3:7: " + getCheckMessage(messages, msgKey, "inputHeaderClass", format), - "5:22: " + getCheckMessage(messages, msgKey, "InputHeader___Interface", format), - "7:17: " + getCheckMessage(messages, msgKey, "inputHeaderEnum", format), - "9:11: " + getCheckMessage(messages, msgKey, "NoValid$Name", format), - "11:11: " + getCheckMessage(messages, msgKey, "$NoValidName", format), - "13:11: " + getCheckMessage(messages, msgKey, "NoValidName$", format), - "19:7: " + getCheckMessage(messages, msgKey, "_ValidName", format), - "21:7: " + getCheckMessage(messages, msgKey, "Valid_Name", format), - "23:7: " + getCheckMessage(messages, msgKey, "ValidName_", format), - "27:11: " + getCheckMessage(messages, msgKey, "_Foo", format), - "29:11: " + getCheckMessage(messages, msgKey, "Fo_o", format), - "31:11: " + getCheckMessage(messages, msgKey, "Foo_", format), - "33:11: " + getCheckMessage(messages, msgKey, "$Foo", format), - "35:11: " + getCheckMessage(messages, msgKey, "Fo$o", format), - "37:11: " + getCheckMessage(messages, msgKey, "Foo$", format), - "41:6: " + getCheckMessage(messages, msgKey, "_FooEnum", format), - "43:6: " + getCheckMessage(messages, msgKey, "Foo_Enum", format), - "45:6: " + getCheckMessage(messages, msgKey, "FooEnum_", format), - "47:6: " + getCheckMessage(messages, msgKey, "$FooEnum", format), - "49:6: " + getCheckMessage(messages, msgKey, "Foo$Enum", format), - "51:6: " + getCheckMessage(messages, msgKey, "FooEnum$", format), - "53:7: " + getCheckMessage(messages, msgKey, "aaa", format), - "55:11: " + getCheckMessage(messages, msgKey, "bbb", format), - "57:6: " + getCheckMessage(messages, msgKey, "ccc", format), - "61:12: " + getCheckMessage(messages, msgKey, "_Annotation", format), - "63:12: " + getCheckMessage(messages, msgKey, "Annot_ation", format), - "65:12: " + getCheckMessage(messages, msgKey, "Annotation_", format), - "67:12: " + getCheckMessage(messages, msgKey, "$Annotation", format), - "69:12: " + getCheckMessage(messages, msgKey, "Annot$ation", format), - "71:12: " + getCheckMessage(messages, msgKey, "Annotation$", format), - }; - - final String filePath = getPath("InputTypeName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule523methodnames/MethodNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule523methodnames/MethodNameTest.java deleted file mode 100644 index 262d55ebe02d..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule523methodnames/MethodNameTest.java +++ /dev/null @@ -1,76 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule523methodnames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class MethodNameTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule523methodnames"; - } - - @Test - public void testMethodName() throws Exception { - final Configuration checkConfig = getModuleConfig("MethodName"); - final String msgKey = "name.invalidPattern"; - final String format = "^[a-z][a-z0-9][a-zA-Z0-9_]*$"; - final Map messages = checkConfig.getMessages(); - - final String[] expected = { - "11:10: " + getCheckMessage(messages, msgKey, "Foo", format), - "12:10: " + getCheckMessage(messages, msgKey, "fOo", format), - "14:10: " + getCheckMessage(messages, msgKey, "f$o", format), - "15:10: " + getCheckMessage(messages, msgKey, "f_oo", format), - "16:10: " + getCheckMessage(messages, msgKey, "f", format), - "17:10: " + getCheckMessage(messages, msgKey, "fO", format), - "21:14: " + getCheckMessage(messages, msgKey, "Foo", format), - "22:14: " + getCheckMessage(messages, msgKey, "fOo", format), - "24:14: " + getCheckMessage(messages, msgKey, "f$o", format), - "25:14: " + getCheckMessage(messages, msgKey, "f_oo", format), - "26:14: " + getCheckMessage(messages, msgKey, "f", format), - "27:14: " + getCheckMessage(messages, msgKey, "fO", format), - "32:14: " + getCheckMessage(messages, msgKey, "Foo", format), - "33:14: " + getCheckMessage(messages, msgKey, "fOo", format), - "35:14: " + getCheckMessage(messages, msgKey, "f$o", format), - "36:14: " + getCheckMessage(messages, msgKey, "f_oo", format), - "37:14: " + getCheckMessage(messages, msgKey, "f", format), - "38:14: " + getCheckMessage(messages, msgKey, "fO", format), - "44:10: " + getCheckMessage(messages, msgKey, "Foo", format), - "45:10: " + getCheckMessage(messages, msgKey, "fOo", format), - "47:10: " + getCheckMessage(messages, msgKey, "f$o", format), - "48:10: " + getCheckMessage(messages, msgKey, "f_oo", format), - "49:10: " + getCheckMessage(messages, msgKey, "f", format), - "50:10: " + getCheckMessage(messages, msgKey, "fO", format), - }; - - final String filePath = getPath("InputMethodName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule523methodnames/MethodNamesTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule523methodnames/MethodNamesTest.java new file mode 100644 index 000000000000..b76ec8fa23cd --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule523methodnames/MethodNamesTest.java @@ -0,0 +1,42 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule523methodnames; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class MethodNamesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming/rule523methodnames"; + } + + @Test + public void testMethodName() throws Exception { + verifyWithWholeConfig(getPath("InputMethodName.java")); + } + + @Test + public void testMethodName2() throws Exception { + verifyWithWholeConfig(getPath("InputMethodName2.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/MemberNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/MemberNameTest.java deleted file mode 100644 index 752c506b77fd..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/MemberNameTest.java +++ /dev/null @@ -1,111 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule525nonconstantfieldnames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class MemberNameTest extends AbstractGoogleModuleTestSupport { - - private static final String MSG_KEY = "name.invalidPattern"; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames"; - } - - @Test - public void testMemberName() throws Exception { - final Configuration checkConfig = getModuleConfig("MemberName"); - final String format = checkConfig.getAttribute("format"); - final Map messages = checkConfig.getMessages(); - final String[] expected = { - "5:16: " + getCheckMessage(messages, MSG_KEY, "mPublic", format), - "6:19: " + getCheckMessage(messages, MSG_KEY, "mProtected", format), - "7:9: " + getCheckMessage(messages, MSG_KEY, "mPackage", format), - "8:17: " + getCheckMessage(messages, MSG_KEY, "mPrivate", format), - "10:16: " + getCheckMessage(messages, MSG_KEY, "_public", format), - "11:19: " + getCheckMessage(messages, MSG_KEY, "prot_ected", format), - "12:9: " + getCheckMessage(messages, MSG_KEY, "package_", format), - "13:17: " + getCheckMessage(messages, MSG_KEY, "priva$te", format), - "20:9: " + getCheckMessage(messages, MSG_KEY, "ABC", format), - "21:15: " + getCheckMessage(messages, MSG_KEY, "C_D_E", format), - "23:16: " + getCheckMessage(messages, MSG_KEY, "$mPublic", format), - "24:19: " + getCheckMessage(messages, MSG_KEY, "mPro$tected", format), - "25:9: " + getCheckMessage(messages, MSG_KEY, "mPackage$", format), - }; - - final String filePath = getPath("InputMemberNameBasic.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testSimple() throws Exception { - final Configuration checkConfig = getModuleConfig("MemberName"); - final String format = checkConfig.getAttribute("format"); - final Map messages = checkConfig.getMessages(); - final String[] expected = { - "12:17: " + getCheckMessage(messages, MSG_KEY, "bad$Static", format), - "17:17: " + getCheckMessage(messages, MSG_KEY, "bad_Member", format), - "19:17: " + getCheckMessage(messages, MSG_KEY, "m", format), - "21:19: " + getCheckMessage(messages, MSG_KEY, "m_M", format), - "24:19: " + getCheckMessage(messages, MSG_KEY, "m$nts", format), - "35:9: " + getCheckMessage(messages, MSG_KEY, "mTest1", format), - "37:16: " + getCheckMessage(messages, MSG_KEY, "mTest2", format), - "39:16: " + getCheckMessage(messages, MSG_KEY, "$mTest2", format), - "41:16: " + getCheckMessage(messages, MSG_KEY, "mTes$t2", format), - "43:16: " + getCheckMessage(messages, MSG_KEY, "mTest2$", format), - "77:21: " + getCheckMessage(messages, MSG_KEY, "bad$Static", format), - "79:22: " + getCheckMessage(messages, MSG_KEY, "sum_Created", format), - "82:21: " + getCheckMessage(messages, MSG_KEY, "bad_Member", format), - "84:21: " + getCheckMessage(messages, MSG_KEY, "m", format), - "86:23: " + getCheckMessage(messages, MSG_KEY, "m_M", format), - "89:23: " + getCheckMessage(messages, MSG_KEY, "m$nts", format), - "93:13: " + getCheckMessage(messages, MSG_KEY, "mTest1", format), - "95:20: " + getCheckMessage(messages, MSG_KEY, "mTest2", format), - "97:20: " + getCheckMessage(messages, MSG_KEY, "$mTest2", format), - "99:20: " + getCheckMessage(messages, MSG_KEY, "mTes$t2", format), - "101:20: " + getCheckMessage(messages, MSG_KEY, "mTest2$", format), - "107:25: " + getCheckMessage(messages, MSG_KEY, "bad$Static", format), - "109:25: " + getCheckMessage(messages, MSG_KEY, "sum_Created", format), - "112:25: " + getCheckMessage(messages, MSG_KEY, "bad_Member", format), - "114:25: " + getCheckMessage(messages, MSG_KEY, "m", format), - "116:25: " + getCheckMessage(messages, MSG_KEY, "m_M", format), - "119:27: " + getCheckMessage(messages, MSG_KEY, "m$nts", format), - "123:25: " + getCheckMessage(messages, MSG_KEY, "mTest1", format), - "125:25: " + getCheckMessage(messages, MSG_KEY, "mTest2", format), - "127:25: " + getCheckMessage(messages, MSG_KEY, "$mTest2", format), - "129:25: " + getCheckMessage(messages, MSG_KEY, "mTes$t2", format), - "131:25: " + getCheckMessage(messages, MSG_KEY, "mTest2$", format), - }; - - final String filePath = getPath("InputMemberNameSimple.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/NonConstantFieldNamesTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/NonConstantFieldNamesTest.java new file mode 100644 index 000000000000..c408ccde3855 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/NonConstantFieldNamesTest.java @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule525nonconstantfieldnames; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class NonConstantFieldNamesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames"; + } + + @Test + public void testMemberName() throws Exception { + verifyWithWholeConfig(getPath("InputNonConstantNamesBasic.java")); + } + + @Test + public void testSimple() throws Exception { + verifyWithWholeConfig(getPath("InputNonConstantNamesSimple.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/LambdaParameterNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/LambdaParameterNameTest.java deleted file mode 100644 index 066217516ff7..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/LambdaParameterNameTest.java +++ /dev/null @@ -1,58 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule526parameternames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class LambdaParameterNameTest extends AbstractGoogleModuleTestSupport { - - public static final String MSG_INVALID_PATTERN = "name.invalidPattern"; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule526parameternames"; - } - - @Test - public void testLambdaParameterName() throws Exception { - final Configuration config = getModuleConfig("LambdaParameterName"); - final String format = config.getAttribute("format"); - final Map messages = config.getMessages(); - - final String[] expected = { - "9:13: " + getCheckMessage(messages, MSG_INVALID_PATTERN, "S", format), - "12:14: " + getCheckMessage(messages, MSG_INVALID_PATTERN, "sT", format), - "14:65: " + getCheckMessage(messages, MSG_INVALID_PATTERN, "sT1", format), - "14:70: " + getCheckMessage(messages, MSG_INVALID_PATTERN, "sT2", format), - "17:21: " + getCheckMessage(messages, MSG_INVALID_PATTERN, "_s", format), - }; - - final String filePath = getPath("InputLambdaParameterName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(config, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/ParameterNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/ParameterNameTest.java deleted file mode 100644 index 764998e5912e..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/ParameterNameTest.java +++ /dev/null @@ -1,64 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule526parameternames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class ParameterNameTest extends AbstractGoogleModuleTestSupport { - - private static final String MSG_KEY = "name.invalidPattern"; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule526parameternames"; - } - - @Test - public void testGeneralParameterName() throws Exception { - final Configuration config = getModuleConfig("ParameterName"); - final String format = config.getAttribute("format"); - final Map messages = config.getMessages(); - final String[] expected = { - "10:21: " + getCheckMessage(messages, MSG_KEY, "bB", format), - "33:18: " + getCheckMessage(messages, MSG_KEY, "llll_llll", format), - "34:21: " + getCheckMessage(messages, MSG_KEY, "bB", format), - "64:13: " + getCheckMessage(messages, MSG_KEY, "$arg1", format), - "65:13: " + getCheckMessage(messages, MSG_KEY, "ar$g2", format), - "66:13: " + getCheckMessage(messages, MSG_KEY, "arg3$", format), - "67:13: " + getCheckMessage(messages, MSG_KEY, "a_rg4", format), - "68:13: " + getCheckMessage(messages, MSG_KEY, "_arg5", format), - "69:13: " + getCheckMessage(messages, MSG_KEY, "arg6_", format), - "70:13: " + getCheckMessage(messages, MSG_KEY, "aArg7", format), - "71:13: " + getCheckMessage(messages, MSG_KEY, "aArg8", format), - "72:13: " + getCheckMessage(messages, MSG_KEY, "aar_g", format), - }; - - final String filePath = getPath("InputParameterName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(config, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/ParameterNamesTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/ParameterNamesTest.java new file mode 100644 index 000000000000..38fae2caff1c --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule526parameternames/ParameterNamesTest.java @@ -0,0 +1,58 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule526parameternames; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ParameterNamesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming/rule526parameternames"; + } + + @Test + public void testLambdaParameterName() throws Exception { + verifyWithWholeConfig(getPath("InputLambdaParameterName.java")); + } + + @Test + public void testGeneralParameterName() throws Exception { + verifyWithWholeConfig(getPath("InputParameterName.java")); + } + + @Test + public void testRecordParameterName() throws Exception { + verifyWithWholeConfig(getPath("InputRecordComponentNameTwo.java")); + } + + @Test + public void testFormattedRecordParameterName() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedRecordComponentNameTwo.java")); + } + + @Test + public void testCatchParameterName() throws Exception { + verifyWithWholeConfig(getPath("InputCatchParameterName.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/LocalVariableNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/LocalVariableNameTest.java deleted file mode 100644 index 28e8e0adb6bf..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/LocalVariableNameTest.java +++ /dev/null @@ -1,82 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule527localvariablenames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class LocalVariableNameTest extends AbstractGoogleModuleTestSupport { - - private static final String MSG_KEY = "name.invalidPattern"; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule527localvariablenames"; - } - - @Test - public void testLocalVariableName() throws Exception { - final Configuration checkConfig = getModuleConfig("LocalVariableName"); - final String format = checkConfig.getAttribute("format"); - final Map messages = checkConfig.getMessages(); - final String[] expected = { - "27:13: " + getCheckMessage(messages, MSG_KEY, "aA", format), - "28:13: " + getCheckMessage(messages, MSG_KEY, "a1_a", format), - "29:13: " + getCheckMessage(messages, MSG_KEY, "A_A", format), - "30:13: " + getCheckMessage(messages, MSG_KEY, "aa2_a", format), - "31:13: " + getCheckMessage(messages, MSG_KEY, "_a", format), - "32:13: " + getCheckMessage(messages, MSG_KEY, "_aa", format), - "33:13: " + getCheckMessage(messages, MSG_KEY, "aa_", format), - "34:13: " + getCheckMessage(messages, MSG_KEY, "aaa$aaa", format), - "35:13: " + getCheckMessage(messages, MSG_KEY, "$aaaaaa", format), - "36:13: " + getCheckMessage(messages, MSG_KEY, "aaaaaa$", format), - }; - - final String filePath = getPath("InputLocalVariableNameSimple.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testOneChar() throws Exception { - final Configuration checkConfig = getModuleConfig("LocalVariableName"); - final String format = checkConfig.getAttribute("format"); - final Map messages = checkConfig.getMessages(); - final String[] expected = { - "21:17: " + getCheckMessage(messages, MSG_KEY, "I_ndex", format), - "45:17: " + getCheckMessage(messages, MSG_KEY, "i_ndex", format), - "49:17: " + getCheckMessage(messages, MSG_KEY, "ii_i1", format), - "53:17: " + getCheckMessage(messages, MSG_KEY, "$index", format), - "57:17: " + getCheckMessage(messages, MSG_KEY, "in$dex", format), - "61:17: " + getCheckMessage(messages, MSG_KEY, "index$", format), - }; - - final String filePath = getPath("InputLocalVariableNameOneCharVarName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/LocalVariableNamesTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/LocalVariableNamesTest.java new file mode 100644 index 000000000000..23e6294dcdd3 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/LocalVariableNamesTest.java @@ -0,0 +1,55 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule527localvariablenames; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class LocalVariableNamesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming/rule527localvariablenames"; + } + + @Test + public void testPatternVariableName() throws Exception { + verifyWithWholeConfig(getPath( + "InputPatternVariableNameEnhancedInstanceofTestDefault.java")); + } + + @Test + public void testFormattedPatternVariableName() throws Exception { + verifyWithWholeConfig(getPath( + "InputFormattedPatternVariableNameEnhancedInstanceofTestDefault.java")); + } + + @Test + public void testLocalAndPatternVariableName() throws Exception { + verifyWithWholeConfig(getPath("InputLocalVariableNameSimple.java")); + } + + @Test + public void testOneChar() throws Exception { + verifyWithWholeConfig(getPath("InputLocalVariableNameOneCharVarName.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/ClassTypeParameterNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/ClassTypeParameterNameTest.java deleted file mode 100644 index 2cd1fc29db48..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/ClassTypeParameterNameTest.java +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule528typevariablenames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class ClassTypeParameterNameTest extends AbstractGoogleModuleTestSupport { - - private static final String MSG_KEY = "name.invalidPattern"; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule528typevariablenames"; - } - - @Test - public void testClassDefault() throws Exception { - final Configuration configuration = getModuleConfig("ClassTypeParameterName"); - final String format = configuration.getAttribute("format"); - final Map messages = configuration.getMessages(); - - final String[] expected = { - "5:36: " + getCheckMessage(messages, MSG_KEY, "t", format), - "13:14: " + getCheckMessage(messages, MSG_KEY, "foo", format), - "27:24: " + getCheckMessage(messages, MSG_KEY, "$foo", format), - }; - - final String filePath = getPath("InputClassTypeParameterName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(configuration, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InterfaceTypeParameterNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InterfaceTypeParameterNameTest.java deleted file mode 100644 index 82fe45a6f7e7..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InterfaceTypeParameterNameTest.java +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule528typevariablenames; - -import java.util.Map; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class InterfaceTypeParameterNameTest extends AbstractGoogleModuleTestSupport { - - private static final String MSG_KEY = "name.invalidPattern"; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule528typevariablenames"; - } - - @Test - public void testInterfaceDefault() throws Exception { - final Configuration configuration = getModuleConfig("InterfaceTypeParameterName"); - final String format = configuration.getAttribute("format"); - final Map messages = configuration.getMessages(); - - final String[] expected = { - "48:15: " + getCheckMessage(messages, MSG_KEY, "Input", format), - "76:25: " + getCheckMessage(messages, MSG_KEY, "Request", format), - "80:25: " + getCheckMessage(messages, MSG_KEY, "TRequest", format), - }; - - final String filePath = getPath("InputInterfaceTypeParameterName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(configuration, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/MethodTypeParameterNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/MethodTypeParameterNameTest.java deleted file mode 100644 index 935d70df45ac..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/MethodTypeParameterNameTest.java +++ /dev/null @@ -1,66 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule528typevariablenames; - -import java.util.Map; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.api.Configuration; - -public class MethodTypeParameterNameTest extends AbstractGoogleModuleTestSupport { - - private static final String MSG_KEY = "name.invalidPattern"; - private static String format; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule528typevariablenames"; - } - - @BeforeAll - public static void setConfigurationBuilder() throws CheckstyleException { - format = getModuleConfig("ClassTypeParameterName").getAttribute("format"); - } - - @Test - public void testMethodDefault() throws Exception { - final Configuration checkConfig = getModuleConfig("MethodTypeParameterName"); - final Map messages = checkConfig.getMessages(); - - final String[] expected = { - "9:6: " + getCheckMessage(messages, MSG_KEY, "e_e", format), - "19:6: " + getCheckMessage(messages, MSG_KEY, "Tfo$o2T", format), - "23:6: " + getCheckMessage(messages, MSG_KEY, "foo_", format), - "28:10: " + getCheckMessage(messages, MSG_KEY, "_abc", format), - "37:14: " + getCheckMessage(messages, MSG_KEY, "T$", format), - "42:14: " + getCheckMessage(messages, MSG_KEY, "EE", format), - }; - - final String filePath = getPath("InputMethodTypeParameterName.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/TypeVariableNamesTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/TypeVariableNamesTest.java new file mode 100644 index 000000000000..5b4be22e6a94 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/TypeVariableNamesTest.java @@ -0,0 +1,52 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule528typevariablenames; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class TypeVariableNamesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming/rule528typevariablenames"; + } + + @Test + public void testMethodDefault() throws Exception { + verifyWithWholeConfig(getPath("InputMethodTypeParameterName.java")); + } + + @Test + public void testClassDefault() throws Exception { + verifyWithWholeConfig(getPath("InputClassTypeParameterName.java")); + } + + @Test + public void testInterfaceDefault() throws Exception { + verifyWithWholeConfig(getPath("InputInterfaceTypeParameterName.java")); + } + + @Test + public void testRecordDefault() throws Exception { + verifyWithWholeConfig(getPath("InputRecordTypeParameterNameOne.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule53camelcase/AbbreviationAsWordInNameTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule53camelcase/AbbreviationAsWordInNameTest.java deleted file mode 100644 index f519f9bdd144..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter5naming/rule53camelcase/AbbreviationAsWordInNameTest.java +++ /dev/null @@ -1,65 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter5naming.rule53camelcase; - -import java.io.IOException; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.naming.AbbreviationAsWordInNameCheck; - -public class AbbreviationAsWordInNameTest extends AbstractGoogleModuleTestSupport { - - private static final String MSG_KEY = "abbreviation.as.word"; - private final Class clazz = AbbreviationAsWordInNameCheck.class; - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter5naming/rule53camelcase"; - } - - @Test - public void testAbbreviationAsWordInName() throws Exception { - final int maxCapitalCount = 2; - - final String[] expected = { - "53:13: " + getWarningMessage("supportsIPv6OnIOS", maxCapitalCount), - "55:10: " + getWarningMessage("XMLHTTPRequest", maxCapitalCount), - "61:17: " + getWarningMessage("supportsIPv6OnIOS", maxCapitalCount), - "63:14: " + getWarningMessage("XMLHTTPRequest", maxCapitalCount), - "71:21: " + getWarningMessage("supportsIPv6OnIOS", maxCapitalCount), - "73:18: " + getWarningMessage("XMLHTTPRequest", maxCapitalCount), - }; - - final String filePath = getPath("InputAbbreviationAsWordInTypeNameCheck.java"); - - final Configuration checkConfig = getModuleConfig("AbbreviationAsWordInName"); - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - private String getWarningMessage(String typeName, int expectedCapitalCount) - throws IOException { - return getCheckMessage(clazz, MSG_KEY, typeName, expectedCapitalCount); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter5naming/rule53camelcase/CamelCaseDefinedTest.java b/src/it/java/com/google/checkstyle/test/chapter5naming/rule53camelcase/CamelCaseDefinedTest.java new file mode 100644 index 000000000000..732dc4c939ac --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter5naming/rule53camelcase/CamelCaseDefinedTest.java @@ -0,0 +1,46 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter5naming.rule53camelcase; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class CamelCaseDefinedTest extends AbstractGoogleModuleTestSupport { + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter5naming/rule53camelcase"; + } + + @Test + public void testCamelCaseNames() throws Exception { + verifyWithWholeConfig(getPath("InputCamelCaseDefined.java")); + } + + @Test + public void testCamelCaseNamesFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedCamelCaseDefined.java")); + } + + @Test + public void testCamelCaseNames2() throws Exception { + verifyWithWholeConfig(getPath("InputUnderscoreUsedInNames.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule61overridealwaysused/OverrideAlwaysUsedTest.java b/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule61overridealwaysused/OverrideAlwaysUsedTest.java new file mode 100644 index 000000000000..d370367efcfe --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule61overridealwaysused/OverrideAlwaysUsedTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter6programpractice.rule61overridealwaysused; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +/** Some Javadoc A {@code Foo} is a simple Javadoc. */ +class OverrideAlwaysUsedTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter6programpractice/rule61overridealwaysused"; + } + + @Test + public void testOverrideAlwaysUsedForRecord() throws Exception { + verifyWithWholeConfig(getPath("InputOverrideAlwaysUsedForRecord.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/CaughtExceptionsNotIgnoredTest.java b/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/CaughtExceptionsNotIgnoredTest.java new file mode 100644 index 000000000000..a0913ed7bc63 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/CaughtExceptionsNotIgnoredTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter6programpractice.rule62donotignoreexceptions; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class CaughtExceptionsNotIgnoredTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions"; + } + + @Test + public void testEmptyFinallyBlock() throws Exception { + verifyWithWholeConfig(getPath("InputEmptyFinallyBlock.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/EmptyBlockTest.java b/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/EmptyBlockTest.java deleted file mode 100644 index 3c72c6582410..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/EmptyBlockTest.java +++ /dev/null @@ -1,50 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter6programpractice.rule62donotignoreexceptions; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.blocks.EmptyBlockCheck; - -public class EmptyBlockTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions"; - } - - @Test - public void testEmptyBlockCatch() throws Exception { - final String[] expected = { - "29:17: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "finally"), - "50:21: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "finally"), - "72:21: " + getCheckMessage(EmptyBlockCheck.class, "block.empty", "finally"), - }; - - final Configuration checkConfig = getModuleConfig("EmptyBlock"); - final String filePath = getPath("InputEmptyBlockCatch.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/FinalizersNotUsedTest.java b/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/FinalizersNotUsedTest.java new file mode 100644 index 000000000000..e80622216a88 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/FinalizersNotUsedTest.java @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter6programpractice.rule64finalizers; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class FinalizersNotUsedTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter6programpractice/rule64finalizers"; + } + + @Test + public void testNoFinalizerBasic() throws Exception { + verifyWithWholeConfig(getPath("InputNoFinalizer.java")); + } + + @Test + public void testNoFinalizerExtended() throws Exception { + verifyWithWholeConfig(getPath("InputNoFinalizeExtend.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/NoFinalizerTest.java b/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/NoFinalizerTest.java deleted file mode 100644 index 4de5d31649c2..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/NoFinalizerTest.java +++ /dev/null @@ -1,73 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter6programpractice.rule64finalizers; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.coding.NoFinalizerCheck; - -public class NoFinalizerTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter6programpractice/rule64finalizers"; - } - - @Test - public void testNoFinalizerBasic() throws Exception { - final String msg = getCheckMessage(NoFinalizerCheck.class, "avoid.finalizer.method"); - - final String[] expected = { - "5: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("NoFinalizer"); - final String filePath = getPath("InputNoFinalizer.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testNoFinalizerExtended() throws Exception { - final String msg = getCheckMessage(NoFinalizerCheck.class, "avoid.finalizer.method"); - - final String[] expected = { - "9: " + msg, - "21: " + msg, - "33: " + msg, - "45: " + msg, - "57: " + msg, - "69: " + msg, - "79: " + msg, - "119: " + msg, - "136: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("NoFinalizer"); - final String filePath = getPath("InputNoFinalizeExtend.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/GeneralFormTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/GeneralFormTest.java new file mode 100644 index 000000000000..267f132d0456 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/GeneralFormTest.java @@ -0,0 +1,109 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class GeneralFormTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter7javadoc/rule711generalform"; + } + + @Test + public void testSingleLineJavadocAndInvalidJavadocPosition() throws Exception { + verifyWithWholeConfig(getPath("InputSingleLineJavadocAndInvalidJavadocPosition.java")); + } + + @Test + public void testSingleLineJavadocAndInvalidJavadocPositionFormatted() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedSingleLineJavadocAndInvalidJavadocPosition.java")); + } + + @Test + public void testJavadocPositionOnCompactConstructorInRecord() throws Exception { + verifyWithWholeConfig(getPath("InputJavadocPositionOnConstructorInRecord.java")); + } + + @Test + public void testFormattedJavadocPositionOnCompactConstructorInRecord() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedJavadocPositionOnConstructorInRecord.java")); + } + + @Test + public void testJavadocPositionOnCompactConstructorWithAnnotation() throws Exception { + verifyWithWholeConfig( + getPath("InputJavadocPositionOnCompactConstructorsWithAnnotation.java")); + } + + @Test + public void testFormattedJavadocPositionOnCompactConstructorWithAnnotation() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedJavadocPositionOnCompactConstructorsWithAnnotation.java")); + } + + @Test + public void testJavadocPositionOnCanonicalConstructorWithAnnotation() throws Exception { + verifyWithWholeConfig( + getPath("InputJavadocPositionOnCanonicalConstructorsWithAnnotation.java")); + } + + @Test + public void testFormattedJavadocPositionOnCanonicalConstructorWithAnnotation() + throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedJavadocPositionOnCanonicalConstructorsWithAnnotation.java")); + } + + @Test + public void testRecordClassJavadocPosition() throws Exception { + verifyWithWholeConfig(getPath("InputRecordClassJavadocPosition.java")); + } + + @Test + public void testFormattedRecordClassJavadocPosition() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedRecordClassJavadocPosition.java")); + } + + @Test + public void testCorrectJavadocLeadingAsteriskAlignment() throws Exception { + verifyWithWholeConfig(getPath("InputCorrectJavadocLeadingAsteriskAlignment.java")); + } + + @Test + public void testFormattedCorrectJavadocLeadingAsteriskAlignment() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedCorrectJavadocLeadingAsteriskAlignment.java")); + } + + @Test + public void testIncorrectJavadocLeadingAsteriskAlignment() throws Exception { + verifyWithWholeConfig(getPath("InputIncorrectJavadocLeadingAsteriskAlignment.java")); + } + + @Test + public void testFormattedIncorrectJavadocLeadingAsteriskAlignment() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedIncorrectJavadocLeadingAsteriskAlignment.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InvalidJavadocPositionTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InvalidJavadocPositionTest.java deleted file mode 100644 index 8e7103fc9578..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InvalidJavadocPositionTest.java +++ /dev/null @@ -1,69 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule711generalform; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.InvalidJavadocPositionCheck; - -public class InvalidJavadocPositionTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule711generalform"; - } - - @Test - public void testDefault() throws Exception { - final String message = getCheckMessage(InvalidJavadocPositionCheck.class, - "invalid.position"); - - final String[] expected = { - "1:9: " + message, - "3:1: " + message, - "6:1: " + message, - "9:5: " + message, - "14:5: " + message, - "17:5: " + message, - "27:9: " + message, - "28:17: " + message, - "29:17: " + message, - "39:10: " + message, - "40:19: " + message, - "41:19: " + message, - "42:21: " + message, - "43:23: " + message, - "44:23: " + message, - "47:1: " + message, - "52:7: " + message, - "53:36: " + message, - "54:1: " + message, - }; - - final Configuration checkConfig = getModuleConfig("InvalidJavadocPosition"); - final String filePath = getPath("InputInvalidJavadocPosition.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/SingleLineJavadocTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/SingleLineJavadocTest.java deleted file mode 100644 index 04090f573281..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule711generalform/SingleLineJavadocTest.java +++ /dev/null @@ -1,56 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule711generalform; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.SingleLineJavadocCheck; - -public class SingleLineJavadocTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule711generalform"; - } - - @Test - public void testSingleLineJavadoc() throws Exception { - final String msg = getCheckMessage(SingleLineJavadocCheck.class, "singleline.javadoc"); - - final String[] expected = { - "5: " + msg, - "13: " + msg, - "29: " + msg, - "32: " + msg, - "35: " + msg, - "38: " + msg, - "41: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("SingleLineJavadoc"); - final String filePath = getPath("InputSingleLineJavadocCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/JavadocParagraphTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/JavadocParagraphTest.java deleted file mode 100644 index be8055401103..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/JavadocParagraphTest.java +++ /dev/null @@ -1,96 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule712paragraphs; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocParagraphCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class JavadocParagraphTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule712paragraphs"; - } - - @Test - public void testJavadocParagraphCorrect() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("JavadocParagraph"); - final String filePath = getPath("InputCorrectJavadocParagraphCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testJavadocParagraphIncorrect() throws Exception { - final String msgBefore = getCheckMessage(JavadocParagraphCheck.class, - "javadoc.paragraph.line.before"); - final String msgRed = getCheckMessage(JavadocParagraphCheck.class, - "javadoc.paragraph.redundant.paragraph"); - final String msgMisplaced = getCheckMessage(JavadocParagraphCheck.class, - "javadoc.paragraph.misplaced.tag"); - - final String[] expected = { - "5: " + msgMisplaced, - "5: " + msgBefore, - "6: " + msgMisplaced, - "6: " + msgBefore, - "12: " + msgMisplaced, - "12: " + msgBefore, - "14: " + msgMisplaced, - "21: " + msgBefore, - "30: " + msgRed, - "31: " + msgMisplaced, - "31: " + msgBefore, - "32: " + msgMisplaced, - "32: " + msgBefore, - "33: " + msgMisplaced, - "33: " + msgBefore, - "37: " + msgMisplaced, - "37: " + msgBefore, - "43: " + msgMisplaced, - "43: " + msgRed, - "46: " + msgMisplaced, - "48: " + msgMisplaced, - "48: " + msgBefore, - "49: " + msgMisplaced, - "49: " + msgBefore, - "59: " + msgRed, - "68: " + msgMisplaced, - "68: " + msgBefore, - "70: " + msgMisplaced, - "73: " + msgMisplaced, - "73: " + msgBefore, - }; - - final Configuration checkConfig = getModuleConfig("JavadocParagraph"); - final String filePath = getPath("InputIncorrectJavadocParagraphCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/ParagraphsTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/ParagraphsTest.java new file mode 100644 index 000000000000..d87f6f54e847 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/ParagraphsTest.java @@ -0,0 +1,75 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter7javadoc.rule712paragraphs; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ParagraphsTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter7javadoc/rule712paragraphs"; + } + + @Test + public void testJavadocParagraphCorrect() throws Exception { + verifyWithWholeConfig(getPath("InputCorrectJavadocParagraph.java")); + } + + @Test + public void testJavadocParagraphCorrectFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedCorrectJavadocParagraph.java")); + } + + @Test + public void testJavadocParagraphIncorrect() throws Exception { + verifyWithWholeConfig(getPath("InputIncorrectJavadocParagraph.java")); + } + + @Test + public void testJavadocParagraphIncorrectFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedIncorrectJavadocParagraph.java")); + } + + @Test + public void testRequireEmptyLineBeforeBlockTagGroupCorrect() throws Exception { + verifyWithWholeConfig(getPath("InputCorrectRequireEmptyLineBeforeBlockTagGroup.java")); + } + + @Test + public void testRequireEmptyLineBeforeBlockTagGroupCorrectFormatted() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedCorrectRequireEmptyLineBeforeBlockTagGroup.java")); + } + + @Test + public void testRequireEmptyLineBeforeBlockTagGroupIncorrect() throws Exception { + verifyWithWholeConfig(getPath("InputIncorrectRequireEmptyLineBeforeBlockTagGroup.java")); + } + + @Test + public void testRequireEmptyLineBeforeBlockTagGroupIncorrectFormatted() throws Exception { + verifyWithWholeConfig( + getPath("InputFormattedIncorrectRequireEmptyLineBeforeBlockTagGroup.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/AtclauseOrderTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/AtclauseOrderTest.java deleted file mode 100644 index 20a6b72622d5..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/AtclauseOrderTest.java +++ /dev/null @@ -1,89 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule713atclauses; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.AtclauseOrderCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class AtclauseOrderTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule713atclauses"; - } - - @Test - public void testCorrect() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("AtclauseOrder"); - final String filePath = getPath("InputCorrectAtClauseOrderCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testIncorrect() throws Exception { - final String tagOrder = "[@param, @return, @throws, @deprecated]"; - final String msg = getCheckMessage(AtclauseOrderCheck.class, "at.clause.order", tagOrder); - - final String[] expected = { - "40: " + msg, - "51: " + msg, - "62: " + msg, - "69: " + msg, - "86: " + msg, - "87: " + msg, - "99: " + msg, - "101: " + msg, - "123: " + msg, - "124: " + msg, - "134: " + msg, - "135: " + msg, - "153: " + msg, - "161: " + msg, - "172: " + msg, - "183: " + msg, - "185: " + msg, - "199: " + msg, - "202: " + msg, - "213: " + msg, - "223: " + msg, - "230: " + msg, - "237: " + msg, - "247: " + msg, - "248: " + msg, - "259: " + msg, - "261: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("AtclauseOrder"); - final String filePath = getPath("InputIncorrectAtClauseOrderCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/BlockTagsTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/BlockTagsTest.java new file mode 100644 index 000000000000..1d7262d907c4 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/BlockTagsTest.java @@ -0,0 +1,82 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter7javadoc.rule713atclauses; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class BlockTagsTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter7javadoc/rule713atclauses"; + } + + @Test + public void testCorrectAtClauseOrder1() throws Exception { + verifyWithWholeConfig(getPath("InputCorrectAtClauseOrderCheck1.java")); + } + + @Test + public void testCorrectAtClauseOrder2() throws Exception { + verifyWithWholeConfig(getPath("InputCorrectAtClauseOrderCheck2.java")); + } + + @Test + public void testCorrectAtClauseOrder3() throws Exception { + verifyWithWholeConfig(getPath("InputCorrectAtClauseOrderCheck3.java")); + } + + @Test + public void testIncorrectAtClauseOrder1() throws Exception { + verifyWithWholeConfig(getPath("InputIncorrectAtClauseOrderCheck1.java")); + } + + @Test + public void testIncorrectAtClauseOrder2() throws Exception { + verifyWithWholeConfig(getPath("InputIncorrectAtClauseOrderCheck2.java")); + } + + @Test + public void testIncorrectAtClauseOrder3() throws Exception { + verifyWithWholeConfig(getPath("InputIncorrectAtClauseOrderCheck3.java")); + } + + @Test + public void testJavadocTagContinuationIndentation() throws Exception { + verifyWithWholeConfig(getPath("InputJavaDocTagContinuationIndentation.java")); + } + + @Test + public void testJavadocTagContinuationIndentationFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedJavaDocTagContinuationIndentation.java")); + } + + @Test + public void testNonEmptyAtclauseDescription() throws Exception { + verifyWithWholeConfig(getPath("InputNonEmptyAtclauseDescription.java")); + } + + @Test + public void testNonEmptyAtclauseDescriptionSpaceSequence() throws Exception { + verifyWithWholeConfig(getPath("InputNonEmptyAtclauseDescriptionSpaceSeq.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/JavadocTagContinuationIndentationTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/JavadocTagContinuationIndentationTest.java deleted file mode 100644 index 5aa29bdcce88..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/JavadocTagContinuationIndentationTest.java +++ /dev/null @@ -1,62 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule713atclauses; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagContinuationIndentationCheck; - -public class JavadocTagContinuationIndentationTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule713atclauses"; - } - - @Test - public void testWithDefaultConfiguration() throws Exception { - final String msg = getCheckMessage(JavadocTagContinuationIndentationCheck.class, - "tag.continuation.indent", 4); - - final String[] expected = { - "47: " + msg, - "109: " + msg, - "112: " + msg, - "203: " + msg, - "206: " + msg, - "221: " + msg, - "223: " + msg, - "285: " + msg, - "288: " + msg, - "290: " + msg, - "310: " + msg, - "322: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("JavadocTagContinuationIndentation"); - final String filePath = getPath("InputJavaDocTagContinuationIndentation.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/NonEmptyAtclauseDescriptionTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/NonEmptyAtclauseDescriptionTest.java deleted file mode 100644 index 538a2165e9bc..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule713atclauses/NonEmptyAtclauseDescriptionTest.java +++ /dev/null @@ -1,97 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule713atclauses; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.NonEmptyAtclauseDescriptionCheck; - -public class NonEmptyAtclauseDescriptionTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule713atclauses"; - } - - @Test - public void testDefaultConfiguration() throws Exception { - final String msg = getCheckMessage(NonEmptyAtclauseDescriptionCheck.class, - "non.empty.atclause"); - - final String[] expected = { - "34: " + msg, - "35: " + msg, - "36: " + msg, - "37: " + msg, - "38: " + msg, - "39: " + msg, - "48: " + msg, - "49: " + msg, - "50: " + msg, - "51: " + msg, - "52: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("NonEmptyAtclauseDescription"); - final String filePath = getPath("InputNonEmptyAtclauseDescriptionCheck.java"); - - final Integer[] warnList = getLineNumbersFromExpected(expected); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testSpaceSequence() throws Exception { - final String msg = getCheckMessage(NonEmptyAtclauseDescriptionCheck.class, - "non.empty.atclause"); - - final String[] expected = { - "27: " + msg, - "28: " + msg, - "29: " + msg, - "38: " + msg, - "39: " + msg, - "40: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("NonEmptyAtclauseDescription"); - final String filePath = getPath("InputNonEmptyAtclauseDescriptionCheckSpaceSeq.java"); - - final Integer[] warnList = getLineNumbersFromExpected(expected); - verify(checkConfig, filePath, expected, warnList); - } - - /** - * Gets line numbers with violations from an array with expected messages. - * This is used as using "warn" comments in input files would affects the work - * of the Check. - * @param expected an array with expected messages. - * @return Integer array with numbers of lines with violations. - */ - private static Integer[] getLineNumbersFromExpected(String... expected) { - final Integer[] result = new Integer[expected.length]; - for (int i = 0; i < expected.length; i++) { - result[i] = Integer.valueOf(expected[i].substring(0, expected[i].indexOf(':'))); - } - return result; - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule72thesummaryfragment/SummaryJavadocTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule72thesummaryfragment/SummaryJavadocTest.java deleted file mode 100644 index f62f9025f5f2..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule72thesummaryfragment/SummaryJavadocTest.java +++ /dev/null @@ -1,75 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule72thesummaryfragment; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.SummaryJavadocCheck; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class SummaryJavadocTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule72thesummaryfragment"; - } - - @Test - public void testCorrect() throws Exception { - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("SummaryJavadoc"); - final String filePath = getPath("InputCorrectSummaryJavaDocCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - - @Test - public void testIncorrect() throws Exception { - final String msgFirstSentence = getCheckMessage(SummaryJavadocCheck.class, - "summary.first.sentence"); - final String msgForbiddenFragment = getCheckMessage(SummaryJavadocCheck.class, - "summary.javaDoc"); - final String msgMissingDoc = getCheckMessage(SummaryJavadocCheck.class, - "summary.javaDoc.missing"); - - final String[] expected = { - "14: " + msgMissingDoc, - "32: " + msgMissingDoc, - "37: " + msgFirstSentence, - "47: " + msgForbiddenFragment, - "53: " + msgMissingDoc, - "58: " + msgMissingDoc, - "69: " + msgMissingDoc, - "83: " + msgForbiddenFragment, - "103: " + msgMissingDoc, - }; - - final Configuration checkConfig = getModuleConfig("SummaryJavadoc"); - final String filePath = getPath("InputIncorrectSummaryJavaDocCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule72thesummaryfragment/TheSummaryFragmentTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule72thesummaryfragment/TheSummaryFragmentTest.java new file mode 100644 index 000000000000..56768417668a --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule72thesummaryfragment/TheSummaryFragmentTest.java @@ -0,0 +1,43 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter7javadoc.rule72thesummaryfragment; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class TheSummaryFragmentTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter7javadoc/rule72thesummaryfragment"; + } + + @Test + public void testCorrect() throws Exception { + verifyWithWholeConfig(getPath("InputCorrectSummaryFragment.java")); + } + + @Test + public void testIncorrect() throws Exception { + verifyWithWholeConfig(getPath("InputIncorrectSummaryFragment.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/ExceptionSelfExplanatoryMembersTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/ExceptionSelfExplanatoryMembersTest.java new file mode 100644 index 000000000000..798de4758215 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/ExceptionSelfExplanatoryMembersTest.java @@ -0,0 +1,47 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter7javadoc.rule731selfexplanatory; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ExceptionSelfExplanatoryMembersTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory"; + } + + @Test + public void testBothModules() throws Exception { + verifyWithWholeConfig(getPath("InputJavadocMethodAndMissingJavadocMethod.java")); + } + + @Test + public void testDefaultRecord() throws Exception { + verifyWithWholeConfig(getPath("InputSelfExplanatoryMembersRecord.java")); + } + + @Test + public void testDefaultRecord2() throws Exception { + verifyWithWholeConfig(getPath("InputSelfExplanatoryMembersRecord2.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/JavadocMethodTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/JavadocMethodTest.java deleted file mode 100644 index f11afc67e2bc..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/JavadocMethodTest.java +++ /dev/null @@ -1,47 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule731selfexplanatory; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.utils.CommonUtil; - -public class JavadocMethodTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory"; - } - - @Test - public void testJavadocMethod() throws Exception { - - final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; - - final Configuration checkConfig = getModuleConfig("JavadocMethod"); - final String filePath = getPath("InputJavadocMethodCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/MissingJavadocMethodTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/MissingJavadocMethodTest.java deleted file mode 100644 index b547512cd910..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory/MissingJavadocMethodTest.java +++ /dev/null @@ -1,50 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule731selfexplanatory; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocMethodCheck; - -public class MissingJavadocMethodTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule731selfexplanatory"; - } - - @Test - public void testJavadocMethod() throws Exception { - final String msg = getCheckMessage(MissingJavadocMethodCheck.class, "javadoc.missing"); - - final String[] expected = { - "57:5: " + msg, - }; - - final Configuration checkConfig = getModuleConfig("MissingJavadocMethod"); - final String filePath = getPath("InputMissingJavadocMethodCheck.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule732exceptionoverrides/ExceptionOverridesTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule732exceptionoverrides/ExceptionOverridesTest.java new file mode 100644 index 000000000000..e102ac0fd3ff --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule732exceptionoverrides/ExceptionOverridesTest.java @@ -0,0 +1,38 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter7javadoc.rule732exceptionoverrides; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class ExceptionOverridesTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter7javadoc/rule732exceptionoverrides"; + } + + @Test + public void testBothModules() throws Exception { + verifyWithWholeConfig(getPath("InputJavadocMethodAndMissingJavadocMethod.java")); + } + +} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc/InvalidJavadocPositionTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc/InvalidJavadocPositionTest.java deleted file mode 100644 index c470df291212..000000000000 --- a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc/InvalidJavadocPositionTest.java +++ /dev/null @@ -1,69 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.google.checkstyle.test.chapter7javadoc.rule734nonrequiredjavadoc; - -import org.junit.jupiter.api.Test; - -import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.InvalidJavadocPositionCheck; - -public class InvalidJavadocPositionTest extends AbstractGoogleModuleTestSupport { - - @Override - protected String getPackageLocation() { - return "com/google/checkstyle/test/chapter7javadoc/rule711generalform"; - } - - @Test - public void testDefault() throws Exception { - final String message = getCheckMessage(InvalidJavadocPositionCheck.class, - "invalid.position"); - - final String[] expected = { - "1:9: " + message, - "3:1: " + message, - "6:1: " + message, - "9:5: " + message, - "14:5: " + message, - "17:5: " + message, - "27:9: " + message, - "28:17: " + message, - "29:17: " + message, - "39:10: " + message, - "40:19: " + message, - "41:19: " + message, - "42:21: " + message, - "43:23: " + message, - "44:23: " + message, - "47:1: " + message, - "52:7: " + message, - "53:36: " + message, - "54:1: " + message, - }; - - final Configuration checkConfig = getModuleConfig("InvalidJavadocPosition"); - final String filePath = getPath("InputInvalidJavadocPosition.java"); - - final Integer[] warnList = getLinesWithWarn(filePath); - verify(checkConfig, filePath, expected, warnList); - } - -} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc/NonRequiredJavadocTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc/NonRequiredJavadocTest.java new file mode 100644 index 000000000000..3026f95442b0 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc/NonRequiredJavadocTest.java @@ -0,0 +1,52 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter7javadoc.rule734nonrequiredjavadoc; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class NonRequiredJavadocTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter7javadoc/rule734nonrequiredjavadoc"; + } + + @Test + public void testDefault() throws Exception { + verifyWithWholeConfig(getPath("InputInvalidJavadocPosition.java")); + } + + @Test + public void testDefaultFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedInvalidJavadocPosition.java")); + } + + @Test + public void testDefaultRecord() throws Exception { + verifyWithWholeConfig(getPath("InputInvalidJavadocPositionRecord.java")); + } + + @Test + public void testDefaultRecordFormatted() throws Exception { + verifyWithWholeConfig(getPath("InputFormattedInvalidJavadocPositionRecord.java")); + } +} diff --git a/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule73wherejavadocrequired/WhereJavadocIsUsedTest.java b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule73wherejavadocrequired/WhereJavadocIsUsedTest.java new file mode 100644 index 000000000000..af1066f1fbd9 --- /dev/null +++ b/src/it/java/com/google/checkstyle/test/chapter7javadoc/rule73wherejavadocrequired/WhereJavadocIsUsedTest.java @@ -0,0 +1,57 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter7javadoc.rule73wherejavadocrequired; + +import org.junit.jupiter.api.Test; + +import com.google.checkstyle.test.base.AbstractGoogleModuleTestSupport; + +public class WhereJavadocIsUsedTest extends AbstractGoogleModuleTestSupport { + + @Override + protected String getPackageLocation() { + return "com/google/checkstyle/test/chapter7javadoc/rule73wherejavadocrequired"; + } + + @Test + public void testMissingJavadocTypeIncorrect() throws Exception { + verifyWithWholeConfig(getPath("InputMissingJavadocTypeIncorrect.java")); + } + + @Test + public void testMissingJavadocTypeCorrect() throws Exception { + verifyWithWholeConfig(getPath("InputMissingJavadocTypeCorrect.java")); + } + + @Test + public void testJavadocMethodAndMissingJavadocMethod() throws Exception { + verifyWithWholeConfig(getPath("InputJavadocMethodAndMissingJavadocMethod.java")); + } + + @Test + public void testJavadocTypeOnRecord() throws Exception { + verifyWithWholeConfig(getPath("InputJavadocTypeOnRecord.java")); + } + + @Test + public void testJavadocTypeOnRecord2() throws Exception { + verifyWithWholeConfig(getPath("InputJavadocTypeOnRecord2.java")); + } +} diff --git a/src/it/java/com/sun/checkstyle/test/base/AbstractSunModuleTestSupport.java b/src/it/java/com/sun/checkstyle/test/base/AbstractSunModuleTestSupport.java index 4a0e37c45a4c..1760ccbeb23c 100644 --- a/src/it/java/com/sun/checkstyle/test/base/AbstractSunModuleTestSupport.java +++ b/src/it/java/com/sun/checkstyle/test/base/AbstractSunModuleTestSupport.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,19 +15,16 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package com.sun.checkstyle.test.base; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import java.util.Set; import org.checkstyle.base.AbstractItModuleTestSupport; import com.puppycrawl.tools.checkstyle.ConfigurationLoader; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.PropertiesExpander; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; @@ -47,14 +44,14 @@ public abstract class AbstractSunModuleTestSupport extends AbstractItModuleTestS CONFIGURATION = ConfigurationLoader.loadConfiguration(XML_NAME, new PropertiesExpander(System.getProperties())); } - catch (CheckstyleException ex) { - throw new IllegalStateException(ex); + catch (CheckstyleException exc) { + throw new IllegalStateException(exc); } try { CHECKSTYLE_MODULES = CheckUtil.getCheckstyleModules(); } - catch (IOException ex) { - throw new IllegalStateException(ex); + catch (IOException exc) { + throw new IllegalStateException(exc); } } @@ -76,14 +73,10 @@ protected ModuleCreationOption findModuleCreationOption(String moduleName) { return moduleCreationOption; } - @Override - protected DefaultConfiguration createModuleConfig(Class clazz) { - return new DefaultConfiguration(clazz.getName()); - } - /** * Returns {@link Configuration} instance for the given module name. * This implementation uses {@link #getModuleConfig(String, String)} method inside. + * * @param moduleName module name. * @return {@link Configuration} instance for the given module name. */ @@ -94,58 +87,14 @@ protected static Configuration getModuleConfig(String moduleName) { /** * Returns {@link Configuration} instance for the given module name. * This implementation uses {@link #getModuleConfig(String)} method inside. + * * @param moduleName module name. * @param moduleId module id. * @return {@link Configuration} instance for the given module name. + * @throws IllegalStateException if there is a problem retrieving the module or config. */ protected static Configuration getModuleConfig(String moduleName, String moduleId) { - final Configuration result; - final List configs = getModuleConfigs(moduleName); - if (configs.size() == 1) { - result = configs.get(0); - } - else if (configs.isEmpty()) { - throw new IllegalStateException("no instances of the Module was found: " + moduleName); - } - else if (moduleId == null) { - throw new IllegalStateException("multiple instances of the same Module are detected"); - } - else { - result = configs.stream().filter(conf -> { - try { - return conf.getAttribute("id").equals(moduleId); - } - catch (CheckstyleException ex) { - throw new IllegalStateException("problem to get ID attribute from " + conf, ex); - } - }) - .findFirst() - .orElseThrow(() -> new IllegalStateException("problem with module config")); - } - - return result; - } - - /** - * Returns a list of all {@link Configuration} instances for the given module name. - * @param moduleName module name. - * @return {@link Configuration} instance for the given module name. - */ - protected static List getModuleConfigs(String moduleName) { - final List result = new ArrayList<>(); - for (Configuration currentConfig : CONFIGURATION.getChildren()) { - if ("TreeWalker".equals(currentConfig.getName())) { - for (Configuration moduleConfig : currentConfig.getChildren()) { - if (moduleName.equals(moduleConfig.getName())) { - result.add(moduleConfig); - } - } - } - else if (moduleName.equals(currentConfig.getName())) { - result.add(currentConfig); - } - } - return result; + return getModuleConfig(CONFIGURATION, moduleName, moduleId); } } diff --git a/src/it/java/com/sun/checkstyle/test/chapter5comments/rule52documentationcomments/InvalidJavadocPositionTest.java b/src/it/java/com/sun/checkstyle/test/chapter5comments/rule52documentationcomments/InvalidJavadocPositionTest.java index 4b727af547a1..11504a7c0e7d 100644 --- a/src/it/java/com/sun/checkstyle/test/chapter5comments/rule52documentationcomments/InvalidJavadocPositionTest.java +++ b/src/it/java/com/sun/checkstyle/test/chapter5comments/rule52documentationcomments/InvalidJavadocPositionTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,7 +15,7 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package com.sun.checkstyle.test.chapter5comments.rule52documentationcomments; diff --git a/src/it/java/com/sun/checkstyle/test/chapter6declarations/rule61numberperline/MultipleVariableDeclarationsTest.java b/src/it/java/com/sun/checkstyle/test/chapter6declarations/rule61numberperline/MultipleVariableDeclarationsTest.java index f7b5159cf141..445769ec0c4a 100644 --- a/src/it/java/com/sun/checkstyle/test/chapter6declarations/rule61numberperline/MultipleVariableDeclarationsTest.java +++ b/src/it/java/com/sun/checkstyle/test/chapter6declarations/rule61numberperline/MultipleVariableDeclarationsTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,7 +15,7 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package com.sun.checkstyle.test.chapter6declarations.rule61numberperline; diff --git a/src/it/java/org/checkstyle/base/AbstractCheckstyleModuleTestSupport.java b/src/it/java/org/checkstyle/base/AbstractCheckstyleModuleTestSupport.java index b55d3e295f20..05097b503f6a 100644 --- a/src/it/java/org/checkstyle/base/AbstractCheckstyleModuleTestSupport.java +++ b/src/it/java/org/checkstyle/base/AbstractCheckstyleModuleTestSupport.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,11 +15,10 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package org.checkstyle.base; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.utils.ModuleReflectionUtil; public abstract class AbstractCheckstyleModuleTestSupport extends AbstractItModuleTestSupport { @@ -44,9 +43,4 @@ protected ModuleCreationOption findModuleCreationOption(String moduleName) { return moduleCreationOption; } - @Override - protected DefaultConfiguration createModuleConfig(Class clazz) { - return new DefaultConfiguration(clazz.getName()); - } - } diff --git a/src/it/java/org/checkstyle/base/AbstractItModuleTestSupport.java b/src/it/java/org/checkstyle/base/AbstractItModuleTestSupport.java index ef28cb744e5b..075650bea5f8 100644 --- a/src/it/java/org/checkstyle/base/AbstractItModuleTestSupport.java +++ b/src/it/java/org/checkstyle/base/AbstractItModuleTestSupport.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,12 +15,11 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package org.checkstyle.base; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static com.google.common.truth.Truth.assertWithMessage; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -31,10 +30,11 @@ import java.io.LineNumberReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.nio.file.Paths; +import java.nio.file.Path; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; @@ -46,7 +46,10 @@ import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.TreeWalker; import com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; +import com.puppycrawl.tools.checkstyle.bdd.InlineConfigParser; +import com.puppycrawl.tools.checkstyle.bdd.TestInputViolation; import com.puppycrawl.tools.checkstyle.internal.utils.BriefUtLogger; import com.puppycrawl.tools.checkstyle.utils.CommonUtil; @@ -73,48 +76,187 @@ public enum ModuleCreationOption { protected static final String ROOT_MODULE_NAME = "root"; private static final Pattern WARN_PATTERN = CommonUtil - .createPattern(".*[ ]*//[ ]*warn[ ]*|/[*]\\*?\\s?warn\\s?[*]/"); + .createPattern(".* *// *warn *|/[*]\\*?\\s?warn\\s?[*]/"); private final ByteArrayOutputStream stream = new ByteArrayOutputStream(); /** * Find the module creation option to use for the module name. - * @param moduleName The module name. - * @return The module creation option. + * + * @param moduleName the module name. + * @return the module creation option. */ protected abstract ModuleCreationOption findModuleCreationOption(String moduleName); - /** - * Creates {@link DefaultConfiguration} instance for the given module class. - * @param clazz module class. - * @return {@link DefaultConfiguration} instance. - */ - protected abstract DefaultConfiguration createModuleConfig(Class clazz); - /** * Returns test logger. - * @return logger test logger + * + * @return logger for tests */ protected final BriefUtLogger getBriefUtLogger() { return new BriefUtLogger(stream); } /** - * Returns canonical path for the file with the given file name. - * The path is formed base on the non-compilable resources location. - * This implementation uses 'src/test/resources-noncompilable/' - * as a non-compilable resource location. - * @param filename file name. - * @return canonical path for the file with the given file name. - * @throws IOException if I/O exception occurs while forming the path. + * Creates a default module configuration {@link DefaultConfiguration} for a given object + * of type {@link Class}. + * + * @param clazz a {@link Class} type object. + * @return default module configuration for the given {@link Class} instance. */ - protected final String getNonCompilablePath(String filename) throws IOException { - return new File("src/" + getResourceLocation() + "/resources-noncompilable/" - + getPackageLocation() + "/" + filename).getCanonicalPath(); + protected static DefaultConfiguration createModuleConfig(Class clazz) { + return new DefaultConfiguration(clazz.getName()); + } + + /** + * Returns {@link Configuration} instance for the given module name pulled + * from the {@code masterConfig}. + * + * @param masterConfig The master configuration to examine. + * @param moduleName module name. + * @param moduleId module id. + * @return {@link Configuration} instance for the given module name. + * @throws IllegalStateException if there is a problem retrieving the module + * or config. + */ + protected static Configuration getModuleConfig(Configuration masterConfig, String moduleName, + String moduleId) { + final Configuration result; + final List configs = getModuleConfigs(masterConfig, moduleName); + if (configs.size() == 1) { + result = configs.get(0); + } + else if (configs.isEmpty()) { + throw new IllegalStateException("no instances of the Module was found: " + moduleName); + } + else if (moduleId == null) { + throw new IllegalStateException("multiple instances of the same Module are detected"); + } + else { + result = configs.stream().filter(conf -> isSameModuleId(conf, moduleId)) + .findFirst() + .orElseThrow(() -> new IllegalStateException("problem with module config")); + } + + return result; + } + + /** + * Verifies if the configuration's ID matches the expected {@code moduleId}. + * + * @param conf The config to examine. + * @param moduleId The module ID to match against. + * @return {@code true} if it matches. + * @throws IllegalStateException If there is an issue with finding the ID. + */ + private static boolean isSameModuleId(Configuration conf, String moduleId) { + try { + return conf.getProperty("id").equals(moduleId); + } + catch (CheckstyleException exc) { + throw new IllegalStateException("problem to get ID attribute from " + conf, exc); + } + } + + /** + * Returns a list of all {@link Configuration} instances for the given module IDs in the + * {@code masterConfig}. + * + * @param masterConfig The master configuration to pull results from. + * @param moduleIds module IDs. + * @return List of {@link Configuration} instances. + * @throws CheckstyleException if there is an error with the config. + */ + protected static List getModuleConfigsByIds(Configuration masterConfig, + String... moduleIds) throws CheckstyleException { + final List result = new ArrayList<>(); + for (Configuration currentConfig : masterConfig.getChildren()) { + if ("TreeWalker".equals(currentConfig.getName())) { + for (Configuration moduleConfig : currentConfig.getChildren()) { + final String id = getProperty(moduleConfig, "id"); + if (id != null && isIn(id, moduleIds)) { + result.add(moduleConfig); + } + } + } + else { + final String id = getProperty(currentConfig, "id"); + if (id != null && isIn(id, moduleIds)) { + result.add(currentConfig); + } + } + } + return result; + } + + /** + * Finds the specific property {@code name} in the {@code config}. + * + * @param config The configuration to examine. + * @param name The property name to find. + * @return The property value or {@code null} if not found. + * @throws CheckstyleException if there is an error with the config. + */ + private static String getProperty(Configuration config, String name) + throws CheckstyleException { + String result = null; + + if (isIn(name, config.getPropertyNames())) { + result = config.getProperty(name); + } + + return result; + } + + /** + * Finds the specific ID in a list of IDs. + * + * @param find The ID to find. + * @param list The list of module IDs. + * @return {@code true} if the ID is in the list. + */ + private static boolean isIn(String find, String... list) { + boolean found = false; + + for (String item : list) { + if (find.equals(item)) { + found = true; + break; + } + } + + return found; + } + + /** + * Returns a list of all {@link Configuration} instances for the given + * module name pulled from the {@code masterConfig}. + * + * @param masterConfig The master configuration to examine. + * @param moduleName module name. + * @return {@link Configuration} instance for the given module name. + */ + private static List getModuleConfigs(Configuration masterConfig, + String moduleName) { + final List result = new ArrayList<>(); + for (Configuration currentConfig : masterConfig.getChildren()) { + if ("TreeWalker".equals(currentConfig.getName())) { + for (Configuration moduleConfig : currentConfig.getChildren()) { + if (moduleName.equals(moduleConfig.getName())) { + result.add(moduleConfig); + } + } + } + else if (moduleName.equals(currentConfig.getName())) { + result.add(currentConfig); + } + } + return result; } /** * Creates {@link Checker} instance based on the given {@link Configuration} instance. + * * @param moduleConfig {@link Configuration} instance. * @return {@link Checker} instance based on the given {@link Configuration} instance. * @throws Exception if an exception occurs during checker configuration. @@ -127,75 +269,116 @@ protected final Checker createChecker(Configuration moduleConfig) } /** - * Creates {@link Checker} instance based on specified {@link Configuration}. + * Creates {@link Checker} instance based on the given {@link Configuration} instance. + * * @param moduleConfig {@link Configuration} instance. * @param moduleCreationOption {@code IN_TREEWALKER} if the {@code moduleConfig} should be added * under {@link TreeWalker}. - * @return {@link Checker} instance. + * @return {@link Checker} instance based on the given {@link Configuration} instance. * @throws Exception if an exception occurs during checker configuration. */ protected final Checker createChecker(Configuration moduleConfig, - ModuleCreationOption moduleCreationOption) + ModuleCreationOption moduleCreationOption) throws Exception { - final Configuration dc; - - if (moduleCreationOption == ModuleCreationOption.IN_TREEWALKER) { - dc = createTreeWalkerConfig(moduleConfig); - } - else if (ROOT_MODULE_NAME.equals(moduleConfig.getName())) { - dc = moduleConfig; - } - else { - dc = createRootConfig(moduleConfig); - } - final Checker checker = new Checker(); + checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); // make sure the tests always run with English error messages // so the tests don't fail in supported locales like German final Locale locale = Locale.ENGLISH; checker.setLocaleCountry(locale.getCountry()); checker.setLocaleLanguage(locale.getLanguage()); - checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); - checker.configure(dc); + + if (moduleCreationOption == ModuleCreationOption.IN_TREEWALKER) { + final Configuration config = createTreeWalkerConfig(moduleConfig); + checker.configure(config); + } + else if (ROOT_MODULE_NAME.equals(moduleConfig.getName()) + || "Checker".equals(moduleConfig.getName())) { + checker.configure(moduleConfig); + } + else { + final Configuration config = createRootConfig(moduleConfig); + checker.configure(config); + } checker.addListener(getBriefUtLogger()); return checker; } /** - * Creates {@link DefaultConfiguration} or the {@link Checker}. - * based on the given {@link Configuration}. + * Creates {@link DefaultConfiguration} for the {@link TreeWalker} + * based on the given {@link Configuration} instance. + * * @param config {@link Configuration} instance. - * @return {@link DefaultConfiguration} for the {@link Checker}. + * @return {@link DefaultConfiguration} for the {@link TreeWalker} + * based on the given {@link Configuration} instance. */ - protected final DefaultConfiguration createTreeWalkerConfig(Configuration config) { - final DefaultConfiguration dc = - new DefaultConfiguration("configuration"); + protected static DefaultConfiguration createTreeWalkerConfig(Configuration config) { + final DefaultConfiguration rootConfig = + new DefaultConfiguration(ROOT_MODULE_NAME); final DefaultConfiguration twConf = createModuleConfig(TreeWalker.class); // make sure that the tests always run with this charset - dc.addAttribute("charset", "iso-8859-1"); - dc.addChild(twConf); + rootConfig.addProperty("charset", StandardCharsets.UTF_8.name()); + rootConfig.addChild(twConf); twConf.addChild(config); - return dc; + return rootConfig; + } + + /** + * Creates {@link DefaultConfiguration} or the Checker. + * based on the the list of {@link Configuration}. + * + * @param configs list of {@link Configuration} instances. + * @return {@link DefaultConfiguration} for the Checker. + */ + protected static DefaultConfiguration createTreeWalkerConfig( + List configs) { + DefaultConfiguration result = null; + + for (Configuration config : configs) { + if (result == null) { + result = (DefaultConfiguration) createTreeWalkerConfig(config).getChildren()[0]; + } + else { + result.addChild(config); + } + } + + return result; } /** * Creates {@link DefaultConfiguration} for the given {@link Configuration} instance. + * * @param config {@link Configuration} instance. * @return {@link DefaultConfiguration} for the given {@link Configuration} instance. */ protected static DefaultConfiguration createRootConfig(Configuration config) { - final DefaultConfiguration dc = new DefaultConfiguration(ROOT_MODULE_NAME); - dc.addChild(config); - return dc; + final DefaultConfiguration rootConfig = new DefaultConfiguration(ROOT_MODULE_NAME); + rootConfig.addChild(config); + return rootConfig; } /** - * Performs verification of the file with given file name. Uses specified configuration. + * Returns canonical path for the file with the given file name. + * The path is formed base on the non-compilable resources location. + * + * @param filename file name. + * @return canonical path for the file with the given file name. + * @throws IOException if I/O exception occurs while forming the path. + */ + protected final String getNonCompilablePath(String filename) throws IOException { + return new File("src/" + getResourceLocation() + "/resources-noncompilable/" + + getPackageLocation() + "/" + filename).getCanonicalPath(); + } + + /** + * Performs verification of the file with the given file name. Uses specified configuration. * Expected messages are represented by the array of strings, warning line numbers are * represented by the array of integers. * This implementation uses overloaded * {@link AbstractItModuleTestSupport#verify(Checker, File[], String, String[], Integer...)} * method inside. + * * @param config configuration. * @param fileName file name to verify. * @param expected an array of expected messages. @@ -210,7 +393,9 @@ protected final void verify(Configuration config, String fileName, String[] expe } /** - * Performs verification of files. Uses provided {@link Checker} instance. + * Performs verification of files. + * Uses provided {@link Checker} instance. + * * @param checker {@link Checker} instance. * @param processedFiles files to process. * @param messageFileName message file name. @@ -238,35 +423,137 @@ protected final void verify(Checker checker, LineNumberReader lnr = new LineNumberReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { int previousLineNumber = 0; - for (int i = 0; i < expected.length; i++) { - final String expectedResult = messageFileName + ":" + expected[i]; + for (int index = 0; index < expected.length; index++) { + final String expectedResult = messageFileName + ":" + expected[index]; final String actual = lnr.readLine(); - assertEquals(expectedResult, actual, "error message " + i); + assertWithMessage("Error message at position %s of 'expected' does " + + "not match actual message", index) + .that(actual) + .isEqualTo(expectedResult); String parseInt = removeDeviceFromPathOnWindows(actual); parseInt = parseInt.substring(parseInt.indexOf(':') + 1); parseInt = parseInt.substring(0, parseInt.indexOf(':')); final int lineNumber = Integer.parseInt(parseInt); - assertTrue(previousLineNumber == lineNumber - || theWarnings.remove((Integer) lineNumber), - "input file is expected to have a warning comment on line number " - + lineNumber); + assertWithMessage( + "input file is expected to have a warning comment on line number %s", + lineNumber) + .that(previousLineNumber == lineNumber + || theWarnings.remove((Integer) lineNumber)) + .isTrue(); previousLineNumber = lineNumber; } - assertEquals(expected.length, - errs, "unexpected output: " + lnr.readLine()); - assertEquals(0, theWarnings.size(), "unexpected warnings " + theWarnings); + assertWithMessage("unexpected output: %s", lnr.readLine()) + .that(errs) + .isEqualTo(expected.length); + assertWithMessage("unexpected warnings %s", theWarnings) + .that(theWarnings) + .isEmpty(); } checker.destroy(); } + /** + * Performs the verification of the file with the given file path and config. + * + * @param config config to check against. + * @param filePath input file path. + * @throws Exception if exception occurs during verification process. + */ + protected void verifyWithItConfig(Configuration config, String filePath) throws Exception { + final List violations = + InlineConfigParser.getViolationsFromInputFile(filePath); + final List actualViolations = getActualViolationsForFile(config, filePath); + + verifyViolations(filePath, violations, actualViolations); + } + + /** + * Tests the file with the check config. + * + * @param config check configuration. + * @param file input file path. + * @return list of actual violations. + * @throws Exception if exception occurs during verification process. + */ + private List getActualViolationsForFile(Configuration config, + String file) throws Exception { + stream.flush(); + stream.reset(); + final List files = Collections.singletonList(new File(file)); + final Checker checker = createChecker(config); + final Map> actualViolations = + getActualViolations(checker.process(files)); + checker.destroy(); + return actualViolations.getOrDefault(file, new ArrayList<>()); + } + + /** + * Returns the actual violations for each file that has been checked against {@link Checker}. + * Each file is mapped to their corresponding violation messages. Reads input stream for these + * messages using instance of {@link InputStreamReader}. + * + * @param errorCount count of errors after checking set of files against {@link Checker}. + * @return a {@link Map} object containing file names and the corresponding violation messages. + * @throws IOException exception can occur when reading input stream. + */ + private Map> getActualViolations(int errorCount) throws IOException { + // process each of the lines + try (ByteArrayInputStream inputStream = + new ByteArrayInputStream(stream.toByteArray()); + LineNumberReader lnr = new LineNumberReader( + new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + final Map> actualViolations = new HashMap<>(); + for (String line = lnr.readLine(); line != null && lnr.getLineNumber() <= errorCount; + line = lnr.readLine()) { + // have at least 2 characters before the splitting colon, + // to not split after the drive letter on Windows + final String[] actualViolation = line.split("(?<=.{2}):", 2); + final String actualViolationFileName = actualViolation[0]; + final String actualViolationMessage = actualViolation[1]; + + actualViolations + .computeIfAbsent(actualViolationFileName, key -> new ArrayList<>()) + .add(actualViolationMessage); + } + + return actualViolations; + } + } + + /** + * Performs verification of violation lines. + * + * @param file file path. + * @param testInputViolations List of TestInputViolation objects. + * @param actualViolations for a file + */ + private static void verifyViolations(String file, List testInputViolations, + List actualViolations) { + final List actualViolationLines = actualViolations.stream() + .map(violation -> violation.substring(0, violation.indexOf(':'))) + .map(Integer::valueOf) + .toList(); + final List expectedViolationLines = testInputViolations.stream() + .map(TestInputViolation::getLineNo) + .toList(); + assertWithMessage("Violation lines for %s differ.", file) + .that(actualViolationLines) + .isEqualTo(expectedViolationLines); + for (int index = 0; index < actualViolations.size(); index++) { + assertWithMessage("Actual and expected violations differ.") + .that(actualViolations.get(index)) + .matches(testInputViolations.get(index).toRegex()); + } + } + /** * Gets the check message 'as is' from appropriate 'messages.properties' * file. * - * @param aClass The package the message is located in. + * @param aClass the package the message is located in. * @param messageKey the key of message in 'messages.properties' file. * @param arguments the arguments of message in 'messages.properties' file. * @return The message of the check with the arguments applied. @@ -283,7 +570,8 @@ protected static String getCheckMessage(Class messages, String mes return checkMessage; } + /** + * Remove device from path string for windows path. + * + * @param path path to correct. + * @return Path without device name. + */ private static String removeDeviceFromPathOnWindows(String path) { String fixedPath = path; final String os = System.getProperty("os.name", "Unix"); @@ -313,14 +607,14 @@ private static String removeDeviceFromPathOnWindows(String path) { /** * Returns an array of integers which represents the warning line numbers in the file * with the given file name. + * * @param fileName file name. * @return an array of integers which represents the warning line numbers. * @throws IOException if I/O exception occurs while reading the file. */ protected Integer[] getLinesWithWarn(String fileName) throws IOException { final List result = new ArrayList<>(); - try (BufferedReader br = Files.newBufferedReader( - Paths.get(fileName), StandardCharsets.UTF_8)) { + try (BufferedReader br = Files.newBufferedReader(Path.of(fileName))) { int lineNumber = 1; while (true) { final String line = br.readLine(); diff --git a/src/it/java/org/checkstyle/checks/imports/ImportOrderTest.java b/src/it/java/org/checkstyle/checks/imports/ImportOrderTest.java index 10083e8dcec8..cd13a589853f 100644 --- a/src/it/java/org/checkstyle/checks/imports/ImportOrderTest.java +++ b/src/it/java/org/checkstyle/checks/imports/ImportOrderTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,7 +15,7 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package org.checkstyle.checks.imports; @@ -36,13 +36,13 @@ protected String getPackageLocation() { @Test public void testAndroid() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ImportOrderCheck.class); - checkConfig.addAttribute("groups", + checkConfig.addProperty("groups", "android,androidx,com.android,dalvik,com,gov,junit,libcore,net,org,java,javax"); - checkConfig.addAttribute("option", "top"); - checkConfig.addAttribute("ordered", "true"); - checkConfig.addAttribute("separated", "true"); - checkConfig.addAttribute("separatedStaticGroups", "true"); - checkConfig.addAttribute("staticGroups", + checkConfig.addProperty("option", "top"); + checkConfig.addProperty("ordered", "true"); + checkConfig.addProperty("separated", "true"); + checkConfig.addProperty("separatedStaticGroups", "true"); + checkConfig.addProperty("staticGroups", "android,androidx,com.android,dalvik,com,gov,junit,libcore,net,org,java,javax"); final String filePath = getNonCompilablePath("InputFromAndroid.java"); @@ -54,12 +54,12 @@ public void testAndroid() throws Exception { @Test public void testSpotify() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ImportOrderCheck.class); - checkConfig.addAttribute("groups", "android,com,net,junit,org,java,javax"); - checkConfig.addAttribute("option", "bottom"); - checkConfig.addAttribute("ordered", "true"); - checkConfig.addAttribute("separated", "true"); - checkConfig.addAttribute("separatedStaticGroups", "true"); - checkConfig.addAttribute("staticGroups", "android,com,net,junit,org,java,javax"); + checkConfig.addProperty("groups", "android,com,net,junit,org,java,javax"); + checkConfig.addProperty("option", "bottom"); + checkConfig.addProperty("ordered", "true"); + checkConfig.addProperty("separated", "true"); + checkConfig.addProperty("separatedStaticGroups", "true"); + checkConfig.addProperty("staticGroups", "android,com,net,junit,org,java,javax"); final String filePath = getNonCompilablePath("InputFromSpotify.java"); final String[] expected = CommonUtil.EMPTY_STRING_ARRAY; @@ -70,13 +70,13 @@ public void testSpotify() throws Exception { @Test public void testTwitter() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(ImportOrderCheck.class); - checkConfig.addAttribute("caseSensitive", "true"); - checkConfig.addAttribute("groups", "android,com.twitter,com,junit,net,org,java,javax"); - checkConfig.addAttribute("option", "bottom"); - checkConfig.addAttribute("ordered", "true"); - checkConfig.addAttribute("separated", "true"); - checkConfig.addAttribute("separatedStaticGroups", "true"); - checkConfig.addAttribute("staticGroups", + checkConfig.addProperty("caseSensitive", "true"); + checkConfig.addProperty("groups", "android,com.twitter,com,junit,net,org,java,javax"); + checkConfig.addProperty("option", "bottom"); + checkConfig.addProperty("ordered", "true"); + checkConfig.addProperty("separated", "true"); + checkConfig.addProperty("separatedStaticGroups", "true"); + checkConfig.addProperty("staticGroups", "android,com.twitter,com,junit,net,org,java,javax"); final String filePath = getNonCompilablePath("InputFromTwitter.java"); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/AbstractXpathTestSupport.java b/src/it/java/org/checkstyle/suppressionxpathfilter/AbstractXpathTestSupport.java index 7e34984f8186..d90b0e464958 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/AbstractXpathTestSupport.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/AbstractXpathTestSupport.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,27 +15,24 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package org.checkstyle.suppressionxpathfilter; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static com.google.common.truth.Truth.assertWithMessage; import java.io.File; -import java.io.IOException; import java.io.Writer; import java.nio.charset.StandardCharsets; -import java.nio.file.DirectoryStream; import java.nio.file.Files; -import java.nio.file.Path; import java.util.List; import java.util.Locale; +import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.checkstyle.base.AbstractCheckstyleModuleTestSupport; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; import com.puppycrawl.tools.checkstyle.JavaParser; @@ -53,51 +50,20 @@ public abstract class AbstractXpathTestSupport extends AbstractCheckstyleModuleT private static final String DELIMITER = " | \n"; private static final Pattern LINE_COLUMN_NUMBER_REGEX = - Pattern.compile("([0-9]+):([0-9]+):"); + Pattern.compile("(\\d+):(\\d+):"); /** - *

    * The temporary folder to hold intermediate files. - *

    - *

    - * Till https://github.com/junit-team/junit5/issues/1786 - * we need to create and clean it manually. - * Once this issue will be resolved, it should be annotated with @TempDir - * and methods setupTemporaryFolder and removeTemporaryFolder should be dropped. - *

    */ - private Path temporaryFolder; - - protected abstract String getCheckName(); - - /** - *

    - * Creates temporary folder for intermediate files. - *

    - * - * @throws IOException if an IO error occurs - */ - @BeforeEach - public void setupTemporaryFolder() throws IOException { - temporaryFolder = Files.createTempDirectory("xpath-test"); - } + @TempDir + public File temporaryFolder; /** - *

    - * Removes temporary folder with intermediate files. - *

    + * Returns name of the check. * - * @throws IOException if an IO error occurs + * @return name of the check as a String. */ - @AfterEach - public void removeTemporaryFolder() throws IOException { - try (DirectoryStream paths = Files.newDirectoryStream(temporaryFolder)) { - for (Path path : paths) { - Files.delete(path); - } - } - Files.delete(temporaryFolder); - } + protected abstract String getCheckName(); @Override protected String getPackageLocation() { @@ -106,6 +72,14 @@ protected String getPackageLocation() { return "org/checkstyle/suppressionxpathfilter/" + subpackage; } + /** + * Returns a list of XPath queries to locate the violation nodes in a Java file. + * + * @param fileToProcess the Java file to be processed. {@link File} type object. + * @param position the position of violation in the file. {@link ViolationPosition} object. + * @return a list of strings containing XPath queries for locating violation nodes. + * @throws Exception can throw exceptions while accessing file contents. + */ private static List generateXpathQueries(File fileToProcess, ViolationPosition position) throws Exception { @@ -120,18 +94,36 @@ private static List generateXpathQueries(File fileToProcess, return queryGenerator.generate(); } + /** + * Verify generated XPath queries by comparing with expected queries. + * + * @param generatedXpathQueries a list of generated XPath queries. + * @param expectedXpathQueries a list of expected XPath queries. + */ private static void verifyXpathQueries(List generatedXpathQueries, List expectedXpathQueries) { - assertEquals(expectedXpathQueries, - generatedXpathQueries, "Generated queries do not match expected ones"); + assertWithMessage("Generated queries do not match expected ones") + .that(generatedXpathQueries) + .isEqualTo(expectedXpathQueries); } + /** + * Returns the path to the generated Suppressions XPath config file. + * This method creates a Suppressions config file containing the Xpath queries for + * any check and returns the path to that file. + * + * @param checkName the name of the check that is run. + * @param xpathQueries a list of generated XPath queries for violations in a file. + * @return path(String) to the generated Suppressions config file. + * @throws Exception can throw exceptions when writing/creating the config file. + */ private String createSuppressionsXpathConfigFile(String checkName, List xpathQueries) throws Exception { - final Path suppressionsXpathConfigPath = - Files.createTempFile(temporaryFolder, "", ""); - try (Writer bw = Files.newBufferedWriter(suppressionsXpathConfigPath, + final String uniqueFileName = + "suppressions_xpath_config_" + UUID.randomUUID() + ".xml"; + final File suppressionsXpathConfigPath = new File(temporaryFolder, uniqueFileName); + try (Writer bw = Files.newBufferedWriter(suppressionsXpathConfigPath.toPath(), StandardCharsets.UTF_8)) { bw.write("\n"); bw.write(" xpathQueries) throws Exception { final DefaultConfiguration suppressionXpathFilterConfig = createModuleConfig(SuppressionXpathFilter.class); - suppressionXpathFilterConfig.addAttribute("file", + suppressionXpathFilterConfig.addProperty("file", createSuppressionsXpathConfigFile(checkName, xpathQueries)); return suppressionXpathFilterConfig; } + /** + * Extract line no and column nos from String of expected violations. + * + * @param expectedViolations the expected violations generated for the check. + * @return instance of type {@link ViolationPosition} which contains the line and column nos. + */ private static ViolationPosition extractLineAndColumnNumber(String... expectedViolations) { ViolationPosition violation = null; final Matcher matcher = @@ -183,18 +189,27 @@ private static ViolationPosition extractLineAndColumnNumber(String... expectedVi * xpath queries. * Third one constructs new configuration with {@code SuppressionXpathFilter} using generated * xpath queries, executes checker and checks if no violation occurred. + * * @param moduleConfig module configuration. * @param fileToProcess input class file. - * @param expectedViolations expected violation messages. + * @param expectedViolation expected violation message. * @param expectedXpathQueries expected generated xpath queries. * @throws Exception if an error occurs + * @throws IllegalArgumentException if length of expectedViolation is more than 1 */ protected void runVerifications(DefaultConfiguration moduleConfig, File fileToProcess, - String[] expectedViolations, + String[] expectedViolation, List expectedXpathQueries) throws Exception { + if (expectedViolation.length != 1) { + throw new IllegalArgumentException( + "Expected violations should contain exactly one element." + + " Multiple violations are not supported." + ); + } + final ViolationPosition position = - extractLineAndColumnNumber(expectedViolations); + extractLineAndColumnNumber(expectedViolation); final List generatedXpathQueries = generateXpathQueries(fileToProcess, position); @@ -205,19 +220,19 @@ protected void runVerifications(DefaultConfiguration moduleConfig, generatedXpathQueries)); final Integer[] warnList = getLinesWithWarn(fileToProcess.getPath()); - verify(moduleConfig, fileToProcess.getPath(), expectedViolations, warnList); + verify(moduleConfig, fileToProcess.getPath(), expectedViolation, warnList); verifyXpathQueries(generatedXpathQueries, expectedXpathQueries); verify(treeWalkerConfigWithXpath, fileToProcess.getPath(), CommonUtil.EMPTY_STRING_ARRAY); } - private static final class ViolationPosition { - private final int violationLineNumber; - private final int violationColumnNumber; - - /* package */ ViolationPosition(int violationLineNumber, - int violationColumnNumber) { - this.violationLineNumber = violationLineNumber; - this.violationColumnNumber = violationColumnNumber; + private record ViolationPosition(int violationLineNumber, int violationColumnNumber) { + /** + * Constructor of the class. + * + * @param violationLineNumber line no of the violation produced for the check. + * @param violationColumnNumber column no of the violation produced for the check. + */ + private ViolationPosition { } } } diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAbstractClassNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAbstractClassNameTest.java deleted file mode 100644 index f7adc9b6bbd0..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAbstractClassNameTest.java +++ /dev/null @@ -1,123 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.naming.AbstractClassNameCheck; - -public class XpathRegressionAbstractClassNameTest extends AbstractXpathTestSupport { - - private final String checkName = AbstractClassNameCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testClassNameTop() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionAbstractClassNameTop.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AbstractClassNameCheck.class); - - final String[] expectedViolation = { - "3:1: " + getCheckMessage(AbstractClassNameCheck.class, - AbstractClassNameCheck.MSG_ILLEGAL_ABSTRACT_CLASS_NAME, - "SuppressionXpathRegressionAbstractClassNameTop", "^Abstract.+$"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAbstractClassNameTop']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAbstractClassNameTop']]" - + "/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAbstractClassNameTop']]" - + "/MODIFIERS/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testClassNameInner() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionAbstractClassNameInner.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AbstractClassNameCheck.class); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(AbstractClassNameCheck.class, - AbstractClassNameCheck.MSG_ILLEGAL_ABSTRACT_CLASS_NAME, - "MyClass", "^Abstract.+$"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAbstractClassNameInner']]" - + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAbstractClassNameInner']]" - + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAbstractClassNameInner']]" - + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass']]/MODIFIERS/ABSTRACT" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testClassNameNoModifier() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionAbstractClassNameNoModifier.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AbstractClassNameCheck.class); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(AbstractClassNameCheck.class, - AbstractClassNameCheck.MSG_NO_ABSTRACT_CLASS_MODIFIER, - "AbstractMyClass"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='" - + "SuppressionXpathRegressionAbstractClassNameNoModifier']]" - + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='AbstractMyClass']]", - "/CLASS_DEF[./IDENT[@text='" - + "SuppressionXpathRegressionAbstractClassNameNoModifier']]" - + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='AbstractMyClass']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='" - + "SuppressionXpathRegressionAbstractClassNameNoModifier']]" - + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='AbstractMyClass']]/LITERAL_CLASS" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAnonInnerLengthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAnonInnerLengthTest.java deleted file mode 100644 index d5e6beee5978..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAnonInnerLengthTest.java +++ /dev/null @@ -1,69 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.sizes.AnonInnerLengthCheck; - -public class XpathRegressionAnonInnerLengthTest extends AbstractXpathTestSupport { - - private final String checkName = AnonInnerLengthCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testMaxLength() throws Exception { - final int maxLen = 5; - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionAnonInnerLength.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AnonInnerLengthCheck.class); - moduleConfig.addAttribute("max", String.valueOf(maxLen)); - - final String[] expectedViolation = { - "7:41: " + getCheckMessage(AnonInnerLengthCheck.class, - AnonInnerLengthCheck.MSG_KEY, 6, maxLen), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAnonInnerLength']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='compare']]/SLIST" - + "/VARIABLE_DEF[./IDENT[@text='comparator']]/ASSIGN/EXPR", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAnonInnerLength']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='compare']]/SLIST" - + "/VARIABLE_DEF[./IDENT[@text='comparator']]/ASSIGN/EXPR" - + "/LITERAL_NEW[./IDENT[@text='Comparator']]" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionArrayTypeStyleTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionArrayTypeStyleTest.java index d1a1386449a8..d8a26e5a4e3d 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionArrayTypeStyleTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionArrayTypeStyleTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,12 +15,12 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package org.checkstyle.suppressionxpathfilter; import java.io.File; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; @@ -38,7 +38,7 @@ protected String getCheckName() { @Test public void testVariable() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionArrayTypeStyleVariable.java")); + new File(getPath("InputXpathArrayTypeStyleVariable.java")); final DefaultConfiguration moduleConfig = createModuleConfig(ArrayTypeStyleCheck.class); @@ -47,16 +47,11 @@ public void testVariable() throws Exception { "4:19: " + getCheckMessage(ArrayTypeStyleCheck.class, ArrayTypeStyleCheck.MSG_KEY), }; - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionArrayTypeStyleVariable']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='strings']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionArrayTypeStyleVariable']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='strings']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionArrayTypeStyleVariable']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='strings']]/TYPE", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionArrayTypeStyleVariable']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='strings']]/TYPE" - + "/ARRAY_DECLARATOR[./IDENT[@text='String']]" + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathArrayTypeStyleVariable']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='strings']]/TYPE[" + + "./IDENT[@text='String']]/ARRAY_DECLARATOR" ); runVerifications(moduleConfig, fileToProcess, expectedViolation, @@ -66,7 +61,7 @@ public void testVariable() throws Exception { @Test public void testMethodDef() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionArrayTypeStyleMethodDef.java")); + new File(getPath("InputXpathArrayTypeStyleMethodDef.java")); final DefaultConfiguration moduleConfig = createModuleConfig(ArrayTypeStyleCheck.class); @@ -75,16 +70,10 @@ public void testMethodDef() throws Exception { "4:19: " + getCheckMessage(ArrayTypeStyleCheck.class, ArrayTypeStyleCheck.MSG_KEY), }; - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionArrayTypeStyleMethodDef']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getData']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionArrayTypeStyleMethodDef']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getData']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionArrayTypeStyleMethodDef']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getData']]/TYPE", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionArrayTypeStyleMethodDef']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getData']]/TYPE/ARRAY_DECLARATOR" - + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathArrayTypeStyleMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getData']]/TYPE/ARRAY_DECLARATOR" ); runVerifications(moduleConfig, fileToProcess, expectedViolation, diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidDoubleBraceInitializationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidDoubleBraceInitializationTest.java deleted file mode 100644 index 82f7b3e04b58..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidDoubleBraceInitializationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.AvoidDoubleBraceInitializationCheck; - -public class XpathRegressionAvoidDoubleBraceInitializationTest extends AbstractXpathTestSupport { - - private final Class clazz = - AvoidDoubleBraceInitializationCheck.class; - - @Override - protected String getCheckName() { - return clazz.getSimpleName(); - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionAvoidDoubleBraceInitialization.java")); - - final DefaultConfiguration moduleConfig = createModuleConfig(clazz); - - final String[] expectedViolation = { - "6:41: " + getCheckMessage(clazz, AvoidDoubleBraceInitializationCheck.MSG_KEY), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAvoidDoubleBraceInitialization']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='list']]/ASSIGN/EXPR/" - + "LITERAL_NEW[./IDENT[@text='ArrayList']]/OBJBLOCK", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAvoidDoubleBraceInitialization']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='list']]/ASSIGN/EXPR/" - + "LITERAL_NEW[./IDENT[@text='ArrayList']]/OBJBLOCK/LCURLY" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidEscapedUnicodeCharactersTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidEscapedUnicodeCharactersTest.java new file mode 100644 index 000000000000..1e5f4b002a26 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidEscapedUnicodeCharactersTest.java @@ -0,0 +1,188 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter; + +import static com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.AvoidEscapedUnicodeCharactersCheck; + +public class XpathRegressionAvoidEscapedUnicodeCharactersTest extends AbstractXpathTestSupport { + private final String checkName = AvoidEscapedUnicodeCharactersCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidEscapedUnicodeCharactersDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidEscapedUnicodeCharactersCheck.class); + + final String[] expectedViolation = { + "4:34: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathAvoidEscapedUnicodeCharactersDefault']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev2']]" + + "/ASSIGN/EXPR[./STRING_LITERAL[@text='\\u03bcs']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathAvoidEscapedUnicodeCharactersDefault']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev2']]" + + "/ASSIGN/EXPR/STRING_LITERAL[@text='\\u03bcs']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testControlCharacters() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidEscapedUnicodeCharactersControlCharacters.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidEscapedUnicodeCharactersCheck.class); + moduleConfig.addProperty("allowEscapesForControlCharacters", "true"); + + final String[] expectedViolation = { + "4:34: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text=" + + "'InputXpathAvoidEscapedUnicodeCharactersControlCharacters']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev9']]" + + "/ASSIGN/EXPR[./STRING_LITERAL[@text='\\u03bcs']]", + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text=" + + "'InputXpathAvoidEscapedUnicodeCharactersControlCharacters']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev9']]" + + "/ASSIGN/EXPR/STRING_LITERAL[@text='\\u03bcs']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTailComment() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidEscapedUnicodeCharactersTailComment.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidEscapedUnicodeCharactersCheck.class); + moduleConfig.addProperty("allowByTailComment", "true"); + + final String[] expectedViolation = { + "4:45: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text=" + + "'InputXpathAvoidEscapedUnicodeCharactersTailComment']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev9']]" + + "/ASSIGN/EXPR[./STRING_LITERAL[@text='\\u03bcs']]", + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text=" + + "'InputXpathAvoidEscapedUnicodeCharactersTailComment']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev9']]" + + "/ASSIGN/EXPR/STRING_LITERAL[@text='\\u03bcs']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testAllCharactersEscaped() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidEscapedUnicodeCharactersAllEscaped.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidEscapedUnicodeCharactersCheck.class); + moduleConfig.addProperty("allowIfAllCharactersEscaped", "true"); + + final String[] expectedViolation = { + "4:34: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text=" + + "'InputXpathAvoidEscapedUnicodeCharactersAllEscaped']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev9']]" + + "/ASSIGN/EXPR[./STRING_LITERAL[@text='\\u03bcs']]", + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text=" + + "'InputXpathAvoidEscapedUnicodeCharactersAllEscaped']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev9']]" + + "/ASSIGN/EXPR/STRING_LITERAL[@text='\\u03bcs']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNonPrintableCharacters() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidEscapedUnicodeCharactersNonPrintable.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidEscapedUnicodeCharactersCheck.class); + moduleConfig.addProperty("allowNonPrintableEscapes", "true"); + + final String[] expectedViolation = { + "4:34: " + getCheckMessage(AvoidEscapedUnicodeCharactersCheck.class, MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text=" + + "'InputXpathAvoidEscapedUnicodeCharactersNonPrintable']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev9']]" + + "/ASSIGN/EXPR[./STRING_LITERAL[@text='\\u03bcs']]", + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text=" + + "'InputXpathAvoidEscapedUnicodeCharactersNonPrintable']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='unitAbbrev9']]" + + "/ASSIGN/EXPR/STRING_LITERAL[@text='\\u03bcs']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidInlineConditionalsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidInlineConditionalsTest.java deleted file mode 100644 index 3895ef22b246..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidInlineConditionalsTest.java +++ /dev/null @@ -1,119 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.AvoidInlineConditionalsCheck; - -public class XpathRegressionAvoidInlineConditionalsTest extends AbstractXpathTestSupport { - - @Override - protected String getCheckName() { - return AvoidInlineConditionalsCheck.class.getSimpleName(); - } - - @Test - public void testInlineConditionalsVariableDef() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionAvoidInlineConditionalsVariableDef.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AvoidInlineConditionalsCheck.class); - - final String[] expectedViolation = { - "5:50: " + getCheckMessage(AvoidInlineConditionalsCheck.class, - AvoidInlineConditionalsCheck.MSG_KEY), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='" - + "SuppressionXpathRegressionAvoidInlineConditionalsVariableDef']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='substring']]/SLIST" - + "/VARIABLE_DEF[./IDENT[@text='b']]/ASSIGN/EXPR", - "/CLASS_DEF[./IDENT[@text='" - + "SuppressionXpathRegressionAvoidInlineConditionalsVariableDef']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='substring']]/SLIST" - + "/VARIABLE_DEF[./IDENT[@text='b']]/ASSIGN/EXPR/QUESTION" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testInlineConditionalsAssign() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionAvoidInlineConditionalsAssign.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AvoidInlineConditionalsCheck.class); - - final String[] expectedViolation = { - "7:43: " + getCheckMessage(AvoidInlineConditionalsCheck.class, - AvoidInlineConditionalsCheck.MSG_KEY), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='" - + "SuppressionXpathRegressionAvoidInlineConditionalsAssign']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='setB']]/SLIST" - + "/EXPR/ASSIGN[./IDENT[@text='b']]/QUESTION" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testInlineConditionalsAssert() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionAvoidInlineConditionalsAssert.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AvoidInlineConditionalsCheck.class); - - final String[] expectedViolation = { - "8:31: " + getCheckMessage(AvoidInlineConditionalsCheck.class, - AvoidInlineConditionalsCheck.MSG_KEY), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='" - + "SuppressionXpathRegressionAvoidInlineConditionalsAssert']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='assertA']]/SLIST" - + "/LITERAL_ASSERT/EXPR[./QUESTION/METHOD_CALL/DOT/IDENT[@text='a']]", - "/CLASS_DEF[./IDENT[@text='" - + "SuppressionXpathRegressionAvoidInlineConditionalsAssert']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='assertA']]/SLIST" - + "/LITERAL_ASSERT/EXPR/QUESTION" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidNestedBlocksTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidNestedBlocksTest.java deleted file mode 100644 index 9bcdca363eaa..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidNestedBlocksTest.java +++ /dev/null @@ -1,142 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.blocks.AvoidNestedBlocksCheck; - -public class XpathRegressionAvoidNestedBlocksTest extends AbstractXpathTestSupport { - - @Override - protected String getCheckName() { - return AvoidNestedBlocksCheck.class.getSimpleName(); - } - - @Test - public void testEmpty() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionAvoidNestedBlocksEmpty.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AvoidNestedBlocksCheck.class); - - final String[] expectedViolation = { - "6:9: " + getCheckMessage(AvoidNestedBlocksCheck.class, - AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAvoidNestedBlocksEmpty']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='empty']]/SLIST/SLIST" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testVariableAssignment() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionAvoidNestedBlocksVariable.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AvoidNestedBlocksCheck.class); - - final String[] expectedViolation = { - "7:9: " + getCheckMessage(AvoidNestedBlocksCheck.class, - AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAvoidNestedBlocksVariable']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='varAssign']]/SLIST/SLIST" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testSwitchAllowInSwitchCaseFalse() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionAvoidNestedBlocksSwitch1.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AvoidNestedBlocksCheck.class); - - final String[] expectedViolation = { - "9:21: " + getCheckMessage(AvoidNestedBlocksCheck.class, - AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), - "16:13: " + getCheckMessage(AvoidNestedBlocksCheck.class, - AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), - "20:21: " + getCheckMessage(AvoidNestedBlocksCheck.class, - AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAvoidNestedBlocksSwitch1']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='s']]/SLIST/LITERAL_SWITCH" - + "/CASE_GROUP/SLIST", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAvoidNestedBlocksSwitch1']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='s']]/SLIST/LITERAL_SWITCH" - + "/CASE_GROUP/SLIST/SLIST" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testSwitchAllowInSwitchCaseTrue() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionAvoidNestedBlocksSwitch2.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(AvoidNestedBlocksCheck.class); - moduleConfig.addAttribute("allowInSwitchCase", "true"); - - final String[] expectedViolation = { - "9:21: " + getCheckMessage(AvoidNestedBlocksCheck.class, - AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), - "16:13: " + getCheckMessage(AvoidNestedBlocksCheck.class, - AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAvoidNestedBlocksSwitch2']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='s']]/SLIST/LITERAL_SWITCH" - + "/CASE_GROUP/SLIST", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionAvoidNestedBlocksSwitch2']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='s']]/SLIST/LITERAL_SWITCH" - + "/CASE_GROUP/SLIST/SLIST" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidNoArgumentSuperConstructorCallTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidNoArgumentSuperConstructorCallTest.java deleted file mode 100644 index 89042760f1f6..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAvoidNoArgumentSuperConstructorCallTest.java +++ /dev/null @@ -1,65 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.AvoidNoArgumentSuperConstructorCallCheck; - -public class XpathRegressionAvoidNoArgumentSuperConstructorCallTest - extends AbstractXpathTestSupport { - - private static final Class CLASS = - AvoidNoArgumentSuperConstructorCallCheck.class; - - @Override - protected String getCheckName() { - return CLASS.getSimpleName(); - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAvoidNoArgumentSuperConstructorCall.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(CLASS); - - final String[] expectedViolation = { - "5:9: " + getCheckMessage(CLASS, - AvoidNoArgumentSuperConstructorCallCheck.MSG_CTOR), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT" - + "[@text='SuppressionXpathRegressionAvoidNoArgumentSuperConstructorCall']]" - + "/OBJBLOCK/CTOR_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAvoidNoArgumentSuperConstructorCall']]" - + "/SLIST/SUPER_CTOR_CALL" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionClassMemberImpliedModifierTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionClassMemberImpliedModifierTest.java deleted file mode 100644 index c34453e61dde..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionClassMemberImpliedModifierTest.java +++ /dev/null @@ -1,94 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.modifier.ClassMemberImpliedModifierCheck; - -public class XpathRegressionClassMemberImpliedModifierTest extends AbstractXpathTestSupport { - - private final String checkName = ClassMemberImpliedModifierCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionClassMemberImpliedModifierOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(ClassMemberImpliedModifierCheck.class); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(ClassMemberImpliedModifierCheck.class, - ClassMemberImpliedModifierCheck.MSG_KEY, "static", 0), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionClassMemberImpliedModifierOne']]" - + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Foo']]", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionClassMemberImpliedModifierOne']]" - + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Foo']]/MODIFIERS", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionClassMemberImpliedModifierOne']]" - + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Foo']]/MODIFIERS/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionClassMemberImpliedModifierTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(ClassMemberImpliedModifierCheck.class); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(ClassMemberImpliedModifierCheck.class, - ClassMemberImpliedModifierCheck.MSG_KEY, "static", "null"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionClassMemberImpliedModifierTwo']]" - + "/OBJBLOCK/ENUM_DEF[./IDENT[@text='Count']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionClassMemberImpliedModifierTwo']]" - + "/OBJBLOCK/ENUM_DEF[./IDENT[@text='Count']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionClassMemberImpliedModifierTwo']]" - + "/OBJBLOCK/ENUM_DEF[./IDENT[@text='Count']]/MODIFIERS/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionCyclomaticComplexityTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionCyclomaticComplexityTest.java deleted file mode 100644 index 89c8a425a108..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionCyclomaticComplexityTest.java +++ /dev/null @@ -1,94 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.metrics.CyclomaticComplexityCheck; - -public class XpathRegressionCyclomaticComplexityTest extends AbstractXpathTestSupport { - - private final String checkName = CyclomaticComplexityCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionCyclomaticComplexityOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(CyclomaticComplexityCheck.class); - moduleConfig.addAttribute("max", "0"); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(CyclomaticComplexityCheck.class, - CyclomaticComplexityCheck.MSG_KEY, 2, 0), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionCyclomaticComplexityOne']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionCyclomaticComplexityOne']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionCyclomaticComplexityOne']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionCyclomaticComplexityTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(CyclomaticComplexityCheck.class); - moduleConfig.addAttribute("max", "0"); - - final String[] expectedViolation = { - "6:5: " + getCheckMessage(CyclomaticComplexityCheck.class, - CyclomaticComplexityCheck.MSG_KEY, 5, 0), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionCyclomaticComplexityTwo']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo2']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionCyclomaticComplexityTwo']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo2']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionCyclomaticComplexityTwo']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo2']]/MODIFIERS/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDeclarationOrderTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDeclarationOrderTest.java deleted file mode 100644 index 8585d8527716..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDeclarationOrderTest.java +++ /dev/null @@ -1,91 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheck; - -public class XpathRegressionDeclarationOrderTest extends AbstractXpathTestSupport { - - private final String checkName = DeclarationOrderCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionDeclarationOrderOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(DeclarationOrderCheck.class); - - final String[] expectedViolation = { - "5:5: " + getCheckMessage(DeclarationOrderCheck.class, - DeclarationOrderCheck.MSG_ACCESS), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDeclarationOrderOne']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='name']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDeclarationOrderOne']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='name']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDeclarationOrderOne']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='name']]/MODIFIERS/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionDeclarationOrderTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(DeclarationOrderCheck.class); - - final String[] expectedViolation = { - "5:5: " + getCheckMessage(DeclarationOrderCheck.class, - DeclarationOrderCheck.MSG_STATIC), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDeclarationOrderTwo']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='MAX']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDeclarationOrderTwo']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='MAX']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDeclarationOrderTwo']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='MAX']]/MODIFIERS/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDefaultComesLastTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDefaultComesLastTest.java deleted file mode 100644 index 5a03474cbe0d..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDefaultComesLastTest.java +++ /dev/null @@ -1,91 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.DefaultComesLastCheck; - -public class XpathRegressionDefaultComesLastTest extends AbstractXpathTestSupport { - - private final String checkName = DefaultComesLastCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionDefaultComesLastOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(DefaultComesLastCheck.class); - - final String[] expectedViolation = { - "8:13: " + getCheckMessage(DefaultComesLastCheck.class, - DefaultComesLastCheck.MSG_KEY), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDefaultComesLastOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP[" - + "./SLIST/EXPR/ASSIGN/IDENT[@text='id']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDefaultComesLastOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP" - + "/LITERAL_DEFAULT" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionDefaultComesLastTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(DefaultComesLastCheck.class); - moduleConfig.addAttribute("skipIfLastAndSharedWithCase", "true"); - - final String[] expectedViolation = { - "15:13: " + getCheckMessage(DefaultComesLastCheck.class, - DefaultComesLastCheck.MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionDefaultComesLastTwo']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP" - + "/LITERAL_DEFAULT" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDescendantTokenTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDescendantTokenTest.java new file mode 100644 index 000000000000..88d0ebb3d164 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionDescendantTokenTest.java @@ -0,0 +1,128 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter; + +import java.io.File; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.DescendantTokenCheck; + +public class XpathRegressionDescendantTokenTest extends AbstractXpathTestSupport { + + private final String checkName = DescendantTokenCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testSwitchNoDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDescendantTokenSwitchNoDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DescendantTokenCheck.class); + moduleConfig.addProperty("tokens", "LITERAL_SWITCH"); + moduleConfig.addProperty("maximumDepth", "2"); + moduleConfig.addProperty("limitedTokens", "LITERAL_DEFAULT"); + moduleConfig.addProperty("minimumNumber", "1"); + + final String[] expected = { + "7:9: " + getCheckMessage(DescendantTokenCheck.class, + DescendantTokenCheck.MSG_KEY_MIN, + 0, 1, "LITERAL_SWITCH", "LITERAL_DEFAULT"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDescendantTokenSwitchNoDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT" + + "[@text='testMethod1']]/SLIST/LITERAL_SWITCH" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + } + + @Test + public void testSwitchTooManyCases() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDescendantTokenSwitchTooManyCases.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DescendantTokenCheck.class); + moduleConfig.addProperty("tokens", "LITERAL_SWITCH"); + moduleConfig.addProperty("limitedTokens", "LITERAL_CASE"); + moduleConfig.addProperty("maximumDepth", "2"); + moduleConfig.addProperty("maximumNumber", "1"); + + final String[] expected = { + "8:13: " + getCheckMessage(DescendantTokenCheck.class, + DescendantTokenCheck.MSG_KEY_MAX, + 2, 1, "LITERAL_SWITCH", "LITERAL_CASE"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathDescendantTokenSwitchTooManyCases']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT" + + "[@text='testMethod1']]/SLIST/VARIABLE_DEF[./IDENT[@text='switchLogic']]" + + "/ASSIGN/LAMBDA/SLIST/LITERAL_SWITCH" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + } + + @Test + public void testNestedSwitch() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDescendantTokenNestedSwitch.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DescendantTokenCheck.class); + + moduleConfig.addProperty("tokens", "CASE_GROUP"); + moduleConfig.addProperty("limitedTokens", "LITERAL_SWITCH"); + moduleConfig.addProperty("maximumNumber", "0"); + + final String[] expected = { + "12:13: " + getCheckMessage(DescendantTokenCheck.class, + DescendantTokenCheck.MSG_KEY_MAX, + 1, 0, "CASE_GROUP", "LITERAL_SWITCH"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathDescendantTokenNestedSwitch']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='testMethod1']]/SLIST/LITERAL_SWITCH/" + + "CASE_GROUP[./LITERAL_CASE/EXPR/NUM_INT[@text='2']]", + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathDescendantTokenNestedSwitch']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='testMethod1']]/SLIST/LITERAL_SWITCH/" + + "CASE_GROUP/LITERAL_CASE" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + } +} + diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionEmptyForInitializerPadTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionEmptyForInitializerPadTest.java deleted file mode 100644 index afa2e3e8ba7d..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionEmptyForInitializerPadTest.java +++ /dev/null @@ -1,92 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForInitializerPadCheck; -import com.puppycrawl.tools.checkstyle.checks.whitespace.PadOption; - -public class XpathRegressionEmptyForInitializerPadTest extends AbstractXpathTestSupport { - - private final String checkName = EmptyForInitializerPadCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testPreceded() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionEmptyForInitializerPadPreceded.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(EmptyForInitializerPadCheck.class); - - final String[] expectedViolation = { - "5:15: " + getCheckMessage(EmptyForInitializerPadCheck.class, - EmptyForInitializerPadCheck.MSG_PRECEDED, ";"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionEmptyForInitializerPadPreceded']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/FOR_INIT", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionEmptyForInitializerPadPreceded']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/SEMI[1]" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testNotPreceded() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionEmptyForInitializerPadNotPreceded.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(EmptyForInitializerPadCheck.class); - moduleConfig.addAttribute("option", PadOption.SPACE.toString()); - - final String[] expectedViolation = { - "5:14: " + getCheckMessage(EmptyForInitializerPadCheck.class, - EmptyForInitializerPadCheck.MSG_NOT_PRECEDED, ";"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionEmptyForInitializerPadNotPreceded']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/FOR_INIT", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionEmptyForInitializerPadNotPreceded']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/SEMI[1]" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionEmptyForIteratorPadTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionEmptyForIteratorPadTest.java deleted file mode 100644 index 25b22b69b3bc..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionEmptyForIteratorPadTest.java +++ /dev/null @@ -1,94 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForIteratorPadCheck; -import com.puppycrawl.tools.checkstyle.checks.whitespace.PadOption; - -public class XpathRegressionEmptyForIteratorPadTest extends AbstractXpathTestSupport { - - private final String checkName = EmptyForIteratorPadCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testFollowed() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionEmptyForIteratorPadFollowed.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(EmptyForIteratorPadCheck.class); - - final String[] expectedViolation = { - "5:34: " + getCheckMessage(EmptyForIteratorPadCheck.class, - EmptyForIteratorPadCheck.MSG_WS_FOLLOWED, ";"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionEmptyForIteratorPadFollowed']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/FOR_ITERATOR", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionEmptyForIteratorPadFollowed']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/RPAREN" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testNotFollowed() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionEmptyForIteratorPadNotFollowed.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(EmptyForIteratorPadCheck.class); - moduleConfig.addAttribute("option", PadOption.SPACE.toString()); - - final String[] expectedViolation = { - "5:33: " + getCheckMessage(EmptyForIteratorPadCheck.class, - EmptyForIteratorPadCheck.MSG_WS_NOT_FOLLOWED, ";"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionEmptyForIteratorPadNotFollowed']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/FOR_ITERATOR", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionEmptyForIteratorPadNotFollowed']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/RPAREN" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionExplicitInitializationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionExplicitInitializationTest.java deleted file mode 100644 index 54b1cdc79f3b..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionExplicitInitializationTest.java +++ /dev/null @@ -1,83 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.ExplicitInitializationCheck; - -public class XpathRegressionExplicitInitializationTest extends AbstractXpathTestSupport { - - private final String checkName = ExplicitInitializationCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionExplicitInitializationOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(ExplicitInitializationCheck.class); - - final String[] expectedViolation = { - "4:17: " + getCheckMessage(ExplicitInitializationCheck.class, - ExplicitInitializationCheck.MSG_KEY, "a", 0), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionExplicitInitializationOne']]" - + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='a']" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionExplicitInitializationTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(ExplicitInitializationCheck.class); - - final String[] expectedViolation = { - "6:20: " + getCheckMessage(ExplicitInitializationCheck.class, - ExplicitInitializationCheck.MSG_KEY, "bar", "null"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionExplicitInitializationTwo']]" - + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='bar']" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionFallThroughTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionFallThroughTest.java deleted file mode 100644 index 4c618d1577ab..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionFallThroughTest.java +++ /dev/null @@ -1,93 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.FallThroughCheck; - -public class XpathRegressionFallThroughTest extends AbstractXpathTestSupport { - - private final String checkName = FallThroughCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionFallThroughOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(FallThroughCheck.class); - - final String[] expectedViolation = { - "11:13: " + getCheckMessage(FallThroughCheck.class, - FallThroughCheck.MSG_FALL_THROUGH), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionFallThroughOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP[" - + "./LITERAL_CASE/EXPR/NUM_INT[@text='2']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionFallThroughOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP/LITERAL_CASE" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionFallThroughTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(FallThroughCheck.class); - moduleConfig.addAttribute("checkLastCaseGroup", "true"); - - final String[] expectedViolation = { - "10:17: " + getCheckMessage(FallThroughCheck.class, - FallThroughCheck.MSG_FALL_THROUGH_LAST), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionFallThroughTwo']]/OBJBLOCK" - + "/METHOD_DEF[" - + "./IDENT[@text='methodFallThruCustomWords']]/SLIST/LITERAL_WHILE/SLIST" - + "/LITERAL_SWITCH/CASE_GROUP[./SLIST/EXPR/POST_INC/IDENT[@text='i']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionFallThroughTwo']]/OBJBLOCK" - + "/METHOD_DEF[" - + "./IDENT[@text='methodFallThruCustomWords']]/SLIST/LITERAL_WHILE/SLIST" - + "/LITERAL_SWITCH/CASE_GROUP/LITERAL_DEFAULT" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionFinalParametersTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionFinalParametersTest.java new file mode 100644 index 000000000000..b5865a15c4eb --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionFinalParametersTest.java @@ -0,0 +1,190 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter; + +import java.io.File; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.FinalParametersCheck; + +public class XpathRegressionFinalParametersTest extends AbstractXpathTestSupport { + + private final String checkName = FinalParametersCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathFinalParametersMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(FinalParametersCheck.class); + + final String[] expectedViolation = { + "5:24: " + getCheckMessage(FinalParametersCheck.class, + FinalParametersCheck.MSG_KEY, "argOne"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/PARAMETERS", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='argOne']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='argOne']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='argOne']]/TYPE", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='argOne']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testCtor() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathFinalParametersCtor.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(FinalParametersCheck.class); + + moduleConfig.addProperty("tokens", "CTOR_DEF"); + + final String[] expectedViolation = { + "5:42: " + getCheckMessage(FinalParametersCheck.class, + FinalParametersCheck.MSG_KEY, "argOne"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathFinalParametersCtor']]" + + "/PARAMETERS", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathFinalParametersCtor']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='argOne']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathFinalParametersCtor']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='argOne']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathFinalParametersCtor']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='argOne']]/TYPE", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathFinalParametersCtor']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='argOne']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAnonymous() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathFinalParametersAnonymous.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(FinalParametersCheck.class); + + moduleConfig.addProperty("ignorePrimitiveTypes", "true"); + + final String[] expectedViolation = { + "11:32: " + getCheckMessage(FinalParametersCheck.class, + FinalParametersCheck.MSG_KEY, "argOne"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersAnonymous']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='createClass']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='obj']]/ASSIGN/EXPR" + + "/LITERAL_NEW[./IDENT[@text='AnonymousClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/PARAMETERS", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersAnonymous']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='createClass']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='obj']]/ASSIGN/EXPR" + + "/LITERAL_NEW[./IDENT[@text='AnonymousClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/PARAMETERS" + + "/PARAMETER_DEF[./IDENT[@text='argOne']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersAnonymous']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='createClass']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='obj']]/ASSIGN/EXPR" + + "/LITERAL_NEW[./IDENT[@text='AnonymousClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/PARAMETERS" + + "/PARAMETER_DEF[./IDENT[@text='argOne']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersAnonymous']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='createClass']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='obj']]/ASSIGN/EXPR" + + "/LITERAL_NEW[./IDENT[@text='AnonymousClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/PARAMETERS" + + "/PARAMETER_DEF[./IDENT[@text='argOne']]/TYPE[./IDENT[@text='String']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalParametersAnonymous']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='createClass']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='obj']]/ASSIGN/EXPR" + + "/LITERAL_NEW[./IDENT[@text='AnonymousClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/PARAMETERS" + + "/PARAMETER_DEF[./IDENT[@text='argOne']]/TYPE/IDENT[@text='String']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionHexLiteralCaseTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionHexLiteralCaseTest.java new file mode 100644 index 000000000000..9760bb0bf080 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionHexLiteralCaseTest.java @@ -0,0 +1,115 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.HexLiteralCaseCheck; + +public class XpathRegressionHexLiteralCaseTest extends AbstractXpathTestSupport { + + private final String checkName = HexLiteralCaseCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testHexLiteralCaseCheck() throws Exception { + final File fileProcess = + new File(getPath("InputXpathHexLiteralCase.java")); + final DefaultConfiguration config = + createModuleConfig(HexLiteralCaseCheck.class); + + final String[] expected = { + "4:14: " + getCheckMessage(HexLiteralCaseCheck.class, + HexLiteralCaseCheck.MSG_KEY), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathHexLiteralCase']]" + + "/OBJBLOCK/VARIABLE_DEF" + + "[./IDENT[@text='i']]/ASSIGN/EXPR[./NUM_INT[@text='0xa']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathHexLiteralCase']]" + + "/OBJBLOCK/VARIABLE_DEF" + + "[./IDENT[@text='i']]/ASSIGN/EXPR/NUM_INT[@text='0xa']" + ); + runVerifications(config, fileProcess, expected, expectedXpathQueries); + } + + @Test + public void testLongHexLiteralCaseCheck() throws Exception { + final File fileProcess = + new File(getPath("InputXpathHexLiteralCaseLong.java")); + final DefaultConfiguration config = + createModuleConfig(HexLiteralCaseCheck.class); + + final String[] expected = { + "4:15: " + getCheckMessage(HexLiteralCaseCheck.class, + HexLiteralCaseCheck.MSG_KEY), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathHexLiteralCaseLong']]" + + "/OBJBLOCK/VARIABLE_DEF" + + "[./IDENT[@text='i']]/ASSIGN/EXPR[./NUM_LONG[@text='0x00efL']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathHexLiteralCaseLong']]" + + "/OBJBLOCK/VARIABLE_DEF" + + "[./IDENT[@text='i']]/ASSIGN/EXPR/NUM_LONG[@text='0x00efL']" + ); + runVerifications(config, fileProcess, expected, expectedXpathQueries); + } + + @Test + public void testHexLiteralCaseCheckTwo() throws Exception { + final File fileProcess = + new File(getPath("InputXpathHexLiteralCaseTwo.java")); + final DefaultConfiguration config = + createModuleConfig(HexLiteralCaseCheck.class); + + final String[] expected = { + "4:14: " + getCheckMessage(HexLiteralCaseCheck.class, + HexLiteralCaseCheck.MSG_KEY), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathHexLiteralCaseTwo']]" + + "/OBJBLOCK/VARIABLE_DEF" + + "[./IDENT[@text='a']]/ASSIGN/EXPR[./NUM_INT[@text='0xFa1']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathHexLiteralCaseTwo']]" + + "/OBJBLOCK/VARIABLE_DEF" + + "[./IDENT[@text='a']]/ASSIGN/EXPR/NUM_INT[@text='0xFa1']" + ); + runVerifications(config, fileProcess, expected, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionHiddenFieldTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionHiddenFieldTest.java deleted file mode 100644 index 6b1010c00ebc..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionHiddenFieldTest.java +++ /dev/null @@ -1,85 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.HiddenFieldCheck; - -public class XpathRegressionHiddenFieldTest extends AbstractXpathTestSupport { - - private final String checkName = HiddenFieldCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionHiddenFieldOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(HiddenFieldCheck.class); - - final String[] expectedViolation = { - "10:34: " + getCheckMessage(HiddenFieldCheck.class, - HiddenFieldCheck.MSG_KEY, "value"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionHiddenFieldOne']]/OBJBLOCK" - + "/INSTANCE_INIT/SLIST/EXPR/METHOD_CALL/ELIST/LAMBDA/PARAMETERS" - + "/PARAMETER_DEF/IDENT[@text='value']" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionHiddenFieldTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(HiddenFieldCheck.class); - - final String[] expectedViolation = { - "8:45: " + getCheckMessage(HiddenFieldCheck.class, - HiddenFieldCheck.MSG_KEY, "other"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionHiddenFieldTwo']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='method']]/PARAMETERS/PARAMETER_DEF" - + "/IDENT[@text='other']" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionIllegalThrowsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionIllegalThrowsTest.java deleted file mode 100644 index 91e38728bdd1..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionIllegalThrowsTest.java +++ /dev/null @@ -1,85 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.IllegalThrowsCheck; - -public class XpathRegressionIllegalThrowsTest extends AbstractXpathTestSupport { - - private final String checkName = IllegalThrowsCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionIllegalThrowsOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(IllegalThrowsCheck.class); - - final String[] expectedViolation = { - "4:35: " + getCheckMessage(IllegalThrowsCheck.class, - IllegalThrowsCheck.MSG_KEY, "RuntimeException"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionIllegalThrowsOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='sayHello']]/LITERAL_THROWS" - + "/IDENT[@text='RuntimeException']" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionIllegalThrowsTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(IllegalThrowsCheck.class); - - final String[] expectedViolation = { - "8:45: " + getCheckMessage(IllegalThrowsCheck.class, - IllegalThrowsCheck.MSG_KEY, "java.lang.Error"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionIllegalThrowsTwo']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='methodTwo']]/LITERAL_THROWS" - + "/DOT[./IDENT[@text='Error']]" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionImportControlTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionImportControlTest.java deleted file mode 100644 index b6e0cc8c1098..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionImportControlTest.java +++ /dev/null @@ -1,129 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.imports.ImportControlCheck; - -public class XpathRegressionImportControlTest extends AbstractXpathTestSupport { - - private final String checkName = ImportControlCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionImportControlOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(ImportControlCheck.class); - moduleConfig.addAttribute("file", getPath( - "SuppressionXpathRegressionImportControlOne.xml")); - - final String[] expectedViolation = { - "3:1: " + getCheckMessage(ImportControlCheck.class, - ImportControlCheck.MSG_DISALLOWED, "java.util.Scanner"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/IMPORT" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionImportControlTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(ImportControlCheck.class); - moduleConfig.addAttribute("file", getPath( - "SuppressionXpathRegressionImportControlTwo.xml")); - - final String[] expectedViolation = { - "1:1: " + getCheckMessage(ImportControlCheck.class, - ImportControlCheck.MSG_UNKNOWN_PKG), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/PACKAGE_DEF" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testThree() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionImportControlThree.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(ImportControlCheck.class); - - final String[] expectedViolation = { - "1:1: " + getCheckMessage(ImportControlCheck.class, - ImportControlCheck.MSG_MISSING_FILE), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/PACKAGE_DEF" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testFour() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionImportControlFour.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(ImportControlCheck.class); - moduleConfig.addAttribute("file", - getPath("SuppressionXpathRegressionImportControlFour.xml")); - - final String[] expectedViolation = { - "4:1: " + getCheckMessage(ImportControlCheck.class, - ImportControlCheck.MSG_DISALLOWED, "java.util.Scanner"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/IMPORT[./DOT/IDENT[@text='Scanner']]" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionJavadocVariableTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionJavadocVariableTest.java deleted file mode 100644 index 3ce57054318a..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionJavadocVariableTest.java +++ /dev/null @@ -1,95 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheck; - -public class XpathRegressionJavadocVariableTest extends AbstractXpathTestSupport { - - private final String checkName = JavadocVariableCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionJavadocVariableOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(JavadocVariableCheck.class); - - final String[] expectedViolation = { - "5:5: " + getCheckMessage(JavadocVariableCheck.class, - JavadocVariableCheck.MSG_JAVADOC_MISSING), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionJavadocVariableOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='age']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionJavadocVariableOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='age']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionJavadocVariableOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='age']]/MODIFIERS/LITERAL_PRIVATE" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionJavadocVariableTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(JavadocVariableCheck.class); - - final String[] expectedViolation = { - "6:9: " + getCheckMessage(JavadocVariableCheck.class, - JavadocVariableCheck.MSG_JAVADOC_MISSING), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionJavadocVariableTwo']]/OBJBLOCK" - + "/CLASS_DEF[./IDENT[@text='InnerInner2']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='fData']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionJavadocVariableTwo']]/OBJBLOCK" - + "/CLASS_DEF[./IDENT[@text='InnerInner2']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='fData']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionJavadocVariableTwo']]/OBJBLOCK" - + "/CLASS_DEF[./IDENT[@text='InnerInner2']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='fData']]/MODIFIERS" - + "/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionLeftCurlyTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionLeftCurlyTest.java deleted file mode 100644 index 51c06eed3a50..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionLeftCurlyTest.java +++ /dev/null @@ -1,108 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.blocks.LeftCurlyCheck; -import com.puppycrawl.tools.checkstyle.checks.blocks.LeftCurlyOption; - -public class XpathRegressionLeftCurlyTest extends AbstractXpathTestSupport { - - private final String checkName = LeftCurlyCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionLeftCurlyOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(LeftCurlyCheck.class); - - final String[] expectedViolation = { - "4:1: " + getCheckMessage(LeftCurlyCheck.class, - LeftCurlyCheck.MSG_KEY_LINE_PREVIOUS, "{", 1), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionLeftCurlyOne']]/OBJBLOCK", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionLeftCurlyOne']]/OBJBLOCK/LCURLY" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionLeftCurlyTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(LeftCurlyCheck.class); - moduleConfig.addAttribute("option", LeftCurlyOption.NL.toString()); - - final String[] expectedViolation = { - "3:53: " + getCheckMessage(LeftCurlyCheck.class, - LeftCurlyCheck.MSG_KEY_LINE_NEW, "{", 53), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionLeftCurlyTwo']]/OBJBLOCK", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionLeftCurlyTwo']]/OBJBLOCK/LCURLY" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testThree() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionLeftCurlyThree.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(LeftCurlyCheck.class); - - final String[] expectedViolation = { - "5:19: " + getCheckMessage(LeftCurlyCheck.class, - LeftCurlyCheck.MSG_KEY_LINE_BREAK_AFTER, "{", 19), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionLeftCurlyThree']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='sample']]/SLIST/LITERAL_IF/SLIST" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionMultipleVariableDeclarationsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionMultipleVariableDeclarationsTest.java deleted file mode 100644 index bf4b08098f82..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionMultipleVariableDeclarationsTest.java +++ /dev/null @@ -1,115 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.MultipleVariableDeclarationsCheck; - -public class XpathRegressionMultipleVariableDeclarationsTest extends AbstractXpathTestSupport { - - private final String checkName = MultipleVariableDeclarationsCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionMultipleVariableDeclarationsOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(MultipleVariableDeclarationsCheck.class); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(MultipleVariableDeclarationsCheck.class, - MultipleVariableDeclarationsCheck.MSG_MULTIPLE_COMMA), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='i']]", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='i']]/MODIFIERS", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='i']]/TYPE", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='i']]/TYPE/LITERAL_INT", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='j']]", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='j']]/MODIFIERS", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='j']]/TYPE", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='j']]/TYPE/LITERAL_INT" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionMultipleVariableDeclarationsTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(MultipleVariableDeclarationsCheck.class); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(MultipleVariableDeclarationsCheck.class, - MultipleVariableDeclarationsCheck.MSG_MULTIPLE), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsTwo']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='i1']]", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsTwo']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='i1']]/MODIFIERS", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsTwo']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='i1']]/TYPE", - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionMultipleVariableDeclarationsTwo']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='i1']]/TYPE/LITERAL_INT" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNPathComplexityTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNPathComplexityTest.java deleted file mode 100644 index 75175781e7d8..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNPathComplexityTest.java +++ /dev/null @@ -1,91 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.metrics.NPathComplexityCheck; - -// -@cs[AbbreviationAsWordInName] Test should be named as its main class. -public class XpathRegressionNPathComplexityTest extends AbstractXpathTestSupport { - - private final String checkName = NPathComplexityCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNPathComplexityOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(NPathComplexityCheck.class); - moduleConfig.addAttribute("max", "0"); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(NPathComplexityCheck.class, - NPathComplexityCheck.MSG_KEY, 3, 0), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNPathComplexityOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNPathComplexityOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNPathComplexityOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS/LITERAL_PUBLIC" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNPathComplexityTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(NPathComplexityCheck.class); - moduleConfig.addAttribute("max", "0"); - - final String[] expectedViolation = { - "4:5: " + getCheckMessage(NPathComplexityCheck.class, - NPathComplexityCheck.MSG_KEY, 3, 0), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNPathComplexityTwo']]" - + "/OBJBLOCK/STATIC_INIT" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedForDepthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedForDepthTest.java deleted file mode 100644 index 197ac47b3307..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedForDepthTest.java +++ /dev/null @@ -1,62 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck; - -public class XpathRegressionNestedForDepthTest extends AbstractXpathTestSupport { - - private final String checkName = NestedForDepthCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testCorrect() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNestedForDepth.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(NestedForDepthCheck.class); - - final String[] expectedViolation = { - "7:17: " + getCheckMessage(NestedForDepthCheck.class, - NestedForDepthCheck.MSG_KEY, 2, 1), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNestedForDepth']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_FOR" - + "/SLIST/LITERAL_FOR/SLIST/LITERAL_FOR" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedIfDepthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedIfDepthTest.java deleted file mode 100644 index 1af99bc63c1d..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedIfDepthTest.java +++ /dev/null @@ -1,62 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.NestedIfDepthCheck; - -public class XpathRegressionNestedIfDepthTest extends AbstractXpathTestSupport { - - private final String checkName = NestedIfDepthCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testCorrect() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNestedIfDepth.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(NestedIfDepthCheck.class); - - final String[] expectedViolation = { - "10:17: " + getCheckMessage(NestedIfDepthCheck.class, - NestedIfDepthCheck.MSG_KEY, 2, 1), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNestedIfDepth']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF" - + "/SLIST/LITERAL_IF/SLIST/LITERAL_IF" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedTryDepthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedTryDepthTest.java deleted file mode 100644 index c47a9e3500c4..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNestedTryDepthTest.java +++ /dev/null @@ -1,62 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.NestedTryDepthCheck; - -public class XpathRegressionNestedTryDepthTest extends AbstractXpathTestSupport { - - private final String checkName = NestedTryDepthCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testCorrect() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNestedTryDepth.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(NestedTryDepthCheck.class); - - final String[] expectedViolation = { - "7:17: " + getCheckMessage(NestedTryDepthCheck.class, - NestedTryDepthCheck.MSG_KEY, 2, 1), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNestedTryDepth']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY/SLIST" - + "/LITERAL_TRY/SLIST/LITERAL_TRY" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoWhitespaceAfterTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoWhitespaceAfterTest.java deleted file mode 100644 index 1d3038b788c4..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoWhitespaceAfterTest.java +++ /dev/null @@ -1,65 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceAfterCheck; - -public class XpathRegressionNoWhitespaceAfterTest extends AbstractXpathTestSupport { - - private final String checkName = NoWhitespaceAfterCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testNoWhitespaceAfter() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNoWhitespaceAfter.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(NoWhitespaceAfterCheck.class); - - final String[] expectedViolation = { - "4:15: " + getCheckMessage(NoWhitespaceAfterCheck.class, - NoWhitespaceAfterCheck.MSG_KEY, "-"), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNoWhitespaceAfter']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNoWhitespaceAfter']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/UNARY_MINUS[" - + "./NUM_INT[@text='1']]" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoWhitespaceBeforeTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoWhitespaceBeforeTest.java deleted file mode 100644 index 2561adc96e2d..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoWhitespaceBeforeTest.java +++ /dev/null @@ -1,62 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceBeforeCheck; - -public class XpathRegressionNoWhitespaceBeforeTest extends AbstractXpathTestSupport { - - private final String checkName = NoWhitespaceBeforeCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testNoWhitespaceBefore() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNoWhitespaceBefore.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(NoWhitespaceBeforeCheck.class); - - final String[] expectedViolation = { - "4:13: " + getCheckMessage(NoWhitespaceBeforeCheck.class, - NoWhitespaceBeforeCheck.MSG_KEY, ";"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNoWhitespaceBefore']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='bad']]/SEMI" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOneStatementPerLineTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOneStatementPerLineTest.java deleted file mode 100644 index aab81e466555..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOneStatementPerLineTest.java +++ /dev/null @@ -1,83 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.OneStatementPerLineCheck; - -public class XpathRegressionOneStatementPerLineTest extends AbstractXpathTestSupport { - - private final String checkName = OneStatementPerLineCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionOneStatementPerLineOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(OneStatementPerLineCheck.class); - - final String[] expectedViolation = { - "4:17: " + getCheckMessage(OneStatementPerLineCheck.class, - OneStatementPerLineCheck.MSG_KEY), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionOneStatementPerLineOne']]/OBJBLOCK" - + "/VARIABLE_DEF[./IDENT[@text='j']]/SEMI" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionOneStatementPerLineTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(OneStatementPerLineCheck.class); - - final String[] expectedViolation = { - "9:39: " + getCheckMessage(OneStatementPerLineCheck.class, - OneStatementPerLineCheck.MSG_KEY), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionOneStatementPerLineTwo']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='foo5']]/SLIST/LITERAL_FOR/SLIST/SEMI[2]" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOuterTypeFilenameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOuterTypeFilenameTest.java new file mode 100644 index 000000000000..7dc15590a0be --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOuterTypeFilenameTest.java @@ -0,0 +1,86 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.OuterTypeFilenameCheck; + +public class XpathRegressionOuterTypeFilenameTest extends AbstractXpathTestSupport { + + private final String checkName = OuterTypeFilenameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testNoPublic() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathOuterTypeFilenameOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OuterTypeFilenameCheck.class); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(OuterTypeFilenameCheck.class, + OuterTypeFilenameCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='Class1']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='Class1']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='Class1']]/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNested() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathOuterTypeFilenameTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OuterTypeFilenameCheck.class); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(OuterTypeFilenameCheck.class, + OuterTypeFilenameCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='Test']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='Test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='Test']]/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOuterTypeNumberTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOuterTypeNumberTest.java deleted file mode 100644 index fc8cf0c2158e..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionOuterTypeNumberTest.java +++ /dev/null @@ -1,61 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.sizes.OuterTypeNumberCheck; - -public class XpathRegressionOuterTypeNumberTest extends AbstractXpathTestSupport { - - private final String checkName = OuterTypeNumberCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionOuterTypeNumber.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(OuterTypeNumberCheck.class); - moduleConfig.addAttribute("max", "0"); - - final String[] expectedViolation = { - "1:1: " + getCheckMessage(OuterTypeNumberCheck.class, - OuterTypeNumberCheck.MSG_KEY, 3, 0), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/PACKAGE_DEF" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRequireThisTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRequireThisTest.java deleted file mode 100644 index fec08aa57076..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRequireThisTest.java +++ /dev/null @@ -1,87 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck; - -public class XpathRegressionRequireThisTest extends AbstractXpathTestSupport { - - private final String checkName = RequireThisCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionRequireThisOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(RequireThisCheck.class); - moduleConfig.addAttribute("validateOnlyOverlapping", "false"); - - final String[] expectedViolation = { - "7:9: " + getCheckMessage(RequireThisCheck.class, - RequireThisCheck.MSG_VARIABLE, "age", ""), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionRequireThisOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='changeAge']]/SLIST/EXPR/ASSIGN" - + "/IDENT[@text='age']" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionRequireThisTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(RequireThisCheck.class); - moduleConfig.addAttribute("validateOnlyOverlapping", "false"); - - final String[] expectedViolation = { - "9:9: " + getCheckMessage(RequireThisCheck.class, - RequireThisCheck.MSG_METHOD, "method1", ""), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionRequireThisTwo']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='method2']]/SLIST/EXPR" - + "/METHOD_CALL/IDENT[@text='method1']" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRightCurlyTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRightCurlyTest.java deleted file mode 100644 index 0116356b8b6e..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRightCurlyTest.java +++ /dev/null @@ -1,131 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck; -import com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyOption; - -public class XpathRegressionRightCurlyTest extends AbstractXpathTestSupport { - - private final String checkName = RightCurlyCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionRightCurlyOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(RightCurlyCheck.class); - - final String[] expectedViolation = { - "8:9: " + getCheckMessage(RightCurlyCheck.class, - RightCurlyCheck.MSG_KEY_LINE_SAME, "}", 9), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionRightCurlyOne']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF/SLIST/RCURLY" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionRightCurlyTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(RightCurlyCheck.class); - moduleConfig.addAttribute("option", RightCurlyOption.ALONE.toString()); - - final String[] expectedViolation = { - "9:15: " + getCheckMessage(RightCurlyCheck.class, - RightCurlyCheck.MSG_KEY_LINE_ALONE, "}", 15), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionRightCurlyTwo']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='fooMethod']]/SLIST/LITERAL_TRY/SLIST/RCURLY" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testThree() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionRightCurlyThree.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(RightCurlyCheck.class); - moduleConfig.addAttribute("option", RightCurlyOption.ALONE.toString()); - - final String[] expectedViolation = { - "5:72: " + getCheckMessage(RightCurlyCheck.class, - RightCurlyCheck.MSG_KEY_LINE_ALONE, "}", 72), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionRightCurlyThree']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='sample']]/SLIST/LITERAL_IF/SLIST/RCURLY" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testFour() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionRightCurlyFour.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(RightCurlyCheck.class); - moduleConfig.addAttribute("option", RightCurlyOption.SAME.toString()); - - final String[] expectedViolation = { - "7:27: " + getCheckMessage(RightCurlyCheck.class, - RightCurlyCheck.MSG_KEY_LINE_BREAK_BEFORE, "}", 27), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionRightCurlyFour']]/OBJBLOCK" - + "/METHOD_DEF[./IDENT[@text='sample']]/SLIST/LITERAL_IF/SLIST/RCURLY" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionSingleSpaceSeparatorTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionSingleSpaceSeparatorTest.java deleted file mode 100644 index ed22be91123a..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionSingleSpaceSeparatorTest.java +++ /dev/null @@ -1,62 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.SingleSpaceSeparatorCheck; - -public class XpathRegressionSingleSpaceSeparatorTest extends AbstractXpathTestSupport { - - private final String checkName = SingleSpaceSeparatorCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testSingleSpaceSeparator() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionSingleSpaceSeparator.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(SingleSpaceSeparatorCheck.class); - - final String[] expectedViolation = { - "4:11: " + getCheckMessage(SingleSpaceSeparatorCheck.class, - SingleSpaceSeparatorCheck.MSG_KEY), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionSingleSpaceSeparator']]/OBJBLOCK" - + "/VARIABLE_DEF/IDENT[@text='bad']" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTodoCommentTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTodoCommentTest.java new file mode 100644 index 000000000000..af5976a9c4b0 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTodoCommentTest.java @@ -0,0 +1,86 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter; + +import static com.puppycrawl.tools.checkstyle.checks.TodoCommentCheck.MSG_KEY; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.TodoCommentCheck; + +public class XpathRegressionTodoCommentTest extends AbstractXpathTestSupport { + private final String checkName = TodoCommentCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testSingleLine() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathTodoCommentSingleLine.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(TodoCommentCheck.class); + moduleConfig.addProperty("format", "FIXME:"); + + final String[] expectedViolation = { + "4:7: " + getCheckMessage(TodoCommentCheck.class, MSG_KEY, "FIXME:"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathTodoCommentSingleLine']]/OBJBLOCK/" + + "SINGLE_LINE_COMMENT/COMMENT_CONTENT[@text=' warn FIXME:\\n']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testBlock() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathTodoCommentBlock.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(TodoCommentCheck.class); + moduleConfig.addProperty("format", "FIXME:"); + + final String[] expectedViolation = { + "4:7: " + getCheckMessage(TodoCommentCheck.class, MSG_KEY, "FIXME:"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathTodoCommentBlock']]/" + + "OBJBLOCK/BLOCK_COMMENT_BEGIN/COMMENT_CONTENT" + + "[@text=' // warn\\n * FIXME:\\n * TODO\\n ']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTrailingCommentTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTrailingCommentTest.java new file mode 100644 index 000000000000..5abb38ff4251 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTrailingCommentTest.java @@ -0,0 +1,85 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.TrailingCommentCheck; + +public class XpathRegressionTrailingCommentTest extends AbstractXpathTestSupport { + private final String checkName = TrailingCommentCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testSingleLine() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathTrailingCommentSingleLine.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(TrailingCommentCheck.class); + + final String[] expectedViolation = { + "4:12: " + getCheckMessage(TrailingCommentCheck.class, + TrailingCommentCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathTrailingCommentSingleLine']]/" + + "OBJBLOCK/SINGLE_LINE_COMMENT[./COMMENT_CONTENT[@text=' don'" + + "'t use trailing comments :) // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testBlock() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathTrailingCommentBlock.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(TrailingCommentCheck.class); + + final String[] expectedViolation = { + "4:40: " + getCheckMessage(TrailingCommentCheck.class, + TrailingCommentCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathTrailingCommentBlock']]" + + "/OBJBLOCK/SINGLE_LINE_COMMENT[./COMMENT_CONTENT[@text=' warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTypecastParenPadTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTypecastParenPadTest.java deleted file mode 100644 index 0aa97be1e761..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionTypecastParenPadTest.java +++ /dev/null @@ -1,138 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.whitespace.AbstractParenPadCheck; -import com.puppycrawl.tools.checkstyle.checks.whitespace.PadOption; -import com.puppycrawl.tools.checkstyle.checks.whitespace.TypecastParenPadCheck; - -public class XpathRegressionTypecastParenPadTest extends AbstractXpathTestSupport { - - private final String checkName = TypecastParenPadCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testLeftFollowed() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionTypecastParenPadLeftFollowed.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(TypecastParenPadCheck.class); - - final String[] expectedViolation = { - "4:18: " + getCheckMessage(TypecastParenPadCheck.class, - AbstractParenPadCheck.MSG_WS_FOLLOWED, "("), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionTypecastParenPadLeftFollowed']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionTypecastParenPadLeftFollowed']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testLeftNotFollowed() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionTypecastParenPadLeftNotFollowed.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(TypecastParenPadCheck.class); - moduleConfig.addAttribute("option", PadOption.SPACE.toString()); - - final String[] expectedViolation = { - "4:18: " + getCheckMessage(TypecastParenPadCheck.class, - AbstractParenPadCheck.MSG_WS_NOT_FOLLOWED, "("), - }; - - final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionTypecastParenPadLeftNotFollowed']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionTypecastParenPadLeftNotFollowed']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testRightPreceded() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionTypecastParenPadRightPreceded.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(TypecastParenPadCheck.class); - - final String[] expectedViolation = { - "4:26: " + getCheckMessage(TypecastParenPadCheck.class, - AbstractParenPadCheck.MSG_WS_PRECEDED, ")"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionTypecastParenPadRightPreceded']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST/RPAREN" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testRightNotPreceded() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionTypecastParenPadRightNotPreceded.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(TypecastParenPadCheck.class); - moduleConfig.addAttribute("option", PadOption.SPACE.toString()); - - final String[] expectedViolation = { - "4:26: " + getCheckMessage(TypecastParenPadCheck.class, - AbstractParenPadCheck.MSG_WS_NOT_PRECEDED, ")"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionTypecastParenPadRightNotPreceded']]" - + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST/RPAREN" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUncommentedMainTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUncommentedMainTest.java new file mode 100644 index 000000000000..ff4ef62e1258 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUncommentedMainTest.java @@ -0,0 +1,101 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.UncommentedMainCheck; + +public class XpathRegressionUncommentedMainTest extends AbstractXpathTestSupport { + + private static final Class CLAZZ = + UncommentedMainCheck.class; + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathUncommentedMainDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UncommentedMainCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(UncommentedMainCheck.class, + UncommentedMainCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUncommentedMainDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='main']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUncommentedMainDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='main']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUncommentedMainDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='main']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInStaticClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathUncommentedMainInStaticClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UncommentedMainCheck.class); + + final String[] expectedViolation = { + "5:9: " + getCheckMessage(UncommentedMainCheck.class, + UncommentedMainCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUncommentedMainInStaticClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Launcher']" + + "]/OBJBLOCK/METHOD_DEF[./IDENT[@text='main']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUncommentedMainInStaticClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Launcher']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='main']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUncommentedMainInStaticClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Launcher']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='main']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonAfterTypeMemberDeclarationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonAfterTypeMemberDeclarationTest.java deleted file mode 100644 index 69efc256a39f..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonAfterTypeMemberDeclarationTest.java +++ /dev/null @@ -1,59 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonAfterTypeMemberDeclarationCheck; - -public class XpathRegressionUnnecessarySemicolonAfterTypeMemberDeclarationTest - extends AbstractXpathTestSupport { - - private static final Class CLASS = - UnnecessarySemicolonAfterTypeMemberDeclarationCheck.class; - - @Override - protected String getCheckName() { - return CLASS.getSimpleName(); - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionUnnecessarySemicolonAfterTypeMemberDeclaration.java")); - final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); - final String[] expectedViolation = { - "4:20: " + getCheckMessage(CLASS, - UnnecessarySemicolonAfterTypeMemberDeclarationCheck.MSG_SEMI), - }; - - final List expectedXpathQueries = Collections.singletonList("/CLASS_DEF[./IDENT" - + "[@text='SuppressionXpathRegressionUnnecessarySemicolonAfterTypeMemberDeclaration']]" - + "/OBJBLOCK/SEMI" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonInEnumerationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonInEnumerationTest.java deleted file mode 100644 index ed43e64b6c27..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonInEnumerationTest.java +++ /dev/null @@ -1,61 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInEnumerationCheck; - -public class XpathRegressionUnnecessarySemicolonInEnumerationTest - extends AbstractXpathTestSupport { - - private final String checkName = - UnnecessarySemicolonInEnumerationCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionUnnecessarySemicolonInEnumeration.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(UnnecessarySemicolonInEnumerationCheck.class); - - final String[] expectedViolation = { - "11:10: " + getCheckMessage(UnnecessarySemicolonInEnumerationCheck.class, - UnnecessarySemicolonInEnumerationCheck.MSG_SEMI), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/ENUM_DEF[./IDENT[@text='Bad']]/OBJBLOCK/SEMI" - ); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonInTryWithResourcesTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonInTryWithResourcesTest.java deleted file mode 100644 index e7285561c9b7..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnnecessarySemicolonInTryWithResourcesTest.java +++ /dev/null @@ -1,62 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInTryWithResourcesCheck; - -public class XpathRegressionUnnecessarySemicolonInTryWithResourcesTest - extends AbstractXpathTestSupport { - - private final String checkName = - UnnecessarySemicolonInTryWithResourcesCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = new File( - getPath("SuppressionXpathRegressionUnnecessarySemicolonInTryWithResources.java")); - final DefaultConfiguration moduleConfig = - createModuleConfig(UnnecessarySemicolonInTryWithResourcesCheck.class); - final String[] expectedViolation = { - "11:43: " + getCheckMessage(UnnecessarySemicolonInTryWithResourcesCheck.class, - UnnecessarySemicolonInTryWithResourcesCheck.MSG_SEMI), - "12:76: " + getCheckMessage(UnnecessarySemicolonInTryWithResourcesCheck.class, - UnnecessarySemicolonInTryWithResourcesCheck.MSG_SEMI), - }; - final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text=" - + "'SuppressionXpathRegressionUnnecessarySemicolonInTryWithResources']]" - + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='m']]/SLIST/LITERAL_TRY" - + "/RESOURCE_SPECIFICATION/SEMI" - ); - runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); - } -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnusedImportsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnusedImportsTest.java deleted file mode 100644 index 868cfb9d17c7..000000000000 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUnusedImportsTest.java +++ /dev/null @@ -1,81 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package org.checkstyle.suppressionxpathfilter; - -import java.io.File; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Test; - -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck; - -public class XpathRegressionUnusedImportsTest extends AbstractXpathTestSupport { - - private final String checkName = UnusedImportsCheck.class.getSimpleName(); - - @Override - protected String getCheckName() { - return checkName; - } - - @Test - public void testOne() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionUnusedImportsOne.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(UnusedImportsCheck.class); - - final String[] expectedViolation = { - "3:8: " + getCheckMessage(UnusedImportsCheck.class, - UnusedImportsCheck.MSG_KEY, "java.util.List"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/IMPORT/DOT[./IDENT[@text='List']]/DOT/IDENT[@text='java']"); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - - @Test - public void testTwo() throws Exception { - final File fileToProcess = - new File(getPath("SuppressionXpathRegressionUnusedImportsTwo.java")); - - final DefaultConfiguration moduleConfig = - createModuleConfig(UnusedImportsCheck.class); - - final String[] expectedViolation = { - "3:15: " + getCheckMessage(UnusedImportsCheck.class, - UnusedImportsCheck.MSG_KEY, "java.util.Map.Entry"), - }; - - final List expectedXpathQueries = Collections.singletonList( - "/STATIC_IMPORT/DOT[./IDENT[@text='Entry']]/DOT[./IDENT[@text='Map']]" - + "/DOT/IDENT[@text='java']"); - - runVerifications(moduleConfig, fileToProcess, expectedViolation, - expectedXpathQueries); - } - -} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUpperEllTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUpperEllTest.java index 54c42d8655d2..cdf630ea53da 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUpperEllTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionUpperEllTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,7 +15,7 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// package org.checkstyle.suppressionxpathfilter; @@ -38,9 +38,9 @@ protected String getCheckName() { } @Test - public void testUpperEll() throws Exception { + public void testUpperEllOne() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionUpperEll.java")); + new File(getPath("InputXpathUpperEllOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(UpperEllCheck.class); @@ -51,9 +51,11 @@ public void testUpperEll() throws Exception { }; final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionUpperEll']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUpperEllOne']]/OBJBLOCK" + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR[./NUM_LONG[@text='0l']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionUpperEll']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUpperEllOne']]/OBJBLOCK" + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR" + "/NUM_LONG[@text='0l']" ); @@ -62,4 +64,31 @@ public void testUpperEll() throws Exception { expectedXpathQueries); } + @Test + public void testUpperEllTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathUpperEllTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UpperEllCheck.class); + + final String[] expectedViolation = { + "6:21: " + getCheckMessage(UpperEllCheck.class, + UpperEllCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathUpperEllTwo']]/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT[@text='var2']]/ASSIGN/EXPR" + + "[./NUM_LONG[@text='508987l']]", + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathUpperEllTwo']]/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT[@text='var2']]/ASSIGN/EXPR" + + "/NUM_LONG[@text='508987l']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } } diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationLocationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationLocationTest.java new file mode 100644 index 000000000000..987e20233c93 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationLocationTest.java @@ -0,0 +1,258 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.annotation; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationLocationCheck; + +public class XpathRegressionAnnotationLocationTest extends AbstractXpathTestSupport { + + private final String checkName = AnnotationLocationCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/annotation/annotationlocation"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testClass() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationLocationClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationLocationCheck.class); + + final String[] expectedViolation = { + "6:1: " + getCheckMessage(AnnotationLocationCheck.class, + AnnotationLocationCheck.MSG_KEY_ANNOTATION_LOCATION_ALONE, "ClassAnnotation"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationClass']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationClass']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationClass']]/" + + "MODIFIERS/ANNOTATION[./IDENT[@text='ClassAnnotation']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationClass']]/" + + "MODIFIERS/ANNOTATION[./IDENT[@text='ClassAnnotation']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInterface() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationLocationInterface.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationLocationCheck.class); + + final String[] expectedViolation = { + "7:1: " + getCheckMessage(AnnotationLocationCheck.class, + AnnotationLocationCheck.MSG_KEY_ANNOTATION_LOCATION_ALONE, + "InterfaceAnnotation"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='" + + "InputXpathAnnotationLocationInterface']]", + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationInterface'" + + "]]/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationInterface']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='InterfaceAnnotation']]", + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationInterface']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='InterfaceAnnotation']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEnum() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationLocationEnum.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationLocationCheck.class); + + final String[] expectedViolation = { + "6:1: " + getCheckMessage(AnnotationLocationCheck.class, + AnnotationLocationCheck.MSG_KEY_ANNOTATION_LOCATION_ALONE, + "EnumAnnotation"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ENUM_DEF[./IDENT[@text='" + + "InputXpathAnnotationLocationEnum']]", + "/COMPILATION_UNIT/ENUM_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationEnum']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/ENUM_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationEnum']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='EnumAnnotation']]", + "/COMPILATION_UNIT/ENUM_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationEnum']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='EnumAnnotation']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationLocationMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationLocationCheck.class); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expectedViolation = { + "4:6: " + getCheckMessage(AnnotationLocationCheck.class, + AnnotationLocationCheck.MSG_KEY_ANNOTATION_LOCATION_ALONE, + "MethodAnnotation"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationMethod']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationMethod']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationMethod']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]/MODIFIERS/" + + "ANNOTATION[./IDENT[@text='MethodAnnotation']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationMethod']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]/MODIFIERS/" + + "ANNOTATION[./IDENT[@text='MethodAnnotation']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testVariable() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationLocationVariable.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationLocationCheck.class); + moduleConfig.addProperty("tokens", "VARIABLE_DEF"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(AnnotationLocationCheck.class, + AnnotationLocationCheck.MSG_KEY_ANNOTATION_LOCATION_ALONE, + "VariableAnnotation"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationVariable']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='b']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationVariable']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='b']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationVariable']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='b']]/MODIFIERS/" + + "ANNOTATION[./IDENT[@text='VariableAnnotation']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationLocationVariable']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='b']]/MODIFIERS/" + + "ANNOTATION[./IDENT[@text='VariableAnnotation']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testConstructor() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationLocationCTOR.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationLocationCheck.class); + moduleConfig.addProperty("tokens", "CTOR_DEF"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(AnnotationLocationCheck.class, + AnnotationLocationCheck.MSG_KEY_ANNOTATION_LOCATION_ALONE, + "CTORAnnotation"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAnnotationLocationCTOR']]/OBJBLOCK/CTOR_DEF" + + "[./IDENT[@text='" + + "InputXpathAnnotationLocationCTOR']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAnnotationLocationCTOR']]/OBJBLOCK/CTOR_DEF" + + "[./IDENT[@text='" + + "InputXpathAnnotationLocationCTOR']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAnnotationLocationCTOR']]/OBJBLOCK/CTOR_DEF" + + "[./IDENT[@text='" + + "InputXpathAnnotationLocationCTOR']]/" + + "MODIFIERS/ANNOTATION[./IDENT[@text='CTORAnnotation']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAnnotationLocationCTOR']]/OBJBLOCK/CTOR_DEF" + + "[./IDENT[@text='" + + "InputXpathAnnotationLocationCTOR']]/" + + "MODIFIERS/ANNOTATION[./IDENT[@text='CTORAnnotation']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationOnSameLineTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationOnSameLineTest.java new file mode 100644 index 000000000000..433240ec5e0b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationOnSameLineTest.java @@ -0,0 +1,160 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.annotation; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationOnSameLineCheck; + +public class XpathRegressionAnnotationOnSameLineTest extends AbstractXpathTestSupport { + + private final String checkName = AnnotationOnSameLineCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/annotation/annotationonsameline"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathAnnotationOnSameLineMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationOnSameLineCheck.class); + + moduleConfig.addProperty("tokens", + "CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, " + + "CTOR_DEF, VARIABLE_DEF, PARAMETER_DEF, ANNOTATION_DEF, TYPECAST, " + + "LITERAL_THROWS, IMPLEMENTS_CLAUSE, TYPE_ARGUMENT, LITERAL_NEW, DOT, " + + "ANNOTATION_FIELD_DEF"); + + final String[] expectedViolation = { + "6:5: " + getCheckMessage(AnnotationOnSameLineCheck.class, + AnnotationOnSameLineCheck.MSG_KEY_ANNOTATION_ON_SAME_LINE, + "Deprecated"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationOnSameLineMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getX']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationOnSameLineMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getX']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationOnSameLineMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getX']]/MODIFIERS" + + "/ANNOTATION[./IDENT[@text='Deprecated']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationOnSameLineMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='getX']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='Deprecated']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathAnnotationOnSameLineField.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationOnSameLineCheck.class); + + final String[] expectedViolation = { + "7:5: " + getCheckMessage(AnnotationOnSameLineCheck.class, + AnnotationOnSameLineCheck.MSG_KEY_ANNOTATION_ON_SAME_LINE, + "Deprecated"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationOnSameLineField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='names']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationOnSameLineField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='names']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationOnSameLineField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='names']]/MODIFIERS" + + "/ANNOTATION[./IDENT[@text='Deprecated']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationOnSameLineField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='names']]/MODIFIERS" + + "/ANNOTATION[./IDENT[@text='Deprecated']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathAnnotationOnSameLineInterface.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationOnSameLineCheck.class); + moduleConfig.addProperty("tokens", "CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, " + + "CTOR_DEF, VARIABLE_DEF, PARAMETER_DEF, ANNOTATION_DEF, TYPECAST, " + + "LITERAL_THROWS, IMPLEMENTS_CLAUSE, TYPE_ARGUMENT, LITERAL_NEW, DOT, " + + "ANNOTATION_FIELD_DEF"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(AnnotationOnSameLineCheck.class, + AnnotationOnSameLineCheck.MSG_KEY_ANNOTATION_ON_SAME_LINE, + "Deprecated"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[" + + "./IDENT[@text='InputXpathAnnotationOnSameLineInterface']]", + "/COMPILATION_UNIT/INTERFACE_DEF[" + + "./IDENT[@text='InputXpathAnnotationOnSameLineInterface']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF[" + + "./IDENT[@text='InputXpathAnnotationOnSameLineInterface']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='Deprecated']]", + "/COMPILATION_UNIT/INTERFACE_DEF[" + + "./IDENT[@text='InputXpathAnnotationOnSameLineInterface']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='Deprecated']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationUseStyleTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationUseStyleTest.java new file mode 100644 index 000000000000..483ef4915e64 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionAnnotationUseStyleTest.java @@ -0,0 +1,300 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.annotation; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.annotation.AnnotationUseStyleCheck; + +public class XpathRegressionAnnotationUseStyleTest extends AbstractXpathTestSupport { + + private final String checkName = AnnotationUseStyleCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/annotation/annotationusestyle"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationUseStyleOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationUseStyleCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(AnnotationUseStyleCheck.class, + AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_INCORRECT_STYLE, + "COMPACT_NO_ARRAY"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleOne']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleOne']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationUseStyleTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationUseStyleCheck.class); + + moduleConfig.addProperty("closingParens", "ALWAYS"); + moduleConfig.addProperty("elementStyle", "ignore"); + moduleConfig.addProperty("trailingArrayComma", "ignore"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(AnnotationUseStyleCheck.class, + AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_PARENS_MISSING), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleTwo']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleTwo']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleTwo']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='Deprecated']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleTwo']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='Deprecated']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationUseStyleThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationUseStyleCheck.class); + + moduleConfig.addProperty("trailingArrayComma", "ignore"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(AnnotationUseStyleCheck.class, + AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_INCORRECT_STYLE, + "COMPACT_NO_ARRAY"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/MODIFIERS" + + "/ANNOTATION[./IDENT[@text='SuppressWarnings']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/MODIFIERS" + + "/ANNOTATION[./IDENT[@text='SuppressWarnings']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationUseStyleFour.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationUseStyleCheck.class); + + moduleConfig.addProperty("closingParens", "ignore"); + moduleConfig.addProperty("elementStyle", "ignore"); + moduleConfig.addProperty("trailingArrayComma", "ALWAYS"); + + final String[] expectedViolation = { + "3:20: " + getCheckMessage(AnnotationUseStyleCheck.class, + AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_TRAILING_COMMA_MISSING), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleFour']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]" + + "/ANNOTATION_ARRAY_INIT/RCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFive() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationUseStyleFive.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationUseStyleCheck.class); + + moduleConfig.addProperty("closingParens", "ignore"); + moduleConfig.addProperty("elementStyle", "COMPACT"); + moduleConfig.addProperty("trailingArrayComma", "ignore"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(AnnotationUseStyleCheck.class, + AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_INCORRECT_STYLE, + "COMPACT"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleFive']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleFive']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleFive']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleFive']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSix() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationUseStyleSix.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationUseStyleCheck.class); + + moduleConfig.addProperty("closingParens", "ignore"); + moduleConfig.addProperty("elementStyle", "EXPANDED"); + moduleConfig.addProperty("trailingArrayComma", "ignore"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(AnnotationUseStyleCheck.class, + AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_INCORRECT_STYLE, + "EXPANDED"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleSix']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleSix']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleSix']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleSix']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSeven() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationUseStyleSeven.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationUseStyleCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(AnnotationUseStyleCheck.class, + AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_INCORRECT_STYLE, + "COMPACT_NO_ARRAY"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleSeven']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleSeven']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEight() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAnnotationUseStyleEight.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnnotationUseStyleCheck.class); + + moduleConfig.addProperty("closingParens", "ignore"); + moduleConfig.addProperty("elementStyle", "ignore"); + moduleConfig.addProperty("trailingArrayComma", "NEVER"); + + final String[] expectedViolation = { + "3:31: " + getCheckMessage(AnnotationUseStyleCheck.class, + AnnotationUseStyleCheck.MSG_KEY_ANNOTATION_TRAILING_COMMA_PRESENT), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnnotationUseStyleEight']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='SuppressWarnings']]" + + "/ANNOTATION_ARRAY_INIT/COMMA" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionMissingOverrideTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionMissingOverrideTest.java new file mode 100644 index 000000000000..98c468cb7483 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionMissingOverrideTest.java @@ -0,0 +1,277 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.annotation; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.annotation.MissingOverrideCheck; + +public class XpathRegressionMissingOverrideTest extends AbstractXpathTestSupport { + + private final String checkName = MissingOverrideCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/annotation/missingoverride"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testClass() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingOverrideClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingOverrideCheck.class); + + final String[] expectedViolation = { + "7:5: " + getCheckMessage(MissingOverrideCheck.class, + MissingOverrideCheck.MSG_KEY_ANNOTATION_MISSING_OVERRIDE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingOverrideClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingOverrideClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingOverrideClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]/MODIFIERS/LITERAL_PUBLIC" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testInterface() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingOverrideInterface.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingOverrideCheck.class); + + final String[] expectedViolation = { + "7:5: " + getCheckMessage(MissingOverrideCheck.class, + MissingOverrideCheck.MSG_KEY_ANNOTATION_MISSING_OVERRIDE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/TYPE", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/TYPE/LITERAL_BOOLEAN" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testAnonymous() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingOverrideAnonymous.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingOverrideCheck.class); + + final String[] expectedViolation = { + "8:9: " + getCheckMessage(MissingOverrideCheck.class, + MissingOverrideCheck.MSG_KEY_ANNOTATION_MISSING_OVERRIDE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideAnonymous']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='r']]/ASSIGN/EXPR/" + + "LITERAL_NEW[./IDENT[@text='Runnable']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='run']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingOverrideAnonymous']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='r']]/ASSIGN/EXPR/" + + "LITERAL_NEW[./IDENT[@text='Runnable']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='run']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingOverrideAnonymous']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='r']]/ASSIGN/EXPR/" + + "LITERAL_NEW[./IDENT[@text='Runnable']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='run']]/MODIFIERS/LITERAL_PUBLIC" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testInheritDocInvalidPrivateMethod() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingOverrideInheritDocInvalidPrivateMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingOverrideCheck.class); + + final String[] expectedViolation = { + "7:5: " + getCheckMessage(MissingOverrideCheck.class, + MissingOverrideCheck.MSG_KEY_TAG_NOT_VALID_ON, "{@inheritDoc}"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInheritDocInvalidPrivateMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInheritDocInvalidPrivateMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInheritDocInvalidPrivateMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS/LITERAL_PRIVATE" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testInheritDocInvalidPublicMethod() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingOverrideInheritDocInvalidPublicMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingOverrideCheck.class); + + final String[] expectedViolation = { + "7:5: " + getCheckMessage(MissingOverrideCheck.class, + MissingOverrideCheck.MSG_KEY_TAG_NOT_VALID_ON, "{@inheritDoc}"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInheritDocInvalidPublicMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInheritDocInvalidPublicMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInheritDocInvalidPublicMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS/LITERAL_PUBLIC" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testJavaFiveCompatibilityOne() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingOverrideClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingOverrideCheck.class); + moduleConfig.addProperty("javaFiveCompatibility", "true"); + + final String[] expectedViolation = { + "7:5: " + getCheckMessage(MissingOverrideCheck.class, + MissingOverrideCheck.MSG_KEY_ANNOTATION_MISSING_OVERRIDE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingOverrideClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingOverrideClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingOverrideClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]/MODIFIERS/LITERAL_PUBLIC" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + + @Test + public void testJavaFiveCompatibilityTwo() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingOverrideInterface.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingOverrideCheck.class); + moduleConfig.addProperty("javaFiveCompatibility", "true"); + + final String[] expectedViolation = { + "7:5: " + getCheckMessage(MissingOverrideCheck.class, + MissingOverrideCheck.MSG_KEY_ANNOTATION_MISSING_OVERRIDE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/TYPE", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathMissingOverrideInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/TYPE/LITERAL_BOOLEAN" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionPackageAnnotationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionPackageAnnotationTest.java new file mode 100644 index 000000000000..c74e3eeb8ed0 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionPackageAnnotationTest.java @@ -0,0 +1,87 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.annotation; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.annotation.PackageAnnotationCheck; + +public class XpathRegressionPackageAnnotationTest extends AbstractXpathTestSupport { + + private final String checkName = PackageAnnotationCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/annotation/packageannotation"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getNonCompilablePath( + "InputXpathPackageAnnotationOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(PackageAnnotationCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(PackageAnnotationCheck.class, + PackageAnnotationCheck.MSG_KEY), + }; + + final List expectedXpathQueries = + Arrays.asList("/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getNonCompilablePath( + "InputXpathPackageAnnotationTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(PackageAnnotationCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(PackageAnnotationCheck.class, + PackageAnnotationCheck.MSG_KEY), + }; + + final List expectedXpathQueries = + Arrays.asList("/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionSuppressWarningsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionSuppressWarningsTest.java new file mode 100644 index 000000000000..f48885299b67 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/annotation/XpathRegressionSuppressWarningsTest.java @@ -0,0 +1,349 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.annotation; + +import static com.puppycrawl.tools.checkstyle.checks.annotation.SuppressWarningsCheck.MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.annotation.SuppressWarningsCheck; + +public class XpathRegressionSuppressWarningsTest extends AbstractXpathTestSupport { + private final String checkName = SuppressWarningsCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/annotation/suppresswarnings"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testClassDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsClassDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "3:19: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsClassDefinition']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsClassDefinition']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testParameterDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsParameterDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "5:76: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsParameterDefinition']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsParameterDefinition']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT" + + "[@text='bar']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsParameterDefinition']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsParameterDefinition']]" + + "/PARAMETERS/PARAMETER_DEF[./IDENT" + + "[@text='bar']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testVariableDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsVariableDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "4:27: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsVariableDefinition']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT" + + "[@text='foo']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsVariableDefinition']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT" + + "[@text='foo']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testEnumDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsEnumDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "3:19: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsEnumDefinition']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsEnumDefinition']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testInterfaceDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsInterfaceDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "3:19: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsInterfaceDefinition']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsInterfaceDefinition']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testEnumConstantDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsEnumConstantDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "4:27: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsEnumConstantDefinition']]" + + "/OBJBLOCK/ENUM_CONSTANT_DEF[./IDENT" + + "[@text='FOO']]" + + "/ANNOTATIONS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsEnumConstantDefinition']]" + + "/OBJBLOCK/ENUM_CONSTANT_DEF[./IDENT" + + "[@text='FOO']]" + + "/ANNOTATIONS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testMethodDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsMethodDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "10:23: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsMethodDefinition']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT" + + "[@text='getFoo']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsMethodDefinition']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT" + + "[@text='getFoo']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testAnnotationDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsAnnotationDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "3:19: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ANNOTATION_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsAnnotationDefinition']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/ANNOTATION_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsAnnotationDefinition']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testAnnotationFieldDefinition() throws Exception { + final File fileToCheck = + new File(getPath("InputXpathSuppressWarningsAnnotationFieldDefinition.java")); + + final DefaultConfiguration configuration = + createModuleConfig(SuppressWarningsCheck.class); + + final String[] expectedViolations = { + "4:27: " + getCheckMessage(SuppressWarningsCheck.class, + MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, + ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ANNOTATION_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsAnnotationFieldDefinition']]" + + "/OBJBLOCK/ANNOTATION_FIELD_DEF[./IDENT" + + "[@text='foo']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR[./STRING_LITERAL[@text='']]", + + "/COMPILATION_UNIT/ANNOTATION_DEF[./IDENT" + + "[@text='InputXpathSuppressWarningsAnnotationFieldDefinition']]" + + "/OBJBLOCK/ANNOTATION_FIELD_DEF[./IDENT" + + "[@text='foo']]" + + "/MODIFIERS/ANNOTATION[./IDENT" + + "[@text='SuppressWarnings']]" + + "/EXPR/STRING_LITERAL[@text='']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionAvoidNestedBlocksTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionAvoidNestedBlocksTest.java new file mode 100644 index 000000000000..b2ff00237e1c --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionAvoidNestedBlocksTest.java @@ -0,0 +1,172 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.blocks; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.blocks.AvoidNestedBlocksCheck; + +public class XpathRegressionAvoidNestedBlocksTest extends AbstractXpathTestSupport { + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/blocks/avoidnestedblocks"; + } + + @Override + protected String getCheckName() { + return AvoidNestedBlocksCheck.class.getSimpleName(); + } + + @Test + public void testEmpty() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidNestedBlocksEmpty.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidNestedBlocksCheck.class); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(AvoidNestedBlocksCheck.class, + AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAvoidNestedBlocksEmpty']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='empty']]/SLIST/SLIST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testVariableAssignment() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidNestedBlocksVariable.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidNestedBlocksCheck.class); + + final String[] expectedViolation = { + "7:9: " + getCheckMessage(AvoidNestedBlocksCheck.class, + AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAvoidNestedBlocksVariable']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='varAssign']]/SLIST/SLIST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSwitchAllowInSwitchCaseFalse() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidNestedBlocksNotAllowedInSwitchCase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidNestedBlocksCheck.class); + + final String[] expectedViolation = { + "9:21: " + getCheckMessage(AvoidNestedBlocksCheck.class, + AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAvoidNestedBlocksNotAllowedInSwitchCase" + + "']]/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='s']]/SLIST/LITERAL_SWITCH/CASE_GROUP/SLIST", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAvoidNestedBlocksNotAllowedInSwitchCase" + + "']]/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='s']]/SLIST/LITERAL_SWITCH/CASE_GROUP/SLIST/SLIST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSwitchAllowInSwitchCaseTrue() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidNestedBlocksAllowedInSwitchCase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidNestedBlocksCheck.class); + moduleConfig.addProperty("allowInSwitchCase", "true"); + + final String[] expectedViolation = { + "11:13: " + getCheckMessage(AvoidNestedBlocksCheck.class, + AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathAvoidNestedBlocksAllowedInSwitchCase" + + "']]/OBJBLOCK/METHOD_DEF[./IDENT[@text='s']]" + + "/SLIST/LITERAL_SWITCH/CASE_GROUP/SLIST/SLIST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSwitchWithBreakOutside() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidNestedBlocksBreakOutside.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidNestedBlocksCheck.class); + + final String[] expectedViolation = { + "8:21: " + getCheckMessage(AvoidNestedBlocksCheck.class, + AvoidNestedBlocksCheck.MSG_KEY_BLOCK_NESTED), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathAvoidNestedBlocksBreakOutside']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='s']]" + + "/SLIST/LITERAL_SWITCH/CASE_GROUP/SLIST", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathAvoidNestedBlocksBreakOutside']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='s']]" + + "/SLIST/LITERAL_SWITCH/CASE_GROUP/SLIST/SLIST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionEmptyBlockTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionEmptyBlockTest.java new file mode 100644 index 000000000000..ef79aa80cb08 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionEmptyBlockTest.java @@ -0,0 +1,87 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.blocks; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.blocks.EmptyBlockCheck; + +public class XpathRegressionEmptyBlockTest extends AbstractXpathTestSupport { + + private final String checkName = EmptyBlockCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/blocks/emptyblock"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testEmptyForLoopEmptyBlock() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathEmptyBlockEmpty.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyBlockCheck.class); + moduleConfig.addProperty("option", "TEXT"); + final String[] expectedViolation = { + "5:38: " + getCheckMessage(EmptyBlockCheck.class, + EmptyBlockCheck.MSG_KEY_BLOCK_EMPTY, "for"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathEmptyBlockEmpty']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='emptyLoop']]" + + "/SLIST/LITERAL_FOR/SLIST" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEmptyForLoopEmptyStatement() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathEmptyBlockEmpty.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyBlockCheck.class); + final String[] expectedViolation = { + "5:38: " + getCheckMessage(EmptyBlockCheck.class, + EmptyBlockCheck.MSG_KEY_BLOCK_NO_STATEMENT), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathEmptyBlockEmpty']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='emptyLoop']]" + + "/SLIST/LITERAL_FOR/SLIST" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionEmptyCatchBlockTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionEmptyCatchBlockTest.java new file mode 100644 index 000000000000..570a42748cc6 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionEmptyCatchBlockTest.java @@ -0,0 +1,88 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.blocks; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.blocks.EmptyCatchBlockCheck; + +public class XpathRegressionEmptyCatchBlockTest extends AbstractXpathTestSupport { + private static final Class CLAZZ = + EmptyCatchBlockCheck.class; + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/blocks/emptycatchblock"; + } + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyCatchBlockOne.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "8:38: " + getCheckMessage(CLAZZ, EmptyCatchBlockCheck.MSG_KEY_CATCH_BLOCK_EMPTY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyCatchBlockOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='main']]" + + "/SLIST/LITERAL_TRY/LITERAL_CATCH/SLIST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyCatchBlockTwo.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "8:47: " + getCheckMessage(CLAZZ, EmptyCatchBlockCheck.MSG_KEY_CATCH_BLOCK_EMPTY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyCatchBlockTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='main']]" + + "/SLIST/LITERAL_TRY/LITERAL_CATCH/SLIST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionLeftCurlyTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionLeftCurlyTest.java new file mode 100644 index 000000000000..a912dda98fdb --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionLeftCurlyTest.java @@ -0,0 +1,119 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.blocks; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.blocks.LeftCurlyCheck; +import com.puppycrawl.tools.checkstyle.checks.blocks.LeftCurlyOption; + +public class XpathRegressionLeftCurlyTest extends AbstractXpathTestSupport { + + private final String checkName = LeftCurlyCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/blocks/leftcurly"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathLeftCurlyOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(LeftCurlyCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(LeftCurlyCheck.class, + LeftCurlyCheck.MSG_KEY_LINE_PREVIOUS, "{", 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLeftCurlyOne']]/OBJBLOCK", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLeftCurlyOne']]/OBJBLOCK/LCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathLeftCurlyTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(LeftCurlyCheck.class); + moduleConfig.addProperty("option", LeftCurlyOption.NL.toString()); + + final String[] expectedViolation = { + "3:37: " + getCheckMessage(LeftCurlyCheck.class, + LeftCurlyCheck.MSG_KEY_LINE_NEW, "{", 37), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLeftCurlyTwo']]/OBJBLOCK", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLeftCurlyTwo']]/OBJBLOCK/LCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathLeftCurlyThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(LeftCurlyCheck.class); + + final String[] expectedViolation = { + "5:19: " + getCheckMessage(LeftCurlyCheck.class, + LeftCurlyCheck.MSG_KEY_LINE_BREAK_AFTER, "{", 19), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLeftCurlyThree']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='sample']]/SLIST/LITERAL_IF/SLIST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionNeedBracesTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionNeedBracesTest.java new file mode 100644 index 000000000000..29bb8af71dbb --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionNeedBracesTest.java @@ -0,0 +1,138 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.blocks; + +import static com.puppycrawl.tools.checkstyle.checks.blocks.NeedBracesCheck.MSG_KEY_NEED_BRACES; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.blocks.NeedBracesCheck; + +public class XpathRegressionNeedBracesTest extends AbstractXpathTestSupport { + + private final String checkName = NeedBracesCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/blocks/needbraces"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testDo() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathNeedBracesDo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NeedBracesCheck.class); + + final String[] expectedViolation = { + "13:9: " + getCheckMessage(NeedBracesCheck.class, MSG_KEY_NEED_BRACES, "do"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNeedBracesDo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_DO" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSingleLine() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathNeedBracesSingleLine.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NeedBracesCheck.class); + moduleConfig.addProperty("allowSingleLineStatement", "true"); + + final String[] expectedViolation = { + "16:9: " + getCheckMessage(NeedBracesCheck.class, MSG_KEY_NEED_BRACES, "if"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNeedBracesSingleLine']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSingleLineLambda() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathNeedBracesSingleLineLambda.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NeedBracesCheck.class); + moduleConfig.addProperty("tokens", "LAMBDA"); + moduleConfig.addProperty("allowSingleLineStatement", "true"); + + final String[] expectedViolation = { + "4:29: " + getCheckMessage(NeedBracesCheck.class, MSG_KEY_NEED_BRACES, "->"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNeedBracesSingleLineLambda']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='r3']]/ASSIGN/LAMBDA" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEmptyLoopBody() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathNeedBracesEmptyLoopBody.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NeedBracesCheck.class); + + final String[] expectedViolation = { + "9:9: " + getCheckMessage(NeedBracesCheck.class, MSG_KEY_NEED_BRACES, "while"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNeedBracesEmptyLoopBody']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_WHILE" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionRightCurlyTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionRightCurlyTest.java new file mode 100644 index 000000000000..ce2968ec1b96 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/blocks/XpathRegressionRightCurlyTest.java @@ -0,0 +1,141 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.blocks; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheck; +import com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyOption; + +public class XpathRegressionRightCurlyTest extends AbstractXpathTestSupport { + + private final String checkName = RightCurlyCheck.class.getSimpleName(); + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/blocks/rightcurly"; + } + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRightCurlyOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RightCurlyCheck.class); + + final String[] expectedViolation = { + "8:9: " + getCheckMessage(RightCurlyCheck.class, + RightCurlyCheck.MSG_KEY_LINE_SAME, "}", 9), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRightCurlyOne']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF/SLIST/RCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRightCurlyTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RightCurlyCheck.class); + moduleConfig.addProperty("option", RightCurlyOption.ALONE.toString()); + + final String[] expectedViolation = { + "9:15: " + getCheckMessage(RightCurlyCheck.class, + RightCurlyCheck.MSG_KEY_LINE_ALONE, "}", 15), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRightCurlyTwo']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='fooMethod']]/SLIST/LITERAL_TRY/SLIST/RCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRightCurlyThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RightCurlyCheck.class); + moduleConfig.addProperty("option", RightCurlyOption.ALONE.toString()); + + final String[] expectedViolation = { + "5:72: " + getCheckMessage(RightCurlyCheck.class, + RightCurlyCheck.MSG_KEY_LINE_ALONE, "}", 72), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRightCurlyThree']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='sample']]/SLIST/LITERAL_IF/SLIST/RCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRightCurlyFour.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RightCurlyCheck.class); + moduleConfig.addProperty("option", RightCurlyOption.SAME.toString()); + + final String[] expectedViolation = { + "7:27: " + getCheckMessage(RightCurlyCheck.class, + RightCurlyCheck.MSG_KEY_LINE_BREAK_BEFORE, "}", 27), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRightCurlyFour']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='sample']]/SLIST/LITERAL_IF/SLIST/RCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionArrayTrailingCommaTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionArrayTrailingCommaTest.java new file mode 100644 index 000000000000..c4f8a6d8baae --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionArrayTrailingCommaTest.java @@ -0,0 +1,99 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.ArrayTrailingCommaCheck; + +public class XpathRegressionArrayTrailingCommaTest extends AbstractXpathTestSupport { + + private final String checkName = ArrayTrailingCommaCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/arraytrailingcomma"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathArrayTrailingCommaLinear.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ArrayTrailingCommaCheck.class); + + final String[] expectedViolation = { + "16:9: " + getCheckMessage(ArrayTrailingCommaCheck.class, + ArrayTrailingCommaCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathArrayTrailingCommaLinear']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a2']]/ASSIGN/EXPR/LITERAL_NEW" + + "/ARRAY_INIT/EXPR[./NUM_INT[@text='3']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathArrayTrailingCommaLinear']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a2']]/ASSIGN/EXPR/LITERAL_NEW" + + "/ARRAY_INIT/EXPR/NUM_INT[@text='3']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathArrayTrailingCommaMatrix.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ArrayTrailingCommaCheck.class); + + final String[] expectedViolation = { + "17:9: " + getCheckMessage(ArrayTrailingCommaCheck.class, + ArrayTrailingCommaCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathArrayTrailingCommaMatrix']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='d2']]/ASSIGN/EXPR/LITERAL_NEW" + + "/ARRAY_INIT/ARRAY_INIT[./EXPR/NUM_INT[@text='5']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidDoubleBraceInitializationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidDoubleBraceInitializationTest.java new file mode 100644 index 000000000000..9520f4162db3 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidDoubleBraceInitializationTest.java @@ -0,0 +1,99 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.AvoidDoubleBraceInitializationCheck; + +public class XpathRegressionAvoidDoubleBraceInitializationTest extends AbstractXpathTestSupport { + + private static final Class CLAZZ = + AvoidDoubleBraceInitializationCheck.class; + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/avoiddoublebraceinitialization"; + } + + @Test + public void testClassFields() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidDoubleBraceInitializationClassFields.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "6:41: " + getCheckMessage(CLAZZ, AvoidDoubleBraceInitializationCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAvoidDoubleBraceInitializationClassFields']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='list']]/ASSIGN/EXPR/" + + "LITERAL_NEW[./IDENT[@text='ArrayList']]/OBJBLOCK", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAvoidDoubleBraceInitializationClassFields']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='list']]/ASSIGN/EXPR/" + + "LITERAL_NEW[./IDENT[@text='ArrayList']]/OBJBLOCK/LCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testMethodDef() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidDoubleBraceInitializationMethodDef.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "7:31: " + getCheckMessage(CLAZZ, AvoidDoubleBraceInitializationCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathAvoidDoubleBraceInitializationMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/EXPR/LITERAL_NEW[./IDENT[@text='HashSet']]" + + "/OBJBLOCK", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathAvoidDoubleBraceInitializationMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/EXPR/LITERAL_NEW[./IDENT[@text='HashSet']]" + + "/OBJBLOCK/LCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidInlineConditionalsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidInlineConditionalsTest.java new file mode 100644 index 000000000000..f5143cc62e37 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidInlineConditionalsTest.java @@ -0,0 +1,125 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.AvoidInlineConditionalsCheck; + +public class XpathRegressionAvoidInlineConditionalsTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return AvoidInlineConditionalsCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/avoidinlineconditionals"; + } + + @Test + public void testInlineConditionalsVariableDef() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidInlineConditionalsVariableDef.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidInlineConditionalsCheck.class); + + final String[] expectedViolation = { + "5:50: " + getCheckMessage(AvoidInlineConditionalsCheck.class, + AvoidInlineConditionalsCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAvoidInlineConditionalsVariableDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='substring']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='b']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAvoidInlineConditionalsVariableDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='substring']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='b']]/ASSIGN/EXPR/QUESTION" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInlineConditionalsAssign() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidInlineConditionalsAssign.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidInlineConditionalsCheck.class); + + final String[] expectedViolation = { + "7:43: " + getCheckMessage(AvoidInlineConditionalsCheck.class, + AvoidInlineConditionalsCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAvoidInlineConditionalsAssign']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='setB']]/SLIST" + + "/EXPR/ASSIGN[./IDENT[@text='b']]/QUESTION" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInlineConditionalsAssert() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathAvoidInlineConditionalsAssert.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AvoidInlineConditionalsCheck.class); + + final String[] expectedViolation = { + "8:31: " + getCheckMessage(AvoidInlineConditionalsCheck.class, + AvoidInlineConditionalsCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAvoidInlineConditionalsAssert']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='assertA']]/SLIST" + + "/LITERAL_ASSERT/EXPR[./QUESTION/METHOD_CALL/DOT/IDENT[@text='a']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAvoidInlineConditionalsAssert']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='assertA']]/SLIST" + + "/LITERAL_ASSERT/EXPR/QUESTION" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidNoArgumentSuperConstructorCallTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidNoArgumentSuperConstructorCallTest.java new file mode 100644 index 000000000000..aef072c3f4bb --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionAvoidNoArgumentSuperConstructorCallTest.java @@ -0,0 +1,97 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.AvoidNoArgumentSuperConstructorCallCheck; + +public class XpathRegressionAvoidNoArgumentSuperConstructorCallTest + extends AbstractXpathTestSupport { + + private static final Class CLASS = + AvoidNoArgumentSuperConstructorCallCheck.class; + + @Override + protected String getCheckName() { + return CLASS.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/avoidnoargumentsuperconstructorcall"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidNoArgumentSuperConstructorCallDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CLASS); + + final String[] expectedViolation = { + "5:9: " + getCheckMessage(CLASS, + AvoidNoArgumentSuperConstructorCallCheck.MSG_CTOR), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathAvoidNoArgumentSuperConstructorCallDefault']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathAvoidNoArgumentSuperConstructorCallDefault']]" + + "/SLIST/SUPER_CTOR_CALL" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidNoArgumentSuperConstructorCallInnerClass.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CLASS); + + final String[] expectedViolation = { + "7:17: " + getCheckMessage(CLASS, + AvoidNoArgumentSuperConstructorCallCheck.MSG_CTOR), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathAvoidNoArgumentSuperConstructorCallInnerClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/CLASS_DEF[./IDENT[@text='Inner']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[@text='Inner']]" + + "/SLIST/SUPER_CTOR_CALL" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionConstructorsDeclarationGroupingTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionConstructorsDeclarationGroupingTest.java new file mode 100644 index 000000000000..808452e09bdc --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionConstructorsDeclarationGroupingTest.java @@ -0,0 +1,144 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.ConstructorsDeclarationGroupingCheck; + +public class XpathRegressionConstructorsDeclarationGroupingTest extends AbstractXpathTestSupport { + + private static final Class CLAZZ = + ConstructorsDeclarationGroupingCheck.class; + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/constructorsdeclarationgrouping"; + } + + @Test + public void testClass() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathConstructorsDeclarationGroupingClass.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "10:5: " + getCheckMessage(CLAZZ, + ConstructorsDeclarationGroupingCheck.MSG_KEY, 6), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingClass']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingClass']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingClass']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingClass']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingClass']]" + + "/OBJBLOCK/CTOR_DEF/IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingClass']" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testEnum() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathConstructorsDeclarationGroupingEnum.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "12:5: " + getCheckMessage(CLAZZ, + ConstructorsDeclarationGroupingCheck.MSG_KEY, 8), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingEnum']]" + + "/OBJBLOCK/CTOR_DEF" + + "[./IDENT[@text='InputXpathConstructorsDeclarationGroupingEnum']]", + + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingEnum']]" + + "/OBJBLOCK/CTOR_DEF" + + "[./IDENT[@text='InputXpathConstructorsDeclarationGroupingEnum']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingEnum']]" + + "/OBJBLOCK/CTOR_DEF/IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingEnum']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testRecords() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathConstructorsDeclarationGroupingRecords.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "14:5: " + getCheckMessage(CLAZZ, + ConstructorsDeclarationGroupingCheck.MSG_KEY, 8), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingRecords']]" + + "/OBJBLOCK/RECORD_DEF[./IDENT[@text='MyRecord']]" + + "/OBJBLOCK/COMPACT_CTOR_DEF[./IDENT[@text='MyRecord']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingRecords']]" + + "/OBJBLOCK/RECORD_DEF[./IDENT[@text='MyRecord']]" + + "/OBJBLOCK/COMPACT_CTOR_DEF[./IDENT[@text='MyRecord']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstructorsDeclarationGroupingRecords']]" + + "/OBJBLOCK/RECORD_DEF[./IDENT[@text='MyRecord']]" + + "/OBJBLOCK/COMPACT_CTOR_DEF[./IDENT[@text='MyRecord']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionCovariantEqualsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionCovariantEqualsTest.java new file mode 100644 index 000000000000..104c0d9a01e7 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionCovariantEqualsTest.java @@ -0,0 +1,114 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.CovariantEqualsCheck; + +public class XpathRegressionCovariantEqualsTest extends AbstractXpathTestSupport { + + private final String checkName = CovariantEqualsCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/covariantequals"; + } + + @Test + public void testCovariantEqualsInClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCovariantEqualsInClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CovariantEqualsCheck.class); + + final String[] expectedViolation = { + "5:20: " + getCheckMessage(CovariantEqualsCheck.class, + CovariantEqualsCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCovariantEqualsInClass']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='equals']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testCovariantEqualsInEnum() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCovariantEqualsInEnum.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CovariantEqualsCheck.class); + + final String[] expectedViolation = { + "7:20: " + getCheckMessage(CovariantEqualsCheck.class, + CovariantEqualsCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/ENUM_DEF" + + "[./IDENT[@text='InputXpathCovariantEqualsInEnum']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='equals']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testCovariantEqualsInRecord() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathCovariantEqualsInRecord.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CovariantEqualsCheck.class); + + final String[] expectedViolation = { + "7:20: " + getCheckMessage(CovariantEqualsCheck.class, + CovariantEqualsCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/RECORD_DEF" + + "[./IDENT[@text='InputXpathCovariantEqualsInRecord']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='equals']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionDeclarationOrderTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionDeclarationOrderTest.java new file mode 100644 index 000000000000..4533ea297c01 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionDeclarationOrderTest.java @@ -0,0 +1,103 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.DeclarationOrderCheck; + +public class XpathRegressionDeclarationOrderTest extends AbstractXpathTestSupport { + + private final String checkName = DeclarationOrderCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/declarationorder"; + } + + @Test + public void testNonStatic() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDeclarationOrderNonStatic.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DeclarationOrderCheck.class); + + final String[] expectedViolation = { + "5:5: " + getCheckMessage(DeclarationOrderCheck.class, + DeclarationOrderCheck.MSG_ACCESS), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathDeclarationOrderNonStatic']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='name']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathDeclarationOrderNonStatic']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='name']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathDeclarationOrderNonStatic']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='name']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testStatic() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDeclarationOrderStatic.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DeclarationOrderCheck.class); + + final String[] expectedViolation = { + "5:5: " + getCheckMessage(DeclarationOrderCheck.class, + DeclarationOrderCheck.MSG_STATIC), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathDeclarationOrderStatic']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='MAX']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathDeclarationOrderStatic']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='MAX']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathDeclarationOrderStatic']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='MAX']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionDefaultComesLastTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionDefaultComesLastTest.java new file mode 100644 index 000000000000..6496403579e1 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionDefaultComesLastTest.java @@ -0,0 +1,100 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.DefaultComesLastCheck; + +public class XpathRegressionDefaultComesLastTest extends AbstractXpathTestSupport { + + private final String checkName = DefaultComesLastCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/defaultcomeslast"; + } + + @Test + public void testNonEmptyCase() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDefaultComesLastNonEmptyCase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DefaultComesLastCheck.class); + + final String[] expectedViolation = { + "8:13: " + getCheckMessage(DefaultComesLastCheck.class, + DefaultComesLastCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDefaultComesLastNonEmptyCase']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP[" + + "./SLIST/EXPR/ASSIGN/IDENT[@text='id']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDefaultComesLastNonEmptyCase']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP" + + "/LITERAL_DEFAULT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEmptyCase() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDefaultComesLastEmptyCase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DefaultComesLastCheck.class); + moduleConfig.addProperty("skipIfLastAndSharedWithCase", "true"); + + final String[] expectedViolation = { + "15:13: " + getCheckMessage(DefaultComesLastCheck.class, + DefaultComesLastCheck.MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDefaultComesLastEmptyCase']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP" + + "/LITERAL_DEFAULT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEmptyStatementTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEmptyStatementTest.java new file mode 100644 index 000000000000..f3a6ad45f75b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEmptyStatementTest.java @@ -0,0 +1,83 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.EmptyStatementCheck; + +public class XpathRegressionEmptyStatementTest extends AbstractXpathTestSupport { + + private final String checkName = EmptyStatementCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/emptystatement"; + } + + @Test + public void testForLoopEmptyStatement() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathEmptyStatementLoops.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyStatementCheck.class); + final String[] expectedViolation = { + "5:36: " + getCheckMessage(EmptyStatementCheck.class, EmptyStatementCheck.MSG_KEY), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathEmptyStatementLoops']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/LITERAL_FOR/EMPTY_STAT" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testIfBlockEmptyStatement() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathEmptyStatementConditionals.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyStatementCheck.class); + final String[] expectedViolation = { + "6:19: " + getCheckMessage(EmptyStatementCheck.class, EmptyStatementCheck.MSG_KEY), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathEmptyStatementConditionals']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/LITERAL_IF/EMPTY_STAT" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEqualsAvoidNullTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEqualsAvoidNullTest.java new file mode 100644 index 000000000000..4b06fddd988a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEqualsAvoidNullTest.java @@ -0,0 +1,91 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck; + +public class XpathRegressionEqualsAvoidNullTest extends AbstractXpathTestSupport { + + private static final Class CLAZZ = EqualsAvoidNullCheck.class; + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/equalsavoidnull"; + } + + @Test + public void testEquals() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEqualsAvoidNull.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "6:26: " + getCheckMessage(CLAZZ, + EqualsAvoidNullCheck.MSG_EQUALS_AVOID_NULL), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsAvoidNull']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsAvoidNull']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/EXPR/METHOD_CALL"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testEqualsIgnoreCase() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEqualsAvoidNullIgnoreCase.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "6:36: " + getCheckMessage(CLAZZ, + EqualsAvoidNullCheck.MSG_EQUALS_IGNORE_CASE_AVOID_NULL), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsAvoidNullIgnoreCase']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsAvoidNullIgnoreCase']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/EXPR/METHOD_CALL"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEqualsHashCodeTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEqualsHashCodeTest.java new file mode 100644 index 000000000000..747eb669ca6c --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionEqualsHashCodeTest.java @@ -0,0 +1,127 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.EqualsHashCodeCheck; + +public class XpathRegressionEqualsHashCodeTest extends AbstractXpathTestSupport { + @Override + protected String getCheckName() { + return EqualsHashCodeCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/equalshashcode"; + } + + @Test + public void testEqualsOnly() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEqualsHashCodeEqualsOnly.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(EqualsHashCodeCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(EqualsHashCodeCheck.class, + EqualsHashCodeCheck.MSG_KEY_HASHCODE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeEqualsOnly']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeEqualsOnly']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='equals']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeEqualsOnly']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='equals']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testHashCodeOnly() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEqualsHashCodeHashCodeOnly.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(EqualsHashCodeCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(EqualsHashCodeCheck.class, + EqualsHashCodeCheck.MSG_KEY_EQUALS), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeHashCodeOnly']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='hashCode']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeHashCodeOnly']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='hashCode']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeHashCodeOnly']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='hashCode']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testNestedCase() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEqualsHashCodeNestedCase.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(EqualsHashCodeCheck.class); + + final String[] expectedViolation = { + "5:9: " + getCheckMessage(EqualsHashCodeCheck.class, + EqualsHashCodeCheck.MSG_KEY_HASHCODE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeNestedCase']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='innerClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeNestedCase']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='innerClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathEqualsHashCodeNestedCase']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='innerClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='equals']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionExplicitInitializationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionExplicitInitializationTest.java new file mode 100644 index 000000000000..85232ee321f4 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionExplicitInitializationTest.java @@ -0,0 +1,91 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.ExplicitInitializationCheck; + +public class XpathRegressionExplicitInitializationTest extends AbstractXpathTestSupport { + + private final String checkName = ExplicitInitializationCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/explicitinitialization"; + } + + @Test + public void testPrimitiveType() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathExplicitInitializationPrimitiveType.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ExplicitInitializationCheck.class); + + final String[] expectedViolation = { + "4:17: " + getCheckMessage(ExplicitInitializationCheck.class, + ExplicitInitializationCheck.MSG_KEY, "a", 0), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathExplicitInitializationPrimitiveType']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='a']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testObjectType() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathExplicitInitializationObjectType.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ExplicitInitializationCheck.class); + + final String[] expectedViolation = { + "6:20: " + getCheckMessage(ExplicitInitializationCheck.class, + ExplicitInitializationCheck.MSG_KEY, "bar", "null"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathExplicitInitializationObjectType']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='bar']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionFallThroughTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionFallThroughTest.java new file mode 100644 index 000000000000..edadf39e6473 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionFallThroughTest.java @@ -0,0 +1,101 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.FallThroughCheck; + +public class XpathRegressionFallThroughTest extends AbstractXpathTestSupport { + + private final String checkName = FallThroughCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/fallthrough"; + } + + @Test + public void testFallThrough() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathFallThrough.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(FallThroughCheck.class); + + final String[] expectedViolation = { + "11:13: " + getCheckMessage(FallThroughCheck.class, + FallThroughCheck.MSG_FALL_THROUGH), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathFallThrough']]" + + "/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP[" + + "./LITERAL_CASE/EXPR/NUM_INT[@text='2']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathFallThrough']]" + + "/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/CASE_GROUP/LITERAL_CASE" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testDefaultCase() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathFallThroughDefaultCase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(FallThroughCheck.class); + moduleConfig.addProperty("checkLastCaseGroup", "true"); + + final String[] expectedViolation = { + "10:17: " + getCheckMessage(FallThroughCheck.class, + FallThroughCheck.MSG_FALL_THROUGH_LAST), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathFallThroughDefaultCase']]" + + "/OBJBLOCK/METHOD_DEF[" + + "./IDENT[@text='methodFallThruCustomWords']]/SLIST/LITERAL_WHILE/SLIST" + + "/LITERAL_SWITCH/CASE_GROUP[./SLIST/EXPR/POST_INC/IDENT[@text='i']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathFallThroughDefaultCase']]" + + "/OBJBLOCK/METHOD_DEF[" + + "./IDENT[@text='methodFallThruCustomWords']]/SLIST/LITERAL_WHILE/SLIST" + + "/LITERAL_SWITCH/CASE_GROUP/LITERAL_DEFAULT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionFinalLocalVariableTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionFinalLocalVariableTest.java new file mode 100644 index 000000000000..22dbaf41f19e --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionFinalLocalVariableTest.java @@ -0,0 +1,249 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.FinalLocalVariableCheck; + +public class XpathRegressionFinalLocalVariableTest extends AbstractXpathTestSupport { + + private final String checkName = FinalLocalVariableCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/finallocalvariable"; + } + + @Test + public void testMethodDef() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableMethodDef.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + + final String[] expectedViolation = { + "5:13: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "x"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalLocalVariableMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod']]" + + "/SLIST/VARIABLE_DEF/IDENT[@text='x']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testForLoop() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableForLoop.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + + final String[] expectedViolation = { + "6:17: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "x"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalLocalVariableForLoop']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method2']]/SLIST/" + + "LITERAL_FOR/SLIST/VARIABLE_DEF/IDENT[@text='x']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testSwitchCase() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableSwitchCase.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + + final String[] expectedViolation = { + "8:25: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "foo"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalLocalVariableSwitchCase']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/" + + "LITERAL_SWITCH/CASE_GROUP/SLIST/VARIABLE_DEF/IDENT[@text='foo']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableInnerClass.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + + final String[] expectedViolation = { + "7:17: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "shouldBeFinal"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalLocalVariableInnerClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test1']]" + + "/SLIST/VARIABLE_DEF/IDENT[@text='shouldBeFinal']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testParameterDef() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableParameterDef.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + moduleConfig.addProperty("tokens", "PARAMETER_DEF"); + + final String[] expectedViolation = { + "4:28: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "aArg"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalLocalVariableParameterDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/PARAMETERS/PARAMETER_DEF/IDENT[@text='aArg']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testEnhancedFor() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableEnhancedFor.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + moduleConfig.addProperty("validateEnhancedForLoopVariable", "true"); + + final String[] expectedViolation = { + "8:20: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "a"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathFinalLocalVariableEnhancedFor']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method1']]" + + "/SLIST/LITERAL_FOR/FOR_EACH_CLAUSE/VARIABLE_DEF/IDENT[@text='a']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testCtor() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableCtor.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + moduleConfig.addProperty("tokens", "PARAMETER_DEF"); + + final String[] expectedViolation = { + "4:42: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "a"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathFinalLocalVariableCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathFinalLocalVariableCtor']]" + + "/PARAMETERS/PARAMETER_DEF/IDENT[@text='a']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testTryBlock() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableTryBlock.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + + final String[] expectedViolation = { + "6:17: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "start"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathFinalLocalVariableTryBlock']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='checkCodeBlock']]" + + "/SLIST/LITERAL_TRY/SLIST/VARIABLE_DEF/IDENT[@text='start']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testConditionals() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathFinalLocalVariableConditionals.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(FinalLocalVariableCheck.class); + + final String[] expectedViolation = { + "11:25: " + getCheckMessage(FinalLocalVariableCheck.class, + FinalLocalVariableCheck.MSG_KEY, "body"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathFinalLocalVariableConditionals']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='checkCodeBlock']]/SLIST/LITERAL_TRY" + + "/SLIST/LITERAL_IF/LITERAL_ELSE/LITERAL_IF" + + "/SLIST/VARIABLE_DEF/IDENT[@text='body']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionHiddenFieldTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionHiddenFieldTest.java new file mode 100644 index 000000000000..5118957c195d --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionHiddenFieldTest.java @@ -0,0 +1,93 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.HiddenFieldCheck; + +public class XpathRegressionHiddenFieldTest extends AbstractXpathTestSupport { + + private final String checkName = HiddenFieldCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/hiddenfield"; + } + + @Test + public void testLambdaExpInMethodCall() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathHiddenFieldLambdaExpInMethodCall.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(HiddenFieldCheck.class); + + final String[] expectedViolation = { + "10:34: " + getCheckMessage(HiddenFieldCheck.class, + HiddenFieldCheck.MSG_KEY, "value"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathHiddenFieldLambdaExpInMethodCall']]/OBJBLOCK" + + "/INSTANCE_INIT/SLIST/EXPR/METHOD_CALL/ELIST/LAMBDA/PARAMETERS" + + "/PARAMETER_DEF/IDENT[@text='value']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMethodParam() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathHiddenFieldMethodParam.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(HiddenFieldCheck.class); + + final String[] expectedViolation = { + "8:45: " + getCheckMessage(HiddenFieldCheck.class, + HiddenFieldCheck.MSG_KEY, "other"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathHiddenFieldMethodParam']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/PARAMETERS/PARAMETER_DEF" + + "/IDENT[@text='other']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalCatchTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalCatchTest.java new file mode 100644 index 000000000000..462ff3a32234 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalCatchTest.java @@ -0,0 +1,93 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.IllegalCatchCheck; + +public class XpathRegressionIllegalCatchTest extends AbstractXpathTestSupport { + + private final String checkName = IllegalCatchCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/illegalcatch"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalCatchOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalCatchCheck.class); + + final String[] expectedViolation = { + "6:11: " + getCheckMessage(IllegalCatchCheck.class, + IllegalCatchCheck.MSG_KEY, "RuntimeException"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIllegalCatchOne']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='fun']]/SLIST" + + "/LITERAL_TRY/LITERAL_CATCH" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalCatchTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalCatchCheck.class); + + final String[] expectedViolation = { + "16:11: " + getCheckMessage(IllegalCatchCheck.class, + IllegalCatchCheck.MSG_KEY, "java.lang.RuntimeException"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIllegalCatchTwo']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='methodTwo']]/SLIST" + + "/LITERAL_TRY/LITERAL_CATCH" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalInstantiationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalInstantiationTest.java new file mode 100644 index 000000000000..ede09c55cd1a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalInstantiationTest.java @@ -0,0 +1,134 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import static com.puppycrawl.tools.checkstyle.checks.coding.IllegalInstantiationCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.IllegalInstantiationCheck; + +public class XpathRegressionIllegalInstantiationTest extends AbstractXpathTestSupport { + @Override + protected String getCheckName() { + return IllegalInstantiationCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation"; + } + + @Test + public void testSimple() throws Exception { + final String fileName = "InputXpathIllegalInstantiationSimple.java"; + final File fileToProcess = new File(getNonCompilablePath(fileName)); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalInstantiationCheck.class); + moduleConfig.addProperty("classes", "java.lang.Boolean"); + + final String[] expectedViolation = { + "8:21: " + getCheckMessage(IllegalInstantiationCheck.class, MSG_KEY, + "java.lang.Boolean"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathIllegalInstantiationSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='x']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIllegalInstantiationSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='x']]/ASSIGN/EXPR/LITERAL_NEW[./IDENT[@text='Boolean']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testAnonymous() throws Exception { + final String fileName = "InputXpathIllegalInstantiationAnonymous.java"; + final File fileToProcess = new File(getNonCompilablePath(fileName)); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalInstantiationCheck.class); + moduleConfig.addProperty("classes", "java.lang.Integer"); + + final String[] expectedViolation = { + "10:25: " + getCheckMessage(IllegalInstantiationCheck.class, MSG_KEY, + "java.lang.Integer"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathIllegalInstantiationAnonymous']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT[@text='e']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathIllegalInstantiationAnonymous']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT[@text='e']]" + + "/ASSIGN/EXPR/LITERAL_NEW[./IDENT[@text='Integer']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInterface() throws Exception { + final String fileName = "InputXpathIllegalInstantiationInterface.java"; + final File fileToProcess = new File(getNonCompilablePath(fileName)); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalInstantiationCheck.class); + moduleConfig.addProperty("classes", "java.lang.String"); + + final String[] expectedViolation = { + "10:24: " + getCheckMessage(IllegalInstantiationCheck.class, MSG_KEY, + "java.lang.String"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathIllegalInstantiationInterface']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Inner']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='s']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathIllegalInstantiationInterface']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Inner']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='s']]/ASSIGN/EXPR/LITERAL_NEW[./IDENT[@text='String']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalThrowsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalThrowsTest.java new file mode 100644 index 000000000000..d97e91d5568f --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalThrowsTest.java @@ -0,0 +1,93 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.IllegalThrowsCheck; + +public class XpathRegressionIllegalThrowsTest extends AbstractXpathTestSupport { + + private final String checkName = IllegalThrowsCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/illegalthrows"; + } + + @Test + public void testRuntimeException() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalThrowsRuntimeException.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalThrowsCheck.class); + + final String[] expectedViolation = { + "4:35: " + getCheckMessage(IllegalThrowsCheck.class, + IllegalThrowsCheck.MSG_KEY, "RuntimeException"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIllegalThrowsRuntimeException']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='sayHello']]/LITERAL_THROWS" + + "/IDENT[@text='RuntimeException']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testError() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalThrowsError.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalThrowsCheck.class); + + final String[] expectedViolation = { + "8:45: " + getCheckMessage(IllegalThrowsCheck.class, + IllegalThrowsCheck.MSG_KEY, "java.lang.Error"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIllegalThrowsError']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='methodTwo']]/LITERAL_THROWS" + + "/DOT[./IDENT[@text='Error']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTokenTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTokenTest.java new file mode 100644 index 000000000000..9a779f767fae --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTokenTest.java @@ -0,0 +1,90 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenCheck; + +public class XpathRegressionIllegalTokenTest extends AbstractXpathTestSupport { + + private final String checkName = IllegalTokenCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/illegaltoken"; + } + + @Test + public void testLabel() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalTokenLabel.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + final String[] expectedViolation = { + "5:10: " + getCheckMessage(IllegalTokenCheck.class, + IllegalTokenCheck.MSG_KEY, "outer:"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathIllegalTokenLabel']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myTest']]" + + "/SLIST/LABELED_STAT[./IDENT[@text='outer']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNative() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalTokenNative.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + + moduleConfig.addProperty("tokens", "LITERAL_NATIVE"); + + final String[] expectedViolation = { + "4:10: " + getCheckMessage(IllegalTokenCheck.class, + IllegalTokenCheck.MSG_KEY, "native"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathIllegalTokenNative']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myTest']]" + + "/MODIFIERS/LITERAL_NATIVE" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTokenTextTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTokenTextTest.java new file mode 100644 index 000000000000..4cf1849d371f --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTokenTextTest.java @@ -0,0 +1,125 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenTextCheck; + +public class XpathRegressionIllegalTokenTextTest extends AbstractXpathTestSupport { + + private final String checkName = IllegalTokenTextCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/illegaltokentext"; + } + + @Test + public void testField() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalTokenTextField.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenTextCheck.class); + moduleConfig.addProperty("format", "12345"); + moduleConfig.addProperty("tokens", "NUM_INT"); + final String[] expectedViolation = { + "4:33: " + getCheckMessage(IllegalTokenTextCheck.class, + IllegalTokenTextCheck.MSG_KEY, "12345"), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathIllegalTokenTextField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='illegalNumber']]" + + "/ASSIGN/EXPR[./NUM_INT[@text='12345']]", + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathIllegalTokenTextField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='illegalNumber']]" + + "/ASSIGN/EXPR/NUM_INT[@text='12345']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalTokenTextMethod.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenTextCheck.class); + moduleConfig.addProperty("format", "forbiddenText"); + moduleConfig.addProperty("tokens", "STRING_LITERAL"); + final String[] expectedViolation = { + "5:32: " + getCheckMessage(IllegalTokenTextCheck.class, + IllegalTokenTextCheck.MSG_KEY, "forbiddenText"), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathIllegalTokenTextMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myMethod']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='illegalString']]" + + "/ASSIGN/EXPR[./STRING_LITERAL[@text='forbiddenText']]", + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathIllegalTokenTextMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myMethod']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='illegalString']]" + + "/ASSIGN/EXPR/STRING_LITERAL[@text='forbiddenText']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInterface() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalTokenTextInterface.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenTextCheck.class); + moduleConfig.addProperty("format", "invalidIdentifier"); + moduleConfig.addProperty("tokens", "IDENT"); + final String[] expectedViolation = { + "4:10: " + getCheckMessage(IllegalTokenTextCheck.class, + IllegalTokenTextCheck.MSG_KEY, "invalidIdentifier"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/INTERFACE_DEF[./IDENT[@text='InputXpathIllegalTokenTextInterface']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='invalidIdentifier']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTypeTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTypeTest.java new file mode 100644 index 000000000000..34621b962a9a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionIllegalTypeTest.java @@ -0,0 +1,91 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.IllegalTypeCheck; + +public class XpathRegressionIllegalTypeTest extends AbstractXpathTestSupport { + + private final String checkName = IllegalTypeCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/illegaltype"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalTypeOne.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTypeCheck.class); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + final String[] expectedViolation = { + "4:23: " + getCheckMessage(IllegalTypeCheck.class, + IllegalTypeCheck.MSG_KEY, "java.util.HashSet"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathIllegalTypeOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='typeParam']]/TYPE_PARAMETERS/TYPE_PARAMETER" + + "[./IDENT[@text='T']]/TYPE_UPPER_BOUNDS/DOT" + + "[./IDENT[@text='HashSet']]/DOT/IDENT[@text='java']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalTypeTwo.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTypeCheck.class); + + moduleConfig.addProperty("illegalClassNames", "Boolean"); + + final String[] expectedViolation = { + "6:20: " + getCheckMessage(IllegalTypeCheck.class, + IllegalTypeCheck.MSG_KEY, "Boolean"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathIllegalTypeTwo']" + + "]/OBJBLOCK/METHOD_DEF[./IDENT[@text='typeParam']]/TYPE_PARAMETERS/" + + "TYPE_PARAMETER[./IDENT[@text='T']]/TYPE_UPPER_BOUNDS/IDENT[@text='Boolean']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionInnerAssignmentTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionInnerAssignmentTest.java new file mode 100644 index 000000000000..a721813c148f --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionInnerAssignmentTest.java @@ -0,0 +1,93 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.InnerAssignmentCheck; + +public class XpathRegressionInnerAssignmentTest extends AbstractXpathTestSupport { + + private final String checkName = InnerAssignmentCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/innerassignment"; + } + + @Test + public void testInnerAssignment() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathInnerAssignment.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(InnerAssignmentCheck.class); + + final String[] expectedViolation = { + "7:15: " + getCheckMessage(InnerAssignmentCheck.class, InnerAssignmentCheck.MSG_KEY), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathInnerAssignment']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod']]" + + "/SLIST/EXPR/ASSIGN[./IDENT[@text='a']]/ASSIGN[./IDENT[@text='b']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testArrays() throws Exception { + final File fileToProcess = new + File(getPath("InputXpathInnerAssignmentArrays.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(InnerAssignmentCheck.class); + + final String[] expectedViolation = { + "6:55: " + getCheckMessage(InnerAssignmentCheck.class, InnerAssignmentCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathInnerAssignmentArrays']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='doubleArray']]" + + "/ASSIGN/EXPR/LITERAL_NEW/ARRAY_INIT/EXPR[./ASSIGN/IDENT[@text='myDouble']]", + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathInnerAssignmentArrays']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod']]/" + + "SLIST/VARIABLE_DEF[./IDENT[@text='doubleArray']]" + + "/ASSIGN/EXPR/LITERAL_NEW/ARRAY_INIT/EXPR/ASSIGN[./IDENT[@text='myDouble']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMagicNumberTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMagicNumberTest.java new file mode 100644 index 000000000000..805476f64f9b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMagicNumberTest.java @@ -0,0 +1,122 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.MagicNumberCheck; + +public class XpathRegressionMagicNumberTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return MagicNumberCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/magicnumber"; + } + + @Test + public void testVariable() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMagicNumberVariable.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MagicNumberCheck.class); + + final String[] expectedViolation = { + "5:13: " + getCheckMessage(MagicNumberCheck.class, MagicNumberCheck.MSG_KEY, "5"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMagicNumberVariable']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='d']]" + + "/ASSIGN/EXPR[./NUM_INT[@text='5']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMagicNumberVariable']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='d']]" + + "/ASSIGN/EXPR/NUM_INT[@text='5']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMethodDef() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMagicNumberMethodDef.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MagicNumberCheck.class); + + final String[] expectedViolation = { + "5:17: " + getCheckMessage(MagicNumberCheck.class, MagicNumberCheck.MSG_KEY, "20"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMagicNumberMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodWithMagicNumber']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='x']]/ASSIGN/EXPR[./" + + "NUM_INT[@text='20']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMagicNumberMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodWithMagicNumber']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='x']]/ASSIGN/EXPR/NU" + + "M_INT[@text='20']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testAnotherVariable() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMagicNumberAnotherVariable.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MagicNumberCheck.class); + + final String[] expectedViolation = { + "13:21: " + getCheckMessage(MagicNumberCheck.class, MagicNumberCheck.MSG_KEY, "20"), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMagicNumberAnotherVariable']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='performOperation']]" + + "/SLIST/LITERAL_TRY/LITERAL_CATCH/SLIST/LITERAL_IF" + + "/LITERAL_ELSE/SLIST/EXPR/ASSIGN" + + "[./IDENT[@text='a']]/NUM_INT[@text='20']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMatchXpathTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMatchXpathTest.java new file mode 100644 index 000000000000..3a1dc4ed9c7c --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMatchXpathTest.java @@ -0,0 +1,472 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenCheck; +import com.puppycrawl.tools.checkstyle.checks.coding.MatchXpathCheck; + +public class XpathRegressionMatchXpathTest extends AbstractXpathTestSupport { + + private final String checkName = MatchXpathCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/matchxpath"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MatchXpathCheck.class); + moduleConfig.addProperty("query", "//METHOD_DEF[./IDENT[@text='test']]"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(MatchXpathCheck.class, MatchXpathCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathMatchXpathOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathMatchXpathOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathMatchXpathOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MatchXpathCheck.class); + moduleConfig.addProperty("query", "//LITERAL_THROWS[./IDENT[@text='Throwable' or " + + "@text='RuntimeException' or ends-with(@text, 'Error')]]"); + + final String[] expectedViolation = { + "4:25: " + getCheckMessage(MatchXpathCheck.class, MatchXpathCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='func1']]" + + "/LITERAL_THROWS[./IDENT[@text='RuntimeException']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEncodedQuoteString() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedQuoteString.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "STRING_LITERAL"); + + final String[] expectedViolation = { + "4:24: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "\"\\\"testOne\\\"\""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedQuoteString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='quoteChar']]/ASSIGN/EXPR" + + "[./STRING_LITERAL[@text='\\"testOne\\"']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedQuoteString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='quoteChar']]/ASSIGN/EXPR" + + "/STRING_LITERAL[@text='\\"testOne\\"']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEncodedLessString() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedLessString.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "STRING_LITERAL"); + + final String[] expectedViolation = { + "4:23: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "\" expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedLessString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='lessChar']]/ASSIGN/EXPR" + + "[./STRING_LITERAL[@text='<testTwo']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedLessString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='lessChar']]/ASSIGN/EXPR/" + + "STRING_LITERAL[@text='<testTwo']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEncodedNewLineString() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedNewLineString.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "STRING_LITERAL"); + + final String[] expectedViolation = { + "4:26: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "\"testFive\\n\""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedNewLineString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='newLineChar']]/ASSIGN/EXPR" + + "[./STRING_LITERAL[@text='testFive\\n']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedNewLineString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='newLineChar']]/ASSIGN/EXPR" + + "/STRING_LITERAL[@text='testFive\\n']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testGreaterString() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedGreaterString.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "STRING_LITERAL"); + + final String[] expectedViolation = { + "4:26: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "\">testFour\""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedGreaterString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='greaterChar']]/ASSIGN/EXPR" + + "[./STRING_LITERAL[@text='>testFour']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedGreaterString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='greaterChar']]/ASSIGN/EXPR" + + "/STRING_LITERAL[@text='>testFour']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEncodedAmpString() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedAmpString.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "STRING_LITERAL"); + + final String[] expectedViolation = { + "4:28: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "\"&testThree\""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedAmpString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='ampersandChar']]/ASSIGN/EXPR" + + "[./STRING_LITERAL[@text='&testThree']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedAmpString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='ampersandChar']]/ASSIGN/EXPR" + + "/STRING_LITERAL[@text='&testThree']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEncodedAposString() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedAposString.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "STRING_LITERAL"); + + final String[] expectedViolation = { + "4:23: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "\"'SingleQuoteOnBothSide'\""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedAposString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='aposChar']]/ASSIGN/EXPR" + + "[./STRING_LITERAL[@text='''SingleQuoteOnBothSide''']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedAposString']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='aposChar']]/ASSIGN/EXPR" + + "/STRING_LITERAL[@text='''SingleQuoteOnBothSide''']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEncodedCarriageString() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedCarriageString.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "STRING_LITERAL"); + + final String[] expectedViolation = { + "4:27: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "\"carriageCharAtEnd\\r\""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedCarriageString" + + "']]/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='carriageChar']]/ASSIGN" + + "/EXPR[./STRING_LITERAL[@text='carriageCharAtEnd\\r']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedCarriageString" + + "']]/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='carriageChar']]/ASSIGN" + + "/EXPR/STRING_LITERAL[@text='carriageCharAtEnd\\r']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEncodedAmpersandChars() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedAmpChar.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "CHAR_LITERAL"); + + final String[] expectedViolationForAmpersand = { + "4:20: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "'&'"), + }; + + final List expectedXpathQueriesForAmpersand = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedAmpChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='ampChar']]/ASSIGN/EXPR" + + "[./CHAR_LITERAL[@text='''&''']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedAmpChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='ampChar']]/ASSIGN/EXPR" + + "/CHAR_LITERAL[@text='''&''']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolationForAmpersand, + expectedXpathQueriesForAmpersand); + } + + @Test + public void testEncodedQuoteChar() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedQuoteChar.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "CHAR_LITERAL"); + + final String[] expectedViolationsForQuote = { + "4:21: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "'\\\"'"), + }; + + final List expectedXpathQueriesForQuote = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedQuoteChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='quotChar']]/ASSIGN/EXPR" + + "[./CHAR_LITERAL[@text='''\\"''']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedQuoteChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='quotChar']]/ASSIGN/EXPR/" + + "CHAR_LITERAL[@text='''\\"''']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolationsForQuote, + expectedXpathQueriesForQuote); + } + + @Test + public void testEncodedLessChar() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedLessChar.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "CHAR_LITERAL"); + + final String[] expectedViolationsForLess = { + "4:21: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "'<'"), + }; + + final List expectedXpathQueriesForLess = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedLessChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='lessChar']]/ASSIGN/EXPR" + + "[./CHAR_LITERAL[@text='''<''']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedLessChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='lessChar']]/ASSIGN/EXPR/" + + "CHAR_LITERAL[@text='''<''']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolationsForLess, + expectedXpathQueriesForLess); + } + + @Test + public void testEncodedAposChar() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedAposChar.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "CHAR_LITERAL"); + + final String[] expectedViolationsForApos = { + "4:21: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "'\\''"), + }; + + final List expectedXpathQueriesForApos = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedAposChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='aposChar']]/ASSIGN/EXPR" + + "[./CHAR_LITERAL[@text='''\\''''']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMatchXpathEncodedAposChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='aposChar']]/ASSIGN/EXPR/" + + "CHAR_LITERAL[@text='''\\''''']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolationsForApos, + expectedXpathQueriesForApos); + } + + @Test + public void testEncodedGreaterChar() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathEncodedGreaterChar.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalTokenCheck.class); + moduleConfig.addProperty("tokens", "CHAR_LITERAL"); + + final String[] expectedViolationsForGreater = { + "4:24: " + getCheckMessage(IllegalTokenCheck.class, IllegalTokenCheck.MSG_KEY, + "'>'"), + }; + + final List expectedXpathQueriesForGreater = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='" + + "InputXpathMatchXpathEncodedGreaterChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='greaterChar']]/ASSIGN/EXPR" + + "[./CHAR_LITERAL[@text='''>''']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='" + + "InputXpathMatchXpathEncodedGreaterChar']]/" + + "OBJBLOCK/VARIABLE_DEF[./IDENT[@text='greaterChar']]/ASSIGN/EXPR/" + + "CHAR_LITERAL[@text='''>''']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolationsForGreater, + expectedXpathQueriesForGreater); + } + + @Test + public void testFollowing() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMatchXpathThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MatchXpathCheck.class); + moduleConfig.addProperty("query", + "//METHOD_DEF/following::*[1]"); + + final String[] expectedViolation = { + "5:1: " + getCheckMessage(MatchXpathCheck.class, MatchXpathCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathMatchXpathThree']]" + + "/OBJBLOCK/RCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingCtorTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingCtorTest.java new file mode 100644 index 000000000000..84a00851a68e --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingCtorTest.java @@ -0,0 +1,101 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.MissingCtorCheck; + +public class XpathRegressionMissingCtorTest extends AbstractXpathTestSupport { + + private final String checkName = MissingCtorCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/missingctor"; + } + + @Test + public void testMissingCtor() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingCtor.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingCtorCheck.class); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(MissingCtorCheck.class, + MissingCtorCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingCtor']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingCtor']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMissingCtor']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingCtorInner.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingCtorCheck.class); + + final String[] expectedViolation = { + "9:5: " + getCheckMessage(MissingCtorCheck.class, + MissingCtorCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMissingCtorInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMissingCtorInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMissingCtorInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingNullCaseInSwitchTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingNullCaseInSwitchTest.java new file mode 100644 index 000000000000..1eef0d322889 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingNullCaseInSwitchTest.java @@ -0,0 +1,94 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.MissingNullCaseInSwitchCheck; + +public class XpathRegressionMissingNullCaseInSwitchTest + extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return MissingNullCaseInSwitchCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/missingnullcaseinswitch"; + } + + @Test + public void testSimple() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathMissingNullCaseInSwitchSimple.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingNullCaseInSwitchCheck.class); + final String[] expectedViolation = { + "8:9: " + getCheckMessage(MissingNullCaseInSwitchCheck.class, + MissingNullCaseInSwitchCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingNullCaseInSwitchSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testNestedExpression() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMissingNullCaseInSwitchNested.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingNullCaseInSwitchCheck.class); + final String[] expectedViolation = { + "11:25: " + getCheckMessage(MissingNullCaseInSwitchCheck.class, + MissingNullCaseInSwitchCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingNullCaseInSwitchNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='x']]/ASSIGN/EXPR/LITERAL_SWITCH/SWITCH_RULE/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='y']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingNullCaseInSwitchNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='x']]/ASSIGN/EXPR/LITERAL_SWITCH" + + "/SWITCH_RULE/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='y']]/ASSIGN/EXPR/LITERAL_SWITCH" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingSwitchDefaultTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingSwitchDefaultTest.java new file mode 100644 index 000000000000..1ececbd46633 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMissingSwitchDefaultTest.java @@ -0,0 +1,92 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.MissingSwitchDefaultCheck; + +public class XpathRegressionMissingSwitchDefaultTest extends AbstractXpathTestSupport { + + private static final Class CLAZZ = MissingSwitchDefaultCheck.class; + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/missingswitchdefault"; + } + + @Test + public void testSimple() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMissingSwitchDefaultSimple.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + final String[] expectedViolation = { + "6:9: " + getCheckMessage(CLAZZ, MissingSwitchDefaultCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingSwitchDefaultSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test1']]" + + "/SLIST/LITERAL_SWITCH" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testNested() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMissingSwitchDefaultNested.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "12:17: " + getCheckMessage(CLAZZ, MissingSwitchDefaultCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingSwitchDefaultNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test2']]" + + "/SLIST/LITERAL_SWITCH/CASE_GROUP/SLIST", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingSwitchDefaultNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test2']]" + + "/SLIST/LITERAL_SWITCH/CASE_GROUP/SLIST/" + + "LITERAL_SWITCH" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionModifiedControlVariableTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionModifiedControlVariableTest.java new file mode 100644 index 000000000000..730e781fea37 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionModifiedControlVariableTest.java @@ -0,0 +1,183 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.ModifiedControlVariableCheck; + +public class XpathRegressionModifiedControlVariableTest extends AbstractXpathTestSupport { + private static final Class CLAZZ = + ModifiedControlVariableCheck.class; + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/modifiedcontrolvariable"; + } + + @Test + public void testDefaultForLoop() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifiedControlVariableWithFor.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + final String[] expectedViolation = { + "6:14: " + getCheckMessage(CLAZZ, + ModifiedControlVariableCheck.MSG_KEY, "i"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableWithFor']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_FOR/SLIST/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableWithFor']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_FOR/SLIST/EXPR/POST_INC[./IDENT[@text='i']]"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testDefaultForeach() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifiedControlVariableWithForeach.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + final String[] expectedViolation = { + "7:15: " + getCheckMessage(CLAZZ, + ModifiedControlVariableCheck.MSG_KEY, "s"), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableWithForeach']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_FOR/SLIST/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableWithForeach']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_FOR/SLIST/EXPR/PLUS_ASSIGN[./IDENT[@text='s']]" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testSkipEnhancedForLoop() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifiedControlVariableSkipEnhancedForLoop.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + moduleConfig.addProperty("skipEnhancedForLoopVariable", "true"); + final String[] expectedViolation = { + "10:14: " + getCheckMessage(CLAZZ, + ModifiedControlVariableCheck.MSG_KEY, "i"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableSkipEnhancedForLoop']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_FOR/SLIST/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableSkipEnhancedForLoop']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_FOR/SLIST/EXPR/POST_INC[./IDENT[@text='i']]" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testDefaultNestedForLoop() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifiedControlVariableNestedWithFor.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + final String[] expectedViolation = { + "7:19: " + getCheckMessage(CLAZZ, + ModifiedControlVariableCheck.MSG_KEY, "j"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableNestedWithFor']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_FOR/SLIST/LITERAL_FOR/SLIST/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableNestedWithFor']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_FOR/SLIST" + + "/LITERAL_FOR/SLIST/EXPR/STAR_ASSIGN[./IDENT[@text='j']]"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testForeachNested() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifiedControlVariableNestedWithForeach.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + final String[] expectedViolation = { + "8:19: " + getCheckMessage(CLAZZ, + ModifiedControlVariableCheck.MSG_KEY, "s"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableNestedWithForeach']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_FOR/SLIST/LITERAL_FOR/SLIST/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableNestedWithForeach']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_FOR/SLIST/LITERAL_FOR/SLIST/EXPR" + + "/PLUS_ASSIGN[./IDENT[@text='s']]"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testSkipEnhancedForLoopNested() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifiedControlVariableNestedSkipEnhancedForLoop.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + moduleConfig.addProperty("skipEnhancedForLoopVariable", "true"); + final String[] expectedViolation = { + "10:15: " + getCheckMessage(CLAZZ, + ModifiedControlVariableCheck.MSG_KEY, "i"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableNestedSkipEnhancedForLoop']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_FOR/SLIST/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathModifiedControlVariableNestedSkipEnhancedForLoop']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_FOR/SLIST/EXPR" + + "/PLUS_ASSIGN[./IDENT[@text='i']]"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMultipleStringLiteralsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMultipleStringLiteralsTest.java new file mode 100644 index 000000000000..4e9b41c0b63a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMultipleStringLiteralsTest.java @@ -0,0 +1,153 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import static com.puppycrawl.tools.checkstyle.checks.coding.MultipleStringLiteralsCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.MultipleStringLiteralsCheck; + +public class XpathRegressionMultipleStringLiteralsTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + + return MultipleStringLiteralsCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/multiplestringliterals"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMultipleStringLiteralsDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MultipleStringLiteralsCheck.class); + + final String[] expectedViolations = { + "4:16: " + getCheckMessage(MultipleStringLiteralsCheck.class, + MSG_KEY, "\"StringContents\"", 2), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMultipleStringLiteralsDefault']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a']]" + + "/ASSIGN/EXPR[./STRING_LITERAL[@text='StringContents']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMultipleStringLiteralsDefault']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a']]" + + "/ASSIGN/EXPR/STRING_LITERAL[@text='StringContents']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testAllowDuplicates() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMultipleStringLiteralsAllowDuplicates.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MultipleStringLiteralsCheck.class); + moduleConfig.addProperty("allowedDuplicates", "2"); + + final String[] expectedViolations = { + "8:19: " + getCheckMessage(MultipleStringLiteralsCheck.class, + MSG_KEY, "\", \"", 3), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMultipleStringLiteralsAllowDuplicates']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myTest']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='a5']]/ASSIGN/EXPR/PLUS[./STRING_LITERAL[@text=', ']]" + + "/PLUS/STRING_LITERAL[@text=', ']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testIgnoreRegexp() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMultipleStringLiteralsIgnoreRegexp.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MultipleStringLiteralsCheck.class); + moduleConfig.addProperty("ignoreStringsRegexp", "((\"\")|(\", \"))$"); + + final String[] expectedViolations = { + "7:19: " + getCheckMessage(MultipleStringLiteralsCheck.class, + MSG_KEY, "\"DoubleString\"", 2), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMultipleStringLiteralsIgnoreRegexp']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myTest']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='a3']]/ASSIGN/EXPR/PLUS/STRING_LITERAL[@text='DoubleString']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testIgnoreOccurrenceContext() throws Exception { + final String filePath = + "InputXpathMultipleStringLiteralsIgnoreOccurrenceContext.java"; + final File fileToProcess = new File(getPath(filePath)); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MultipleStringLiteralsCheck.class); + moduleConfig.addProperty("ignoreOccurrenceContext", ""); + + final String[] expectedViolations = { + "5:17: " + getCheckMessage(MultipleStringLiteralsCheck.class, + MSG_KEY, "\"unchecked\"", 3), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathMultipleStringLiteralsIgnoreOccurrenceContext']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a1']]" + + "/ASSIGN/EXPR[./STRING_LITERAL[@text='unchecked']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathMultipleStringLiteralsIgnoreOccurrenceContext']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a1']]" + + "/ASSIGN/EXPR/STRING_LITERAL[@text='unchecked']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMultipleVariableDeclarationsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMultipleVariableDeclarationsTest.java new file mode 100644 index 000000000000..3d90fa9f9d21 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionMultipleVariableDeclarationsTest.java @@ -0,0 +1,121 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.MultipleVariableDeclarationsCheck; + +public class XpathRegressionMultipleVariableDeclarationsTest extends AbstractXpathTestSupport { + + private final String checkName = MultipleVariableDeclarationsCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/multiplevariabledeclarations"; + } + + @Test + public void testCommaSeparator() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMultipleVariableDeclarationsCommaSeparator.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MultipleVariableDeclarationsCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(MultipleVariableDeclarationsCheck.class, + MultipleVariableDeclarationsCheck.MSG_MULTIPLE_COMMA), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarationsCommaSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='i']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarationsCommaSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='i']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarationsCommaSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='i']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarationsCommaSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='i']]/TYPE/LITERAL_INT", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarationsCommaSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='j']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarationsCommaSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='j']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarationsCommaSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='j']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarationsCommaSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='j']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMultipleVariableDeclarations() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMultipleVariableDeclarations.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MultipleVariableDeclarationsCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(MultipleVariableDeclarationsCheck.class, + MultipleVariableDeclarationsCheck.MSG_MULTIPLE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarations']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='i1']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarations']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='i1']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarations']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='i1']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMultipleVariableDeclarations']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='i1']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedForDepthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedForDepthTest.java new file mode 100644 index 000000000000..fd238e133244 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedForDepthTest.java @@ -0,0 +1,97 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.NestedForDepthCheck; + +public class XpathRegressionNestedForDepthTest extends AbstractXpathTestSupport { + + private final String checkName = NestedForDepthCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/nestedfordepth"; + } + + @Test + public void testCorrect() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNestedForDepth.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NestedForDepthCheck.class); + + final String[] expectedViolation = { + "7:17: " + getCheckMessage(NestedForDepthCheck.class, + NestedForDepthCheck.MSG_KEY, 2, 1), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNestedForDepth']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_FOR" + + "/SLIST/LITERAL_FOR/SLIST/LITERAL_FOR" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMax() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNestedForDepthMax.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NestedForDepthCheck.class); + moduleConfig.addProperty("max", "2"); + + final String[] expectedViolation = { + "8:21: " + getCheckMessage(NestedForDepthCheck.class, + NestedForDepthCheck.MSG_KEY, 3, 2), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNestedForDepthMax']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_FOR/" + + "SLIST/LITERAL_FOR/" + + "SLIST/LITERAL_FOR/" + + "SLIST/LITERAL_FOR" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedIfDepthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedIfDepthTest.java new file mode 100644 index 000000000000..9bbba374df0b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedIfDepthTest.java @@ -0,0 +1,98 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.NestedIfDepthCheck; + +public class XpathRegressionNestedIfDepthTest extends AbstractXpathTestSupport { + + private final String checkName = NestedIfDepthCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/nestedifdepth"; + } + + @Test + public void testCorrect() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNestedIfDepth.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NestedIfDepthCheck.class); + + final String[] expectedViolation = { + "10:17: " + getCheckMessage(NestedIfDepthCheck.class, + NestedIfDepthCheck.MSG_KEY, 2, 1), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNestedIfDepth']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF" + + "/SLIST/LITERAL_IF/SLIST/LITERAL_IF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMax() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNestedIfDepthMax.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NestedIfDepthCheck.class); + moduleConfig.addProperty("max", "3"); + + final String[] expectedViolation = { + "12:25: " + getCheckMessage(NestedIfDepthCheck.class, + NestedIfDepthCheck.MSG_KEY, 4, 3), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNestedIfDepthMax']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_IF/" + + "SLIST/LITERAL_IF/" + + "SLIST/LITERAL_IF/" + + "SLIST/LITERAL_IF/" + + "SLIST/LITERAL_IF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedTryDepthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedTryDepthTest.java new file mode 100644 index 000000000000..dca206e9df6e --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNestedTryDepthTest.java @@ -0,0 +1,98 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.NestedTryDepthCheck; + +public class XpathRegressionNestedTryDepthTest extends AbstractXpathTestSupport { + + private final String checkName = NestedTryDepthCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/nestedtrydepth"; + } + + @Test + public void testCorrect() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNestedTryDepth.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NestedTryDepthCheck.class); + + final String[] expectedViolation = { + "7:17: " + getCheckMessage(NestedTryDepthCheck.class, + NestedTryDepthCheck.MSG_KEY, 2, 1), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNestedTryDepth']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY/SLIST" + + "/LITERAL_TRY/SLIST/LITERAL_TRY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMax() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNestedTryDepthMax.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NestedTryDepthCheck.class); + moduleConfig.addProperty("max", "3"); + + final String[] expectedViolation = { + "9:25: " + getCheckMessage(NestedTryDepthCheck.class, + NestedTryDepthCheck.MSG_KEY, 4, 3), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNestedTryDepthMax']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_TRY" + + "/SLIST/LITERAL_TRY" + + "/SLIST/LITERAL_TRY" + + "/SLIST/LITERAL_TRY" + + "/SLIST/LITERAL_TRY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoArrayTrailingCommaTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoArrayTrailingCommaTest.java similarity index 76% rename from src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoArrayTrailingCommaTest.java rename to src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoArrayTrailingCommaTest.java index 0f2d27cb0b8e..3dca63c2866e 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoArrayTrailingCommaTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoArrayTrailingCommaTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,14 +15,15 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// -package org.checkstyle.suppressionxpathfilter; +package org.checkstyle.suppressionxpathfilter.coding; import java.io.File; import java.util.Collections; import java.util.List; +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; import org.junit.jupiter.api.Test; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -37,10 +38,15 @@ protected String getCheckName() { return checkName; } + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/noarraytrailingcomma"; + } + @Test public void testOne() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNoArrayTrailingCommaOne.java")); + new File(getPath("InputXpathNoArrayTrailingCommaOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(NoArrayTrailingCommaCheck.class); @@ -51,7 +57,8 @@ public void testOne() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNoArrayTrailingCommaOne']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathNoArrayTrailingCommaOne']]" + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='t1']]/ASSIGN/EXPR" + "/LITERAL_NEW/ARRAY_INIT/COMMA[4]" ); @@ -63,7 +70,7 @@ public void testOne() throws Exception { @Test public void testTwo() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionNoArrayTrailingCommaTwo.java")); + new File(getPath("InputXpathNoArrayTrailingCommaTwo.java")); final DefaultConfiguration moduleConfig = createModuleConfig(NoArrayTrailingCommaCheck.class); @@ -74,7 +81,8 @@ public void testTwo() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNoArrayTrailingCommaTwo']]" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoArrayTrailingCommaTwo']]" + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='t4']]" + "/ASSIGN/EXPR/LITERAL_NEW/ARRAY_INIT/COMMA" ); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoCloneTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoCloneTest.java new file mode 100644 index 000000000000..90839fc2d7f5 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoCloneTest.java @@ -0,0 +1,104 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.NoCloneCheck; + +public class XpathRegressionNoCloneTest extends AbstractXpathTestSupport { + + private final String checkName = NoCloneCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/noclone"; + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNoCloneMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoCloneCheck.class); + + final String[] expectedViolation = { + "5:5: " + getCheckMessage(NoCloneCheck.class, NoCloneCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoCloneMethod']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='clone']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoCloneMethod']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='clone']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoCloneMethod']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='clone']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNoCloneInnerClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoCloneCheck.class); + + final String[] expectedViolation = { + "6:5: " + getCheckMessage(NoCloneCheck.class, NoCloneCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathNoCloneInnerClass']]" + + "/OBJBLOCK" + + "/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='clone']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathNoCloneInnerClass']]" + + "/OBJBLOCK" + + "/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='clone']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathNoCloneInnerClass']]" + + "/OBJBLOCK" + + "/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='clone']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoEnumTrailingCommaTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoEnumTrailingCommaTest.java similarity index 76% rename from src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoEnumTrailingCommaTest.java rename to src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoEnumTrailingCommaTest.java index 93b044039480..6f15cc7f5e3f 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionNoEnumTrailingCommaTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoEnumTrailingCommaTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,14 +15,15 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// -package org.checkstyle.suppressionxpathfilter; +package org.checkstyle.suppressionxpathfilter.coding; import java.io.File; import java.util.Collections; import java.util.List; +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; import org.junit.jupiter.api.Test; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -37,10 +38,15 @@ protected String getCheckName() { return checkName; } + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/noenumtrailingcomma"; + } + @Test public void testOne() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionNoEnumTrailingCommaOne.java")); + "InputXpathNoEnumTrailingCommaOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(NoEnumTrailingCommaCheck.class); @@ -51,7 +57,8 @@ public void testOne() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNoEnumTrailingCommaOne']]" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoEnumTrailingCommaOne']]" + "/OBJBLOCK/ENUM_DEF[./IDENT[@text='Foo3']]/OBJBLOCK/COMMA[2]" ); @@ -61,7 +68,7 @@ public void testOne() throws Exception { @Test public void testTwo() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionNoEnumTrailingCommaTwo.java")); + "InputXpathNoEnumTrailingCommaTwo.java")); final DefaultConfiguration moduleConfig = createModuleConfig(NoEnumTrailingCommaCheck.class); @@ -72,7 +79,8 @@ public void testTwo() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionNoEnumTrailingCommaTwo']]" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoEnumTrailingCommaTwo']]" + "/OBJBLOCK/ENUM_DEF[./IDENT[@text='Foo6']]/OBJBLOCK/COMMA[2]" ); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoFinalizerTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoFinalizerTest.java new file mode 100644 index 000000000000..9b2a6545167a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionNoFinalizerTest.java @@ -0,0 +1,111 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.NoFinalizerCheck; + +public class XpathRegressionNoFinalizerTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return NoFinalizerCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/nofinalizer"; + } + + @Test + public void testMain() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathNoFinalizerMain.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoFinalizerCheck.class); + + final String[] expectedViolation = { + "8:5: " + getCheckMessage(NoFinalizerCheck.class, + NoFinalizerCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoFinalizerMain']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='finalize']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoFinalizerMain']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='finalize']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoFinalizerMain']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='finalize']]/MODIFIERS/LITERAL_PROTECTED" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInner() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathNoFinalizerInner.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoFinalizerCheck.class); + + final String[] expectedViolation = { + "10:9: " + getCheckMessage(NoFinalizerCheck.class, + NoFinalizerCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoFinalizerInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='finalize']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoFinalizerInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='finalize']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoFinalizerInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='finalize']]/MODIFIERS/" + + "ANNOTATION[./IDENT[@text='Override']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoFinalizerInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='finalize']]/MODIFIERS/" + + "ANNOTATION[./IDENT[@text='Override']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionOneStatementPerLineTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionOneStatementPerLineTest.java new file mode 100644 index 000000000000..20ab2851efe9 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionOneStatementPerLineTest.java @@ -0,0 +1,91 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.OneStatementPerLineCheck; + +public class XpathRegressionOneStatementPerLineTest extends AbstractXpathTestSupport { + + private final String checkName = OneStatementPerLineCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/onestatementperline"; + } + + @Test + public void testClassFields() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathOneStatementPerLineClassFields.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OneStatementPerLineCheck.class); + + final String[] expectedViolation = { + "4:17: " + getCheckMessage(OneStatementPerLineCheck.class, + OneStatementPerLineCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathOneStatementPerLineClassFields']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='j']]/SEMI" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testForLoopBlock() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathOneStatementPerLineForLoopBlock.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OneStatementPerLineCheck.class); + + final String[] expectedViolation = { + "9:39: " + getCheckMessage(OneStatementPerLineCheck.class, + OneStatementPerLineCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathOneStatementPerLineForLoopBlock']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='foo5']]/SLIST/LITERAL_FOR/SLIST/SEMI[2]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionOverloadMethodsDeclarationOrderTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionOverloadMethodsDeclarationOrderTest.java new file mode 100644 index 000000000000..7233e080c763 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionOverloadMethodsDeclarationOrderTest.java @@ -0,0 +1,109 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.OverloadMethodsDeclarationOrderCheck; + +public class XpathRegressionOverloadMethodsDeclarationOrderTest extends AbstractXpathTestSupport { + + private static final Class CLAZZ = + OverloadMethodsDeclarationOrderCheck.class; + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/overloadmethodsdeclarationorder"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathOverloadMethodsDeclarationOrderDefault.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "14:5: " + getCheckMessage(CLAZZ, + OverloadMethodsDeclarationOrderCheck.MSG_KEY, "5"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathOverloadMethodsDeclarationOrderDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='overloadMethod']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathOverloadMethodsDeclarationOrderDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='overloadMethod']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathOverloadMethodsDeclarationOrderDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='overloadMethod']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAnonymous() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathOverloadMethodsDeclarationOrderAnonymous.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "30:9: " + getCheckMessage(CLAZZ, + OverloadMethodsDeclarationOrderCheck.MSG_KEY, "21"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathOverloadMethodsDeclarationOrderAnonymous']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text=" + + "'MyInputXpathOverloadMethodsDeclarationOrderAnonymous']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='overloadMethod']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathOverloadMethodsDeclarationOrderAnonymous']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text=" + + "'MyInputXpathOverloadMethodsDeclarationOrderAnonymous']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='overloadMethod']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathOverloadMethodsDeclarationOrderAnonymous']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text=" + + "'MyInputXpathOverloadMethodsDeclarationOrderAnonymous']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='overloadMethod']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionPackageDeclarationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionPackageDeclarationTest.java new file mode 100644 index 000000000000..98a680bf42e3 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionPackageDeclarationTest.java @@ -0,0 +1,93 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.PackageDeclarationCheck; + +public class XpathRegressionPackageDeclarationTest extends AbstractXpathTestSupport { + + private final String checkName = PackageDeclarationCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/packagedeclaration"; + } + + @Test + public void testWrongPackage() throws Exception { + final File fileToProcess = + new File(getNonCompilablePath("InputXpathWrongPackage.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(PackageDeclarationCheck.class); + + final String[] expectedViolation = { + "2:1: " + getCheckMessage(PackageDeclarationCheck.class, + PackageDeclarationCheck.MSG_KEY_MISMATCH), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMissingPackage() throws Exception { + final File fileToProcess = + new File(getNonCompilablePath("InputXpathMissingPackage.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(PackageDeclarationCheck.class); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(PackageDeclarationCheck.class, + PackageDeclarationCheck.MSG_KEY_MISSING), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathMissingPackage']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingPackage']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingPackage']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionParameterAssignmentTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionParameterAssignmentTest.java new file mode 100644 index 000000000000..e2bc0731ff58 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionParameterAssignmentTest.java @@ -0,0 +1,130 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import static com.puppycrawl.tools.checkstyle.checks.coding.ParameterAssignmentCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.ParameterAssignmentCheck; + +public class XpathRegressionParameterAssignmentTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return ParameterAssignmentCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/parameterassignment"; + } + + @Test + public void testMethods() throws Exception { + final String filePath = + getPath("InputXpathParameterAssignmentMethods.java"); + final File fileToProcess = new File(filePath); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ParameterAssignmentCheck.class); + + final String[] expectedViolations = { + "9:15: " + getCheckMessage(ParameterAssignmentCheck.class, MSG_KEY, "field"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathParameterAssignmentMethods']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='Test1']]/SLIST/EXPR" + + "[./PLUS_ASSIGN/IDENT[@text='field']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathParameterAssignmentMethods']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='Test1']]" + + "/SLIST/EXPR/PLUS_ASSIGN[./IDENT[@text='field']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + + } + + @Test + public void testLambdas() throws Exception { + final String filePath = + getPath("InputXpathParameterAssignmentLambdas.java"); + final File fileToProcess = new File(filePath); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ParameterAssignmentCheck.class); + + final String[] expectedViolations = { + "9:32: " + getCheckMessage(ParameterAssignmentCheck.class, MSG_KEY, "q"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathParameterAssignmentLambdas']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='obj1']]" + + "/ASSIGN/LAMBDA[./IDENT[@text='q']]/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathParameterAssignmentLambdas']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='obj1']]/ASSIGN/LAMBDA[./IDENT[" + + "@text='q']]/EXPR/POST_INC[./IDENT[@text='q']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testCtor() throws Exception { + final String filePath = + getPath("InputXpathParameterAssignmentCtor.java"); + final File fileToProcess = new File(filePath); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ParameterAssignmentCheck.class); + + final String[] expectedViolations = { + "9:15: " + getCheckMessage(ParameterAssignmentCheck.class, MSG_KEY, "field"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathParameterAssignmentCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathParameterAssignmentCtor']]" + + "/SLIST/EXPR[./PLUS_ASSIGN/IDENT[@text='field']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathParameterAssignmentCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathParameterAssignmentCtor']]" + + "/SLIST/EXPR/PLUS_ASSIGN[./IDENT[@text='field']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionPatternVariableAssignmentTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionPatternVariableAssignmentTest.java new file mode 100644 index 000000000000..80180c1024d7 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionPatternVariableAssignmentTest.java @@ -0,0 +1,116 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.PatternVariableAssignmentCheck; + +public class XpathRegressionPatternVariableAssignmentTest extends AbstractXpathTestSupport { + private final String checkName = PatternVariableAssignmentCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/patternvariableassignment"; + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathPatternVariableAssignmentMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(PatternVariableAssignmentCheck.class); + + final String[] expectedViolation = { + "8:7: " + getCheckMessage(PatternVariableAssignmentCheck.class, + PatternVariableAssignmentCheck.MSG_KEY, + "s"), + }; + + final List expectedXpathQueries = List.of("/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathPatternVariableAssignmentMethod']]/OBJBLOCK/METHOD_DEF[" + + "./IDENT[@text='test']]/SLIST/LITERAL_IF/SLIST/EXPR/ASSIGN/IDENT[@text='s']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testLambda() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathPatternVariableAssignmentLambda.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(PatternVariableAssignmentCheck.class); + + final String[] expectedViolation = { + "12:17: " + getCheckMessage(PatternVariableAssignmentCheck.class, + PatternVariableAssignmentCheck.MSG_KEY, + "x"), + }; + + final List expectedXpathQueries = List.of("/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathPatternVariableAssignmentLambda']]/OBJBLOCK/METHOD_DEF[" + + "./IDENT[@text='foo']]/SLIST/EXPR/METHOD_CALL/ELIST/LAMBDA[" + + "./IDENT[@text='item']]/SLIST/LITERAL_IF/SLIST/EXPR/ASSIGN/IDENT[@text='x']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testClass() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathPatternVariableAssignmentClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(PatternVariableAssignmentCheck.class); + + final String[] expectedViolation = { + "10:21: " + getCheckMessage(PatternVariableAssignmentCheck.class, + PatternVariableAssignmentCheck.MSG_KEY, + "x"), + }; + + final List expectedXpathQueries = List.of("/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathPatternVariableAssignmentClass']]/OBJBLOCK/METHOD_DEF[" + + "./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[./IDENT[@text='annClass']]/ASSIGN/EXPR/" + + "LITERAL_NEW[./IDENT[@text='AnonymousClass']]/OBJBLOCK/METHOD_DEF[" + + "./IDENT[@text='test']]/SLIST/LITERAL_IF/SLIST/EXPR/ASSIGN/IDENT[@text='x']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionRequireThisTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionRequireThisTest.java new file mode 100644 index 000000000000..2aac78420fd2 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionRequireThisTest.java @@ -0,0 +1,95 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck; + +public class XpathRegressionRequireThisTest extends AbstractXpathTestSupport { + + private final String checkName = RequireThisCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/requirethis"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRequireThisOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RequireThisCheck.class); + moduleConfig.addProperty("validateOnlyOverlapping", "false"); + + final String[] expectedViolation = { + "7:9: " + getCheckMessage(RequireThisCheck.class, + RequireThisCheck.MSG_VARIABLE, "age", ""), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRequireThisOne']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='changeAge']]/SLIST/EXPR/ASSIGN" + + "/IDENT[@text='age']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRequireThisTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RequireThisCheck.class); + moduleConfig.addProperty("validateOnlyOverlapping", "false"); + + final String[] expectedViolation = { + "9:9: " + getCheckMessage(RequireThisCheck.class, + RequireThisCheck.MSG_METHOD, "method1", ""), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRequireThisTwo']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method2']]/SLIST/EXPR" + + "/METHOD_CALL/IDENT[@text='method1']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionReturnCountTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionReturnCountTest.java new file mode 100644 index 000000000000..a0c20a3b68bf --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionReturnCountTest.java @@ -0,0 +1,230 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck; + +public class XpathRegressionReturnCountTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return ReturnCountCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/returncount"; + } + + @Test + public void testVoid() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathReturnCountVoid.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ReturnCountCheck.class); + + final String[] expectedViolation = { + "16:5: " + getCheckMessage(ReturnCountCheck.class, + ReturnCountCheck.MSG_KEY_VOID, 5, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testVoid']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testVoid']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testVoid']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testVoid']]/TYPE/LITERAL_VOID" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testCustomMaxForVoid() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathReturnCountVoid.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ReturnCountCheck.class); + + moduleConfig.addProperty("maxForVoid", "3"); + + final String[] expectedViolation = { + "16:5: " + getCheckMessage(ReturnCountCheck.class, + ReturnCountCheck.MSG_KEY_VOID, 5, 3), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testVoid']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testVoid']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testVoid']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testVoid']]/TYPE/LITERAL_VOID" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testNonVoid() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathReturnCountNonVoid.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ReturnCountCheck.class); + + final String[] expectedViolation = { + "16:5: " + getCheckMessage(ReturnCountCheck.class, + ReturnCountCheck.MSG_KEY, 4, 2), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountNonVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testNonVoid']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountNonVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testNonVoid']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountNonVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testNonVoid']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountNonVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testNonVoid']]/TYPE/LITERAL_BOOLEAN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testCustomMax() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathReturnCountNonVoid.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ReturnCountCheck.class); + + moduleConfig.addProperty("max", "3"); + + final String[] expectedViolation = { + "16:5: " + getCheckMessage(ReturnCountCheck.class, + ReturnCountCheck.MSG_KEY, 4, 3), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountNonVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testNonVoid']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountNonVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testNonVoid']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountNonVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testNonVoid']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountNonVoid']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testNonVoid']]/TYPE/LITERAL_BOOLEAN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testCtor() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathReturnCountCtor.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ReturnCountCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(ReturnCountCheck.class, + ReturnCountCheck.MSG_KEY_VOID, 5, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[@text='InputXpathReturnCountCtor']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountCtor']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[@text='InputXpathReturnCountCtor']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountCtor']]" + + "/OBJBLOCK/CTOR_DEF/IDENT[@text='InputXpathReturnCountCtor']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testLambda() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathReturnCountLambda.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ReturnCountCheck.class); + + final String[] expectedViolation = { + "7:42: " + getCheckMessage(ReturnCountCheck.class, + ReturnCountCheck.MSG_KEY, 4, 2), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathReturnCountLambda']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testLambda']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='a']]/ASSIGN/LAMBDA[./IDENT[@text='i']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} + diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSimplifyBooleanExpressionTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSimplifyBooleanExpressionTest.java new file mode 100644 index 000000000000..c90235cb37cd --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSimplifyBooleanExpressionTest.java @@ -0,0 +1,120 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import static com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanExpressionCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanExpressionCheck; + +public class XpathRegressionSimplifyBooleanExpressionTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return SimplifyBooleanExpressionCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/simplifybooleanexpression"; + } + + @Test + public void testSimple() throws Exception { + final String fileName = "InputXpathSimplifyBooleanExpressionSimple.java"; + final File fileToProcess = new File(getPath(fileName)); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SimplifyBooleanExpressionCheck.class); + + final String[] expectedViolations = { + "8:13: " + getCheckMessage(SimplifyBooleanExpressionCheck.class, MSG_KEY), + }; + + final List expectedXpathQuery = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSimplifyBooleanExpressionSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSimplifyBooleanExpressionSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF/EXPR/LNOT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQuery); + } + + @Test + public void testAnonymous() throws Exception { + final String fileName = + "InputXpathSimplifyBooleanExpressionAnonymous.java"; + final File fileToProcess = new File(getPath(fileName)); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SimplifyBooleanExpressionCheck.class); + + final String[] expectedViolations = { + "8:19: " + getCheckMessage(SimplifyBooleanExpressionCheck.class, MSG_KEY), + }; + + final List expectedXpathQuery = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSimplifyBooleanExpressionAnonymous']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]/SLIST/LITERAL_IF/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSimplifyBooleanExpressionAnonymous']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]/SLIST/LITERAL_IF/EXPR/EQUAL[./IDENT[@text='a']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQuery); + } + + @Test + public void testInterface() throws Exception { + final String fileName = + "InputXpathSimplifyBooleanExpressionInterface.java"; + final File fileToProcess = new File(getPath(fileName)); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SimplifyBooleanExpressionCheck.class); + + final String[] expectedViolations = { + "7:20: " + getCheckMessage(SimplifyBooleanExpressionCheck.class, MSG_KEY), + }; + + final List expectedXpathQuery = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSimplifyBooleanExpressionInterface']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Inner']]/OBJBLOCK/METHOD_DEF[./IDENT" + + "[@text='test']]/SLIST/LITERAL_IF/EXPR/LNOT/NOT_EQUAL[./IDENT[@text='b']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQuery); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSimplifyBooleanReturnTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSimplifyBooleanReturnTest.java new file mode 100644 index 000000000000..9373ae300e01 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSimplifyBooleanReturnTest.java @@ -0,0 +1,94 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import static com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanReturnCheck.MSG_KEY; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.SimplifyBooleanReturnCheck; + +public class XpathRegressionSimplifyBooleanReturnTest extends AbstractXpathTestSupport { + + private static final Class CLASS = SimplifyBooleanReturnCheck.class; + private final String checkName = CLASS.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/simplifybooleanreturn"; + } + + @Test + public void testIfBooleanEqualsBoolean() throws Exception { + final File fileToProcess = new File( + getPath( + "InputXpathSimplifyBooleanReturnIfBooleanEqualsBoolean.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(CLASS, MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathSimplifyBooleanReturnIfBooleanEqualsBoolean']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='toTest']]/SLIST/LITERAL_IF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testIfBooleanReturnBoolean() throws Exception { + final File fileToProcess = new File( + getPath( + "InputXpathSimplifyBooleanReturnIfBooleanReturnBoolean.java" + )); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + + final String[] expectedViolation = { + "11:13: " + getCheckMessage(CLASS, MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathSimplifyBooleanReturnIfBooleanReturnBoolean']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='toTest']]/SLIST/EXPR/METHOD_CALL/ELIST" + + "/LAMBDA[./IDENT[@text='statement']]/SLIST/LITERAL_IF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionStringLiteralEqualityTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionStringLiteralEqualityTest.java new file mode 100644 index 000000000000..fee56e2bfb2f --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionStringLiteralEqualityTest.java @@ -0,0 +1,121 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.StringLiteralEqualityCheck; + +public class XpathRegressionStringLiteralEqualityTest extends AbstractXpathTestSupport { + + private final String checkName = StringLiteralEqualityCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/stringliteralequality"; + } + + @Test + public void testEqualityTrue() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathStringLiteralEqualityTrue.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(StringLiteralEqualityCheck.class); + final String[] expectedViolation = { + "6:17: " + getCheckMessage(StringLiteralEqualityCheck.class, + StringLiteralEqualityCheck.MSG_KEY, "=="), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathStringLiteralEqualityTrue']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myFunction']]" + + "/SLIST/LITERAL_IF/EXPR", + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathStringLiteralEqualityTrue']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myFunction']]" + + "/SLIST/LITERAL_IF/EXPR/EQUAL[./IDENT[@text='foo']]" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEqualityFalse() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathStringLiteralEqualityFalse.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(StringLiteralEqualityCheck.class); + final String[] expectedViolation = { + "6:20: " + getCheckMessage(StringLiteralEqualityCheck.class, + StringLiteralEqualityCheck.MSG_KEY, "!="), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathStringLiteralEqualityFalse']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myFunction']]" + + "/SLIST/LITERAL_WHILE/EXPR", + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathStringLiteralEqualityFalse']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myFunction']]" + + "/SLIST/LITERAL_WHILE/EXPR/NOT_EQUAL[./IDENT[@text='foo']]" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEqualityExp() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathStringLiteralEqualityExp.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(StringLiteralEqualityCheck.class); + final String[] expectedViolation = { + "6:29: " + getCheckMessage(StringLiteralEqualityCheck.class, + StringLiteralEqualityCheck.MSG_KEY, "=="), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathStringLiteralEqualityExp']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myFunction']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='flag']]" + + "/ASSIGN/EXPR/EQUAL[./IDENT[@text='foo']]" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSuperCloneTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSuperCloneTest.java new file mode 100644 index 000000000000..9b4ccf043446 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSuperCloneTest.java @@ -0,0 +1,112 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.AbstractSuperCheck; +import com.puppycrawl.tools.checkstyle.checks.coding.SuperCloneCheck; + +public class XpathRegressionSuperCloneTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return SuperCloneCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/superclone"; + } + + @Test + public void testInnerClone() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSuperCloneInnerClone.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SuperCloneCheck.class); + + final String[] expectedViolation = { + "6:23: " + getCheckMessage(SuperCloneCheck.class, AbstractSuperCheck.MSG_KEY, "clone"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathSuperCloneInnerClone']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClone']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='clone']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNoSuperClone() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSuperCloneNoSuperClone.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SuperCloneCheck.class); + + final String[] expectedViolation = { + "6:23: " + getCheckMessage(SuperCloneCheck.class, AbstractSuperCheck.MSG_KEY, "clone"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathSuperCloneNoSuperClone']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='NoSuperClone']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='clone']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testPlainAndSubclasses() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSuperClonePlainAndSubclasses.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SuperCloneCheck.class); + + final String[] expectedViolation = { + "4:19: " + getCheckMessage(SuperCloneCheck.class, AbstractSuperCheck.MSG_KEY, "clone"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathSuperClonePlainAndSubclasses']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='clone']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSuperFinalizeTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSuperFinalizeTest.java new file mode 100644 index 000000000000..06f6948cb047 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionSuperFinalizeTest.java @@ -0,0 +1,105 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.AbstractSuperCheck; +import com.puppycrawl.tools.checkstyle.checks.coding.SuperFinalizeCheck; + +public class XpathRegressionSuperFinalizeTest extends AbstractXpathTestSupport { + + private final String checkName = SuperFinalizeCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/superfinalize"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File(getPath("InputXpathSuperFinalizeNoFinalize.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(SuperFinalizeCheck.class); + + final String[] expectedViolation = { + "4:17: " + getCheckMessage(SuperFinalizeCheck.class, + AbstractSuperCheck.MSG_KEY, "finalize"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathSuperFinalizeNoFinalize']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='finalize']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSuperFinalizeInnerClass.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(SuperFinalizeCheck.class); + + final String[] expectedViolation = { + "5:17: " + getCheckMessage(SuperFinalizeCheck.class, + AbstractSuperCheck.MSG_KEY, "finalize"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathSuperFinalizeInnerClass']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='finalize']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAnonymousClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSuperFinalizeAnonymousClass.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(SuperFinalizeCheck.class); + + final String[] expectedViolation = { + "9:28: " + getCheckMessage(SuperFinalizeCheck.class, + AbstractSuperCheck.MSG_KEY, "finalize"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathSuperFinalizeAnonymousClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='createAnonymousClass']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='anonymousClassObject']]" + + "/ASSIGN/EXPR/LITERAL_NEW[./IDENT[@text='Object']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='finalize']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessaryNullCheckWithInstanceOfTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessaryNullCheckWithInstanceOfTest.java new file mode 100644 index 000000000000..6975fe3ae96a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessaryNullCheckWithInstanceOfTest.java @@ -0,0 +1,112 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryNullCheckWithInstanceOfCheck; + +public class XpathRegressionUnnecessaryNullCheckWithInstanceOfTest + extends AbstractXpathTestSupport { + + private final String checkName = UnnecessaryNullCheckWithInstanceOfCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/unnecessarynullcheckwithinstanceof"; + } + + @Test + public void test1() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathUnnecessaryNullCheckWithInstanceOf.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryNullCheckWithInstanceOfCheck.class); + + final String[] expected = { + "5:13: " + getCheckMessage(UnnecessaryNullCheckWithInstanceOfCheck.class, + UnnecessaryNullCheckWithInstanceOfCheck.MSG_UNNECESSARY_NULLCHECK), + }; + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathUnnecessaryNullCheckWithInstanceOf']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodWithUnnecessaryNullCheck1']]" + + "/SLIST/LITERAL_IF/EXPR/LAND/NOT_EQUAL/IDENT[@text='obj']" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + } + + @Test + public void test2() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathUnnecessaryNullCheckWithInstanceOfAnonymous.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryNullCheckWithInstanceOfCheck.class); + + final String[] expected = { + "8:17: " + getCheckMessage(UnnecessaryNullCheckWithInstanceOfCheck.class, + UnnecessaryNullCheckWithInstanceOfCheck.MSG_UNNECESSARY_NULLCHECK), + }; + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathUnnecessaryNullCheckWithInstanceOfAnonymous']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='runnable']]/ASSIGN/EXPR/LITERAL_NEW" + + "[./IDENT[@text='Runnable']]/OBJBLOCK/METHOD_DEF[./IDENT[@text='run']]" + + "/SLIST/LITERAL_IF/EXPR/LAND/NOT_EQUAL/IDENT[@text='obj']" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + } + + @Test + public void test3() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathUnnecessaryNullCheckWithInstanceOfInterface.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryNullCheckWithInstanceOfCheck.class); + + final String[] expected = { + "6:16: " + getCheckMessage(UnnecessaryNullCheckWithInstanceOfCheck.class, + UnnecessaryNullCheckWithInstanceOfCheck.MSG_UNNECESSARY_NULLCHECK), + }; + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathUnnecessaryNullCheckWithInstanceOfInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='validateString']]/SLIST/LITERAL_RETURN" + + "/EXPR/LAND/NOT_EQUAL/IDENT[@text='obj']" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + } +} + diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessaryParenthesesTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessaryParenthesesTest.java new file mode 100644 index 000000000000..7f1acca7c493 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessaryParenthesesTest.java @@ -0,0 +1,261 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessaryParenthesesCheck; + +public class XpathRegressionUnnecessaryParenthesesTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return UnnecessaryParenthesesCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/unnecessaryparentheses"; + } + + @Test + public void testClassFields() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessaryParenthesesClassFields.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryParenthesesCheck.class); + + final String[] expectedViolation = { + "4:13: " + getCheckMessage(UnnecessaryParenthesesCheck.class, + UnnecessaryParenthesesCheck.MSG_ASSIGN), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesClassFields']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a']]" + + "/ASSIGN/EXPR", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesClassFields']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a']]" + + "/ASSIGN/EXPR/LPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testConditionals() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessaryParenthesesConditionals.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryParenthesesCheck.class); + + final String[] expectedViolation = { + "5:13: " + getCheckMessage(UnnecessaryParenthesesCheck.class, + UnnecessaryParenthesesCheck.MSG_EXPR), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesConditionals']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/LITERAL_IF/EXPR", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesConditionals']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/LITERAL_IF/EXPR/LPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testLambdas() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessaryParenthesesLambdas.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryParenthesesCheck.class); + + final String[] expectedViolation = { + "7:35: " + getCheckMessage(UnnecessaryParenthesesCheck.class, + UnnecessaryParenthesesCheck.MSG_LAMBDA), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesLambdas']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='predicate']]" + + "/ASSIGN/LAMBDA" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testLocalVariables() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessaryParenthesesLocalVariables.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryParenthesesCheck.class); + + final String[] expectedViolation = { + "5:18: " + getCheckMessage(UnnecessaryParenthesesCheck.class, + UnnecessaryParenthesesCheck.MSG_IDENT, "a"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesLocalVariables']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='b']]" + + "/ASSIGN/EXPR/PLUS/IDENT[@text='a']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testStringLiteral() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessaryParenthesesStringLiteral.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryParenthesesCheck.class); + + final String[] expectedViolation = { + "5:23: " + getCheckMessage(UnnecessaryParenthesesCheck.class, + UnnecessaryParenthesesCheck.MSG_STRING, "\"Checkstyle\""), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesStringLiteral']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='str']]" + + "/ASSIGN/EXPR/PLUS/STRING_LITERAL[@text='Checkstyle']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testMethodDef() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessaryParenthesesMethodDef.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryParenthesesCheck.class); + + final String[] expectedViolation = { + "5:18: " + getCheckMessage(UnnecessaryParenthesesCheck.class, + UnnecessaryParenthesesCheck.MSG_LITERAL, "10"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='a']]" + + "/ASSIGN/EXPR/PLUS/NUM_INT[@text='10']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testReturnExpr() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessaryParenthesesReturnExpr.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryParenthesesCheck.class); + + final String[] expectedViolation = { + "5:16: " + getCheckMessage(UnnecessaryParenthesesCheck.class, + UnnecessaryParenthesesCheck.MSG_RETURN), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesReturnExpr']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/LITERAL_RETURN/EXPR", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesReturnExpr']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/LITERAL_RETURN/EXPR/LPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testExprWithMethodParam() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessaryParenthesesExprWithMethodParam.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessaryParenthesesCheck.class); + + final String[] expectedViolation = { + "5:17: " + getCheckMessage(UnnecessaryParenthesesCheck.class, + UnnecessaryParenthesesCheck.MSG_ASSIGN), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesExprWithMethodParam']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='c']]" + + "/ASSIGN/EXPR", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnnecessaryParenthesesExprWithMethodParam']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='c']]" + + "/ASSIGN/EXPR/LPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonAfterOuterTypeDeclarationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonAfterOuterTypeDeclarationTest.java new file mode 100644 index 000000000000..28de91bba700 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonAfterOuterTypeDeclarationTest.java @@ -0,0 +1,81 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonAfterOuterTypeDeclarationCheck; + +public class XpathRegressionUnnecessarySemicolonAfterOuterTypeDeclarationTest + extends AbstractXpathTestSupport { + + private static final Class CLASS = + UnnecessarySemicolonAfterOuterTypeDeclarationCheck.class; + + @Override + protected String getCheckName() { + return CLASS.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/" + + "unnecessarysemicolonafteroutertypedeclaration"; + } + + @Test + public void testSimple() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathUnnecessarySemicolonAfterOuterTypeDeclarationSimple.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + final String[] expectedViolation = { + "5:2: " + getCheckMessage(CLASS, + UnnecessarySemicolonAfterOuterTypeDeclarationCheck.MSG_SEMI), + }; + + final List expectedXpathQueries = + Collections.singletonList("/COMPILATION_UNIT/SEMI"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInnerTypes() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathUnnecessarySemicolonAfterOuterTypeDeclarationInnerTypes" + + ".java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + final String[] expectedViolation = { + "21:2: " + getCheckMessage(CLASS, + UnnecessarySemicolonAfterOuterTypeDeclarationCheck.MSG_SEMI), + }; + + final List expectedXpathQueries = + Collections.singletonList("/COMPILATION_UNIT/SEMI"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonAfterTypeMemberDeclarationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonAfterTypeMemberDeclarationTest.java new file mode 100644 index 000000000000..ef7c5e5ea841 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonAfterTypeMemberDeclarationTest.java @@ -0,0 +1,91 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonAfterTypeMemberDeclarationCheck; + +public class XpathRegressionUnnecessarySemicolonAfterTypeMemberDeclarationTest + extends AbstractXpathTestSupport { + + private static final Class CLASS = + UnnecessarySemicolonAfterTypeMemberDeclarationCheck.class; + + @Override + protected String getCheckName() { + return CLASS.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/" + + "unnecessarysemicolonaftertypememberdeclaration"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathUnnecessarySemicolonAfterTypeMemberDeclarationDefault.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + final String[] expectedViolation = { + "4:20: " + getCheckMessage(CLASS, + UnnecessarySemicolonAfterTypeMemberDeclarationCheck.MSG_SEMI), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text=" + + "'InputXpathUnnecessarySemicolonAfterTypeMemberDeclarationDefault']]" + + "/OBJBLOCK/SEMI" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testTokens() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathUnnecessarySemicolonAfterTypeMemberDeclarationTokens" + + ".java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expectedViolation = { + "4:21: " + getCheckMessage(CLASS, + UnnecessarySemicolonAfterTypeMemberDeclarationCheck.MSG_SEMI), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text='InputXpathUnnecessarySemicolonAfterTypeMember" + + "DeclarationTokens']]" + + "/OBJBLOCK/SEMI[1]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonInEnumerationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonInEnumerationTest.java new file mode 100644 index 000000000000..a0354bd0f5d8 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonInEnumerationTest.java @@ -0,0 +1,90 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInEnumerationCheck; + +public class XpathRegressionUnnecessarySemicolonInEnumerationTest + extends AbstractXpathTestSupport { + + private final String checkName = + UnnecessarySemicolonInEnumerationCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/unnecessarysemicoloninenumeration"; + } + + @Test + public void testSimple() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessarySemicolonInEnumerationSimple.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessarySemicolonInEnumerationCheck.class); + + final String[] expectedViolation = { + "11:10: " + getCheckMessage(UnnecessarySemicolonInEnumerationCheck.class, + UnnecessarySemicolonInEnumerationCheck.MSG_SEMI), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/ENUM_DEF[./IDENT[@text='Bad']]/OBJBLOCK/SEMI" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAll() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathUnnecessarySemicolonInEnumerationAll.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessarySemicolonInEnumerationCheck.class); + + final String[] expectedViolation = { + "4:52: " + getCheckMessage(UnnecessarySemicolonInEnumerationCheck.class, + UnnecessarySemicolonInEnumerationCheck.MSG_SEMI), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/ENUM_DEF[./IDENT[@text=" + + "'InputXpathUnnecessarySemicolonInEnumerationAll']]" + + "/OBJBLOCK/SEMI" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonInTryWithResourcesTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonInTryWithResourcesTest.java new file mode 100644 index 000000000000..0a526fce3bfe --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnnecessarySemicolonInTryWithResourcesTest.java @@ -0,0 +1,91 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnnecessarySemicolonInTryWithResourcesCheck; + +public class XpathRegressionUnnecessarySemicolonInTryWithResourcesTest + extends AbstractXpathTestSupport { + + private final String checkName = + UnnecessarySemicolonInTryWithResourcesCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/" + + "unnecessarysemicolonintrywithresources"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathUnnecessarySemicolonInTryWithResourcesDefault.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessarySemicolonInTryWithResourcesCheck.class); + final String[] expectedViolation = { + "11:76: " + getCheckMessage(UnnecessarySemicolonInTryWithResourcesCheck.class, + UnnecessarySemicolonInTryWithResourcesCheck.MSG_SEMI), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathUnnecessarySemicolonInTryWithResourcesDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='m']]/SLIST/LITERAL_TRY" + + "/RESOURCE_SPECIFICATION/SEMI" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testNoBrace() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathUnnecessarySemicolonInTryWithResourcesNoBrace.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnnecessarySemicolonInTryWithResourcesCheck.class); + moduleConfig.addProperty("allowWhenNoBraceAfterSemicolon", "false"); + + final String[] expectedViolation = { + "8:44: " + getCheckMessage(UnnecessarySemicolonInTryWithResourcesCheck.class, + UnnecessarySemicolonInTryWithResourcesCheck.MSG_SEMI), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathUnnecessarySemicolonInTryWithResourcesNoBrace']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/LITERAL_TRY/RESOURCE_SPECIFICATION/SEMI" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedCatchParameterShouldBeUnnamedTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedCatchParameterShouldBeUnnamedTest.java new file mode 100644 index 000000000000..a38b81dbddc1 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedCatchParameterShouldBeUnnamedTest.java @@ -0,0 +1,128 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnusedCatchParameterShouldBeUnnamedCheck; + +public class XpathRegressionUnusedCatchParameterShouldBeUnnamedTest + extends AbstractXpathTestSupport { + + private final String checkName = UnusedCatchParameterShouldBeUnnamedCheck.class + .getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/unusedcatchparametershouldbeunnamed"; + } + + @Test + public void testSimple() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathUnusedCatchParameterShouldBeUnnamedSimple.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnusedCatchParameterShouldBeUnnamedCheck.class); + + final String[] expectedViolation = { + "10:16: " + getCheckMessage(UnusedCatchParameterShouldBeUnnamedCheck.class, + UnusedCatchParameterShouldBeUnnamedCheck.MSG_UNUSED_CATCH_PARAMETER, + "e"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathUnusedCatchParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY/" + + "LITERAL_CATCH/PARAMETER_DEF[./IDENT[@text='e']]", + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedCatchParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF[./IDENT[@text='e']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedCatchParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY/" + + "LITERAL_CATCH/PARAMETER_DEF[./IDENT[@text='e']]" + + "/TYPE[./IDENT[@text='Exception']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnusedCatchParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY" + + "/LITERAL_CATCH/PARAMETER_DEF[./IDENT[@text='e']]" + + "/TYPE/IDENT[@text='Exception']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNested() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathUnusedCatchParameterShouldBeUnnamedNested.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnusedCatchParameterShouldBeUnnamedCheck.class); + + final String[] expectedViolation = { + "14:20: " + getCheckMessage(UnusedCatchParameterShouldBeUnnamedCheck.class, + UnusedCatchParameterShouldBeUnnamedCheck.MSG_UNUSED_CATCH_PARAMETER, + "exception"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedCatchParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY/" + + "LITERAL_CATCH/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF" + + "[./IDENT[@text='exception']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathUnusedCatchParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY" + + "/LITERAL_CATCH/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF[" + + "./IDENT[@text='exception']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnusedCatchParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY/" + + "LITERAL_CATCH/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF" + + "[./IDENT[@text='exception']]/TYPE[./IDENT[@text='Exception']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnusedCatchParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_TRY" + + "/LITERAL_CATCH/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF" + + "[./IDENT[@text='exception']]/TYPE/IDENT[@text='Exception']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedLambdaParameterShouldBeUnnamedTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedLambdaParameterShouldBeUnnamedTest.java new file mode 100644 index 000000000000..ea037384ef3d --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedLambdaParameterShouldBeUnnamedTest.java @@ -0,0 +1,137 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnusedLambdaParameterShouldBeUnnamedCheck; + +public class XpathRegressionUnusedLambdaParameterShouldBeUnnamedTest + extends AbstractXpathTestSupport { + + private final String checkName = UnusedLambdaParameterShouldBeUnnamedCheck.class + .getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/unusedlambdaparametershouldbeunnamed"; + } + + @Test + public void testSimple() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathUnusedLambdaParameterShouldBeUnnamedSimple.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnusedLambdaParameterShouldBeUnnamedCheck.class); + + final String[] expectedViolation = { + "9:41: " + getCheckMessage(UnusedLambdaParameterShouldBeUnnamedCheck.class, + UnusedLambdaParameterShouldBeUnnamedCheck.MSG_UNUSED_LAMBDA_PARAMETER, + "x"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT[" + + "@text='f']]/ASSIGN/LAMBDA/PARAMETERS", + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='f']]/ASSIGN/LAMBDA/PARAMETERS/PARAMETER_DEF[./IDENT[@text='x']]", + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT" + + "[@text='f']]/ASSIGN/LAMBDA/PARAMETERS" + + "/PARAMETER_DEF[./IDENT[@text='x']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT" + + "[@text='f']]/ASSIGN/LAMBDA/PARAMETERS/" + + "PARAMETER_DEF[./IDENT[@text='x']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT" + + "[@text='f']]/ASSIGN/LAMBDA/PARAMETERS/PARAMETER_DEF/IDENT[@text='x']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNested() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathUnusedLambdaParameterShouldBeUnnamedNested.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnusedLambdaParameterShouldBeUnnamedCheck.class); + + final String[] expectedViolation = { + "10:45: " + getCheckMessage(UnusedLambdaParameterShouldBeUnnamedCheck.class, + UnusedLambdaParameterShouldBeUnnamedCheck.MSG_UNUSED_LAMBDA_PARAMETER, + "y"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT" + + "[@text='f1']]/ASSIGN/LAMBDA/SLIST/VARIABLE_DEF[./IDENT[@text='f']]" + + "/ASSIGN/LAMBDA/PARAMETERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT" + + "[@text='f1']]/ASSIGN/LAMBDA/SLIST/VARIABLE_DEF[./IDENT[@text='f']]" + + "/ASSIGN/LAMBDA/PARAMETERS/PARAMETER_DEF[./IDENT[@text='y']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT" + + "[@text='f1']]/ASSIGN/LAMBDA/SLIST/VARIABLE_DEF[./IDENT[@text='f']]" + + "/ASSIGN/LAMBDA/PARAMETERS/PARAMETER_DEF[./IDENT[@text='y']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[./IDENT" + + "[@text='f1']]/ASSIGN/LAMBDA/SLIST/VARIABLE_DEF[./IDENT[@text='f']]/ASSIGN" + + "/LAMBDA/PARAMETERS/PARAMETER_DEF[./IDENT[@text='y']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathUnusedLambdaParameterShouldBeUnnamedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='f1']]/ASSIGN/LAMBDA/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='f']]/ASSIGN/LAMBDA/PARAMETERS/PARAMETER_DEF/IDENT[@text='y']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedLocalVariableTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedLocalVariableTest.java new file mode 100644 index 000000000000..29de8212b76a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionUnusedLocalVariableTest.java @@ -0,0 +1,115 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.UnusedLocalVariableCheck; + +public class XpathRegressionUnusedLocalVariableTest extends AbstractXpathTestSupport { + private final String checkName = UnusedLocalVariableCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/unusedlocalvariable"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathUnusedLocalVariableOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnusedLocalVariableCheck.class); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(UnusedLocalVariableCheck.class, + UnusedLocalVariableCheck.MSG_UNUSED_NAMED_LOCAL_VARIABLE, "a"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathUnusedLocalVariableOne']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[./IDENT[@text='a']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathUnusedLocalVariableOne']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='a']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathUnusedLocalVariableOne']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='a']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathUnusedLocalVariableOne']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='a']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathUnusedLocalVariableTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnusedLocalVariableCheck.class); + moduleConfig.addProperty("allowUnnamedVariables", "false"); + + final String[] expectedViolation = { + "10:9: " + getCheckMessage(UnusedLocalVariableCheck.class, + UnusedLocalVariableCheck.MSG_UNUSED_LOCAL_VARIABLE, "b"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathUnusedLocalVariableTwo']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[./IDENT[@text='b']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathUnusedLocalVariableTwo']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='b']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathUnusedLocalVariableTwo']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='b']]/TYPE", "/COMPILATION_UNIT/CLASS_DEF[" + + "./IDENT[@text='InputXpathUnusedLocalVariableTwo']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='b']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionVariableDeclarationUsageDistanceTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionVariableDeclarationUsageDistanceTest.java new file mode 100644 index 000000000000..69b262e2d56f --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionVariableDeclarationUsageDistanceTest.java @@ -0,0 +1,126 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.VariableDeclarationUsageDistanceCheck; + +public class XpathRegressionVariableDeclarationUsageDistanceTest extends AbstractXpathTestSupport { + private final String checkName = VariableDeclarationUsageDistanceCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/variabledeclarationusagedistance"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathVariableDeclarationUsageDistanceOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(VariableDeclarationUsageDistanceCheck.class); + moduleConfig.addProperty("allowedDistance", "1"); + moduleConfig.addProperty("ignoreVariablePattern", ""); + moduleConfig.addProperty("validateBetweenScopes", "true"); + moduleConfig.addProperty("ignoreFinal", "false"); + + final String[] expectedViolation = { + "7:9: " + getCheckMessage(VariableDeclarationUsageDistanceCheck.class, + VariableDeclarationUsageDistanceCheck.MSG_KEY, "temp", 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathVariableDeclarationUsageDistanceOne']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='temp']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathVariableDeclarationUsageDistanceOne']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='temp']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathVariableDeclarationUsageDistanceOne']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='temp']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathVariableDeclarationUsageDistanceOne']]/" + + "OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='temp']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathVariableDeclarationUsageDistanceTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(VariableDeclarationUsageDistanceCheck.class); + + moduleConfig.addProperty("allowedDistance", "1"); + moduleConfig.addProperty("ignoreVariablePattern", ""); + moduleConfig.addProperty("validateBetweenScopes", "true"); + moduleConfig.addProperty("ignoreFinal", "false"); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(VariableDeclarationUsageDistanceCheck.class, + VariableDeclarationUsageDistanceCheck.MSG_KEY, "count", 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathVariableDeclarationUsageDistanceTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod2']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='count']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathVariableDeclarationUsageDistanceTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod2']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='count']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathVariableDeclarationUsageDistanceTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod2']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='count']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathVariableDeclarationUsageDistanceTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod2']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='count']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionWhenShouldBeUsedTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionWhenShouldBeUsedTest.java new file mode 100644 index 000000000000..871c117cf773 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/coding/XpathRegressionWhenShouldBeUsedTest.java @@ -0,0 +1,97 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.coding; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.coding.WhenShouldBeUsedCheck; + +public class XpathRegressionWhenShouldBeUsedTest + extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return WhenShouldBeUsedCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/coding/whenshouldbeused"; + } + + @Test + public void testSimple() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathWhenShouldBeUsedSimple.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(WhenShouldBeUsedCheck.class); + final String[] expectedViolation = { + "7:13: " + getCheckMessage(WhenShouldBeUsedCheck.class, + WhenShouldBeUsedCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathWhenShouldBeUsedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/SWITCH_RULE" + + "[./LITERAL_CASE/PATTERN_VARIABLE_DEF/IDENT[@text='s']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathWhenShouldBeUsedSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "LITERAL_SWITCH/SWITCH_RULE/LITERAL_CASE" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testNested() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathWhenShouldBeUsedNested.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(WhenShouldBeUsedCheck.class); + final String[] expectedViolation = { + "10:21: " + getCheckMessage(WhenShouldBeUsedCheck.class, + WhenShouldBeUsedCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathWhenShouldBeUsedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='x']]/ASSIGN/EXPR/LITERAL_SWITCH" + + "/SWITCH_RULE/SLIST/" + + "LITERAL_SWITCH/SWITCH_RULE[./LITERAL_CASE/PATTERN_VARIABLE_DEF/" + + "IDENT[@text='_']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathWhenShouldBeUsedNested']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='x']]/ASSIGN/EXPR/LITERAL_SWITCH/" + + "SWITCH_RULE/SLIST/" + + "LITERAL_SWITCH/SWITCH_RULE/LITERAL_CASE" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionDesignForExtensionTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionDesignForExtensionTest.java new file mode 100644 index 000000000000..a6ba7b3a1613 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionDesignForExtensionTest.java @@ -0,0 +1,112 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.DesignForExtensionCheck; + +public class XpathRegressionDesignForExtensionTest extends AbstractXpathTestSupport { + + private final String checkName = DesignForExtensionCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/designforextension"; + } + + @Test + public void test() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDesignForExtensionClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DesignForExtensionCheck.class); + moduleConfig.addProperty("ignoredAnnotations", "Override"); + + final String[] expected = { + "7:5: " + getCheckMessage(DesignForExtensionCheck.class, + DesignForExtensionCheck.MSG_KEY, + "InputXpathDesignForExtensionClass", + "calculateValue"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDesignForExtensionClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='calculateValue']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDesignForExtensionClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='calculateValue']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDesignForExtensionClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='calculateValue']]/MODIFIERS/LITERAL_PUBLIC" + ); + + // Run the verifications + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + + } + + @Test + public void test2() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathDesignForExtensionWithEnum.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(DesignForExtensionCheck.class); + moduleConfig.addProperty("ignoredAnnotations", "Override"); + moduleConfig.addProperty("requiredJavadocPhrase", "This[\\s\\S]*implementation"); + + final String[] expected = { + "23:5: " + getCheckMessage(DesignForExtensionCheck.class, + DesignForExtensionCheck.MSG_KEY, + "InputXpathDesignForExtensionWithEnum", + "processData"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDesignForExtensionWithEnum']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='processData']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDesignForExtensionWithEnum']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='processData']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathDesignForExtensionWithEnum']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='processData']]/MODIFIERS/LITERAL_PUBLIC" + ); + + // Run the verifications + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionFinalClassTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionFinalClassTest.java new file mode 100644 index 000000000000..22d695c608dd --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionFinalClassTest.java @@ -0,0 +1,100 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; + +public class XpathRegressionFinalClassTest extends AbstractXpathTestSupport { + private final String checkName = FinalClassCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/finalclass"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathFinalClassDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(FinalClassCheck.class); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(FinalClassCheck.class, + FinalClassCheck.MSG_KEY, "InputXpathFinalClassDefault"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathFinalClassDefault']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathFinalClassDefault']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathFinalClassDefault']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathFinalClassInnerClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(FinalClassCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(FinalClassCheck.class, + FinalClassCheck.MSG_KEY, "Test"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathFinalClassInnerClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathFinalClassInnerClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathFinalClassInnerClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} + diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionHideUtilityClassConstructorTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionHideUtilityClassConstructorTest.java new file mode 100644 index 000000000000..ec3ca1eaaf51 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionHideUtilityClassConstructorTest.java @@ -0,0 +1,91 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import static com.puppycrawl.tools.checkstyle.checks.design.HideUtilityClassConstructorCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.HideUtilityClassConstructorCheck; + +public class XpathRegressionHideUtilityClassConstructorTest extends AbstractXpathTestSupport { + + private final String checkName = HideUtilityClassConstructorCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/hideutilityclassconstructor"; + } + + @Test + public void testDefaultConstructor() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathHideUtilityClassConstructorDefault.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(HideUtilityClassConstructorCheck.class); + final String[] expectedViolation = { + "3:1: " + getCheckMessage(HideUtilityClassConstructorCheck.class, MSG_KEY), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathHideUtilityClassConstructorDefault']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathHideUtilityClassConstructorDefault']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathHideUtilityClassConstructorDefault']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testPublicConstructor() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathHideUtilityClassConstructorPublic.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(HideUtilityClassConstructorCheck.class); + final String[] expectedViolation = { + "3:1: " + getCheckMessage(HideUtilityClassConstructorCheck.class, MSG_KEY), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathHideUtilityClassConstructorPublic']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathHideUtilityClassConstructorPublic']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathHideUtilityClassConstructorPublic']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionInnerTypeLastTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionInnerTypeLastTest.java new file mode 100644 index 000000000000..9f1aaba844ce --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionInnerTypeLastTest.java @@ -0,0 +1,147 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import static com.puppycrawl.tools.checkstyle.checks.design.InnerTypeLastCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.InnerTypeLastCheck; + +public class XpathRegressionInnerTypeLastTest extends AbstractXpathTestSupport { + + private final String checkName = InnerTypeLastCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/innertypelast"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathInnerTypeLastOne.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(InnerTypeLastCheck.class); + + final String[] expectedViolations = { + "8:5: " + getCheckMessage(InnerTypeLastCheck.class, MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastOne']]" + + "/OBJBLOCK/CTOR_DEF" + + "[./IDENT[@text='InputXpathInnerTypeLastOne']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastOne']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastOne']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastOne']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastOne']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + + final File fileToProcess = + new File(getPath("InputXpathInnerTypeLastTwo.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(InnerTypeLastCheck.class); + + final String[] expectedViolations = { + "11:9: " + getCheckMessage(InnerTypeLastCheck.class, MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastTwo']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='innerMethod']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastTwo']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT" + + "[@text='innerMethod']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastTwo']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT" + + "[@text='innerMethod']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, + expectedXpathQueries); + + } + + @Test + public void testThree() throws Exception { + + final File fileToProcess = new File( + getPath("InputXpathInnerTypeLastThree.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(InnerTypeLastCheck.class); + + final String[] expectedViolations = { + "10:5: " + getCheckMessage(InnerTypeLastCheck.class, MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastThree']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastThree']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastThree']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastThree']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastThree']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathInnerTypeLastThree']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, + expectedXpathQueries); + + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionInterfaceIsTypeTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionInterfaceIsTypeTest.java new file mode 100644 index 000000000000..e83df2f42684 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionInterfaceIsTypeTest.java @@ -0,0 +1,101 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.InterfaceIsTypeCheck; + +public class XpathRegressionInterfaceIsTypeTest extends AbstractXpathTestSupport { + + private final String checkName = InterfaceIsTypeCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/interfaceistype"; + } + + @Test + public void testAllowMarker() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathInterfaceIsTypeAllowMarker.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InterfaceIsTypeCheck.class); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(InterfaceIsTypeCheck.class, + InterfaceIsTypeCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[" + + "@text='InputXpathInterfaceIsTypeAllowMarker']]", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[" + + "@text='InputXpathInterfaceIsTypeAllowMarker']]/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[" + + "@text='InputXpathInterfaceIsTypeAllowMarker']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testAllowMarkerFalse() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathInterfaceIsType.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InterfaceIsTypeCheck.class); + + moduleConfig.addProperty("allowMarkerInterfaces", "false"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(InterfaceIsTypeCheck.class, + InterfaceIsTypeCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[" + + "@text='InputXpathInterfaceIsType']]", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[" + + "@text='InputXpathInterfaceIsType']]/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[" + + "@text='InputXpathInterfaceIsType']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionMutableExceptionTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionMutableExceptionTest.java new file mode 100644 index 000000000000..03226ab76b16 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionMutableExceptionTest.java @@ -0,0 +1,144 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.MutableExceptionCheck; + +public class XpathRegressionMutableExceptionTest extends AbstractXpathTestSupport { + + private final String checkName = MutableExceptionCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/mutableexception"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMutableExceptionDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MutableExceptionCheck.class); + + final String[] expectedViolation = { + "5:9: " + getCheckMessage(MutableExceptionCheck.class, + MutableExceptionCheck.MSG_KEY, "code"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionDefault']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='FooException']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionDefault']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='FooException']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionDefault']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='FooException']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]/MODIFIERS/LITERAL_PRIVATE" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testClassName() throws Exception { + final String classFormat = "^.*ExceptionClassName$"; + final File fileToProcess = + new File(getPath("InputXpathMutableExceptionClassName.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MutableExceptionCheck.class); + moduleConfig.addProperty("format", classFormat); + + final String[] expectedViolation = { + "4:3: " + getCheckMessage(MutableExceptionCheck.class, + MutableExceptionCheck.MSG_KEY, "code"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionClassName']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionClassName']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionClassName']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionClassName']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]/TYPE/LITERAL_INT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testExtendedClassName() throws Exception { + final String extendedClassNameFormat = "^.*Throwable$"; + final File fileToProcess = + new File(getPath("InputXpathMutableExceptionExtendedClassName.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MutableExceptionCheck.class); + moduleConfig.addProperty("extendedClassNameFormat", extendedClassNameFormat); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(MutableExceptionCheck.class, + MutableExceptionCheck.MSG_KEY, "code"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionExtendedClassName']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='FooException']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionExtendedClassName']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='FooException']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMutableExceptionExtendedClassName']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='FooException']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='code']]/MODIFIERS/LITERAL_PRIVATE"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionOneTopLevelClassTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionOneTopLevelClassTest.java new file mode 100644 index 000000000000..aaa2f40b6c19 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionOneTopLevelClassTest.java @@ -0,0 +1,91 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.OneTopLevelClassCheck; + +public class XpathRegressionOneTopLevelClassTest extends AbstractXpathTestSupport { + + private final String checkName = OneTopLevelClassCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/onetoplevelclass"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathOneTopLevelClassFirst.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OneTopLevelClassCheck.class); + + final String[] expectedViolation = { + "7:1: " + getCheckMessage(OneTopLevelClassCheck.class, + OneTopLevelClassCheck.MSG_KEY, "ViolatingSecondClass"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='ViolatingSecondClass']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='ViolatingSecondClass']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='ViolatingSecondClass']]/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathOneTopLevelClassSecond.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OneTopLevelClassCheck.class); + + final String[] expectedViolation = { + "7:1: " + getCheckMessage(OneTopLevelClassCheck.class, + OneTopLevelClassCheck.MSG_KEY, "ViolationClass"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ENUM_DEF[./IDENT[@text='ViolationClass']]", + "/COMPILATION_UNIT/ENUM_DEF[./IDENT[@text='ViolationClass']]/MODIFIERS", + "/COMPILATION_UNIT/ENUM_DEF[./IDENT[@text='ViolationClass']]/ENUM" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionSealedShouldHavePermitsListTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionSealedShouldHavePermitsListTest.java new file mode 100644 index 000000000000..0e4e8c90dbc8 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionSealedShouldHavePermitsListTest.java @@ -0,0 +1,102 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.SealedShouldHavePermitsListCheck; + +public class XpathRegressionSealedShouldHavePermitsListTest extends AbstractXpathTestSupport { + + private final String checkName = SealedShouldHavePermitsListCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/sealedshouldhavepermitslist"; + } + + @Test + public void testInner() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSealedShouldHavePermitsListInner.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SealedShouldHavePermitsListCheck.class); + + final String[] expectedViolation = { + "5:4: " + getCheckMessage(SealedShouldHavePermitsListCheck.class, + SealedShouldHavePermitsListCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSealedShouldHavePermitsListInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='A']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSealedShouldHavePermitsListInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='A']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSealedShouldHavePermitsListInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='A']]/MODIFIERS/LITERAL_SEALED" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTopLevel() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathSealedShouldHavePermitsListTopLevel.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SealedShouldHavePermitsListCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(SealedShouldHavePermitsListCheck.class, + SealedShouldHavePermitsListCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSealedShouldHavePermitsListTopLevel']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSealedShouldHavePermitsListTopLevel']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathSealedShouldHavePermitsListTopLevel']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionThrowsCountTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionThrowsCountTest.java new file mode 100644 index 000000000000..0205fb249712 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionThrowsCountTest.java @@ -0,0 +1,120 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck; + +public class XpathRegressionThrowsCountTest extends AbstractXpathTestSupport { + + private final String checkName = ThrowsCountCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/throwscount"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathThrowsCountDefault.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(ThrowsCountCheck.class); + final String[] expectedViolation = { + "4:30: " + getCheckMessage(ThrowsCountCheck.class, + ThrowsCountCheck.MSG_KEY, 5, 4), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathThrowsCountDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myFunction']]" + + "/LITERAL_THROWS[./IDENT[@text='CloneNotSupportedException']]" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testCustomMax() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathThrowsCountCustomMax.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(ThrowsCountCheck.class); + + moduleConfig.addProperty("max", "2"); + + final String[] expectedViolation = { + "4:30: " + getCheckMessage(ThrowsCountCheck.class, + ThrowsCountCheck.MSG_KEY, 3, 2), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/INTERFACE_DEF[./IDENT[@text='InputXpathThrowsCountCustomMax']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myFunction']]" + + "/LITERAL_THROWS[./IDENT[@text='IllegalStateException']]" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testPrivateMethods() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathThrowsCountPrivateMethods.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(ThrowsCountCheck.class); + + moduleConfig.addProperty("ignorePrivateMethods", "false"); + + final String[] expectedViolation = { + "9:40: " + getCheckMessage(ThrowsCountCheck.class, + ThrowsCountCheck.MSG_KEY, 5, 4), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathThrowsCountPrivateMethods']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myFunc']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='foo']]" + + "/ASSIGN/EXPR/LITERAL_NEW[./IDENT[@text='myClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='privateFunc']]" + + "/LITERAL_THROWS[./IDENT[@text='CloneNotSupportedException']]" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionVisibilityModifierTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionVisibilityModifierTest.java new file mode 100644 index 000000000000..69d77c7ec967 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/design/XpathRegressionVisibilityModifierTest.java @@ -0,0 +1,136 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.design; + +import static com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck.MSG_KEY; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck; + +public class XpathRegressionVisibilityModifierTest extends AbstractXpathTestSupport { + + private final String checkName = VisibilityModifierCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/design/visibilitymodifier"; + } + + @Test + public void testDefaultModifier() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathVisibilityModifierDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(VisibilityModifierCheck.class); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(VisibilityModifierCheck.class, MSG_KEY, "field"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathVisibilityModifierDefault']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='field']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAnnotation() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathVisibilityModifierAnnotation.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(VisibilityModifierCheck.class); + moduleConfig.addProperty("ignoreAnnotationCanonicalNames", "Deprecated"); + + final String[] expectedViolation = { + "5:12: " + getCheckMessage(VisibilityModifierCheck.class, MSG_KEY, + "annotatedString"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathVisibilityModifierAnnotation']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='annotatedString']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAnonymousClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathVisibilityModifierAnonymous.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(VisibilityModifierCheck.class); + + final String[] expectedViolation = { + "6:23: " + getCheckMessage(VisibilityModifierCheck.class, MSG_KEY, "field1"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathVisibilityModifierAnonymous']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='runnable']]" + + "/ASSIGN/EXPR/LITERAL_NEW[./IDENT[@text='Runnable']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='field1']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathVisibilityModifierInner.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(VisibilityModifierCheck.class); + + final String[] expectedViolation = { + "7:20: " + getCheckMessage(VisibilityModifierCheck.class, MSG_KEY, "field2"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathVisibilityModifierInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK/" + + "VARIABLE_DEF/IDENT[@text='field2']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionAvoidStarImportTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionAvoidStarImportTest.java new file mode 100644 index 000000000000..e675b8ea282b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionAvoidStarImportTest.java @@ -0,0 +1,88 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.imports; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.AvoidStarImportCheck; + +public class XpathRegressionAvoidStarImportTest + extends AbstractXpathTestSupport { + + private static final Class CLASS = + AvoidStarImportCheck.class; + + @Override + protected String getCheckName() { + return CLASS.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/imports/avoidstarimport"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidStarImportOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CLASS); + + final String[] expectedViolation = { + "3:42: " + getCheckMessage(CLASS, + AvoidStarImportCheck.MSG_KEY, "javax.swing.WindowConstants.*"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT/DOT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidStarImportTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CLASS); + + final String[] expectedViolation = { + "4:15: " + getCheckMessage(CLASS, + AvoidStarImportCheck.MSG_KEY, "java.io.*"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT/DOT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionAvoidStaticImportTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionAvoidStaticImportTest.java new file mode 100644 index 000000000000..fde0396d78bc --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionAvoidStaticImportTest.java @@ -0,0 +1,88 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.imports; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.AvoidStaticImportCheck; + +public class XpathRegressionAvoidStaticImportTest + extends AbstractXpathTestSupport { + + private static final Class CLASS = + AvoidStaticImportCheck.class; + + @Override + protected String getCheckName() { + return CLASS.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/imports/avoidstaticimport"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidStaticImportOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CLASS); + + final String[] expectedViolation = { + "3:42: " + getCheckMessage(CLASS, + AvoidStaticImportCheck.MSG_KEY, "javax.swing.WindowConstants.*"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT/DOT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathAvoidStaticImportTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CLASS); + + final String[] expectedViolation = { + "3:27: " + getCheckMessage(CLASS, + AvoidStaticImportCheck.MSG_KEY, "java.io.File.createTempFile"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT/DOT[./IDENT[@text='createTempFile']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionCustomImportOrderTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionCustomImportOrderTest.java new file mode 100644 index 000000000000..d6d8a64b2b37 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionCustomImportOrderTest.java @@ -0,0 +1,185 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.imports; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck; + +public class XpathRegressionCustomImportOrderTest extends AbstractXpathTestSupport { + + private final String checkName = CustomImportOrderCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/imports/customimportorder"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCustomImportOrderOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CustomImportOrderCheck.class); + moduleConfig.addProperty("customImportOrderRules", "STATIC###STANDARD_JAVA_PACKAGE"); + moduleConfig.addProperty("sortImportsInGroupAlphabetically", "true"); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(CustomImportOrderCheck.class, + CustomImportOrderCheck.MSG_LEX, "java.lang.Math.PI", + "java.util.Arrays.sort"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT[./DOT/IDENT[@text='PI']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCustomImportOrderTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CustomImportOrderCheck.class); + moduleConfig.addProperty("customImportOrderRules", "STATIC###STANDARD_JAVA_PACKAGE"); + + final String[] expectedViolation = { + "5:1: " + getCheckMessage(CustomImportOrderCheck.class, + CustomImportOrderCheck.MSG_LINE_SEPARATOR, "java.io.File"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/IDENT[@text='File']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCustomImportOrderThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CustomImportOrderCheck.class); + moduleConfig.addProperty("customImportOrderRules", "STATIC###STANDARD_JAVA_PACKAGE"); + + final String[] expectedViolation = { + "5:1: " + getCheckMessage(CustomImportOrderCheck.class, + CustomImportOrderCheck.MSG_SEPARATED_IN_GROUP, "java.lang.Math.PI"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT[./DOT/IDENT[@text='PI']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCustomImportOrderFour.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CustomImportOrderCheck.class); + moduleConfig.addProperty("customImportOrderRules", "STATIC###STANDARD_JAVA_PACKAGE"); + + final String[] expectedViolation = { + "5:1: " + getCheckMessage(CustomImportOrderCheck.class, + CustomImportOrderCheck.MSG_NONGROUP_IMPORT, + "com.puppycrawl.tools.checkstyle.api.DetailAST"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/IDENT[@text='DetailAST']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFive() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCustomImportOrderFive.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CustomImportOrderCheck.class); + moduleConfig.addProperty("customImportOrderRules", "STATIC###STANDARD_JAVA_PACKAGE"); + + final String[] expectedViolation = { + "7:1: " + getCheckMessage(CustomImportOrderCheck.class, + CustomImportOrderCheck.MSG_NONGROUP_EXPECTED, "STATIC", + "java.lang.Math.PI"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT[./DOT/IDENT[@text='PI']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSix() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCustomImportOrderSix.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CustomImportOrderCheck.class); + moduleConfig.addProperty("customImportOrderRules", + "STATIC###STANDARD_JAVA_PACKAGE###THIRD_PARTY_PACKAGE"); + + final String[] expectedViolation = { + "6:1: " + getCheckMessage(CustomImportOrderCheck.class, + CustomImportOrderCheck.MSG_ORDER, "THIRD_PARTY_PACKAGE", + "STANDARD_JAVA_PACKAGE", + "com.puppycrawl.tools.checkstyle.api.DetailAST"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/IDENT[@text='DetailAST']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionIllegalImportTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionIllegalImportTest.java new file mode 100644 index 000000000000..76188c8207c0 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionIllegalImportTest.java @@ -0,0 +1,86 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.imports; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.IllegalImportCheck; + +public class XpathRegressionIllegalImportTest extends AbstractXpathTestSupport { + + private final String checkName = IllegalImportCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/imports/illegalimport"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalImportDefault.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalImportCheck.class); + moduleConfig.addProperty("illegalPkgs", "java.util"); + final String[] expectedViolation = { + "3:1: " + getCheckMessage(IllegalImportCheck.class, + IllegalImportCheck.MSG_KEY, "java.util.List"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testStatic() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIllegalImportStatic.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalImportCheck.class); + + moduleConfig.addProperty("illegalPkgs", "java.lang"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(IllegalImportCheck.class, + IllegalImportCheck.MSG_KEY, "java.lang.Math.pow"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionImportControlTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionImportControlTest.java new file mode 100644 index 000000000000..7eec2f0c85de --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionImportControlTest.java @@ -0,0 +1,136 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.imports; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.ImportControlCheck; + +public class XpathRegressionImportControlTest extends AbstractXpathTestSupport { + + private final String checkName = ImportControlCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/imports/importcontrol"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportControlOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportControlCheck.class); + moduleConfig.addProperty("file", getPath( + "InputXpathImportControlOne.xml")); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(ImportControlCheck.class, + ImportControlCheck.MSG_DISALLOWED, "java.util.Scanner"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportControlTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportControlCheck.class); + moduleConfig.addProperty("file", getPath( + "InputXpathImportControlTwo.xml")); + + final String[] expectedViolation = { + "1:1: " + getCheckMessage(ImportControlCheck.class, + ImportControlCheck.MSG_UNKNOWN_PKG), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportControlThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportControlCheck.class); + + final String[] expectedViolation = { + "1:1: " + getCheckMessage(ImportControlCheck.class, + ImportControlCheck.MSG_MISSING_FILE), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportControlFour.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportControlCheck.class); + moduleConfig.addProperty("file", + getPath("InputXpathImportControlFour.xml")); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(ImportControlCheck.class, + ImportControlCheck.MSG_DISALLOWED, "java.util.Scanner"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/IDENT[@text='Scanner']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionImportOrderTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionImportOrderTest.java new file mode 100644 index 000000000000..5d95eba17b18 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionImportOrderTest.java @@ -0,0 +1,155 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.imports; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.ImportOrderCheck; + +public class XpathRegressionImportOrderTest extends AbstractXpathTestSupport { + + private final String checkName = ImportOrderCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/imports/importorder"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportOrderOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportOrderCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(ImportOrderCheck.class, + ImportOrderCheck.MSG_ORDERING, "java.util.Set"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportOrderTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportOrderCheck.class); + + final String[] expectedViolation = { + "5:1: " + getCheckMessage(ImportOrderCheck.class, + ImportOrderCheck.MSG_SEPARATED_IN_GROUP, "java.util.Set"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/IDENT[@text='Set']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportOrderThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportOrderCheck.class); + moduleConfig.addProperty("groups", "/^java\\./,javax,org"); + moduleConfig.addProperty("separated", "true"); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(ImportOrderCheck.class, + ImportOrderCheck.MSG_SEPARATION, "org.junit.*"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/DOT/IDENT[@text='org']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportOrderFour.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportOrderCheck.class); + moduleConfig.addProperty("option", "inflow"); + + final String[] expectedViolation = { + "5:1: " + getCheckMessage(ImportOrderCheck.class, + ImportOrderCheck.MSG_ORDERING, "java.lang.Math.PI"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFive() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathImportOrderFive.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ImportOrderCheck.class); + moduleConfig.addProperty("groups", "/^java\\./,javax,org"); + + final String[] expectedViolation = { + "5:1: " + getCheckMessage(ImportOrderCheck.class, + ImportOrderCheck.MSG_ORDERING, "java.util.Date"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/IDENT[@text='Date']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionRedundantImportTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionRedundantImportTest.java new file mode 100644 index 000000000000..2c34c5b6f8b3 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionRedundantImportTest.java @@ -0,0 +1,98 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.imports; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.RedundantImportCheck; + +public class XpathRegressionRedundantImportTest extends AbstractXpathTestSupport { + + private final String checkName = RedundantImportCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/imports/redundantimport"; + } + + @Test + public void testInternal() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRedundantImportInternal.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantImportCheck.class); + final String[] expectedViolation = { + "3:1: " + getCheckMessage(RedundantImportCheck.class, + RedundantImportCheck.MSG_SAME, "org.checkstyle.suppressionxpathfilter" + + ".imports.redundantimport.InputXpathRedundantImportInternal"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testLibrary() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRedundantImportLibrary.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantImportCheck.class); + final String[] expectedViolation = { + "3:1: " + getCheckMessage(RedundantImportCheck.class, + RedundantImportCheck.MSG_LANG, "java.lang.String"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testDuplicate() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRedundantImportDuplicate.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantImportCheck.class); + final String[] expectedViolation = { + "4:1: " + getCheckMessage(RedundantImportCheck.class, + RedundantImportCheck.MSG_DUPLICATE, 3, "java.util.Scanner"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/IDENT[@text='Scanner']]"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionUnusedImportsTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionUnusedImportsTest.java new file mode 100644 index 000000000000..60d7c4f3c888 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/imports/XpathRegressionUnusedImportsTest.java @@ -0,0 +1,88 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.imports; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.UnusedImportsCheck; + +public class XpathRegressionUnusedImportsTest extends AbstractXpathTestSupport { + + private final String checkName = UnusedImportsCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/imports/unusedimports"; + } + + @Test + public void testUnusedImports() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathUnusedImports.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnusedImportsCheck.class); + + final String[] expectedViolation = { + "3:8: " + getCheckMessage(UnusedImportsCheck.class, + UnusedImportsCheck.MSG_KEY, "java.util.List"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT/DOT[./IDENT[@text='List']]/DOT/IDENT[@text='java']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testStatic() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathUnusedImportsStatic.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(UnusedImportsCheck.class); + + final String[] expectedViolation = { + "3:15: " + getCheckMessage(UnusedImportsCheck.class, + UnusedImportsCheck.MSG_KEY, "java.util.Map.Entry"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/STATIC_IMPORT/DOT" + + "[./IDENT[@text='Entry']]/DOT[./IDENT[@text='Map']]" + + "/DOT/IDENT[@text='java']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/indentation/XpathRegressionCommentsIndentationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/indentation/XpathRegressionCommentsIndentationTest.java new file mode 100644 index 000000000000..dde735f233e7 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/indentation/XpathRegressionCommentsIndentationTest.java @@ -0,0 +1,237 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.indentation; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.indentation.CommentsIndentationCheck; + +public class XpathRegressionCommentsIndentationTest extends AbstractXpathTestSupport { + + private final String checkName = CommentsIndentationCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/indentation/commentsindentation"; + } + + @Test + public void testSingleLine() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCommentsIndentationSingleLine.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CommentsIndentationCheck.class); + + final String[] expectedViolation = { + "5:9: " + getCheckMessage(CommentsIndentationCheck.class, + "comments.indentation.single", 4, 8, 4), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathCommentsIndentationSingleLine']]" + + "/OBJBLOCK/SINGLE_LINE_COMMENT[./COMMENT_CONTENT[@text=' Comment // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testBlock() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCommentsIndentationBlock.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CommentsIndentationCheck.class); + + final String[] expectedViolation = { + "4:11: " + getCheckMessage(CommentsIndentationCheck.class, + "comments.indentation.block", 7, 10, 4), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathCommentsIndentationBlock']]/OBJBLOCK/" + + "VARIABLE_DEF[./IDENT[@text='f']]/TYPE/BLOCK_COMMENT_BEGIN[./COMMENT_CONTENT" + + "[@text=' // warn\\n * Javadoc comment\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSeparator() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCommentsIndentationSeparator.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CommentsIndentationCheck.class); + + final String[] expectedViolation = { + "8:13: " + getCheckMessage(CommentsIndentationCheck.class, + "comments.indentation.single", 10, 12, 4), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathCommentsIndentationSeparator']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/MODIFIERS/SINGLE_LINE_COMMENT" + + "[./COMMENT_CONTENT[@text='///////////// Comment separator // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testDistributedStatement() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCommentsIndentationDistributedStatement.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CommentsIndentationCheck.class); + + final String[] expectedViolation = { + "10:25: " + getCheckMessage(CommentsIndentationCheck.class, + "comments.indentation.single", 8, 24, 8), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathCommentsIndentationDistributedStatement']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/SLIST/SINGLE_LINE_COMMENT" + + "[./COMMENT_CONTENT[@text=' Comment // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSingleLineBlock() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCommentsIndentationSingleLineBlock.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CommentsIndentationCheck.class); + + final String[] expectedViolation = { + "6:1: " + getCheckMessage(CommentsIndentationCheck.class, + "comments.indentation.single", 7, 0, 4), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathCommentsIndentationSingleLineBlock']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/SLIST/SINGLE_LINE_COMMENT" + + "[./COMMENT_CONTENT[@text=' block Comment // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNonEmptyCase() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCommentsIndentationNonEmptyCase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CommentsIndentationCheck.class); + + final String[] expectedViolation = { + "10:20: " + getCheckMessage(CommentsIndentationCheck.class, + "comments.indentation.single", "9, 11", 19, "16, 12"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathCommentsIndentationNonEmptyCase']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/SLIST/LITERAL_SWITCH/" + + "CASE_GROUP/SINGLE_LINE_COMMENT[./COMMENT_CONTENT[@text=' Comment // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEmptyCase() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCommentsIndentationEmptyCase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CommentsIndentationCheck.class); + + final String[] expectedViolation = { + "9:1: " + getCheckMessage(CommentsIndentationCheck.class, + "comments.indentation.single", "8, 10", 0, "12, 12"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathCommentsIndentationEmptyCase']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/SLIST/LITERAL_SWITCH/" + + "CASE_GROUP/SINGLE_LINE_COMMENT[./COMMENT_CONTENT[@text=' Comment // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testWithinBlockStatement() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCommentsIndentationWithinBlockStatement.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CommentsIndentationCheck.class); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(CommentsIndentationCheck.class, + "comments.indentation.single", 7, 8, 12), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathCommentsIndentationWithinBlockStatement']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='s']]/ASSIGN/EXPR/PLUS[./STRING_LITERAL[@text='O']]" + + "/SINGLE_LINE_COMMENT[./COMMENT_CONTENT[@text=' Comment // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/indentation/XpathRegressionIndentationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/indentation/XpathRegressionIndentationTest.java new file mode 100644 index 000000000000..7ad21413ac3e --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/indentation/XpathRegressionIndentationTest.java @@ -0,0 +1,290 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.indentation; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.indentation.IndentationCheck; + +public class XpathRegressionIndentationTest extends AbstractXpathTestSupport { + private final String checkName = IndentationCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/indentation/indentation"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIndentationDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IndentationCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(IndentationCheck.class, + IndentationCheck.MSG_ERROR, "method def modifier", 0, 4), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='wrongIntend']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='wrongIntend']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='wrongIntend']]/TYPE", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='wrongIntend']]/TYPE/LITERAL_VOID" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testBasicOffset() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIndentationBasicOffset.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IndentationCheck.class); + moduleConfig.addProperty("arrayInitIndent", "4"); + moduleConfig.addProperty("basicOffset", "10"); + moduleConfig.addProperty("braceAdjustment", "0"); + moduleConfig.addProperty("caseIndent", "4"); + moduleConfig.addProperty("forceStrictCondition", "false"); + moduleConfig.addProperty("lineWrappingIndentation", "4"); + moduleConfig.addProperty("tabWidth", "4"); + moduleConfig.addProperty("throwsIndent", "4"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(IndentationCheck.class, + IndentationCheck.MSG_ERROR, "method def modifier", 4, 10), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationBasicOffset']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationBasicOffset']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationBasicOffset']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/TYPE", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationBasicOffset']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/TYPE/LITERAL_VOID" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testCaseIndent() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIndentationSwitchCase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IndentationCheck.class); + moduleConfig.addProperty("arrayInitIndent", "4"); + moduleConfig.addProperty("basicOffset", "4"); + moduleConfig.addProperty("braceAdjustment", "0"); + moduleConfig.addProperty("caseIndent", "4"); + moduleConfig.addProperty("forceStrictCondition", "false"); + moduleConfig.addProperty("lineWrappingIndentation", "4"); + moduleConfig.addProperty("tabWidth", "4"); + moduleConfig.addProperty("throwsIndent", "4"); + + final String[] expectedViolation = { + "7:9: " + getCheckMessage(IndentationCheck.class, + IndentationCheck.MSG_CHILD_ERROR, "case", 8, 12), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationSwitchCase']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/" + + "CASE_GROUP", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationSwitchCase']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_SWITCH/" + + "CASE_GROUP/LITERAL_CASE" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testLambdaOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIndentationLambdaOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IndentationCheck.class); + moduleConfig.addProperty("arrayInitIndent", "4"); + moduleConfig.addProperty("basicOffset", "4"); + moduleConfig.addProperty("braceAdjustment", "0"); + moduleConfig.addProperty("caseIndent", "4"); + moduleConfig.addProperty("forceStrictCondition", "false"); + moduleConfig.addProperty("lineWrappingIndentation", "4"); + moduleConfig.addProperty("tabWidth", "4"); + moduleConfig.addProperty("throwsIndent", "4"); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(IndentationCheck.class, + IndentationCheck.MSG_ERROR, "(", 8, 12), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationLambdaOne" + + "']]/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='getA']]/ASSIGN/LAMBDA/LPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testLambdaTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIndentationLambdaTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IndentationCheck.class); + moduleConfig.addProperty("arrayInitIndent", "4"); + moduleConfig.addProperty("basicOffset", "4"); + moduleConfig.addProperty("braceAdjustment", "0"); + moduleConfig.addProperty("caseIndent", "4"); + moduleConfig.addProperty("forceStrictCondition", "false"); + moduleConfig.addProperty("lineWrappingIndentation", "4"); + moduleConfig.addProperty("tabWidth", "4"); + moduleConfig.addProperty("throwsIndent", "4"); + + final String[] expectedViolation = { + "14:15: " + getCheckMessage(IndentationCheck.class, + IndentationCheck.MSG_CHILD_ERROR_MULTI, "block", 14, "12, 16"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationLambdaTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='div']]/ASSIGN/LAMBDA/SLIST/LITERAL_RETURN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testIfWithNoCurlies() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIndentationIfWithoutCurly.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IndentationCheck.class); + + moduleConfig.addProperty("arrayInitIndent", "4"); + moduleConfig.addProperty("basicOffset", "4"); + moduleConfig.addProperty("braceAdjustment", "0"); + moduleConfig.addProperty("caseIndent", "4"); + moduleConfig.addProperty("forceStrictCondition", "false"); + moduleConfig.addProperty("lineWrappingIndentation", "4"); + moduleConfig.addProperty("tabWidth", "4"); + moduleConfig.addProperty("throwsIndent", "4"); + + final String[] expectedViolation = { + "8:9: " + getCheckMessage(IndentationCheck.class, + IndentationCheck.MSG_CHILD_ERROR, "if", 8, 12), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationIfWithoutCurly']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF/EXPR/" + + "METHOD_CALL/IDENT[@text='e']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testElseWithNoCurlies() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathIndentationElseWithoutCurly.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IndentationCheck.class); + + moduleConfig.addProperty("arrayInitIndent", "4"); + moduleConfig.addProperty("basicOffset", "4"); + moduleConfig.addProperty("braceAdjustment", "0"); + moduleConfig.addProperty("caseIndent", "4"); + moduleConfig.addProperty("forceStrictCondition", "false"); + moduleConfig.addProperty("lineWrappingIndentation", "4"); + moduleConfig.addProperty("tabWidth", "4"); + moduleConfig.addProperty("throwsIndent", "4"); + + final String[] expectedViolation = { + "12:9: " + getCheckMessage(IndentationCheck.class, + IndentationCheck.MSG_CHILD_ERROR, "else", 8, 12), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIndentationElseWithoutCurly']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/LITERAL_IF/LITERAL_ELSE" + + "/EXPR/METHOD_CALL/IDENT[@text='exp']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionInvalidJavadocPositionTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionInvalidJavadocPositionTest.java new file mode 100644 index 000000000000..0529661cf8b1 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionInvalidJavadocPositionTest.java @@ -0,0 +1,190 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.javadoc; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.javadoc.InvalidJavadocPositionCheck; + +public class XpathRegressionInvalidJavadocPositionTest extends AbstractXpathTestSupport { + + private final String checkName = InvalidJavadocPositionCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/javadoc/invalidjavadocposition"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathInvalidJavadocPositionOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InvalidJavadocPositionCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(InvalidJavadocPositionCheck.class, + InvalidJavadocPositionCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathInvalidJavadocPositionOne']]" + + "/MODIFIERS/BLOCK_COMMENT_BEGIN[./COMMENT_CONTENT" + + "[@text='* // warn\\n * Javadoc Comment\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathInvalidJavadocPositionTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InvalidJavadocPositionCheck.class); + + final String[] expectedViolation = { + "5:1: " + getCheckMessage(InvalidJavadocPositionCheck.class, + InvalidJavadocPositionCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInvalidJavadocPositionTwo']]" + + "/OBJBLOCK/BLOCK_COMMENT_BEGIN[./COMMENT_CONTENT" + + "[@text='* // warn\\n * Javadoc comment\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathInvalidJavadocPositionThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InvalidJavadocPositionCheck.class); + + final String[] expectedViolation = { + "6:5: " + getCheckMessage(InvalidJavadocPositionCheck.class, + InvalidJavadocPositionCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathInvalidJavadocPositionThree']]/" + + "OBJBLOCK/BLOCK_COMMENT_BEGIN[./COMMENT_CONTENT" + + "[@text='* // warn\\n * Javadoc comment\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathInvalidJavadocPositionFour.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InvalidJavadocPositionCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(InvalidJavadocPositionCheck.class, + InvalidJavadocPositionCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathInvalidJavadocPositionFour']]" + + "/OBJBLOCK/BLOCK_COMMENT_BEGIN[./COMMENT_CONTENT" + + "[@text='* // warn\\n * Javadoc Comment\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFive() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathInvalidJavadocPositionFive.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InvalidJavadocPositionCheck.class); + + final String[] expectedViolation = { + "5:9: " + getCheckMessage(InvalidJavadocPositionCheck.class, + InvalidJavadocPositionCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathInvalidJavadocPositionFive']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/SLIST/BLOCK_COMMENT_BEGIN[./COMMENT_CONTENT" + + "[@text='* // warn\\n * Javadoc comment\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSix() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathInvalidJavadocPositionSix.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InvalidJavadocPositionCheck.class); + + final String[] expectedViolation = { + "5:5: " + getCheckMessage(InvalidJavadocPositionCheck.class, + InvalidJavadocPositionCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathInvalidJavadocPositionSix']]" + + "/OBJBLOCK/BLOCK_COMMENT_BEGIN[./COMMENT_CONTENT" + + "[@text='* // warn\\n * Javadoc Comment\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocContentLocationTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocContentLocationTest.java new file mode 100644 index 000000000000..b2b4de4b69e8 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocContentLocationTest.java @@ -0,0 +1,96 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.javadoc; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocContentLocationCheck; + +public class XpathRegressionJavadocContentLocationTest extends AbstractXpathTestSupport { + + private final String checkName = JavadocContentLocationCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/javadoc/javadoccontentlocation"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocContentLocationOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocContentLocationCheck.class); + + final String[] expectedViolation = { + "5:5: " + getCheckMessage(JavadocContentLocationCheck.class, + JavadocContentLocationCheck.MSG_JAVADOC_CONTENT_SECOND_LINE), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathJavadocContentLocationOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/TYPE/BLOCK_COMMENT_BEGIN" + + "[./COMMENT_CONTENT[@text='* Text. // warn\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocContentLocationTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocContentLocationCheck.class); + + moduleConfig.addProperty("location", "first_line"); + + final String[] expectedViolation = { + "5:16: " + getCheckMessage(JavadocContentLocationCheck.class, + JavadocContentLocationCheck.MSG_JAVADOC_CONTENT_FIRST_LINE), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathJavadocContentLocationTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/TYPE/BLOCK_COMMENT_BEGIN" + + "[./COMMENT_CONTENT[@text='*\\n * Text.\\n ']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocMethodTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocMethodTest.java new file mode 100644 index 000000000000..3e62df8c5f45 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocMethodTest.java @@ -0,0 +1,182 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.javadoc; + +import static com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.MSG_EXPECTED_TAG; +import static com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck.MSG_INVALID_INHERIT_DOC; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocMethodCheck; + +public class XpathRegressionJavadocMethodTest extends AbstractXpathTestSupport { + + private final String checkName = JavadocMethodCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/javadoc/javadocmethod"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocMethodOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocMethodCheck.class); + + final String[] expectedViolation = { + "14:5: " + getCheckMessage(JavadocMethodCheck.class, MSG_INVALID_INHERIT_DOC), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocMethodOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='uninheritableMethod']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocMethodOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='uninheritableMethod']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocMethodOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='uninheritableMethod']]/MODIFIERS" + + "/LITERAL_PRIVATE"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocMethodTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocMethodCheck.class); + + final String[] expectedViolation = { + "13:31: " + getCheckMessage(JavadocMethodCheck.class, MSG_EXPECTED_TAG, + "@param", "x"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocMethodTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='checkParam']]/PARAMETERS" + + "/PARAMETER_DEF/IDENT[@text='x']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocMethodThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocMethodCheck.class); + + final String[] expectedViolation = { + "14:13: " + getCheckMessage(JavadocMethodCheck.class, MSG_EXPECTED_TAG, + "@param", ""), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocMethodThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='checkTypeParam']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER[./IDENT[@text='T']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocMethodThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='checkTypeParam']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER/IDENT[@text='T']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocMethodFour.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocMethodCheck.class); + + moduleConfig.addProperty("validateThrows", "true"); + + final String[] expectedViolation = { + "12:30: " + getCheckMessage(JavadocMethodCheck.class, MSG_EXPECTED_TAG, + "@throws", "Exception"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocMethodFour']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/LITERAL_THROWS/IDENT[@text='Exception']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFive() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocMethodFive.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocMethodCheck.class); + + moduleConfig.addProperty("validateThrows", "true"); + + final String[] expectedViolation = { + "13:19: " + getCheckMessage(JavadocMethodCheck.class, MSG_EXPECTED_TAG, + "@throws", "org.apache.tools.ant.BuildException"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocMethodFive']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bar']]/SLIST" + + "/LITERAL_THROW/EXPR/LITERAL_NEW" + + "/DOT[./IDENT[@text='BuildException']]" + + "/DOT[./IDENT[@text='ant']]" + + "/DOT[./IDENT[@text='tools']]" + + "/DOT/IDENT[@text='org']"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocTypeTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocTypeTest.java new file mode 100644 index 000000000000..6f31957f5b48 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocTypeTest.java @@ -0,0 +1,133 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.javadoc; + +import static com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTypeCheck.MSG_MISSING_TAG; +import static com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTypeCheck.MSG_TAG_FORMAT; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagInfo; +import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTypeCheck; + +public class XpathRegressionJavadocTypeTest extends AbstractXpathTestSupport { + + private final String checkName = JavadocTypeCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/javadoc/javadoctype"; + } + + @Test + public void testMissingTag() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocTypeMissingTag.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocTypeCheck.class); + + moduleConfig.addProperty("authorFormat", "\\S"); + + final String[] expectedViolation = { + "6:1: " + getCheckMessage(JavadocTypeCheck.class, + MSG_MISSING_TAG, "@author"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocTypeMissingTag']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocTypeMissingTag']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocTypeMissingTag']]" + + "/MODIFIERS/LITERAL_PUBLIC"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testWrongFormat() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocTypeWrongFormat.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocTypeCheck.class); + + moduleConfig.addProperty("authorFormat", "foo"); + + final String[] expectedViolation = { + "7:1: " + getCheckMessage(JavadocTypeCheck.class, + MSG_TAG_FORMAT, "@author", "foo"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathJavadocTypeWrongFormat']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathJavadocTypeWrongFormat']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathJavadocTypeWrongFormat']]" + + "/MODIFIERS/LITERAL_PUBLIC"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testIncomplete() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocTypeIncomplete.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocTypeCheck.class); + + final String[] expectedViolation = { + "8:1: " + getCheckMessage(JavadocTypeCheck.class, + MSG_MISSING_TAG, JavadocTagInfo.PARAM.getText() + " "), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocTypeIncomplete']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocTypeIncomplete']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocTypeIncomplete']]" + + "/MODIFIERS/LITERAL_PUBLIC"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocVariableTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocVariableTest.java new file mode 100644 index 000000000000..b93a97e4c1fd --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionJavadocVariableTest.java @@ -0,0 +1,107 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.javadoc; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheck; + +public class XpathRegressionJavadocVariableTest extends AbstractXpathTestSupport { + + private final String checkName = JavadocVariableCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/javadoc/javadocvariable"; + } + + @Test + public void testPrivateClassFields() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocVariablePrivateClassFields.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocVariableCheck.class); + + final String[] expectedViolation = { + "5:5: " + getCheckMessage(JavadocVariableCheck.class, + JavadocVariableCheck.MSG_JAVADOC_MISSING), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocVariablePrivateClassFields']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='age']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocVariablePrivateClassFields']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='age']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocVariablePrivateClassFields']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='age']]/MODIFIERS/LITERAL_PRIVATE" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInnerClassFields() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavadocVariableInnerClassFields.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavadocVariableCheck.class); + + final String[] expectedViolation = { + "6:9: " + getCheckMessage(JavadocVariableCheck.class, + JavadocVariableCheck.MSG_JAVADOC_MISSING), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocVariableInnerClassFields']]/OBJBLOCK" + + "/CLASS_DEF[./IDENT[@text='InnerInner2']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='fData']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocVariableInnerClassFields']]/OBJBLOCK" + + "/CLASS_DEF[./IDENT[@text='InnerInner2']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='fData']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavadocVariableInnerClassFields']]/OBJBLOCK" + + "/CLASS_DEF[./IDENT[@text='InnerInner2']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='fData']]/MODIFIERS" + + "/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocMethodTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocMethodTest.java new file mode 100644 index 000000000000..8173f488c40b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocMethodTest.java @@ -0,0 +1,114 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.javadoc; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocMethodCheck; + +public class XpathRegressionMissingJavadocMethodTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return MissingJavadocMethodCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/javadoc/missingjavadocmethod"; + } + + @Test + public void testMissingJavadocMethodCtor() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMissingJavadocMethodCtor.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocMethodCheck.class); + moduleConfig.addProperty("tokens", "CTOR_DEF"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(MissingJavadocMethodCheck.class, + MissingJavadocMethodCheck.MSG_JAVADOC_MISSING), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMissingJavadocMethodCtor']]" + + "/OBJBLOCK/CTOR_DEF[." + + "/IDENT[@text='InputXpathMissingJavadocMethodCtor']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocMethodCtor']]" + + "/OBJBLOCK/CTOR_DEF[." + + "/IDENT[@text='InputXpathMissingJavadocMethodCtor']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocMethodCtor']]" + + "/OBJBLOCK/CTOR_DEF[." + + "/IDENT[@text='InputXpathMissingJavadocMethodCtor']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testMissingJavadocMethod() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMissingJavadocMethod.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocMethodCheck.class); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(MissingJavadocMethodCheck.class, + MissingJavadocMethodCheck.MSG_JAVADOC_MISSING), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocPackageTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocPackageTest.java new file mode 100644 index 000000000000..71582d5e5811 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocPackageTest.java @@ -0,0 +1,87 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.javadoc; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocPackageCheck; + +public class XpathRegressionMissingJavadocPackageTest extends AbstractXpathTestSupport { + + private final String checkName = MissingJavadocPackageCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/javadoc/missingjavadocpackage"; + } + + @Test + public void testBlockComment() throws Exception { + final File fileToProcess = new File(getPath( + "blockcomment/package-info.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocPackageCheck.class); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(MissingJavadocPackageCheck.class, + MissingJavadocPackageCheck.MSG_PKG_JAVADOC_MISSING), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNoJavadoc() throws Exception { + final File fileToProcess = new File(getPath( + "nojavadoc/package-info.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocPackageCheck.class); + + final String[] expectedViolation = { + "1:1: " + getCheckMessage(MissingJavadocPackageCheck.class, + MissingJavadocPackageCheck.MSG_PKG_JAVADOC_MISSING), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocTypeTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocTypeTest.java new file mode 100644 index 000000000000..379ed97d7b9b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/javadoc/XpathRegressionMissingJavadocTypeTest.java @@ -0,0 +1,203 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.javadoc; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.javadoc.MissingJavadocTypeCheck; + +public class XpathRegressionMissingJavadocTypeTest extends AbstractXpathTestSupport { + + private final String checkName = MissingJavadocTypeCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/javadoc/missingjavadoctype"; + } + + @Test + public void testClass() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingJavadocTypeClass.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocTypeCheck.class); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(MissingJavadocTypeCheck.class, + MissingJavadocTypeCheck.MSG_JAVADOC_MISSING, + "ClassMissingJavadocType"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeClass']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeClass']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeClass']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testScope() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingJavadocTypeScope.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocTypeCheck.class); + moduleConfig.addProperty("scope", "private"); + + final String[] expectedViolation = { + "7:5: " + getCheckMessage(MissingJavadocTypeCheck.class, + MissingJavadocTypeCheck.MSG_JAVADOC_MISSING, + "ScopeMissingJavadocType"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeScope']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeScope']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeScope']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]/MODIFIERS/LITERAL_PRIVATE" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testExcluded() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingJavadocTypeExcluded.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocTypeCheck.class); + moduleConfig.addProperty("scope", "private"); + moduleConfig.addProperty("excludeScope", "package"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(MissingJavadocTypeCheck.class, + MissingJavadocTypeCheck.MSG_JAVADOC_MISSING, + "ExcludedMissingJavadocType"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeExcluded']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeExcluded']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMissingJavadocTypeExcluded']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Test']]/MODIFIERS/LITERAL_PRIVATE" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAnnotation() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingJavadocTypeAnnotation.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocTypeCheck.class); + moduleConfig.addProperty("skipAnnotations", "TestAnnotation"); + + final String[] expectedViolation = { + "5:5: " + getCheckMessage(MissingJavadocTypeCheck.class, + MissingJavadocTypeCheck.MSG_JAVADOC_MISSING, + "AnnotationMissingJavadocType"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathMissingJavadocTypeAnnotation']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='innerClass']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathMissingJavadocTypeAnnotation']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='innerClass']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathMissingJavadocTypeAnnotation']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='innerClass']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='TestAnnotation2']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathMissingJavadocTypeAnnotation']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='innerClass']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='TestAnnotation2']]/AT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testToken() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathMissingJavadocTypeToken.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MissingJavadocTypeCheck.class); + moduleConfig.addProperty("tokens", "INTERFACE_DEF"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(MissingJavadocTypeCheck.class, + MissingJavadocTypeCheck.MSG_JAVADOC_MISSING, + "TokenMissingJavadocType"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[@text=" + + "'InputXpathMissingJavadocTypeToken']]", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[@text=" + + "'InputXpathMissingJavadocTypeToken']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[@text=" + + "'InputXpathMissingJavadocTypeToken']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionBooleanExpressionComplexityTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionBooleanExpressionComplexityTest.java new file mode 100644 index 000000000000..3e43d2a3b623 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionBooleanExpressionComplexityTest.java @@ -0,0 +1,116 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.metrics; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.metrics.BooleanExpressionComplexityCheck; + +public class XpathRegressionBooleanExpressionComplexityTest + extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return BooleanExpressionComplexityCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/metrics/booleanexpressioncomplexity"; + } + + @Test + public void testCatchBlock() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathBooleanExpressionComplexityCatchBlock.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(BooleanExpressionComplexityCheck.class); + + final String[] expectedViolationMessages = { + "10:23: " + getCheckMessage(BooleanExpressionComplexityCheck.class, + BooleanExpressionComplexityCheck.MSG_KEY, 11, 3), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathBooleanExpressionComplexityCatchBlock']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodOne']]/SLIST" + + "/LITERAL_TRY/LITERAL_CATCH/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='d']]/ASSIGN" + ); + + runVerifications(moduleConfig, fileToProcess, + expectedViolationMessages, expectedXpathQueries); + } + + @Test + public void testClassFields() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathBooleanExpressionComplexityClassFields.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(BooleanExpressionComplexityCheck.class); + + final String[] expectedViolationMessages = { + "9:19: " + getCheckMessage(BooleanExpressionComplexityCheck.class, + BooleanExpressionComplexityCheck.MSG_KEY, 11, 3), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathBooleanExpressionComplexityClassFields']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodTwo']]/SLIST/VARIABLE_DEF" + + "[./IDENT[@text='d']]/ASSIGN" + ); + + runVerifications(moduleConfig, fileToProcess, + expectedViolationMessages, expectedXpathQueries); + } + + @Test + public void testConditionals() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathBooleanExpressionComplexityConditionals.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(BooleanExpressionComplexityCheck.class); + + final String[] expectedViolationMessages = { + "9:9: " + getCheckMessage(BooleanExpressionComplexityCheck.class, + BooleanExpressionComplexityCheck.MSG_KEY, 4, 3), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathBooleanExpressionComplexityConditionals']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodThree']]/SLIST/LITERAL_IF" + ); + + runVerifications(moduleConfig, fileToProcess, + expectedViolationMessages, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionClassDataAbstractionCouplingTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionClassDataAbstractionCouplingTest.java new file mode 100644 index 000000000000..a1415f1d41b4 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionClassDataAbstractionCouplingTest.java @@ -0,0 +1,162 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.metrics; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.metrics.ClassDataAbstractionCouplingCheck; + +public class XpathRegressionClassDataAbstractionCouplingTest extends AbstractXpathTestSupport { + + private final String checkName = ClassDataAbstractionCouplingCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/metrics/classdataabstractioncoupling"; + } + + @Test + public void testClassDataAbstractCouplingClass() throws Exception { + final File classPath = + new File(getPath("InputXpathClassDataAbstractionCouplingClass.java")); + + final DefaultConfiguration configuration = + createModuleConfig(ClassDataAbstractionCouplingCheck.class); + + final String expectedClasses = List.of( + "AtomicInteger", + "BigDecimal", + "BigInteger", + "ByteArrayInputStream", + "CharArrayWriter", + "File", + "MathContext", + "StringWriter" + ).toString(); + + final String[] expectedViolations = { + "14:1: " + getCheckMessage(ClassDataAbstractionCouplingCheck.class, + ClassDataAbstractionCouplingCheck.MSG_KEY, 8, 7, expectedClasses), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingClass']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingClass']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingClass']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(configuration, classPath, expectedViolations, + expectedXpathQueries); + } + + @Test + public void testClassDataAbstractCouplingEnum() throws Exception { + final File classPath = + new File(getPath("InputXpathClassDataAbstractionCouplingEnum.java")); + + final DefaultConfiguration configuration = + createModuleConfig(ClassDataAbstractionCouplingCheck.class); + + final String expectedClasses = List.of( + "BigDecimal", + "BigInteger", + "CharArrayWriter", + "File", + "MathContext", + "Runnable", + "StringWriter", + "Thread" + ).toString(); + + final String[] expectedViolations = { + "11:1: " + getCheckMessage(ClassDataAbstractionCouplingCheck.class, + ClassDataAbstractionCouplingCheck.MSG_KEY, 8, 7, expectedClasses), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingEnum']]", + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingEnum']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/ENUM_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingEnum']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(configuration, classPath, expectedViolations, + expectedXpathQueries); + } + + @Test + public void testClassDataAbstractCouplingInterface() throws Exception { + final File classPath = + new File(getPath("InputXpathClassDataAbstractionCouplingInterface.java")); + + final DefaultConfiguration configuration = + createModuleConfig(ClassDataAbstractionCouplingCheck.class); + + final String expectedClasses = List.of( + "BigDecimal", + "BigInteger", + "CharArrayWriter", + "File", + "MathContext", + "Runnable", + "StringWriter", + "Thread" + ).toString(); + + final String[] expectedViolations = { + "11:1: " + getCheckMessage(ClassDataAbstractionCouplingCheck.class, + ClassDataAbstractionCouplingCheck.MSG_KEY, 8, 7, expectedClasses), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingInterface']]", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingInterface']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathClassDataAbstractionCouplingInterface']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(configuration, classPath, expectedViolations, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionClassFanOutComplexityTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionClassFanOutComplexityTest.java new file mode 100644 index 000000000000..06f5fd7353cb --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionClassFanOutComplexityTest.java @@ -0,0 +1,120 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.metrics; + +import java.io.File; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.metrics.ClassFanOutComplexityCheck; + +public class XpathRegressionClassFanOutComplexityTest extends AbstractXpathTestSupport { + + private final String checkName = ClassFanOutComplexityCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/metrics/classfanoutcomplexity"; + } + + @Test + public void testInClass() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathClassFanOutComplexityClass.java") + ); + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassFanOutComplexityCheck.class); + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolation = { + "6:1: " + getCheckMessage(ClassFanOutComplexityCheck.class, + ClassFanOutComplexityCheck.MSG_KEY, 4, 0), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassFanOutComplexityClass']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassFanOutComplexityClass']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassFanOutComplexityClass']]/MODIFIERS/LITERAL_PUBLIC" + + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInInterface() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathClassFanOutComplexityInterface.java") + ); + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassFanOutComplexityCheck.class); + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolation = { + "7:1: " + getCheckMessage(ClassFanOutComplexityCheck.class, + ClassFanOutComplexityCheck.MSG_KEY, 1, 0), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='BadInterface']]", + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='BadInterface']]/MODIFIERS", + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='BadInterface']]/LITERAL_INTERFACE" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInEnum() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathClassFanOutComplexityEnum.java") + ); + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassFanOutComplexityCheck.class); + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolation = { + "9:1: " + getCheckMessage(ClassFanOutComplexityCheck.class, + ClassFanOutComplexityCheck.MSG_KEY, 1, 0), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/ENUM_DEF" + + "[./IDENT[@text='MyEnum']]", + "/COMPILATION_UNIT/ENUM_DEF" + + "[./IDENT[@text='MyEnum']]/MODIFIERS", + "/COMPILATION_UNIT/ENUM_DEF" + + "[./IDENT[@text='MyEnum']]/ENUM" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionCyclomaticComplexityTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionCyclomaticComplexityTest.java new file mode 100644 index 000000000000..71df34966698 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionCyclomaticComplexityTest.java @@ -0,0 +1,106 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.metrics; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.metrics.CyclomaticComplexityCheck; + +public class XpathRegressionCyclomaticComplexityTest extends AbstractXpathTestSupport { + + private final String checkName = CyclomaticComplexityCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/metrics/cyclomaticcomplexity"; + } + + @Test + public void testConditionals() throws Exception { + + final File fileToProcess = + new File(getPath("InputXpathCyclomaticComplexityConditionals.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CyclomaticComplexityCheck.class); + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(CyclomaticComplexityCheck.class, + CyclomaticComplexityCheck.MSG_KEY, 2, 0), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCyclomaticComplexityConditionals']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCyclomaticComplexityConditionals']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCyclomaticComplexityConditionals']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testSwitchBlock() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathCyclomaticComplexitySwitchBlock.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(CyclomaticComplexityCheck.class); + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolation = { + "6:5: " + getCheckMessage(CyclomaticComplexityCheck.class, + CyclomaticComplexityCheck.MSG_KEY, 5, 0), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCyclomaticComplexitySwitchBlock']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo2']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCyclomaticComplexitySwitchBlock']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo2']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCyclomaticComplexitySwitchBlock']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo2']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionJavaNCSSTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionJavaNCSSTest.java new file mode 100644 index 000000000000..1bc926a1a95a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionJavaNCSSTest.java @@ -0,0 +1,128 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.metrics; + +import java.io.File; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.metrics.JavaNCSSCheck; + +// -@cs[AbbreviationAsWordInName] Test should be named as its main class. +public class XpathRegressionJavaNCSSTest extends AbstractXpathTestSupport { + + private final String checkName = JavaNCSSCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/metrics/javancss"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavaNCSSOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavaNCSSCheck.class); + + final String[] expectedViolation = { + "5:5: " + getCheckMessage(JavaNCSSCheck.class, + JavaNCSSCheck.MSG_METHOD, 51, 50), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavaNCSSOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavaNCSSOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavaNCSSOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavaNCSSTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavaNCSSCheck.class); + + moduleConfig.addProperty("classMaximum", "50"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(JavaNCSSCheck.class, + JavaNCSSCheck.MSG_CLASS, 51, 50), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavaNCSSTwo']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavaNCSSTwo']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathJavaNCSSTwo']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathJavaNCSSThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(JavaNCSSCheck.class); + + moduleConfig.addProperty("fileMaximum", "50"); + + final String[] expectedViolation = { + "1:1: " + getCheckMessage(JavaNCSSCheck.class, + JavaNCSSCheck.MSG_FILE, 51, 50), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT", + "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionNPathComplexityTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionNPathComplexityTest.java new file mode 100644 index 000000000000..c70d57515609 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/metrics/XpathRegressionNPathComplexityTest.java @@ -0,0 +1,101 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.metrics; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.metrics.NPathComplexityCheck; + +// -@cs[AbbreviationAsWordInName] Test should be named as its main class. +public class XpathRegressionNPathComplexityTest extends AbstractXpathTestSupport { + + private final String checkName = NPathComplexityCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/metrics/npathcomplexity"; + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNPathComplexityMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NPathComplexityCheck.class); + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(NPathComplexityCheck.class, + NPathComplexityCheck.MSG_KEY, 3, 0), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNPathComplexityMethod']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNPathComplexityMethod']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNPathComplexityMethod']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='test']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testStaticBlock() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNPathComplexityStaticBlock.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NPathComplexityCheck.class); + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(NPathComplexityCheck.class, + NPathComplexityCheck.MSG_KEY, 3, 0), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNPathComplexityStaticBlock']]" + + "/OBJBLOCK/STATIC_INIT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionClassMemberImpliedModifierTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionClassMemberImpliedModifierTest.java new file mode 100644 index 000000000000..3f4b8e7ba6cc --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionClassMemberImpliedModifierTest.java @@ -0,0 +1,103 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.modifier; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.modifier.ClassMemberImpliedModifierCheck; + +public class XpathRegressionClassMemberImpliedModifierTest extends AbstractXpathTestSupport { + + private final String checkName = ClassMemberImpliedModifierCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/modifier/classmemberimpliedmodifier"; + } + + @Test + public void testInterface() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathClassMemberImpliedModifierInterface.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassMemberImpliedModifierCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(ClassMemberImpliedModifierCheck.class, + ClassMemberImpliedModifierCheck.MSG_KEY, "static", 0), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathClassMemberImpliedModifierInterface']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Foo']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathClassMemberImpliedModifierInterface']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Foo']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathClassMemberImpliedModifierInterface']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Foo']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testEnum() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathClassMemberImpliedModifierEnum.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassMemberImpliedModifierCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(ClassMemberImpliedModifierCheck.class, + ClassMemberImpliedModifierCheck.MSG_KEY, "static", "null"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassMemberImpliedModifierEnum']]" + + "/OBJBLOCK/ENUM_DEF[./IDENT[@text='Count']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassMemberImpliedModifierEnum']]" + + "/OBJBLOCK/ENUM_DEF[./IDENT[@text='Count']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassMemberImpliedModifierEnum']]" + + "/OBJBLOCK/ENUM_DEF[./IDENT[@text='Count']]/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionInterfaceMemberImpliedModifierTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionInterfaceMemberImpliedModifierTest.java new file mode 100644 index 000000000000..37dc553dbd88 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionInterfaceMemberImpliedModifierTest.java @@ -0,0 +1,142 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.modifier; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.modifier.InterfaceMemberImpliedModifierCheck; + +public class XpathRegressionInterfaceMemberImpliedModifierTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return InterfaceMemberImpliedModifierCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/modifier/interfacememberimpliedmodifier"; + } + + @Test + public void testField() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathInterfaceMemberImpliedModifierField.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InterfaceMemberImpliedModifierCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(InterfaceMemberImpliedModifierCheck.class, + InterfaceMemberImpliedModifierCheck.MSG_KEY, "final"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='str']]", + + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='str']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierField']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='str']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathInterfaceMemberImpliedModifierMethod.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InterfaceMemberImpliedModifierCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(InterfaceMemberImpliedModifierCheck.class, + InterfaceMemberImpliedModifierCheck.MSG_KEY, "public"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='setData']]", + + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='setData']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='setData']]" + + "/MODIFIERS/ABSTRACT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInner() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathInterfaceMemberImpliedModifierInner.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(InterfaceMemberImpliedModifierCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(InterfaceMemberImpliedModifierCheck.class, + InterfaceMemberImpliedModifierCheck.MSG_KEY, "static"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierInner']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Data']]", + + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierInner']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Data']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceMemberImpliedModifierInner']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='Data']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionModifierOrderTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionModifierOrderTest.java new file mode 100644 index 000000000000..16d4f6a3d14a --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionModifierOrderTest.java @@ -0,0 +1,115 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.modifier; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.modifier.ModifierOrderCheck; + +public class XpathRegressionModifierOrderTest extends AbstractXpathTestSupport { + + private static final Class CLAZZ = ModifierOrderCheck.class; + + @Override + protected String getCheckName() { + return CLAZZ.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/modifier/modifierorder"; + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifierOrderMethod.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "4:13: " + getCheckMessage(CLAZZ, + ModifierOrderCheck.MSG_ANNOTATION_ORDER, "@MethodAnnotation"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathModifierOrderMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/MODIFIERS" + + "/ANNOTATION[./IDENT[@text='MethodAnnotation']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathModifierOrderMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/MODIFIERS" + + "/ANNOTATION[./IDENT[@text='MethodAnnotation']]/AT"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testVariable() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifierOrderVariable.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "3:12: " + getCheckMessage(CLAZZ, + ModifierOrderCheck.MSG_MODIFIER_ORDER, "private"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathModifierOrderVariable']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='var']]/MODIFIERS/LITERAL_PRIVATE"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAnnotation() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathModifierOrderAnnotation.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLAZZ); + + final String[] expectedViolation = { + "3:8: " + getCheckMessage(CLAZZ, + ModifierOrderCheck.MSG_ANNOTATION_ORDER, "@InterfaceAnnotation"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/ANNOTATION_DEF[./IDENT" + + "[@text='InputXpathModifierOrderAnnotation']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='InterfaceAnnotation']]", + "/COMPILATION_UNIT/ANNOTATION_DEF[./IDENT" + + "[@text='InputXpathModifierOrderAnnotation']]" + + "/MODIFIERS/ANNOTATION[./IDENT[@text='InterfaceAnnotation']]/AT"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionRedundantModifierTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionRedundantModifierTest.java new file mode 100644 index 000000000000..1a8d3e27442f --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/modifier/XpathRegressionRedundantModifierTest.java @@ -0,0 +1,190 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.modifier; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.modifier.RedundantModifierCheck; + +public class XpathRegressionRedundantModifierTest extends AbstractXpathTestSupport { + + private final String checkName = RedundantModifierCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/modifier/redundantmodifier"; + } + + @Test + public void test1() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRedundantModifierClass.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantModifierCheck.class); + + final String[] expected = { + "7:10: " + getCheckMessage(RedundantModifierCheck.class, + RedundantModifierCheck.MSG_KEY, + "final"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierClass']]" + + "/OBJBLOCK/CLASS_DEF" + + "[./IDENT[@text='Example1']]" + + "/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]" + + "/SLIST/LITERAL_TRY/RESOURCE_SPECIFICATION/RESOURCES", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierClass']]" + + "/OBJBLOCK/CLASS_DEF" + + "[./IDENT[@text='Example1']]" + + "/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]" + + "/SLIST/LITERAL_TRY/RESOURCE_SPECIFICATION/RESOURCES" + + "/RESOURCE" + + "[./IDENT[@text='a']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierClass']]" + + "/OBJBLOCK/CLASS_DEF" + + "[./IDENT[@text='Example1']]" + + "/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]" + + "/SLIST/LITERAL_TRY/RESOURCE_SPECIFICATION/RESOURCES" + + "/RESOURCE" + + "[./IDENT[@text='a']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierClass']]" + + "/OBJBLOCK/CLASS_DEF" + + "[./IDENT[@text='Example1']]" + + "/OBJBLOCK/METHOD_DEF" + + "[./IDENT[@text='test']]" + + "/SLIST/LITERAL_TRY/RESOURCE_SPECIFICATION/RESOURCES" + + "/RESOURCE" + + "[./IDENT[@text='a']]/MODIFIERS/FINAL" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + + } + + @Test + public void test2() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRedundantModifierInterface.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantModifierCheck.class); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expected = { + "5:5: " + getCheckMessage(RedundantModifierCheck.class, + RedundantModifierCheck.MSG_KEY, + "public"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierInterface']]" + + "/OBJBLOCK" + + "/METHOD_DEF" + + "[./IDENT[@text='m']]", + + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierInterface']]" + + "/OBJBLOCK" + + "/METHOD_DEF" + + "[./IDENT[@text='m']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierInterface']]" + + "/OBJBLOCK" + + "/METHOD_DEF" + + "[./IDENT[@text='m']]" + + "/MODIFIERS" + + "/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + } + + @Test + public void test3() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathRedundantModifierWithEnum.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantModifierCheck.class); + moduleConfig.addProperty("jdkVersion", "11"); + + final String[] expected = { + "5:9: " + getCheckMessage(RedundantModifierCheck.class, + RedundantModifierCheck.MSG_KEY, + "static"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierWithEnum']]" + + "/OBJBLOCK/INTERFACE_DEF" + + "[./IDENT[@text='I']]" + + "/OBJBLOCK/ENUM_DEF" + + "[./IDENT[@text='E']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierWithEnum']]" + + "/OBJBLOCK/INTERFACE_DEF" + + "[./IDENT[@text='I']]" + + "/OBJBLOCK/ENUM_DEF" + + "[./IDENT[@text='E']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRedundantModifierWithEnum']]" + + "/OBJBLOCK/INTERFACE_DEF" + + "[./IDENT[@text='I']]" + + "/OBJBLOCK/ENUM_DEF" + + "[./IDENT[@text='E']]" + + "/MODIFIERS" + + "/LITERAL_STATIC" + ); + + runVerifications(moduleConfig, fileToProcess, expected, expectedXpathQueries); + + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAbbreviationAsWordInNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionAbbreviationAsWordInNameTest.java similarity index 77% rename from src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAbbreviationAsWordInNameTest.java rename to src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionAbbreviationAsWordInNameTest.java index 12d10cf578e6..7ea9fe080d89 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionAbbreviationAsWordInNameTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionAbbreviationAsWordInNameTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,14 +15,15 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// -package org.checkstyle.suppressionxpathfilter; +package org.checkstyle.suppressionxpathfilter.naming; import java.io.File; import java.util.Collections; import java.util.List; +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; import org.junit.jupiter.api.Test; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -37,10 +38,15 @@ protected String getCheckName() { return checkName; } + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/abbreviationaswordinname"; + } + @Test public void testAnnotation() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameAnnotation.java")); + "InputXpathAbbreviationAsWordInNameAnnotation.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -51,8 +57,8 @@ public void testAnnotation() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameAnnotation']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameAnnotation']]" + "/OBJBLOCK/ANNOTATION_DEF/IDENT[@text='ANNOTATION']" ); @@ -63,7 +69,7 @@ public void testAnnotation() throws Exception { @Test public void testAnnotationField() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameAnnotationField.java")); + "InputXpathAbbreviationAsWordInNameAnnotationField.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -74,8 +80,8 @@ public void testAnnotationField() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/ANNOTATION_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameAnnotationField']]" + "/COMPILATION_UNIT/ANNOTATION_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameAnnotationField']]" + "/OBJBLOCK/ANNOTATION_FIELD_DEF/IDENT[@text='ANNOTATION_FIELD']" ); @@ -86,7 +92,7 @@ public void testAnnotationField() throws Exception { @Test public void testClass() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameClass.java")); + "InputXpathAbbreviationAsWordInNameClass.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -97,8 +103,8 @@ public void testClass() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameClass']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameClass']]" + "/OBJBLOCK/CLASS_DEF/IDENT[@text='CLASS']" ); @@ -109,7 +115,7 @@ public void testClass() throws Exception { @Test public void testEnum() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameEnum.java")); + "InputXpathAbbreviationAsWordInNameEnum.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -120,8 +126,8 @@ public void testEnum() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameEnum']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameEnum']]" + "/OBJBLOCK/ENUM_DEF/IDENT[@text='ENUMERATION']" ); @@ -132,7 +138,7 @@ public void testEnum() throws Exception { @Test public void testField() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameField.java")); + "InputXpathAbbreviationAsWordInNameField.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -143,8 +149,8 @@ public void testField() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameField']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameField']]" + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='FIELD']" ); @@ -155,7 +161,7 @@ public void testField() throws Exception { @Test public void testInterface() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameInterface.java")); + "InputXpathAbbreviationAsWordInNameInterface.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -166,8 +172,8 @@ public void testInterface() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameInterface']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameInterface']]" + "/OBJBLOCK/INTERFACE_DEF/IDENT[@text='INTERFACE']" ); @@ -178,7 +184,7 @@ public void testInterface() throws Exception { @Test public void testMethod() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameMethod.java")); + "InputXpathAbbreviationAsWordInNameMethod.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -189,8 +195,8 @@ public void testMethod() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/INTERFACE_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameMethod']]" + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameMethod']]" + "/OBJBLOCK/METHOD_DEF/IDENT[@text='METHOD']" ); @@ -201,7 +207,7 @@ public void testMethod() throws Exception { @Test public void testParameter() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameParameter.java")); + "InputXpathAbbreviationAsWordInNameParameter.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -212,8 +218,8 @@ public void testParameter() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/INTERFACE_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameParameter']]" + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameParameter']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + "/PARAMETERS/PARAMETER_DEF/IDENT[@text='PARAMETER']" ); @@ -225,7 +231,7 @@ public void testParameter() throws Exception { @Test public void testVariable() throws Exception { final File fileToProcess = new File(getPath( - "SuppressionXpathRegressionAbbreviationAsWordInNameVariable.java")); + "InputXpathAbbreviationAsWordInNameVariable.java")); final DefaultConfiguration moduleConfig = createModuleConfig(AbbreviationAsWordInNameCheck.class); @@ -236,8 +242,8 @@ public void testVariable() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionAbbreviationAsWordInNameVariable']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathAbbreviationAsWordInNameVariable']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + "/SLIST/VARIABLE_DEF/IDENT[@text='VARIABLE']" ); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionAbstractClassNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionAbstractClassNameTest.java new file mode 100644 index 000000000000..09fa14917b9d --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionAbstractClassNameTest.java @@ -0,0 +1,135 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractClassNameCheck; + +public class XpathRegressionAbstractClassNameTest extends AbstractXpathTestSupport { + + private final String checkName = AbstractClassNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/abstractclassname"; + } + + @Test + public void testClassNameTop() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathAbstractClassNameTop.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AbstractClassNameCheck.class); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(AbstractClassNameCheck.class, + AbstractClassNameCheck.MSG_ILLEGAL_ABSTRACT_CLASS_NAME, + "InputXpathAbstractClassNameTop", "^Abstract.+$"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAbstractClassNameTop']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAbstractClassNameTop']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAbstractClassNameTop']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testClassNameInner() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathAbstractClassNameInner.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AbstractClassNameCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(AbstractClassNameCheck.class, + AbstractClassNameCheck.MSG_ILLEGAL_ABSTRACT_CLASS_NAME, + "MyClass", "^Abstract.+$"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAbstractClassNameInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAbstractClassNameInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAbstractClassNameInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass']]/MODIFIERS/ABSTRACT" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testClassNameNoModifier() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathAbstractClassNameNoModifier.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AbstractClassNameCheck.class); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(AbstractClassNameCheck.class, + AbstractClassNameCheck.MSG_NO_ABSTRACT_CLASS_MODIFIER, + "AbstractMyClass"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAbstractClassNameNoModifier']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='AbstractMyClass']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAbstractClassNameNoModifier']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='AbstractMyClass']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='" + + "InputXpathAbstractClassNameNoModifier']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='AbstractMyClass']]/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionCatchParameterNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionCatchParameterNameTest.java new file mode 100644 index 000000000000..3739c6ad42c2 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionCatchParameterNameTest.java @@ -0,0 +1,236 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import static com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck.MSG_INVALID_PATTERN; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.CatchParameterNameCheck; + +public class XpathRegressionCatchParameterNameTest extends AbstractXpathTestSupport { + private final String checkName = CatchParameterNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/catchparametername"; + } + + @Test + public void testSimple() throws Exception { + final String pattern = "^(e|t|ex|[a-z][a-z][a-zA-Z]+|_)$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(CatchParameterNameCheck.class); + + final File fileToProcess = + new File(getPath("InputXpathCatchParameterNameSimple.java")); + + final String[] expectedViolation = { + "6:28: " + getCheckMessage(CatchParameterNameCheck.class, + MSG_INVALID_PATTERN, "e1", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCatchParameterNameSimple']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF/IDENT[@text='e1']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testNested() throws Exception { + final String pattern = "^(e|t|ex|[a-z][a-z][a-zA-Z]+|_)$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(CatchParameterNameCheck.class); + + final File fileToProcess = + new File(getPath("InputXpathCatchParameterNameNested.java")); + + final String[] expectedViolation = { + "9:40: " + getCheckMessage(CatchParameterNameCheck.class, + MSG_INVALID_PATTERN, "i", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCatchParameterNameNested']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='NestedClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/SLIST/LITERAL_IF/SLIST" + + "/LITERAL_TRY/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF/IDENT[@text='i']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testStaticInit() throws Exception { + final String pattern = "^[a-z][a-zA-Z0-9]+$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(CatchParameterNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final File fileToProcess = + new File(getPath("InputXpathCatchParameterNameStaticInit.java")); + + final String[] expectedViolation = { + "7:32: " + getCheckMessage(CatchParameterNameCheck.class, + MSG_INVALID_PATTERN, "Ex", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCatchParameterNameStaticInit']]" + + "/OBJBLOCK/STATIC_INIT/SLIST" + + "/LITERAL_DO/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF/IDENT[@text='Ex']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testAnonymous() throws Exception { + final String pattern = "^[a-z][a-zA-Z0-9]+$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(CatchParameterNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final File fileToProcess = + new File(getPath("InputXpathCatchParameterNameAnonymous.java")); + + final String[] expectedViolation = { + "12:40: " + getCheckMessage(CatchParameterNameCheck.class, + MSG_INVALID_PATTERN, "E1", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCatchParameterNameAnonymous']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[@text='InnerClass']]" + + "/SLIST/EXPR/LITERAL_NEW[./IDENT[@text='Runnable']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='run']]" + + "/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF/IDENT[@text='E1']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testLambda() throws Exception { + final String pattern = "^[A-Z][a-z]+$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(CatchParameterNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final File fileToProcess = + new File(getPath("InputXpathCatchParameterNameLambda.java")); + + final String[] expectedViolation = { + "12:32: " + getCheckMessage(CatchParameterNameCheck.class, + MSG_INVALID_PATTERN, "e", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathCatchParameterNameLambda']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='lambdaFunction']]" + + "/ASSIGN/LAMBDA[./IDENT[@text='a']]" + + "/SLIST/LITERAL_FOR/SLIST/LITERAL_TRY/LITERAL_CATCH" + + "/PARAMETER_DEF/IDENT[@text='e']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testEnum() throws Exception { + final String pattern = "^[A-Z][a-z]+$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(CatchParameterNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final File fileToProcess = + new File(getPath("InputXpathCatchParameterNameEnum.java")); + + final String[] expectedViolation = { + "10:40: " + getCheckMessage(CatchParameterNameCheck.class, + MSG_INVALID_PATTERN, "eX", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/ENUM_DEF" + + "[./IDENT[@text='InputXpathCatchParameterNameEnum']]" + + "/OBJBLOCK/ENUM_CONSTANT_DEF[./IDENT[@text='VALUE']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/SLIST/LITERAL_SWITCH/CASE_GROUP/SLIST/LITERAL_TRY/LITERAL_CATCH/" + + "PARAMETER_DEF/IDENT[@text='eX']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInterface() throws Exception { + final String pattern = "^[A-Z][a-z]+$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(CatchParameterNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final File fileToProcess = + new File(getPath("InputXpathCatchParameterNameInterface.java")); + + final String[] expectedViolation = { + "7:32: " + getCheckMessage(CatchParameterNameCheck.class, + MSG_INVALID_PATTERN, "EX", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathCatchParameterNameInterface']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT[@text='InnerInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/SLIST/LITERAL_TRY/LITERAL_CATCH/PARAMETER_DEF/IDENT[@text='EX']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionClassTypeParameterNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionClassTypeParameterNameTest.java new file mode 100644 index 000000000000..f59fd2474b4b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionClassTypeParameterNameTest.java @@ -0,0 +1,134 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractClassNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.ClassTypeParameterNameCheck; + +public class XpathRegressionClassTypeParameterNameTest extends AbstractXpathTestSupport { + + private final String checkName = ClassTypeParameterNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/classtypeparametername"; + } + + @Test + public void testClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathClassTypeParameterNameClass.java")); + final String pattern = "^[A-Z]$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassTypeParameterNameCheck.class); + + final String[] expectedViolation = { + "5:20: " + getCheckMessage(ClassTypeParameterNameCheck.class, + AbstractClassNameCheck.MSG_ILLEGAL_ABSTRACT_CLASS_NAME, "abc", pattern), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassTypeParameterNameClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass2']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER[./IDENT[@text='abc']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassTypeParameterNameClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass2']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER/IDENT[@text='abc']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInterface() throws Exception { + final String pattern = "^[A-Z]{2,}$"; + final File fileToProcess = + new File(getPath("InputXpathClassTypeParameterNameInterface.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassTypeParameterNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final String[] expectedViolation = { + "9:20: " + getCheckMessage(ClassTypeParameterNameCheck.class, + AbstractClassNameCheck.MSG_ILLEGAL_ABSTRACT_CLASS_NAME, "aBc", pattern), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathClassTypeParameterNameInterface']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass2']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER[./IDENT[@text='aBc']]", + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathClassTypeParameterNameInterface']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='MyClass2']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER/IDENT[@text='aBc']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMethod() throws Exception { + final String pattern = "(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"; + final File fileToProcess = + new File(getPath("InputXpathClassTypeParameterNameMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ClassTypeParameterNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final String[] expectedViolation = { + "12:24: " + getCheckMessage(ClassTypeParameterNameCheck.class, + AbstractClassNameCheck.MSG_ILLEGAL_ABSTRACT_CLASS_NAME, "ABC", pattern), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassTypeParameterNameMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myTest2']]/SLIST/CLASS_DEF" + + "[./IDENT[@text='MyClass2']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER[./IDENT[@text='ABC']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathClassTypeParameterNameMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myTest2']]/SLIST/CLASS_DEF" + + "[./IDENT[@text='MyClass2']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER/IDENT[@text='ABC']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionConstantNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionConstantNameTest.java new file mode 100644 index 000000000000..ddafae53d355 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionConstantNameTest.java @@ -0,0 +1,134 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import static com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck.MSG_INVALID_PATTERN; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheck; + +public class XpathRegressionConstantNameTest extends AbstractXpathTestSupport { + + private static final Class CLASS = ConstantNameCheck.class; + private static final String PATTERN = "^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$"; + private final String checkName = CLASS.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/constantname"; + } + + @Test + public void testLowercase() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathConstantNameLowercase.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + + final String[] expectedViolation = { + "4:29: " + getCheckMessage(CLASS, MSG_INVALID_PATTERN, "number", PATTERN), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstantNameLowercase']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='number']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testCamelCase() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathConstantNameCamelCase.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + + final String[] expectedViolation = { + "4:29: " + getCheckMessage(CLASS, + MSG_INVALID_PATTERN, "badConstant", PATTERN), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathConstantNameCamelCase']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='badConstant']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testWithBeginningUnderscore() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathConstantNameWithBeginningUnderscore.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + + final String[] expectedViolation = { + "4:33: " + getCheckMessage(CLASS, MSG_INVALID_PATTERN, "_CONSTANT", PATTERN), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstantNameWithBeginningUnderscore']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='_CONSTANT']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testWithTwoUnderscores() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathConstantNameWithTwoUnderscores.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + + final String[] expectedViolation = { + "4:30: " + getCheckMessage(CLASS, MSG_INVALID_PATTERN, "BAD__NAME", PATTERN), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathConstantNameWithTwoUnderscores']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='BAD__NAME']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionIllegalIdentifierNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionIllegalIdentifierNameTest.java new file mode 100644 index 000000000000..1f5297e50fb3 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionIllegalIdentifierNameTest.java @@ -0,0 +1,97 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.IllegalIdentifierNameCheck; + +public class XpathRegressionIllegalIdentifierNameTest extends AbstractXpathTestSupport { + + private final String checkName = IllegalIdentifierNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/illegalidentifiername"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathIllegalIdentifierNameOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalIdentifierNameCheck.class); + + final String format = "^(?!var$|\\S*\\$)\\S+$"; + + final String[] expectedViolation = { + "10:20: " + getCheckMessage(IllegalIdentifierNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "var", format), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/RECORD_DEF" + + "[./IDENT[@text='InputXpathIllegalIdentifierNameOne'" + + "]]/RECORD_COMPONENTS/RECORD_COMPONENT_DEF/IDENT[@text='var']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathIllegalIdentifierNameTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(IllegalIdentifierNameCheck.class); + + final String format = "^(?!var$|\\S*\\$)\\S+$"; + + final String[] expectedViolation = { + "9:17: " + getCheckMessage(IllegalIdentifierNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "te$t", format), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathIllegalIdentifierNameTwo']" + + "]/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/PARAMETERS/PARAMETER_DEF" + + "/IDENT[@text='te$t']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionInterfaceTypeParameterNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionInterfaceTypeParameterNameTest.java new file mode 100644 index 000000000000..b3b078abbea4 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionInterfaceTypeParameterNameTest.java @@ -0,0 +1,146 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import static com.puppycrawl.tools.checkstyle.checks.naming.InterfaceTypeParameterNameCheck.MSG_INVALID_PATTERN; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.InterfaceTypeParameterNameCheck; + +public class XpathRegressionInterfaceTypeParameterNameTest extends AbstractXpathTestSupport { + private final String checkName = InterfaceTypeParameterNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/interfacetypeparametername"; + } + + @Test + public void testInsideClass() throws Exception { + final File fileToCheck = + new File(getPath( + "InputXpathInterfaceTypeParameterNameInsideClass.java" + )); + + final DefaultConfiguration configuration = + createModuleConfig(InterfaceTypeParameterNameCheck.class); + + final String[] expectedViolations = { + "5:29: " + getCheckMessage(InterfaceTypeParameterNameCheck.class, + MSG_INVALID_PATTERN, + "t", "^[A-Z]$"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInterfaceTypeParameterNameInsideClass']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT" + + "[@text='SecondInterface']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER[./IDENT" + + "[@text='t']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInterfaceTypeParameterNameInsideClass']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT" + + "[@text='SecondInterface']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER/IDENT[@text='t']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testInsideInnerClass() throws Exception { + final File fileToCheck = + new File(getPath( + "InputXpathInterfaceTypeParameterNameInsideInnerClass.java" + )); + + final DefaultConfiguration configuration = + createModuleConfig(InterfaceTypeParameterNameCheck.class); + + final String[] expectedViolations = { + "5:37: " + getCheckMessage(InterfaceTypeParameterNameCheck.class, + MSG_INVALID_PATTERN, + "t", "^[A-Z]$"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInterfaceTypeParameterNameInsideInnerClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT" + + "[@text='InnerClass']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT" + + "[@text='InnerInterface']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER[./IDENT[@text='t']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathInterfaceTypeParameterNameInsideInnerClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT" + + "[@text='InnerClass']]" + + "/OBJBLOCK/INTERFACE_DEF[./IDENT" + + "[@text='InnerInterface']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER/IDENT[@text='t']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } + + @Test + public void testTopLevelPublic() throws Exception { + final File fileToCheck = + new File(getPath( + "InputXpathInterfaceTypeParameterNameTopLevelPublic.java" + )); + + final DefaultConfiguration configuration = + createModuleConfig(InterfaceTypeParameterNameCheck.class); + + final String[] expectedViolations = { + "3:69: " + getCheckMessage(InterfaceTypeParameterNameCheck.class, + MSG_INVALID_PATTERN, + "t", "^[A-Z]$"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceTypeParameterNameTopLevelPublic']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER[./IDENT[@text='t']]", + + "/COMPILATION_UNIT/INTERFACE_DEF[./IDENT" + + "[@text='InputXpathInterfaceTypeParameterNameTopLevelPublic']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER/IDENT[@text='t']" + ); + + runVerifications(configuration, fileToCheck, expectedViolations, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLambdaParameterNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLambdaParameterNameTest.java new file mode 100644 index 000000000000..688a709ae9a0 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLambdaParameterNameTest.java @@ -0,0 +1,123 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.LambdaParameterNameCheck; + +public class XpathRegressionLambdaParameterNameTest extends AbstractXpathTestSupport { + + private final String checkName = LambdaParameterNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/lambdaparametername"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathLambdaParameterNameDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(LambdaParameterNameCheck.class); + final String defaultPattern = "^([a-z][a-zA-Z0-9]*|_)$"; + + final String[] expectedViolation = { + "7:44: " + getCheckMessage(LambdaParameterNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "S", defaultPattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLambdaParameterNameDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/VARIABLE_DEF[" + + "./IDENT[@text='trimmer']]/ASSIGN/LAMBDA/IDENT[@text='S']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNonDefaultPattern() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathLambdaParameterNameNonDefaultPattern.java")); + + final String nonDefaultPattern = "^_[a-zA-Z0-9]*$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(LambdaParameterNameCheck.class); + moduleConfig.addProperty("format", nonDefaultPattern); + + final String[] expectedViolation = { + "7:45: " + getCheckMessage(LambdaParameterNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "s", nonDefaultPattern), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLambdaParameterNameNonDefaultPattern']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='trimmer']]/ASSIGN/LAMBDA/PARAMETERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLambdaParameterNameNonDefaultPattern']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='trimmer']]/ASSIGN/LAMBDA/PARAMETERS" + + "/PARAMETER_DEF[./IDENT[@text='s']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLambdaParameterNameNonDefaultPattern']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='trimmer']]/ASSIGN/LAMBDA/PARAMETERS" + + "/PARAMETER_DEF[./IDENT[@text='s']]/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLambdaParameterNameNonDefaultPattern']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='trimmer']]/ASSIGN/LAMBDA/PARAMETERS" + + "/PARAMETER_DEF[./IDENT[@text='s']]/TYPE", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLambdaParameterNameNonDefaultPattern']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST/" + + "VARIABLE_DEF[./IDENT[@text='trimmer']]/ASSIGN/LAMBDA/PARAMETERS" + + "/PARAMETER_DEF/IDENT[@text='s']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLocalFinalVariableNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLocalFinalVariableNameTest.java new file mode 100644 index 000000000000..e939be4ac01e --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLocalFinalVariableNameTest.java @@ -0,0 +1,121 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import static com.puppycrawl.tools.checkstyle.checks.naming.LocalFinalVariableNameCheck.MSG_INVALID_PATTERN; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.LocalFinalVariableNameCheck; + +public class XpathRegressionLocalFinalVariableNameTest extends AbstractXpathTestSupport { + + private final String checkName = LocalFinalVariableNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/localfinalvariablename"; + } + + @Test + public void testResource() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathLocalFinalVariableNameResource.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(LocalFinalVariableNameCheck.class); + moduleConfig.addProperty("format", "^[A-Z][A-Z0-9]*$"); + moduleConfig.addProperty("tokens", "PARAMETER_DEF,RESOURCE"); + + final String[] expectedViolation = { + "7:21: " + getCheckMessage(LocalFinalVariableNameCheck.class, + MSG_INVALID_PATTERN, "scanner", "^[A-Z][A-Z0-9]*$"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathLocalFinalVariableNameResource']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='MyMethod']]/SLIST/LITERAL_TRY" + + "/RESOURCE_SPECIFICATION/RESOURCES/RESOURCE/IDENT[@text='scanner']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testVariable() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathLocalFinalVariableNameVar.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(LocalFinalVariableNameCheck.class); + moduleConfig.addProperty("format", "^[A-Z][a-z0-9]*$"); + + final String[] expectedViolation = { + "5:19: " + getCheckMessage(LocalFinalVariableNameCheck.class, + MSG_INVALID_PATTERN, "VAR1", "^[A-Z][a-z0-9]*$"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathLocalFinalVariableNameVar']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='MyMethod']]/SLIST/VARIABLE_DEF" + + "/IDENT[@text='VAR1']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathLocalFinalVariableNameInner.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(LocalFinalVariableNameCheck.class); + moduleConfig.addProperty("format", "^[A-Z][a-z0-9]*$"); + + final String[] expectedViolation = { + "8:23: " + getCheckMessage(LocalFinalVariableNameCheck.class, + MSG_INVALID_PATTERN, "VAR1", "^[A-Z][a-z0-9]*$"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathLocalFinalVariableNameInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='MyMethod']]/SLIST/VARIABLE_DEF" + + "/IDENT[@text='VAR1']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLocalVariableNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLocalVariableNameTest.java new file mode 100644 index 000000000000..18bf43c66541 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionLocalVariableNameTest.java @@ -0,0 +1,116 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import static com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck.MSG_INVALID_PATTERN; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck; + +public class XpathRegressionLocalVariableNameTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return LocalVariableNameCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/localvariablename"; + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = new File(getPath("InputXpathLocalVariableNameMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(LocalVariableNameCheck.class); + + final String pattern = "^([a-z][a-zA-Z0-9]*|_)$"; + final String[] expectedViolations = { + "5:9: " + getCheckMessage(LocalVariableNameCheck.class, MSG_INVALID_PATTERN, + "VAR", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathLocalVariableNameMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='MyMethod']]" + + "/SLIST/VARIABLE_DEF/IDENT[@text='VAR']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + + } + + @Test + public void testIteration() throws Exception { + final File fileToProcess = new File(getPath("InputXpathLocalVariableNameIteration.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(LocalVariableNameCheck.class); + + final String pattern = "^([a-z][a-zA-Z0-9]*|_)$"; + final String[] expectedViolations = { + "7:14: " + getCheckMessage(LocalVariableNameCheck.class, MSG_INVALID_PATTERN, + "var_1", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathLocalVariableNameIteration']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='MyMethod']]/" + + "SLIST/LITERAL_FOR/FOR_INIT/VARIABLE_DEF/IDENT[@text='var_1']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = new File(getPath("InputXpathLocalVariableNameInnerClass.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(LocalVariableNameCheck.class); + + final String pattern = "^([a-z][a-zA-Z0-9]*|_)$"; + final String[] expectedViolations = { + "6:11: " + getCheckMessage(LocalVariableNameCheck.class, MSG_INVALID_PATTERN, + "VAR", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathLocalVariableNameInnerClass']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]/OBJBLOCK/" + + "METHOD_DEF[./IDENT[@text='myMethod']]/SLIST/VARIABLE_DEF/IDENT[@text='VAR']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMemberNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMemberNameTest.java new file mode 100644 index 000000000000..9598040d62b9 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMemberNameTest.java @@ -0,0 +1,99 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.MemberNameCheck; + +public class XpathRegressionMemberNameTest extends AbstractXpathTestSupport { + + private final String checkName = MemberNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/membername"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMemberNameDefault.java")); + + final String pattern = "^[a-z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(MemberNameCheck.class); + + final String[] expectedViolation = { + "5:17: " + getCheckMessage(MemberNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "NUM2", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathMemberNameDefault']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='NUM2']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testIgnoreProtected() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMemberNameIgnoreProtected.java")); + + final String pattern = "^m[A-Z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(MemberNameCheck.class); + moduleConfig.addProperty("format", "^m[A-Z][a-zA-Z0-9]*$"); + moduleConfig.addProperty("applyToProtected", "false"); + moduleConfig.addProperty("applyToPackage", "false"); + + final String[] expectedViolation = { + "6:20: " + getCheckMessage(MemberNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "NUM1", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathMemberNameIgnoreProtected']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='NUM1']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMethodNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMethodNameTest.java new file mode 100644 index 000000000000..9f6619c793a7 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMethodNameTest.java @@ -0,0 +1,124 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.MethodNameCheck; + +public class XpathRegressionMethodNameTest extends AbstractXpathTestSupport { + + private final String checkName = MethodNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/methodname"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMethodNameDefault.java")); + + final String pattern = "^[a-z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodNameCheck.class); + + final String[] expectedViolation = { + "6:16: " + getCheckMessage(MethodNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "SecondMethod", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathMethodNameDefault']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='SecondMethod']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInnerClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMethodNameInner.java")); + + final String pattern = "^[a-z](_?[a-zA-Z0-9]+)*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodNameCheck.class); + moduleConfig.addProperty("format", "^[a-z](_?[a-zA-Z0-9]+)*$"); + + final String[] expectedViolation = { + "7:21: " + getCheckMessage(MethodNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "MyMethod2", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathMethodNameInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Inner']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='MyMethod2']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testCustomProperties() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMethodNameCustomProperties.java")); + + final String pattern = "^[a-z](_?[a-zA-Z0-9]+)*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodNameCheck.class); + moduleConfig.addProperty("format", "^[a-z](_?[a-zA-Z0-9]+)*$"); + moduleConfig.addProperty("applyToPublic", "false"); + moduleConfig.addProperty("applyToProtected", "false"); + + final String[] expectedViolation = { + "7:19: " + getCheckMessage(MethodNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, + "ThirdMethod", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/INTERFACE_DEF[./IDENT[@text='Check']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='ThirdMethod']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMethodTypeParameterNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMethodTypeParameterNameTest.java new file mode 100644 index 000000000000..41ded61c4605 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionMethodTypeParameterNameTest.java @@ -0,0 +1,132 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import static com.puppycrawl.tools.checkstyle.checks.naming.MethodTypeParameterNameCheck.MSG_INVALID_PATTERN; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.MethodTypeParameterNameCheck; + +public class XpathRegressionMethodTypeParameterNameTest extends AbstractXpathTestSupport { + + private final String checkName = MethodTypeParameterNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/methodtypeparametername"; + } + + @Test + public void test1() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMethodTypeParameterNameDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodTypeParameterNameCheck.class); + + final String[] expectedViolation = { + "4:11: " + getCheckMessage(MethodTypeParameterNameCheck.class, + MSG_INVALID_PATTERN, "TT", "^[A-Z]$"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./" + + "IDENT[@text='InputXpathMethodTypeParameterNameDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER[./IDENT[@text='TT']]", "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[" + + "@text='InputXpathMethodTypeParameterNameDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER/IDENT[@text='TT']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void test2() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMethodTypeParameterNameInner.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodTypeParameterNameCheck.class); + moduleConfig.addProperty("format", "^foo$"); + + final String[] expectedViolation = { + "6:10: " + getCheckMessage(MethodTypeParameterNameCheck.class, + MSG_INVALID_PATTERN, "fo_", "^foo$"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathMethodTypeParameterNameInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Junk']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='foo']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER[./IDENT[@text='fo_']]", "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text=" + + "'InputXpathMethodTypeParameterNameInner']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='Junk']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='foo']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER/IDENT[@text='fo_']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void test3() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMethodTypeParameterNameLowercase.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodTypeParameterNameCheck.class); + moduleConfig.addProperty("format", "^[a-z]$"); + + final String[] expectedViolation = { + "7:6: " + getCheckMessage(MethodTypeParameterNameCheck.class, + MSG_INVALID_PATTERN, "a_a", "^[a-z]$"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodTypeParameterNameLowercase']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myMethod']]/TYPE_PARAMETERS" + + "/TYPE_PARAMETER[./IDENT[@text='a_a']]", "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text=" + + "'InputXpathMethodTypeParameterNameLowercase']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='myMethod']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER/IDENT[@text='a_a']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionPackageNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionPackageNameTest.java new file mode 100644 index 000000000000..60728741fb2e --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionPackageNameTest.java @@ -0,0 +1,132 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import static com.puppycrawl.tools.checkstyle.checks.naming.PackageNameCheck.MSG_KEY; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.PackageNameCheck; + +public class XpathRegressionPackageNameTest extends AbstractXpathTestSupport { + + private final String checkName = PackageNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/packagename"; + } + + @Test + public void testOne() throws Exception { + + final File fileToProcess = + new File(getPath("InputXpathPackageNameOne.java")); + + final String pattern = "[A-Z]+"; + + final DefaultConfiguration moduleConfig = createModuleConfig(PackageNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final String[] expectedViolation = { + "1:9: " + getCheckMessage(PackageNameCheck.class, MSG_KEY, + "org.checkstyle.suppressionxpathfilter.naming.packagename", + pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/PACKAGE_DEF/DOT" + + "[./IDENT[@text='packagename']]/DOT" + + "[./IDENT[@text='naming']]/DOT" + + "[./IDENT[@text='suppressionxpathfilter']]" + + "/DOT/IDENT[@text='org']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + + } + + @Test + public void testThree() throws Exception { + + final File fileToProcess = + new File(getNonCompilablePath("InputXpathPackageNameThree.java")); + + final String pattern = "^[a-z]+(\\.[a-z][a-z0-9]*)*$"; + + final DefaultConfiguration moduleConfig = createModuleConfig(PackageNameCheck.class); + moduleConfig.addProperty("format", pattern); + final String[] expectedViolations = { + "1:9: " + getCheckMessage(PackageNameCheck.class, MSG_KEY, + "org.checkstyle.suppressionxpathfilter.PACKAGENAME", + pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/PACKAGE_DEF/DOT[./IDENT" + + "[@text='PACKAGENAME']]/DOT[./IDENT" + + "[@text='suppressionxpathfilter']]" + + "/DOT/IDENT[@text='org']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + + final File fileToProcess = + new File(getPath("InputXpathPackageNameTwo.java")); + + final String pattern = "[A-Z]+"; + + final DefaultConfiguration moduleConfig = createModuleConfig(PackageNameCheck.class); + moduleConfig.addProperty("format", pattern); + + final String[] expectedViolation = { + "2:9: " + getCheckMessage(PackageNameCheck.class, MSG_KEY, + "org.checkstyle.suppressionxpathfilter.naming.packagename", + pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/PACKAGE_DEF/DOT" + + "[./IDENT[@text='packagename']]/DOT" + + "[./IDENT[@text='naming']]/DOT" + + "[./IDENT[@text='suppressionxpathfilter']]" + + "/DOT/IDENT[@text='org']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionParameterNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionParameterNameTest.java new file mode 100644 index 000000000000..2730811fbbd5 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionParameterNameTest.java @@ -0,0 +1,150 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.ParameterNameCheck; + +public class XpathRegressionParameterNameTest extends AbstractXpathTestSupport { + + private final String checkName = ParameterNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/parametername"; + } + + @Test + public void testDefaultPattern() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathParameterNameDefaultPattern.java")); + + final String pattern = "^[a-z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(ParameterNameCheck.class); + + final String[] expectedViolation = { + "5:22: " + getCheckMessage(ParameterNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "v_1", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathParameterNameDefaultPattern']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method1']]" + + "/PARAMETERS/PARAMETER_DEF/IDENT[@text='v_1']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testDifferentPattern() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathParameterNameDifferentPattern.java")); + + final String pattern = "^[a-z][_a-zA-Z0-9]+$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(ParameterNameCheck.class); + moduleConfig.addProperty("format", "^[a-z][_a-zA-Z0-9]+$"); + + final String[] expectedViolation = { + "5:22: " + getCheckMessage(ParameterNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "V2", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathParameterNameDifferentPattern']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method2']]" + + "/PARAMETERS/PARAMETER_DEF/IDENT[@text='V2']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testIgnoreOverridden() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathParameterNameIgnoreOverridden.java")); + + final String pattern = "^[a-z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(ParameterNameCheck.class); + moduleConfig.addProperty("ignoreOverridden", "true"); + + final String[] expectedViolation = { + "5:22: " + getCheckMessage(ParameterNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "V2", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathParameterNameIgnoreOverridden']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method2']]" + + "/PARAMETERS/PARAMETER_DEF/IDENT[@text='V2']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testAccessModifiers() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathParameterNameAccessModifier.java")); + + final String pattern = "^[a-z][a-z0-9][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(ParameterNameCheck.class); + moduleConfig.addProperty("format", "^[a-z][a-z0-9][a-zA-Z0-9]*$"); + moduleConfig.addProperty("accessModifiers", "public"); + + final String[] expectedViolation = { + "8:29: " + getCheckMessage(ParameterNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "b", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathParameterNameAccessModifier']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method2']]" + + "/PARAMETERS/PARAMETER_DEF/IDENT[@text='b']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionPatternVariableNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionPatternVariableNameTest.java new file mode 100644 index 000000000000..dc96d662cbe0 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionPatternVariableNameTest.java @@ -0,0 +1,161 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.PatternVariableNameCheck; + +public class XpathRegressionPatternVariableNameTest extends AbstractXpathTestSupport { + + private final String checkName = PatternVariableNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/patternvariablename"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathPatternVariableNameOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(PatternVariableNameCheck.class); + final String defaultPattern = "^([a-z][a-zA-Z0-9]*|_)$"; + + final String[] expectedViolation = { + "6:33: " + getCheckMessage(PatternVariableNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, + "STRING1", defaultPattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathPatternVariableNameOne']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='MyClass']]/SLIST/LITERAL_IF/EXPR/" + + "LITERAL_INSTANCEOF[./IDENT[@text='o1']]/PATTERN_VARIABLE_DEF/" + + "IDENT[@text='STRING1']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathPatternVariableNameTwo.java")); + + final String nonDefaultPattern = "^_[a-zA-Z0-9]*$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(PatternVariableNameCheck.class); + moduleConfig.addProperty("format", nonDefaultPattern); + + final String[] expectedViolation = { + "6:34: " + getCheckMessage(PatternVariableNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "s", nonDefaultPattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathPatternVariableNameTwo']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='MyClass']]/SLIST/LITERAL_IF/EXPR/" + + "LITERAL_INSTANCEOF[./IDENT[@text='o1']]/" + + "PATTERN_VARIABLE_DEF/IDENT[@text='s']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathPatternVariableNameThree.java")); + + final String nonDefaultPattern = "^[a-z](_?[a-zA-Z0-9]+)*$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(PatternVariableNameCheck.class); + moduleConfig.addProperty("format", nonDefaultPattern); + + final String[] expectedViolation = { + "6:34: " + getCheckMessage(PatternVariableNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "STR", nonDefaultPattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathPatternVariableNameThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='MyClass']]/SLIST/LITERAL_IF/" + + "EXPR/LITERAL_INSTANCEOF[./IDENT[@text='o1']]/" + + "PATTERN_VARIABLE_DEF/IDENT[@text='STR']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathPatternVariableNameFour.java")); + + final String nonDefaultPattern = "^[a-z][_a-zA-Z0-9]{2,}$"; + + final DefaultConfiguration moduleConfig = + createModuleConfig(PatternVariableNameCheck.class); + moduleConfig.addProperty("format", nonDefaultPattern); + + final String[] expectedViolation = { + "6:34: " + getCheckMessage(PatternVariableNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "st", nonDefaultPattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathPatternVariableNameFour']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='MyClass']]/SLIST/LITERAL_IF/EXPR/" + + "LITERAL_INSTANCEOF[./IDENT[@text='o1']]/" + + "PATTERN_VARIABLE_DEF/IDENT[@text='st']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionRecordComponentNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionRecordComponentNameTest.java new file mode 100644 index 000000000000..6e940658e654 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionRecordComponentNameTest.java @@ -0,0 +1,95 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.RecordComponentNameCheck; + +public class XpathRegressionRecordComponentNameTest extends AbstractXpathTestSupport { + + private final String checkName = RecordComponentNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/recordcomponentname"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathRecordComponentNameDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RecordComponentNameCheck.class); + + final String[] expectedViolation = { + "6:56: " + getCheckMessage(RecordComponentNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, + "_value", "^[a-z][a-zA-Z0-9]*$"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/RECORD_DEF[./IDENT[@text='InputXpathRecordComponentNameDefault']]" + + "/RECORD_COMPONENTS/RECORD_COMPONENT_DEF/IDENT[@text='_value']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFormat() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathRecordComponentNameFormat.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RecordComponentNameCheck.class); + moduleConfig.addProperty("format", "^_[a-z][a-zA-Z0-9]*$"); + + final String[] expectedViolation = { + "9:32: " + getCheckMessage(RecordComponentNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, + "otherValue", "^_[a-z][a-zA-Z0-9]*$"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathRecordComponentNameFormat']]/OBJBLOCK" + + "/RECORD_DEF[./IDENT[@text='MyRecord']]" + + "/RECORD_COMPONENTS/RECORD_COMPONENT_DEF/IDENT[@text='otherValue']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionRecordTypeParameterNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionRecordTypeParameterNameTest.java new file mode 100644 index 000000000000..a7597ac39549 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionRecordTypeParameterNameTest.java @@ -0,0 +1,102 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.RecordTypeParameterNameCheck; + +public class XpathRegressionRecordTypeParameterNameTest extends AbstractXpathTestSupport { + + private final String checkName = RecordTypeParameterNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/recordtypeparametername"; + } + + @Test + public void testTypeDeclared() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathRecordTypeParameterNameTypeDeclared.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RecordTypeParameterNameCheck.class); + + final String pattern = "^[A-Z]$"; + + final String[] expectedViolation = { + "10:55: " + getCheckMessage(RecordTypeParameterNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "foo", pattern), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/RECORD_DEF[./IDENT[@text='" + + "InputXpathRecordTypeParameterNameTypeDeclared']]/" + + "TYPE_PARAMETERS/TYPE_PARAMETER[./IDENT[@text='foo']]", + "/COMPILATION_UNIT/RECORD_DEF[./IDENT[@text='" + + "InputXpathRecordTypeParameterNameTypeDeclared']]/TYPE_PARAMETERS/" + + "TYPE_PARAMETER/IDENT[@text='foo']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTypeDefault() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathRecordTypeParameterNameTypeDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RecordTypeParameterNameCheck.class); + + final String pattern = "^[A-Z]$"; + + final String[] expectedViolation = { + "4:60: " + getCheckMessage(RecordTypeParameterNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "t", pattern), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/RECORD_DEF[./IDENT" + + "[@text='InputXpathRecordTypeParameterNameTypeDefault']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER[./IDENT[@text='t']]", + "/COMPILATION_UNIT/RECORD_DEF[./IDENT" + + "[@text='InputXpathRecordTypeParameterNameTypeDefault']]" + + "/TYPE_PARAMETERS/TYPE_PARAMETER/IDENT[@text='t']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionStaticVariableNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionStaticVariableNameTest.java new file mode 100644 index 000000000000..b775d135947c --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionStaticVariableNameTest.java @@ -0,0 +1,123 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.StaticVariableNameCheck; + +public class XpathRegressionStaticVariableNameTest extends AbstractXpathTestSupport { + + private final String checkName = StaticVariableNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/staticvariablename"; + } + + @Test + public void testStaticVariableName() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathStaticVariableName.java")); + + final String pattern = "^[a-z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(StaticVariableNameCheck.class); + + final String[] expectedViolation = { + "6:24: " + getCheckMessage(StaticVariableNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "NUM2", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathStaticVariableName']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='NUM2']" + + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInnerClassField() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathStaticVariableNameInnerClassField.java")); + + final String pattern = "^[a-z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(StaticVariableNameCheck.class); + + final String[] expectedViolation = { + "14:24: " + getCheckMessage(StaticVariableNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "NUM3", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathStaticVariableNameInnerClassField']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='outerMethod']]" + + "/SLIST/CLASS_DEF[./IDENT[@text='MyLocalClass']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='NUM3']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNoAccessModifier() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathStaticVariableNameNoAccessModifier.java")); + + final String pattern = "^[a-z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(StaticVariableNameCheck.class); + + final String[] expectedViolation = { + "5:16: " + getCheckMessage(StaticVariableNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "NUM3", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathStaticVariableNameNoAccessModifier']]" + + "/OBJBLOCK/VARIABLE_DEF/IDENT[@text='NUM3']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionTypeNameTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionTypeNameTest.java new file mode 100644 index 000000000000..5ef0f87b7232 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/naming/XpathRegressionTypeNameTest.java @@ -0,0 +1,97 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.naming; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.naming.AbstractNameCheck; +import com.puppycrawl.tools.checkstyle.checks.naming.TypeNameCheck; + +public class XpathRegressionTypeNameTest extends AbstractXpathTestSupport { + + private final String checkName = TypeNameCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/naming/typename"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathTypeNameDefault.java")); + + final String pattern = "^[A-Z][a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(TypeNameCheck.class); + + final String[] expectedViolation = { + "5:19: " + getCheckMessage(TypeNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "SecondName_", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathTypeNameDefault']]" + + "/OBJBLOCK/CLASS_DEF/IDENT[@text='SecondName_']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInterfaceDef() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathTypeNameInterfaceDef.java")); + + final String pattern = "^I_[a-zA-Z0-9]*$"; + final DefaultConfiguration moduleConfig = + createModuleConfig(TypeNameCheck.class); + moduleConfig.addProperty("format", "^I_[a-zA-Z0-9]*$"); + moduleConfig.addProperty("tokens", "INTERFACE_DEF"); + + final String[] expectedViolation = { + "6:15: " + getCheckMessage(TypeNameCheck.class, + AbstractNameCheck.MSG_INVALID_PATTERN, "SecondName", pattern), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathTypeNameInterfaceDef']]" + + "/OBJBLOCK/INTERFACE_DEF/IDENT[@text='SecondName']" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionAnonInnerLengthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionAnonInnerLengthTest.java new file mode 100644 index 000000000000..8d293ddb5647 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionAnonInnerLengthTest.java @@ -0,0 +1,106 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.sizes; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.sizes.AnonInnerLengthCheck; + +public class XpathRegressionAnonInnerLengthTest extends AbstractXpathTestSupport { + + private final String checkName = AnonInnerLengthCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/sizes/anoninnerlength"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathAnonInnerLengthDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnonInnerLengthCheck.class); + + final String[] expectedViolation = { + "7:29: " + getCheckMessage(AnonInnerLengthCheck.class, + AnonInnerLengthCheck.MSG_KEY, 26, 20), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnonInnerLengthDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='runnable']]" + + "/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnonInnerLengthDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='runnable']]" + + "/ASSIGN/EXPR/LITERAL_NEW[./IDENT[@text='Runnable']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMaxLength() throws Exception { + final int maxLen = 5; + final File fileToProcess = + new File(getPath("InputXpathAnonInnerLength.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(AnonInnerLengthCheck.class); + moduleConfig.addProperty("max", String.valueOf(maxLen)); + + final String[] expectedViolation = { + "7:35: " + getCheckMessage(AnonInnerLengthCheck.class, + AnonInnerLengthCheck.MSG_KEY, 6, maxLen), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnonInnerLength']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='compare']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='comp']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathAnonInnerLength']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='compare']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='comp']]/ASSIGN/EXPR" + + "/LITERAL_NEW[./IDENT[@text='Comparator']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionExecutableStatementCountTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionExecutableStatementCountTest.java new file mode 100644 index 000000000000..71a6ac4e028b --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionExecutableStatementCountTest.java @@ -0,0 +1,140 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.sizes; + +import static com.puppycrawl.tools.checkstyle.checks.sizes.ExecutableStatementCountCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.sizes.ExecutableStatementCountCheck; + +public class XpathRegressionExecutableStatementCountTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return ExecutableStatementCountCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/sizes/executablestatementcount"; + } + + @Test + public void testDefaultConfig() throws Exception { + final String filePath = + getPath("InputXpathExecutableStatementCountDefault.java"); + final File fileToProcess = new File(filePath); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ExecutableStatementCountCheck.class); + + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolations = { + "4:5: " + getCheckMessage(ExecutableStatementCountCheck.class, MSG_KEY, 3, 0), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='ElseIfLadder']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='ElseIfLadder']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountDefault']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='ElseIfLadder']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + + } + + @Test + public void testCustomMax() throws Exception { + final String filePath = + getPath("InputXpathExecutableStatementCountCustomMax.java"); + final File fileToProcess = new File(filePath); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ExecutableStatementCountCheck.class); + + moduleConfig.addProperty("max", "0"); + moduleConfig.addProperty("tokens", "CTOR_DEF"); + + final String[] expectedViolations = { + "4:5: " + getCheckMessage(ExecutableStatementCountCheck.class, MSG_KEY, 2, 0), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountCustomMax']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountCustomMax']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountCustomMax']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountCustomMax']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountCustomMax']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[" + + "@text='InputXpathExecutableStatementCountCustomMax']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testLambdas() throws Exception { + final String filePath = + getPath("InputXpathExecutableStatementCountLambdas.java"); + final File fileToProcess = new File(filePath); + + final DefaultConfiguration moduleConfig = + createModuleConfig(ExecutableStatementCountCheck.class); + + moduleConfig.addProperty("max", "1"); + moduleConfig.addProperty("tokens", "LAMBDA"); + + final String[] expectedViolations = { + "7:22: " + getCheckMessage(ExecutableStatementCountCheck.class, MSG_KEY, 2, 1), + }; + + final List expectedXpathQueries = List.of( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathExecutableStatementCountLambdas']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='c']]/ASSIGN/LAMBDA" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionLambdaBodyLengthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionLambdaBodyLengthTest.java new file mode 100644 index 000000000000..56fb37d06a3c --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionLambdaBodyLengthTest.java @@ -0,0 +1,84 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.sizes; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.sizes.LambdaBodyLengthCheck; + +public class XpathRegressionLambdaBodyLengthTest + extends AbstractXpathTestSupport { + + private static final Class CLASS = + LambdaBodyLengthCheck.class; + + @Override + protected String getCheckName() { + return CLASS.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/sizes/lambdabodylength"; + } + + @Test + public void testDefaultMax() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathLambdaBodyLengthDefaultMax.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + final String[] expectedViolation = { + "7:48: " + getCheckMessage(CLASS, LambdaBodyLengthCheck.MSG_KEY, 11, 10), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLambdaBodyLengthDefaultMax']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='trimmer']]/ASSIGN/LAMBDA"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testCustomMax() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathLambdaBodyLengthCustomMax.java")); + final DefaultConfiguration moduleConfig = createModuleConfig(CLASS); + moduleConfig.addProperty("max", "5"); + final String[] expectedViolation = { + "7:25: " + getCheckMessage(CLASS, LambdaBodyLengthCheck.MSG_KEY, 6, 5), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathLambdaBodyLengthCustomMax']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='r']]/ASSIGN/LAMBDA"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionMethodCountTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionMethodCountTest.java new file mode 100644 index 000000000000..b73e42016c01 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionMethodCountTest.java @@ -0,0 +1,198 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.sizes; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.sizes.MethodCountCheck; + +public class XpathRegressionMethodCountTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return MethodCountCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/sizes/methodcount"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMethodCountDefault.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodCountCheck.class); + moduleConfig.addProperty("maxTotal", "1"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(MethodCountCheck.class, + MethodCountCheck.MSG_MANY_METHODS, 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountDefault']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountDefault']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountDefault']]" + + "/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testPrivate() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMethodCountPrivate.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodCountCheck.class); + moduleConfig.addProperty("maxPrivate", "1"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(MethodCountCheck.class, + MethodCountCheck.MSG_PRIVATE_METHODS, 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountPrivate']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountPrivate']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountPrivate']]" + + "/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testPackage() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMethodCountDefault.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodCountCheck.class); + moduleConfig.addProperty("maxPackage", "1"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(MethodCountCheck.class, + MethodCountCheck.MSG_PACKAGE_METHODS, 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountDefault']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountDefault']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountDefault']]" + + "/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testProtected() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMethodCountProtected.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodCountCheck.class); + moduleConfig.addProperty("maxProtected", "1"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(MethodCountCheck.class, + MethodCountCheck.MSG_PROTECTED_METHODS, 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountProtected']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountProtected']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountProtected']]" + + "/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testPublic() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMethodCountPublic.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(MethodCountCheck.class); + moduleConfig.addProperty("maxPublic", "1"); + + final String[] expectedViolation = { + "3:1: " + getCheckMessage(MethodCountCheck.class, + MethodCountCheck.MSG_PUBLIC_METHODS, 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountPublic']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountPublic']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathMethodCountPublic']]" + + "/LITERAL_CLASS" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionMethodLengthTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionMethodLengthTest.java new file mode 100644 index 000000000000..38244dad5495 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionMethodLengthTest.java @@ -0,0 +1,144 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.sizes; + +import static com.puppycrawl.tools.checkstyle.checks.sizes.MethodLengthCheck.MSG_KEY; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.sizes.MethodLengthCheck; + +public class XpathRegressionMethodLengthTest extends AbstractXpathTestSupport { + + private final String checkName = MethodLengthCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/sizes/methodlength"; + } + + @Test + public void testSimple() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMethodLengthSimple.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(MethodLengthCheck.class); + moduleConfig.addProperty("max", "10"); + + final String[] expectedViolations = { + "4:5: " + getCheckMessage(MethodLengthCheck.class, MSG_KEY, + 11, 10, "InputXpathMethodLengthSimple"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSimple']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSimple']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSimple']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSimple']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSimple']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSimple']]" + + "/MODIFIERS/LITERAL_PROTECTED" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testNoEmptyLines() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathMethodLengthNoEmptyLines.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(MethodLengthCheck.class); + moduleConfig.addProperty("max", "5"); + moduleConfig.addProperty("countEmpty", "false"); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expectedViolations = { + "15:5: " + getCheckMessage(MethodLengthCheck.class, MSG_KEY, 6, 5, "methodOne"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthNoEmptyLines']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodOne']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthNoEmptyLines']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodOne']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthNoEmptyLines']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodOne']]" + + "/MODIFIERS/LITERAL_PROTECTED" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testSingleToken() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathMethodLengthSingleToken.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(MethodLengthCheck.class); + moduleConfig.addProperty("max", "1"); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expectedViolations = { + "9:9: " + getCheckMessage(MethodLengthCheck.class, MSG_KEY, 3, 1, "methodOne"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSingleToken']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a']]/ASSIGN/EXPR/LITERAL_NEW" + + "[./IDENT[@text='InputXpathMethodLengthSingleToken']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodOne']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSingleToken']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a']]/ASSIGN/EXPR/LITERAL_NEW" + + "[./IDENT[@text='InputXpathMethodLengthSingleToken']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodOne']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodLengthSingleToken']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='a']]/ASSIGN/EXPR/LITERAL_NEW" + + "[./IDENT[@text='InputXpathMethodLengthSingleToken']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='methodOne']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionOuterTypeNumberTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionOuterTypeNumberTest.java new file mode 100644 index 000000000000..0170bd742e53 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionOuterTypeNumberTest.java @@ -0,0 +1,88 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.sizes; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.sizes.OuterTypeNumberCheck; + +public class XpathRegressionOuterTypeNumberTest extends AbstractXpathTestSupport { + + private final String checkName = OuterTypeNumberCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/sizes/outertypenumber"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathOuterTypeNumberDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OuterTypeNumberCheck.class); + + final String[] expectedViolation = { + "1:1: " + getCheckMessage(OuterTypeNumberCheck.class, + OuterTypeNumberCheck.MSG_KEY, 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMax() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathOuterTypeNumber.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OuterTypeNumberCheck.class); + moduleConfig.addProperty("max", "0"); + + final String[] expectedViolation = { + "1:1: " + getCheckMessage(OuterTypeNumberCheck.class, + OuterTypeNumberCheck.MSG_KEY, 3, 0), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionParameterNumberTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionParameterNumberTest.java new file mode 100644 index 000000000000..a1a625028646 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionParameterNumberTest.java @@ -0,0 +1,138 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.sizes; + +import static com.puppycrawl.tools.checkstyle.checks.sizes.ParameterNumberCheck.MSG_KEY; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.sizes.ParameterNumberCheck; + +public class XpathRegressionParameterNumberTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return ParameterNumberCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/sizes/parameternumber"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathParameterNumberDefault.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(ParameterNumberCheck.class); + + final String[] expectedViolations = { + "5:10: " + getCheckMessage(ParameterNumberCheck.class, MSG_KEY, 7, 11), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathParameterNumberDefault']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='myMethod']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + + } + + @Test + public void testMethods() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathParameterNumberMethods.java")); + + final DefaultConfiguration moduleConfig = createModuleConfig(ParameterNumberCheck.class); + moduleConfig.addProperty("max", "10"); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expectedViolations = { + "7:10: " + getCheckMessage(ParameterNumberCheck.class, MSG_KEY, 10, 11), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathParameterNumberMethods']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='myMethod']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testIgnoreOverriddenMethods() throws Exception { + final String filePath = + getPath("InputXpathParameterNumberIgnoreOverriddenMethods.java"); + final File fileToProcess = new File(filePath); + + final DefaultConfiguration moduleConfig = createModuleConfig(ParameterNumberCheck.class); + moduleConfig.addProperty("ignoreOverriddenMethods", "true"); + + final String[] expectedViolations = { + "6:13: " + getCheckMessage(ParameterNumberCheck.class, MSG_KEY, 7, 8), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathParameterNumberIgnoreOverriddenMethods']]" + + "/OBJBLOCK/CTOR_DEF/IDENT" + + "[@text='InputXpathParameterNumberIgnoreOverriddenMethods']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } + + @Test + public void testIgnoreAnnotatedBy() throws Exception { + final String filePath = + getPath("InputXpathParameterNumberIgnoreAnnotatedBy.java"); + final File fileToProcess = new File(filePath); + + final DefaultConfiguration moduleConfig = createModuleConfig(ParameterNumberCheck.class); + moduleConfig.addProperty("ignoreAnnotatedBy", "MyAnno"); + moduleConfig.addProperty("max", "2"); + + final String[] expectedViolations = { + "15:34: " + getCheckMessage(ParameterNumberCheck.class, MSG_KEY, 2, 3), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathParameterNumberIgnoreAnnotatedBy']]" + + "/OBJBLOCK/CLASS_DEF[./IDENT[@text='InnerClass']]" + + "/OBJBLOCK/STATIC_INIT/SLIST/EXPR/LITERAL_NEW[./IDENT[@text='Object']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]" + + "/SLIST/LITERAL_IF/SLIST/EXPR/LITERAL_NEW[./IDENT[@text='Object']]" + + "/OBJBLOCK/METHOD_DEF/IDENT[@text='checkedMethod']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolations, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionRecordComponentNumberTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionRecordComponentNumberTest.java new file mode 100644 index 000000000000..ce94452ac8c0 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/sizes/XpathRegressionRecordComponentNumberTest.java @@ -0,0 +1,100 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.sizes; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.sizes.RecordComponentNumberCheck; + +public class XpathRegressionRecordComponentNumberTest extends AbstractXpathTestSupport { + + private final String checkName = RecordComponentNumberCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/sizes/recordcomponentnumber"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathRecordComponentNumberDefault.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RecordComponentNumberCheck.class); + + final String[] expectedViolation = { + "8:1: " + getCheckMessage(RecordComponentNumberCheck.class, + RecordComponentNumberCheck.MSG_KEY, + 15, 8), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/RECORD_DEF[./IDENT[@text='InputXpathRecordComponentNumberDefault']]", + "/COMPILATION_UNIT/RECORD_DEF[./IDENT[@text='InputXpathRecordComponentNumberDefault']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/RECORD_DEF[./IDENT[@text='InputXpathRecordComponentNumberDefault']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testCustomMax() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathRecordComponentNumberCustomMax.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(RecordComponentNumberCheck.class); + moduleConfig.addProperty("max", "1"); + + final String[] expectedViolation = { + "9:5: " + getCheckMessage(RecordComponentNumberCheck.class, + RecordComponentNumberCheck.MSG_KEY, + 2, 1), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathRecordComponentNumberCustomMax']]" + + "/OBJBLOCK/RECORD_DEF[./IDENT[@text='MyRecord']]", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathRecordComponentNumberCustomMax']]" + + "/OBJBLOCK/RECORD_DEF[./IDENT[@text='MyRecord']]/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text='InputXpathRecordComponentNumberCustomMax']]" + + "/OBJBLOCK/RECORD_DEF[./IDENT[@text='MyRecord']]/MODIFIERS" + + "/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyForInitializerPadTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyForInitializerPadTest.java new file mode 100644 index 000000000000..d05c044a6d28 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyForInitializerPadTest.java @@ -0,0 +1,100 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForInitializerPadCheck; +import com.puppycrawl.tools.checkstyle.checks.whitespace.PadOption; + +public class XpathRegressionEmptyForInitializerPadTest extends AbstractXpathTestSupport { + + private final String checkName = EmptyForInitializerPadCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/emptyforinitializerpad"; + } + + @Test + public void testPreceded() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyForInitializerPadPreceded.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyForInitializerPadCheck.class); + + final String[] expectedViolation = { + "5:15: " + getCheckMessage(EmptyForInitializerPadCheck.class, + EmptyForInitializerPadCheck.MSG_PRECEDED, ";"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyForInitializerPadPreceded']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/FOR_INIT", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyForInitializerPadPreceded']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/SEMI[1]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNotPreceded() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyForInitializerPadNotPreceded.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyForInitializerPadCheck.class); + moduleConfig.addProperty("option", PadOption.SPACE.toString()); + + final String[] expectedViolation = { + "5:14: " + getCheckMessage(EmptyForInitializerPadCheck.class, + EmptyForInitializerPadCheck.MSG_NOT_PRECEDED, ";"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathEmptyForInitializerPadNotPreceded']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/FOR_INIT", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathEmptyForInitializerPadNotPreceded']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/SEMI[1]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyForIteratorPadTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyForIteratorPadTest.java new file mode 100644 index 000000000000..5ae3d5bf60a5 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyForIteratorPadTest.java @@ -0,0 +1,100 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyForIteratorPadCheck; +import com.puppycrawl.tools.checkstyle.checks.whitespace.PadOption; + +public class XpathRegressionEmptyForIteratorPadTest extends AbstractXpathTestSupport { + + private final String checkName = EmptyForIteratorPadCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/emptyforiteratorpad"; + } + + @Test + public void testFollowed() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathEmptyForIteratorPadFollowed.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyForIteratorPadCheck.class); + + final String[] expectedViolation = { + "5:34: " + getCheckMessage(EmptyForIteratorPadCheck.class, + EmptyForIteratorPadCheck.MSG_WS_FOLLOWED, ";"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathEmptyForIteratorPadFollowed']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/FOR_ITERATOR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathEmptyForIteratorPadFollowed']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/RPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testNotFollowed() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathEmptyForIteratorPadNotFollowed.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyForIteratorPadCheck.class); + moduleConfig.addProperty("option", PadOption.SPACE.toString()); + + final String[] expectedViolation = { + "5:33: " + getCheckMessage(EmptyForIteratorPadCheck.class, + EmptyForIteratorPadCheck.MSG_WS_NOT_FOLLOWED, ";"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathEmptyForIteratorPadNotFollowed']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/FOR_ITERATOR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathEmptyForIteratorPadNotFollowed']]/OBJBLOCK" + + "/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_FOR/RPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyLineSeparatorTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyLineSeparatorTest.java new file mode 100644 index 000000000000..67a8accd6f68 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionEmptyLineSeparatorTest.java @@ -0,0 +1,172 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.EmptyLineSeparatorCheck; + +public class XpathRegressionEmptyLineSeparatorTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return EmptyLineSeparatorCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/emptylineseparator"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyLineSeparatorOne.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyLineSeparatorCheck.class); + moduleConfig.addProperty("tokens", "PACKAGE_DEF"); + + final String[] expectedViolation = { + "4:1: " + getCheckMessage(EmptyLineSeparatorCheck.class, + EmptyLineSeparatorCheck.MSG_SHOULD_BE_SEPARATED, "package"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyLineSeparatorTwo.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyLineSeparatorCheck.class); + moduleConfig.addProperty("allowMultipleEmptyLines", "false"); + + final String[] expectedViolation = { + "6:1: " + getCheckMessage(EmptyLineSeparatorCheck.class, + EmptyLineSeparatorCheck.MSG_MULTIPLE_LINES, "package"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyLineSeparatorThree.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyLineSeparatorCheck.class); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expectedViolation = { + "9:5: " + getCheckMessage(EmptyLineSeparatorCheck.class, + EmptyLineSeparatorCheck.MSG_SHOULD_BE_SEPARATED, "METHOD_DEF"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyLineSeparatorThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyLineSeparatorThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyLineSeparatorThree']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]" + + "/MODIFIERS/LITERAL_PUBLIC" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyLineSeparatorFour.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyLineSeparatorCheck.class); + moduleConfig.addProperty("allowMultipleEmptyLines", "false"); + + final String[] expectedViolation = { + "12:25: " + getCheckMessage(EmptyLineSeparatorCheck.class, + EmptyLineSeparatorCheck.MSG_MULTIPLE_LINES_AFTER, "}"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyLineSeparatorFour']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]/SLIST/RCURLY" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testFive() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathEmptyLineSeparatorFive.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(EmptyLineSeparatorCheck.class); + moduleConfig.addProperty("allowMultipleEmptyLines", "false"); + moduleConfig.addProperty("allowMultipleEmptyLinesInsideClassMembers", "false"); + + final String[] expectedViolation = { + "14:15: " + getCheckMessage(EmptyLineSeparatorCheck.class, + EmptyLineSeparatorCheck.MSG_MULTIPLE_LINES_INSIDE), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathEmptyLineSeparatorFive']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='foo1']]/SLIST/LITERAL_TRY/SLIST" + + "/SINGLE_LINE_COMMENT/COMMENT_CONTENT[@text=' warn\\n']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionGenericWhitespaceTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionGenericWhitespaceTest.java similarity index 76% rename from src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionGenericWhitespaceTest.java rename to src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionGenericWhitespaceTest.java index 9fafd536a5cd..ad428d15129d 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionGenericWhitespaceTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionGenericWhitespaceTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,15 +15,16 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// -package org.checkstyle.suppressionxpathfilter; +package org.checkstyle.suppressionxpathfilter.whitespace; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; import org.junit.jupiter.api.Test; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -38,10 +39,15 @@ protected String getCheckName() { return checkName; } + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/genericwhitespace"; + } + @Test public void testProcessEnd() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceEnd.java")); + getPath("InputXpathGenericWhitespaceEnd.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -52,7 +58,8 @@ public void testProcessEnd() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceEnd']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathGenericWhitespaceEnd']]/OBJBLOCK" + "/METHOD_DEF[./IDENT[@text='bad']]" + "/PARAMETERS/PARAMETER_DEF[./IDENT[@text='cls']]" + "/TYPE[./IDENT[@text='Class']]/TYPE_ARGUMENTS/GENERIC_END" @@ -65,7 +72,7 @@ public void testProcessEnd() throws Exception { @Test public void testProcessNestedGenericsOne() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceNestedGenericsOne.java")); + getPath("InputXpathGenericWhitespaceNestedOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -76,8 +83,8 @@ public void testProcessNestedGenericsOne() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionGenericWhitespaceNestedGenericsOne']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathGenericWhitespaceNestedOne']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/TYPE_PARAMETERS" + "/TYPE_PARAMETER[./IDENT[@text='E']]" + "/TYPE_UPPER_BOUNDS[./IDENT[@text='Enum']]/TYPE_ARGUMENTS/GENERIC_END" @@ -90,7 +97,7 @@ public void testProcessNestedGenericsOne() throws Exception { @Test public void testProcessNestedGenericsTwo() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceNestedGenericsTwo.java")); + getPath("InputXpathGenericWhitespaceNestedTwo.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -101,8 +108,8 @@ public void testProcessNestedGenericsTwo() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionGenericWhitespaceNestedGenericsTwo']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathGenericWhitespaceNestedTwo']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/TYPE_PARAMETERS" + "/TYPE_PARAMETER[./IDENT[@text='E']]" + "/TYPE_UPPER_BOUNDS[./IDENT[@text='Enum']]/TYPE_ARGUMENTS/GENERIC_END" @@ -115,7 +122,7 @@ public void testProcessNestedGenericsTwo() throws Exception { @Test public void testProcessNestedGenericsThree() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceNestedGenericsThree.java")); + getPath("InputXpathGenericWhitespaceNestedThree.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -126,8 +133,8 @@ public void testProcessNestedGenericsThree() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionGenericWhitespaceNestedGenericsThree']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathGenericWhitespaceNestedThree']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/TYPE_PARAMETERS" + "/TYPE_PARAMETER[./IDENT[@text='E']]" + "/TYPE_UPPER_BOUNDS[./IDENT[@text='Enum']]/TYPE_ARGUMENTS/GENERIC_END" @@ -140,7 +147,7 @@ public void testProcessNestedGenericsThree() throws Exception { @Test public void testProcessSingleGenericOne() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceSingleGenericOne.java")); + getPath("InputXpathGenericWhitespaceSingleOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -151,8 +158,8 @@ public void testProcessSingleGenericOne() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionGenericWhitespaceSingleGenericOne']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathGenericWhitespaceSingleOne']]" + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/METHOD_CALL" + "/DOT[./IDENT[@text='Collections']]" + "/TYPE_ARGUMENTS/GENERIC_END" @@ -165,7 +172,7 @@ public void testProcessSingleGenericOne() throws Exception { @Test public void testProcessSingleGenericTwo() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceSingleGenericTwo.java")); + getPath("InputXpathGenericWhitespaceSingleTwo.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -176,8 +183,8 @@ public void testProcessSingleGenericTwo() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionGenericWhitespaceSingleGenericTwo']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathGenericWhitespaceSingleTwo']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/TYPE_PARAMETERS/GENERIC_END" ); @@ -188,7 +195,7 @@ public void testProcessSingleGenericTwo() throws Exception { @Test public void testProcessStartOne() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceStartOne.java")); + getPath("InputXpathGenericWhitespaceStartOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -199,9 +206,11 @@ public void testProcessStartOne() throws Exception { }; final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceStartOne']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathGenericWhitespaceStartOne']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/TYPE_PARAMETERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceStartOne']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathGenericWhitespaceStartOne']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/TYPE_PARAMETERS/GENERIC_START" ); @@ -212,7 +221,7 @@ public void testProcessStartOne() throws Exception { @Test public void testProcessStartTwo() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceStartTwo.java")); + getPath("InputXpathGenericWhitespaceStartTwo.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -223,11 +232,13 @@ public void testProcessStartTwo() throws Exception { }; final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceStartTwo']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathGenericWhitespaceStartTwo']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/PARAMETERS" + "/PARAMETER_DEF[./IDENT[@text='consumer']]" + "/TYPE[./IDENT[@text='Consumer']]/TYPE_ARGUMENTS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceStartTwo']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathGenericWhitespaceStartTwo']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/PARAMETERS" + "/PARAMETER_DEF[./IDENT[@text='consumer']]" + "/TYPE[./IDENT[@text='Consumer']]/TYPE_ARGUMENTS/GENERIC_START" @@ -240,7 +251,7 @@ public void testProcessStartTwo() throws Exception { @Test public void testProcessStartThree() throws Exception { final File fileToProcess = new File( - getPath("SuppressionXpathRegressionGenericWhitespaceStartThree.java")); + getPath("InputXpathGenericWhitespaceStartThree.java")); final DefaultConfiguration moduleConfig = createModuleConfig(GenericWhitespaceCheck.class); @@ -251,13 +262,17 @@ public void testProcessStartThree() throws Exception { }; final List expectedXpathQueries = Arrays.asList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceStartThree']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathGenericWhitespaceStartThree']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceStartThree']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathGenericWhitespaceStartThree']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/MODIFIERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceStartThree']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathGenericWhitespaceStartThree']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/TYPE_PARAMETERS", - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionGenericWhitespaceStartThree']]" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathGenericWhitespaceStartThree']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='bad']]/TYPE_PARAMETERS/GENERIC_START" ); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionMethodParamPadTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionMethodParamPadTest.java similarity index 75% rename from src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionMethodParamPadTest.java rename to src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionMethodParamPadTest.java index e895626181d5..5829fe440608 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionMethodParamPadTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionMethodParamPadTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,14 +15,15 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// -package org.checkstyle.suppressionxpathfilter; +package org.checkstyle.suppressionxpathfilter.whitespace; import java.io.File; import java.util.Collections; import java.util.List; +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; import org.junit.jupiter.api.Test; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -37,10 +38,15 @@ protected String getCheckName() { return checkName; } + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/methodparampad"; + } + @Test public void testOne() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionMethodParamPadOne.java")); + new File(getPath("InputXpathMethodParamPadOne.java")); final DefaultConfiguration moduleConfig = createModuleConfig(MethodParamPadCheck.class); @@ -51,7 +57,8 @@ public void testOne() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionMethodParamPadOne']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodParamPadOne']]/OBJBLOCK" + "/METHOD_DEF[./IDENT[@text='InputMethodParamPad']]/LPAREN" ); @@ -62,7 +69,7 @@ public void testOne() throws Exception { @Test public void testTwo() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionMethodParamPadTwo.java")); + new File(getPath("InputXpathMethodParamPadTwo.java")); final DefaultConfiguration moduleConfig = createModuleConfig(MethodParamPadCheck.class); @@ -73,7 +80,8 @@ public void testTwo() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionMethodParamPadTwo']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodParamPadTwo']]/OBJBLOCK" + "/METHOD_DEF[./IDENT[@text='sayHello']]/LPAREN" ); @@ -84,11 +92,11 @@ public void testTwo() throws Exception { @Test public void testThree() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionMethodParamPadThree.java")); + new File(getPath("InputXpathMethodParamPadThree.java")); final DefaultConfiguration moduleConfig = createModuleConfig(MethodParamPadCheck.class); - moduleConfig.addAttribute("option", "space"); + moduleConfig.addProperty("option", "space"); final String[] expectedViolation = { "4:25: " + getCheckMessage(MethodParamPadCheck.class, @@ -96,7 +104,8 @@ public void testThree() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionMethodParamPadThree']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathMethodParamPadThree']]/OBJBLOCK" + "/METHOD_DEF[./IDENT[@text='sayHello']]/LPAREN" ); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoLineWrapTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoLineWrapTest.java new file mode 100644 index 000000000000..a218dcd964af --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoLineWrapTest.java @@ -0,0 +1,133 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.NoLineWrapCheck; + +public class XpathRegressionNoLineWrapTest extends AbstractXpathTestSupport { + + @Override + protected String getCheckName() { + return NoLineWrapCheck.class.getSimpleName(); + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/nolinewrap"; + } + + @Test + public void testDefault() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathNoLineWrapDefault.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoLineWrapCheck.class); + + final String[] expectedViolation = { + "1:1: " + getCheckMessage(NoLineWrapCheck.class, + NoLineWrapCheck.MSG_KEY, "package"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT", "/COMPILATION_UNIT/PACKAGE_DEF" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testMethodDef() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathNoLineWrapTokensMethodDef.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoLineWrapCheck.class); + moduleConfig.addProperty("tokens", "METHOD_DEF"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(NoLineWrapCheck.class, + NoLineWrapCheck.MSG_KEY, "METHOD_DEF"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathNoLineWrapTokensMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test2']]", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathNoLineWrapTokensMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test2']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF[./IDENT" + + "[@text='InputXpathNoLineWrapTokensMethodDef']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test2']]" + + "/MODIFIERS/LITERAL_PUBLIC" + + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + + @Test + public void testTokensCtorDef() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathNoLineWrapTokensCtorDef.java") + ); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoLineWrapCheck.class); + moduleConfig.addProperty("tokens", "CTOR_DEF"); + + final String[] expectedViolation = { + "4:5: " + getCheckMessage(NoLineWrapCheck.class, + NoLineWrapCheck.MSG_KEY, "CTOR_DEF"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoLineWrapTokensCtorDef']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[@text='InputXpathNoLineWrapTokensCtorDef']]", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoLineWrapTokensCtorDef']]" + + "/OBJBLOCK/CTOR_DEF[./IDENT[@text='InputXpathNoLineWrapTokensCtorDef']]" + + "/MODIFIERS", + + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoLineWrapTokensCtorDef']]" + + "/OBJBLOCK/CTOR_DEF/IDENT[@text='InputXpathNoLineWrapTokensCtorDef']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceAfterTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceAfterTest.java new file mode 100644 index 000000000000..3853099db2e3 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceAfterTest.java @@ -0,0 +1,138 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceAfterCheck; + +public class XpathRegressionNoWhitespaceAfterTest extends AbstractXpathTestSupport { + + private final String checkName = NoWhitespaceAfterCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/nowhitespaceafter"; + } + + @Test + public void testNoWhitespaceAfter() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNoWhitespaceAfter.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceAfterCheck.class); + + final String[] expectedViolation = { + "4:15: " + getCheckMessage(NoWhitespaceAfterCheck.class, + NoWhitespaceAfterCheck.MSG_KEY, "-"), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceAfter']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceAfter']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/UNARY_MINUS[" + + "./NUM_INT[@text='1']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTokens() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNoWhitespaceAfterTokens.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceAfterCheck.class); + moduleConfig.addProperty("tokens", "DOT"); + + final String[] expectedViolation = { + "4:16: " + getCheckMessage(NoWhitespaceAfterCheck.class, + NoWhitespaceAfterCheck.MSG_KEY, "."), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceAfterTokens']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/TYPE/DOT[./IDENT[@text='String']]" + + "/DOT[./IDENT[@text='java']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testAllowLineBreaks() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNoWhitespaceAfterLineBreaks.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceAfterCheck.class); + moduleConfig.addProperty("allowLineBreaks", "false"); + + final String[] expectedViolation = { + "6:13: " + getCheckMessage(NoWhitespaceAfterCheck.class, + NoWhitespaceAfterCheck.MSG_KEY, "."), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceAfterLineBreaks']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='s']]", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceAfterLineBreaks']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='s']]" + + "/MODIFIERS", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceAfterLineBreaks']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='s']]/TYPE", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceAfterLineBreaks']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='s']]" + + "/TYPE/DOT[./IDENT[@text='String']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceBeforeCaseDefaultColonTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceBeforeCaseDefaultColonTest.java new file mode 100644 index 000000000000..ac2ffb7fc4f0 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceBeforeCaseDefaultColonTest.java @@ -0,0 +1,146 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceBeforeCaseDefaultColonCheck; + +public class XpathRegressionNoWhitespaceBeforeCaseDefaultColonTest + extends AbstractXpathTestSupport { + + private final String checkName = NoWhitespaceBeforeCaseDefaultColonCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/" + + "nowhitespacebeforecasedefaultcolon"; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathNoWhitespaceBeforeCaseDefaultColonOne.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceBeforeCaseDefaultColonCheck.class); + + final String[] expectedViolation = { + "6:20: " + getCheckMessage(NoWhitespaceBeforeCaseDefaultColonCheck.class, + NoWhitespaceBeforeCaseDefaultColonCheck.MSG_KEY, ":"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathNoWhitespaceBeforeCaseDefaultColonOne']]" + + "/OBJBLOCK/INSTANCE_INIT/SLIST/LITERAL_SWITCH/CASE_GROUP/LITERAL_CASE/COLON" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathNoWhitespaceBeforeCaseDefaultColonTwo.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceBeforeCaseDefaultColonCheck.class); + + final String[] expectedViolation = { + "10:21: " + getCheckMessage(NoWhitespaceBeforeCaseDefaultColonCheck.class, + NoWhitespaceBeforeCaseDefaultColonCheck.MSG_KEY, ":"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathNoWhitespaceBeforeCaseDefaultColonTwo']]" + + "/OBJBLOCK/INSTANCE_INIT/SLIST/LITERAL_SWITCH/CASE_GROUP" + + "/LITERAL_DEFAULT/COLON" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathNoWhitespaceBeforeCaseDefaultColonThree.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceBeforeCaseDefaultColonCheck.class); + + final String[] expectedViolation = { + "7:21: " + getCheckMessage(NoWhitespaceBeforeCaseDefaultColonCheck.class, + NoWhitespaceBeforeCaseDefaultColonCheck.MSG_KEY, ":"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathNoWhitespaceBeforeCaseDefaultColonThree']]" + + "/OBJBLOCK/INSTANCE_INIT/SLIST/LITERAL_SWITCH/CASE_GROUP" + + "/LITERAL_CASE/COLON" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testFour() throws Exception { + final File fileToProcess = + new File(getPath( + "InputXpathNoWhitespaceBeforeCaseDefaultColonFour.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceBeforeCaseDefaultColonCheck.class); + + final String[] expectedViolation = { + "11:21: " + getCheckMessage(NoWhitespaceBeforeCaseDefaultColonCheck.class, + NoWhitespaceBeforeCaseDefaultColonCheck.MSG_KEY, ":"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathNoWhitespaceBeforeCaseDefaultColonFour']]" + + "/OBJBLOCK/INSTANCE_INIT/SLIST/LITERAL_SWITCH/CASE_GROUP" + + "/LITERAL_DEFAULT/COLON" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceBeforeTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceBeforeTest.java new file mode 100644 index 000000000000..be5694af2eff --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionNoWhitespaceBeforeTest.java @@ -0,0 +1,120 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.NoWhitespaceBeforeCheck; + +public class XpathRegressionNoWhitespaceBeforeTest extends AbstractXpathTestSupport { + + private final String checkName = NoWhitespaceBeforeCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/nowhitespacebefore"; + } + + @Test + public void testNoWhitespaceBefore() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNoWhitespaceBefore.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceBeforeCheck.class); + + final String[] expectedViolation = { + "4:13: " + getCheckMessage(NoWhitespaceBeforeCheck.class, + NoWhitespaceBeforeCheck.MSG_KEY, ";"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceBefore']]/OBJBLOCK" + + "/VARIABLE_DEF[./IDENT[@text='bad']]/SEMI" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTokens() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNoWhitespaceBeforeTokens.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceBeforeCheck.class); + moduleConfig.addProperty("tokens", "DOT"); + + final String[] expectedViolation = { + "4:17: " + getCheckMessage(NoWhitespaceBeforeCheck.class, + NoWhitespaceBeforeCheck.MSG_KEY, "."), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceBeforeTokens']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/TYPE/DOT[./IDENT[@text='String']]" + + "/DOT[./IDENT[@text='java']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testAllowLineBreaks() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathNoWhitespaceBeforeLineBreaks.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(NoWhitespaceBeforeCheck.class); + moduleConfig.addProperty("allowLineBreaks", "false"); + + final String[] expectedViolation = { + "6:13: " + getCheckMessage(NoWhitespaceBeforeCheck.class, + NoWhitespaceBeforeCheck.MSG_KEY, ","), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathNoWhitespaceBeforeLineBreaks']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='array']]" + + "/ASSIGN/ARRAY_INIT/COMMA" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionOperatorWrapTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionOperatorWrapTest.java new file mode 100644 index 000000000000..cde018999ff4 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionOperatorWrapTest.java @@ -0,0 +1,98 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.OperatorWrapCheck; + +public class XpathRegressionOperatorWrapTest extends AbstractXpathTestSupport { + + private final String checkName = OperatorWrapCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/operatorwrap"; + } + + @Test + public void testOperatorWrapNewLine() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathOperatorWrapNewLine.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OperatorWrapCheck.class); + + final String[] expectedViolation = { + "6:19: " + getCheckMessage(OperatorWrapCheck.class, + OperatorWrapCheck.MSG_LINE_NEW, "+"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text" + + "='InputXpathOperatorWrapNewLine']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='test']]" + + "/SLIST/VARIABLE_DEF[./IDENT[@text='x']]" + + "/ASSIGN/EXPR/MINUS[./NUM_INT[@text='4']]" + + "/MINUS[./NUM_INT[@text='3']]" + + "/PLUS[./NUM_INT[@text='1']]" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testOperatorWrapPreviousLine() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathOperatorWrapPreviousLine.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(OperatorWrapCheck.class); + moduleConfig.addProperty("tokens", "ASSIGN"); + moduleConfig.addProperty("option", "eol"); + + final String[] expectedViolation = { + "5:11: " + getCheckMessage(OperatorWrapCheck.class, + OperatorWrapCheck.MSG_LINE_PREVIOUS, "="), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT" + + "/CLASS_DEF[./IDENT[@text='InputXpathOperatorWrapPreviousLine']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='b']]" + + "/ASSIGN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionParenPadTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionParenPadTest.java similarity index 75% rename from src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionParenPadTest.java rename to src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionParenPadTest.java index eac619ebb234..05ea26105a20 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionParenPadTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionParenPadTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,14 +15,15 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// -package org.checkstyle.suppressionxpathfilter; +package org.checkstyle.suppressionxpathfilter.whitespace; import java.io.File; import java.util.Collections; import java.util.List; +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; import org.junit.jupiter.api.Test; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -39,10 +40,15 @@ protected String getCheckName() { return checkName; } + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/parenpad"; + } + @Test public void testLeftFollowed() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionParenPadLeftFollowed.java")); + new File(getPath("InputXpathParenPadLeftFollowed.java")); final DefaultConfiguration moduleConfig = createModuleConfig(ParenPadCheck.class); @@ -53,7 +59,8 @@ public void testLeftFollowed() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionParenPadLeftFollowed']]" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathParenPadLeftFollowed']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_IF/LPAREN" ); @@ -64,11 +71,11 @@ public void testLeftFollowed() throws Exception { @Test public void testLeftNotFollowed() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionParenPadLeftNotFollowed.java")); + new File(getPath("InputXpathParenPadLeftNotFollowed.java")); final DefaultConfiguration moduleConfig = createModuleConfig(ParenPadCheck.class); - moduleConfig.addAttribute("option", PadOption.SPACE.toString()); + moduleConfig.addProperty("option", PadOption.SPACE.toString()); final String[] expectedViolation = { "5:12: " + getCheckMessage(ParenPadCheck.class, @@ -76,7 +83,8 @@ public void testLeftNotFollowed() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionParenPadLeftNotFollowed']]" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathParenPadLeftNotFollowed']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_IF/LPAREN" ); @@ -87,7 +95,7 @@ public void testLeftNotFollowed() throws Exception { @Test public void testRightPreceded() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionParenPadRightPreceded.java")); + new File(getPath("InputXpathParenPadRightPreceded.java")); final DefaultConfiguration moduleConfig = createModuleConfig(ParenPadCheck.class); @@ -98,7 +106,8 @@ public void testRightPreceded() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionParenPadRightPreceded']]" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathParenPadRightPreceded']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_IF/RPAREN" ); @@ -109,11 +118,11 @@ public void testRightPreceded() throws Exception { @Test public void testRightNotPreceded() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionParenPadRightNotPreceded.java")); + new File(getPath("InputXpathParenPadRightNotPreceded.java")); final DefaultConfiguration moduleConfig = createModuleConfig(ParenPadCheck.class); - moduleConfig.addAttribute("option", PadOption.SPACE.toString()); + moduleConfig.addProperty("option", PadOption.SPACE.toString()); final String[] expectedViolation = { "5:19: " + getCheckMessage(ParenPadCheck.class, @@ -121,7 +130,8 @@ public void testRightNotPreceded() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[@text='SuppressionXpathRegressionParenPadRightNotPreceded']]" + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathParenPadRightNotPreceded']]" + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method']]/SLIST/LITERAL_IF/RPAREN" ); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionSeparatorWrapTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionSeparatorWrapTest.java new file mode 100644 index 000000000000..58c740e53b45 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionSeparatorWrapTest.java @@ -0,0 +1,122 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.SeparatorWrapCheck; + +public class XpathRegressionSeparatorWrapTest extends AbstractXpathTestSupport { + + private final String checkName = SeparatorWrapCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/separatorwrap"; + } + + @Test + public void testClass() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSeparatorWrapClass.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(SeparatorWrapCheck.class); + + final String[] expectedViolation = { + "10:17: " + getCheckMessage(SeparatorWrapCheck.class, + SeparatorWrapCheck.MSG_LINE_PREVIOUS, ","), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathSeparatorWrapClass']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod']]" + + "/PARAMETERS/COMMA" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testInterface() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSeparatorWrapInterface.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SeparatorWrapCheck.class); + moduleConfig.addProperty("tokens", "ELLIPSIS"); + final String[] expectedViolation = { + "9:13: " + getCheckMessage(SeparatorWrapCheck.class, + SeparatorWrapCheck.MSG_LINE_PREVIOUS, "..."), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/INTERFACE_DEF" + + "[./IDENT[@text='InputXpathSeparatorWrapInterface']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='testMethod2']]" + + "/PARAMETERS/PARAMETER_DEF" + + "[./IDENT[@text='parameters']]/ELLIPSIS" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testMethod() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSeparatorWrapMethod.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SeparatorWrapCheck.class); + moduleConfig.addProperty("tokens", "DOT"); + + final String[] expectedViolation = { + "9:13: " + getCheckMessage(SeparatorWrapCheck.class, + SeparatorWrapCheck.MSG_LINE_PREVIOUS, "."), + }; + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathSeparatorWrapMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method1']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='stringLength']]" + + "/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[@text=" + + "'InputXpathSeparatorWrapMethod']]" + + "/OBJBLOCK/METHOD_DEF[./IDENT[@text='method1']]/SLIST" + + "/VARIABLE_DEF[./IDENT[@text='stringLength']]/ASSIGN" + + "/EXPR/DOT[./IDENT[@text='stringArray']]" + ); + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionSingleSpaceSeparatorTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionSingleSpaceSeparatorTest.java new file mode 100644 index 000000000000..cb39207a99e9 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionSingleSpaceSeparatorTest.java @@ -0,0 +1,94 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.SingleSpaceSeparatorCheck; + +public class XpathRegressionSingleSpaceSeparatorTest extends AbstractXpathTestSupport { + + private final String checkName = SingleSpaceSeparatorCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/singlespaceseparator"; + } + + @Test + public void testSingleSpaceSeparator() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathSingleSpaceSeparator.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SingleSpaceSeparatorCheck.class); + + final String[] expectedViolation = { + "4:11: " + getCheckMessage(SingleSpaceSeparatorCheck.class, + SingleSpaceSeparatorCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathSingleSpaceSeparator']]/OBJBLOCK" + + "/VARIABLE_DEF/IDENT[@text='bad']" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testValidateComments() throws Exception { + final File fileToProcess = new File(getPath( + "InputXpathSingleSpaceSeparatorValidateComments.java" + )); + + final DefaultConfiguration moduleConfig = + createModuleConfig(SingleSpaceSeparatorCheck.class); + moduleConfig.addProperty("validateComments", "true"); + + final String[] expectedViolation = { + "4:17: " + getCheckMessage(SingleSpaceSeparatorCheck.class, + SingleSpaceSeparatorCheck.MSG_KEY), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[." + + "/IDENT[@text='InputXpathSingleSpaceSeparatorValidateComments']]" + + "/OBJBLOCK/SINGLE_LINE_COMMENT[./COMMENT_CONTENT" + + "[@text=' an invalid comment // warn\\n']]" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionTypecastParenPadTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionTypecastParenPadTest.java new file mode 100644 index 000000000000..6af170f83484 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionTypecastParenPadTest.java @@ -0,0 +1,149 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.checkstyle.suppressionxpathfilter.whitespace; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.whitespace.AbstractParenPadCheck; +import com.puppycrawl.tools.checkstyle.checks.whitespace.PadOption; +import com.puppycrawl.tools.checkstyle.checks.whitespace.TypecastParenPadCheck; + +public class XpathRegressionTypecastParenPadTest extends AbstractXpathTestSupport { + + private final String checkName = TypecastParenPadCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/typecastparenpad"; + } + + @Test + public void testLeftFollowed() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathTypecastParenPadLeftFollowed.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(TypecastParenPadCheck.class); + + final String[] expectedViolation = { + "4:18: " + getCheckMessage(TypecastParenPadCheck.class, + AbstractParenPadCheck.MSG_WS_FOLLOWED, "("), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathTypecastParenPadLeftFollowed']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathTypecastParenPadLeftFollowed']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testLeftNotFollowed() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathTypecastParenPadLeftNotFollowed.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(TypecastParenPadCheck.class); + moduleConfig.addProperty("option", PadOption.SPACE.toString()); + + final String[] expectedViolation = { + "4:18: " + getCheckMessage(TypecastParenPadCheck.class, + AbstractParenPadCheck.MSG_WS_NOT_FOLLOWED, "("), + }; + + final List expectedXpathQueries = Arrays.asList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathTypecastParenPadLeftNotFollowed']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR", + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathTypecastParenPadLeftNotFollowed']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testRightPreceded() throws Exception { + final File fileToProcess = + new File(getPath("InputXpathTypecastParenPadRightPreceded.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(TypecastParenPadCheck.class); + + final String[] expectedViolation = { + "4:26: " + getCheckMessage(TypecastParenPadCheck.class, + AbstractParenPadCheck.MSG_WS_PRECEDED, ")"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF" + + "[./IDENT[@text='InputXpathTypecastParenPadRightPreceded']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST/RPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testRightNotPreceded() throws Exception { + final File fileToProcess = new File( + getPath("InputXpathTypecastParenPadRightNotPreceded.java")); + + final DefaultConfiguration moduleConfig = + createModuleConfig(TypecastParenPadCheck.class); + moduleConfig.addProperty("option", PadOption.SPACE.toString()); + + final String[] expectedViolation = { + "4:26: " + getCheckMessage(TypecastParenPadCheck.class, + AbstractParenPadCheck.MSG_WS_NOT_PRECEDED, ")"), + }; + + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathTypecastParenPadRightNotPreceded']]" + + "/OBJBLOCK/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST/RPAREN" + ); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionWhitespaceAfterTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionWhitespaceAfterTest.java similarity index 75% rename from src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionWhitespaceAfterTest.java rename to src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionWhitespaceAfterTest.java index 155882504bae..84e3b2926b56 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionWhitespaceAfterTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionWhitespaceAfterTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,14 +15,15 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// -package org.checkstyle.suppressionxpathfilter; +package org.checkstyle.suppressionxpathfilter.whitespace; import java.io.File; import java.util.Collections; import java.util.List; +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; import org.junit.jupiter.api.Test; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -37,10 +38,15 @@ protected String getCheckName() { return checkName; } + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/whitespaceafter"; + } + @Test public void testWhitespaceAfterTypecast() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionWhitespaceAfterTypecast.java")); + new File(getPath("InputXpathWhitespaceAfterTypecast.java")); final DefaultConfiguration moduleConfig = createModuleConfig(WhitespaceAfterCheck.class); @@ -51,8 +57,8 @@ public void testWhitespaceAfterTypecast() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionWhitespaceAfterTypecast']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathWhitespaceAfterTypecast']]/OBJBLOCK" + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/EXPR/TYPECAST/RPAREN" ); @@ -63,7 +69,7 @@ public void testWhitespaceAfterTypecast() throws Exception { @Test public void testWhitespaceAfterNotFollowed() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionWhitespaceAfterNotFollowed.java")); + new File(getPath("InputXpathWhitespaceAfterNotFollowed.java")); final DefaultConfiguration moduleConfig = createModuleConfig(WhitespaceAfterCheck.class); @@ -74,8 +80,8 @@ public void testWhitespaceAfterNotFollowed() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionWhitespaceAfterNotFollowed']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathWhitespaceAfterNotFollowed']]/OBJBLOCK" + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN/ARRAY_INIT/COMMA" ); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionWhitespaceAroundTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionWhitespaceAroundTest.java similarity index 75% rename from src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionWhitespaceAroundTest.java rename to src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionWhitespaceAroundTest.java index 346188dd5b94..3ac77fe421af 100644 --- a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionWhitespaceAroundTest.java +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/whitespace/XpathRegressionWhitespaceAroundTest.java @@ -1,6 +1,6 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2020 the original author or authors. +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// Copyright (C) 2001-2025 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -15,14 +15,15 @@ // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////////////////////// -package org.checkstyle.suppressionxpathfilter; +package org.checkstyle.suppressionxpathfilter.whitespace; import java.io.File; import java.util.Collections; import java.util.List; +import org.checkstyle.suppressionxpathfilter.AbstractXpathTestSupport; import org.junit.jupiter.api.Test; import com.puppycrawl.tools.checkstyle.DefaultConfiguration; @@ -37,10 +38,15 @@ protected String getCheckName() { return checkName; } + @Override + protected String getPackageLocation() { + return "org/checkstyle/suppressionxpathfilter/whitespace/whitespacearound"; + } + @Test public void testWhitespaceAroundNotPreceded() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionWhitespaceAroundNotPreceded.java")); + new File(getPath("InputXpathWhitespaceAroundNotPreceded.java")); final DefaultConfiguration moduleConfig = createModuleConfig(WhitespaceAroundCheck.class); @@ -51,8 +57,8 @@ public void testWhitespaceAroundNotPreceded() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionWhitespaceAroundNotPreceded']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathWhitespaceAroundNotPreceded']]/OBJBLOCK" + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN" ); @@ -63,7 +69,7 @@ public void testWhitespaceAroundNotPreceded() throws Exception { @Test public void testWhitespaceAroundNotFollowed() throws Exception { final File fileToProcess = - new File(getPath("SuppressionXpathRegressionWhitespaceAroundNotFollowed.java")); + new File(getPath("InputXpathWhitespaceAroundNotFollowed.java")); final DefaultConfiguration moduleConfig = createModuleConfig(WhitespaceAroundCheck.class); @@ -74,8 +80,8 @@ public void testWhitespaceAroundNotFollowed() throws Exception { }; final List expectedXpathQueries = Collections.singletonList( - "/CLASS_DEF[./IDENT[" - + "@text='SuppressionXpathRegressionWhitespaceAroundNotFollowed']]/OBJBLOCK" + "/COMPILATION_UNIT/CLASS_DEF[./IDENT[" + + "@text='InputXpathWhitespaceAroundNotFollowed']]/OBJBLOCK" + "/VARIABLE_DEF[./IDENT[@text='bad']]/ASSIGN" ); diff --git a/src/it/resources-noncompilable/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputFormattedOneStatementPerLine2.java b/src/it/resources-noncompilable/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputFormattedOneStatementPerLine2.java new file mode 100644 index 000000000000..bba495daa157 --- /dev/null +++ b/src/it/resources-noncompilable/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputFormattedOneStatementPerLine2.java @@ -0,0 +1,110 @@ +// non-compiled with eclipse: extra semicolumn in imports + +package com.puppycrawl.tools.checkstyle.checks.coding.onestatementperline; + +/* + * This file contains test inputs for InputFormattedOneStatementPerLine2 + * which cause compilation problem in Eclipse 4.2.2 but still must be tested. + */ + +/* + * Two import statements and one 'empty' statement + * which are not on the same line are legal. + */ +import java.awt.event.ActionEvent; +import java.util.LinkedList; +import java.util.List; +import javax.swing.JCheckBox; + +/** Some javadoc. */ +public class InputFormattedOneStatementPerLine2 { + /* + * According to java language specifications, + * statements end with ';'. That is why ';;' + * may be considered as two empty statements on the same line + * and rises violation. + */ + ; + + static { + new JCheckBox() + .addActionListener( + (final ActionEvent e) -> { + good(); + }); + List ints = new LinkedList(); + ints.stream() + .map( + t -> { + return t * 2; + }) + .filter( + t -> { + return false; + }); + + ints.stream() + .map( + t -> { + int m = t * 2; + return m; + }); + + ints.stream() + .map( + t -> { + int m = t * 2; + return m; + }); + int i = 3; + + ints.stream().map(t -> t * 2); + int k = 4; + + ints.stream().map(t -> t * 2); + List ints2 = new LinkedList(); + + ints.stream() + .map( + t -> { + return ints2.stream() + .map( + w -> { + return w * 2; + }); + }); + + ints.stream() + .map( + t -> { + return ints2.stream() + .map( + w -> { + int m = w; + return m; + }); + }); + + ints.stream() + .map( + t -> { + return ints2.stream() + .map( + w -> { + int m = w * 2; + return m; + }); + }); + ints.stream() + .map( + t -> { + int l = 0; + for (int j = 0; j < 10; j++) { + l = j + l; + } + return l; + }); + } + + private static void good() {} +} diff --git a/src/it/resources-noncompilable/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine2.java b/src/it/resources-noncompilable/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine2.java new file mode 100644 index 000000000000..b9dadf0f9d39 --- /dev/null +++ b/src/it/resources-noncompilable/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine2.java @@ -0,0 +1,83 @@ +// non-compiled with eclipse: extra semicolumn in imports + +package com.puppycrawl.tools.checkstyle.checks.coding.onestatementperline; + +/* + * This file contains test inputs for InputOneStatementPerLine2 + * which cause compilation problem in Eclipse 4.2.2 but still must be tested. + */ + +/* + * Two import statements and one 'empty' statement + * which are not on the same line are legal. + */ +import java.awt.event.ActionEvent; +import java.lang.Integer; +import java.lang.String; +import java.lang.annotation.Annotation; +; // non-compilable by eclipse +// violation above '';' should be separated from previous line.' +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import javax.swing.JCheckBox; + +/** Some javadoc. */ +public class InputOneStatementPerLine2 { + /* + * According to java language specifications, + * statements end with ';'. That is why ';;' + * may be considered as two empty statements on the same line + * and rises violation. + */ + ;; // violation 'Only one statement per line allowed.' + static { + new JCheckBox().addActionListener((final ActionEvent e) -> { good(); }); + // violation above ''{' at column 64 should have line break after.' + List ints = new LinkedList(); + ints.stream().map(t -> { return t * 2; }).filter(t -> { return false; }); + // 2 violations above: + // ''{' at column 28 should have line break after.' + // ''{' at column 59 should have line break after.' + ints.stream().map(t -> { int m = t * 2; return m; }); + // 2 violations above: + // ''{' at column 28 should have line break after.' + // 'Only one statement per line allowed.' + ints.stream().map(t -> { int m = t * 2; return m; }); int i = 3; + // 3 violations above: + // ''{' at column 28 should have line break after.' + // 'Only one statement per line allowed.' + // 'Only one statement per line allowed.' + ints.stream().map(t -> t * 2); int k = 4; + // violation above 'Only one statement per line allowed.' + ints.stream().map(t -> t * 2); + List ints2 = new LinkedList(); + ints.stream().map(t -> { return ints2.stream().map(w -> { return w * 2; }); }); + // 2 violations above: + // ''{' at column 28 should have line break after.' + // ''{' at column 61 should have line break after.' + ints.stream().map(t -> { return ints2.stream().map(w -> { int m = w; return m; }); }); + // 3 violations above: + // ''{' at column 28 should have line break after.' + // ''{' at column 61 should have line break after.' + // 'Only one statement per line allowed.' + + ints.stream().map(t -> { + return ints2.stream().map( + w -> { + int m = w * 2; + return m; + }); + }); + ints.stream().map(t -> { + int l = 0; + for (int j = 0; j < 10; j++) { + l = j + l; + } + return l; + }); + } + + private static void good() {} +} diff --git a/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromAndroid.java b/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromAndroid.java index 43bd37dc5db9..b7f53bc5594b 100644 --- a/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromAndroid.java +++ b/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromAndroid.java @@ -1,8 +1,8 @@ -//non-compiled with javac: contains specially crafted set of imports for testing +// non-compiled with javac: contains specially crafted set of imports for testing package org.checkstyle.checks.importorder; /** * This test-input is intended to be checked using following configuration: - * + * Config * groups = {android,androidx,com.android,dalvik,com,gov,junit,libcore,net,org,java,javax} * option = top * ordered = true diff --git a/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromSpotify.java b/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromSpotify.java index 03b2210a2340..8bdc010fe050 100644 --- a/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromSpotify.java +++ b/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromSpotify.java @@ -1,8 +1,8 @@ -//non-compiled with javac: contains specially crafted set of imports for testing +// non-compiled with javac: contains specially crafted set of imports for testing package org.checkstyle.checks.importorder; /** * This test-input is intended to be checked using following configuration: - * + * Config * groups = {android,com,net,junit,org,java,javax} * option = bottom * ordered = true diff --git a/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromTwitter.java b/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromTwitter.java index b7d25b90bc6e..8a83be12a76d 100644 --- a/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromTwitter.java +++ b/src/it/resources-noncompilable/org/checkstyle/checks/imports/importorder/InputFromTwitter.java @@ -1,8 +1,8 @@ -//non-compiled with javac: contains specially crafted set of imports for testing +// non-compiled with javac: contains specially crafted set of imports for testing package org.checkstyle.checks.importorder; /** * This test-input is intended to be checked using following configuration: - * + * Config * caseSensitive = true * groups = {android,com.twitter,com,junit,net,org,java,javax} * option = bottom diff --git a/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/annotation/packageannotation/InputXpathPackageAnnotationOne.java b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/annotation/packageannotation/InputXpathPackageAnnotationOne.java new file mode 100644 index 000000000000..3b57e891ec55 --- /dev/null +++ b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/annotation/packageannotation/InputXpathPackageAnnotationOne.java @@ -0,0 +1,8 @@ +// non-compiled with javac: compiling on jdk before 8 +//more details at https://github.com/checkstyle/checkstyle/issues/7846 +@Deprecated +package com.puppycrawl.tools.checkstyle.checks.annotation.packageannotation; // warn + +public class InputXpathPackageAnnotationOne { + +} diff --git a/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/annotation/packageannotation/InputXpathPackageAnnotationTwo.java b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/annotation/packageannotation/InputXpathPackageAnnotationTwo.java new file mode 100644 index 000000000000..ce0e6aecb8dc --- /dev/null +++ b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/annotation/packageannotation/InputXpathPackageAnnotationTwo.java @@ -0,0 +1,10 @@ +// non-compiled with javac: compiling on jdk before 8 +//more details at https://github.com/checkstyle/checkstyle/issues/7846 +@Deprecated @Generated("foo") +package com.puppycrawl.tools.checkstyle.checks.annotation.packageannotation.two; // warn + +import javax.annotation.Generated; + +public class InputXpathPackageAnnotationTwo { + +} diff --git a/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationAnonymous.java b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationAnonymous.java new file mode 100644 index 000000000000..edeb36c97994 --- /dev/null +++ b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationAnonymous.java @@ -0,0 +1,13 @@ +// non-compiled with javac: compiling on jdk before 9 + +package org.checkstyle.suppressionxpathfilter.coding.illegalinstantiation; + +public class InputXpathIllegalInstantiationAnonymous { + int b = 5; // ok + class Inner{ + public void test() { + Boolean x = new Boolean(true); // ok + Integer e = new Integer(b); // warn + } + } +} diff --git a/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationInterface.java b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationInterface.java new file mode 100644 index 000000000000..00aaab6d73b3 --- /dev/null +++ b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationInterface.java @@ -0,0 +1,13 @@ +// non-compiled with javac: compiling on jdk before 9 + +package org.checkstyle.suppressionxpathfilter.coding.illegalinstantiation; + +public class InputXpathIllegalInstantiationInterface { + interface Inner { + default void test() { + Boolean x = new Boolean(true); // ok + Integer e = new Integer(5); // ok + String s = new String(); // warn + } + } +} diff --git a/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationSimple.java b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationSimple.java new file mode 100644 index 000000000000..5065fc6562d8 --- /dev/null +++ b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/illegalinstantiation/InputXpathIllegalInstantiationSimple.java @@ -0,0 +1,11 @@ +// non-compiled with javac: compiling on jdk before 9 + +package org.checkstyle.suppressionxpathfilter.coding.illegalinstantiation; + +public class InputXpathIllegalInstantiationSimple { + int b = 5; // ok + public void test() { + Boolean x = new Boolean(true); // warn + Integer e = new Integer(b); // ok + } +} diff --git a/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/packagedeclaration/InputXpathMissingPackage.java b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/packagedeclaration/InputXpathMissingPackage.java new file mode 100644 index 000000000000..39c32922a5e2 --- /dev/null +++ b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/packagedeclaration/InputXpathMissingPackage.java @@ -0,0 +1,5 @@ +// non-compiled with javac: missing package. Used for Testing purpose. +// package is missing. +public class InputXpathMissingPackage { // warn + // code +} diff --git a/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/packagedeclaration/InputXpathWrongPackage.java b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/packagedeclaration/InputXpathWrongPackage.java new file mode 100644 index 000000000000..e99f4c59afd0 --- /dev/null +++ b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/coding/packagedeclaration/InputXpathWrongPackage.java @@ -0,0 +1,6 @@ +// non-compiled with javac: wrong package. Used for Testing purpose. +package my.packagename.mismatch.with.folder; // warn + +public class InputXpathWrongPackage { + // code +} diff --git a/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/naming/packagename/InputXpathPackageNameThree.java b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/naming/packagename/InputXpathPackageNameThree.java new file mode 100644 index 000000000000..9bc1d0519f96 --- /dev/null +++ b/src/it/resources-noncompilable/org/checkstyle/suppressionxpathfilter/naming/packagename/InputXpathPackageNameThree.java @@ -0,0 +1,4 @@ +package org.checkstyle.suppressionxpathfilter.PACKAGENAME; // warn + +public class InputXpathPackageNameThree { +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule21filename/InputFileName1.java b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule21filename/InputFileName1.java new file mode 100644 index 000000000000..0e2a68a25a51 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule21filename/InputFileName1.java @@ -0,0 +1,38 @@ +package com.google.checkstyle.test.chapter2filebasic.rule21filename; + +// violation below 'Top-level class MyAnnotation1 has to reside in its own source file.' +@interface MyAnnotation1 { + String name(); + + int version(); +} + +/** Some javadoc. */ +@MyAnnotation1(name = "ABC", version = 1) +public class InputFileName1 {} + +// violation below 'Top-level class Enum1 has to reside in its own source file.' +enum Enum1 { + A, + B, + C; + + Enum1() {} + + public String toString() { + return ""; // some custom implementation + } +} + +// violation below 'Top-level class TestRequireThisEnum has to reside in its own source file.' +interface TestRequireThisEnum { + enum DayOfWeek { + SUNDAY, + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + FRIDAY, + SATURDAY + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule21filename/InputFileName2.java b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule21filename/InputFileName2.java new file mode 100644 index 000000000000..a3e41aaa5b73 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule21filename/InputFileName2.java @@ -0,0 +1,24 @@ +package com.google.checkstyle.test.chapter2filebasic.rule21filename; + +/** Test for illegal tokens. */ +public class InputFileName2 { + /** Some javadoc. */ + public void defaultMethod() { + int i = 0; + switch (i) { + default: + i--; + i++; + break; + } + } + + /** Some javadoc. */ + public native void nativeMethod(); + + /** Some javadoc. */ + public void methodWithLiterals() { + final String ref = " <- //warn - // Contains trailing whitespace -> - - /** Invalid format **/ - public static final int badConstant = 2; - /** Valid format **/ - public static final int MAX_ROWS = 2; - - /** Invalid format **/ - private static int badStatic = 2; - /** Valid format **/ - private static int sNumCreated = 0; - - /** Invalid format **/ - private int badMember = 2; - /** Valid format **/ - private int mNumCreated1 = 0; - /** Valid format **/ - protected int mNumCreated2 = 0; - - /** commas are wrong **/ - private int[] mInts = new int[] {1,2, 3, - 4}; - - public static int sTest1; - /** should be private **/ - protected static int sTest3; - /** should be private **/ - static int sTest2; - - /** should be private **/ - int mTest1; - /** should be private **/ - public int mTest2; - - /** - * @return hack - * @param badFormat1 bad format - * @param badFormat2 bad format - * @param badFormat3 bad format - * @throws java.lang.Exception abc - **/ - int test1(int badFormat1,int badFormat2, - final int badFormat3) //warn - throws java.lang.Exception - { - return 0; - } - - /** method that is 20 lines long **/ - private void longMethod() - { - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - } - - /** constructor that is 10 lines long **/ - private InputFileTabCharacter() - { - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - } - - /** test local variables */ - private void localVariables() - { - int abc = 0; - int ABC = 0; - - final int cde = 0; - final int CDE = 0; - - for (int k = 0; k < 1; k++) - { - String innerBlockVariable = ""; - } - for (int I = 0; I < 1; I++) - { - String InnerBlockVariable = ""; - } - } - - /** test method pattern */ - void ALL_UPPERCASE_METHOD() - { - } - - /** test illegal constant **/ - private static final int BAD__NAME = 3; - - // A very, very long line that is OK because it matches the regexp "^.*is OK.*regexp.*$" - // long line that has a tab -> <- and would be OK if tab counted as 1 char //warn - // tabs that count as one char because of their position -> <- -> <- //warn - - /** some lines to test the column after tabs */ - void violateColumnAfterTabs() - { - // with tab-width 8 all statements below start at the same column, - // with different combinations of ' ' and '\t' before the statement - int tab0 =1; - int tab1 =1; //warn - int tab2 =1; //warn - int tab3 =1; //warn - int tab4 =1; //warn - int tab5 =1; //warn - } - - // MEMME: - /* MEMME: a - * MEMME: - * OOOO - */ - /* NOTHING */ - /* YES */ /* MEMME: x */ /* YES!! */ - - /** test long comments **/ - void veryLong() - { - /* - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - enough talk */ - } - - /** - * @see to lazy to document all args. Testing excessive # args - **/ - void toManyArgs(int aArg1, int aArg2, int aArg3, int aArg4, int aArg5, - int aArg6, int aArg7, int aArg8, int aArg9) - { - } -} - -/** Test class for variable naming in for each clauses. */ -class InputSimple2 -{ - /** Some more Javadoc. */ - public void doSomething() - { - //"O" should be named "o" - for (Object O : new java.util.ArrayList()) - { - - } - } -} - -/** Test enum for member naming check */ -enum MyEnum1 -{ - /** ABC constant */ - ABC, - - /** XYZ constant */ - XYZ; - - /** Should be mSomeMember */ - private int someMember; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule231filetab/InputFormattedWhitespaceCharacters.java b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule231filetab/InputFormattedWhitespaceCharacters.java new file mode 100644 index 000000000000..cd94df83eab6 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule231filetab/InputFormattedWhitespaceCharacters.java @@ -0,0 +1,39 @@ +package com.google.checkstyle.test.chapter2filebasic.rule231filetab; + +final class InputFormattedWhitespaceCharacters { + // Long line ---------------------------------------------------------------- + // Contains a tab -> <- // violation 'Line contains a tab character.' + // Contains trailing whitespace -> + + /** + * Some javadoc. + * + * @param badFormat1 bad format + * @param badFormat2 bad format + * @param badFormat3 bad format + * @return hack + * @throws Exception abc + */ + int test1(int badFormat1, int badFormat2, final int badFormat3) throws Exception { + return 0; + } + + // A very, very long line that is OK because it matches the regexp "^.*is OK.*regexp.*$" + // long line that has a tab -> <- and would be OK if tab counted as 1 char + // violation above 'Line contains a tab character.' + + // tabs that count as one char because of their position -> <- -> <- + // violation above 'Line contains a tab character.' + + /** some lines to test the column after tabs. */ + void violateColumnAfterTabs() { + // with tab-width 8 all statements below start at the same column, + // with different combinations of ' ' and '\t' before the statement + int tab0 = 1; + int tab1 = 1; + int tab2 = 1; + int tab3 = 1; + int tab4 = 1; + int tab5 = 1; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule231filetab/InputWhitespaceCharacters.java b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule231filetab/InputWhitespaceCharacters.java new file mode 100644 index 000000000000..274622820910 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule231filetab/InputWhitespaceCharacters.java @@ -0,0 +1,55 @@ +package com.google.checkstyle.test.chapter2filebasic.rule231filetab; + +final class InputWhitespaceCharacters { + // Long line ---------------------------------------------------------------- + // Contains a tab -> <- // violation 'Line contains a tab character.' + // Contains trailing whitespace -> + + /** + * Some javadoc. + * + * @param badFormat1 bad format + * @param badFormat2 bad format + * @param badFormat3 bad format + * @return hack + * @throws java.lang.Exception abc + **/ + int test1(int badFormat1, int badFormat2, + final int badFormat3) // violation 'Line contains a tab character.' + throws java.lang.Exception { + return 0; + } + + // A very, very long line that is OK because it matches the regexp "^.*is OK.*regexp.*$" + // long line that has a tab -> <- and would be OK if tab counted as 1 char + // violation above 'Line contains a tab character.' + // tabs that count as one char because of their position -> <- -> <- + // violation above 'Line contains a tab character.' + + /** some lines to test the column after tabs. */ + void violateColumnAfterTabs() { + // with tab-width 8 all statements below start at the same column, + // with different combinations of ' ' and '\t' before the statement + int tab0 = 1; + int tab1 = 1; + // 2 violations above: + // 'Line contains a tab character.' + // ''method def' child has incorrect indentation level 8, expected level should be 4.' + int tab2 = 1; + // 2 violations above: + // 'Line contains a tab character.' + // ''method def' child has incorrect indentation level 8, expected level should be 4.' + int tab3 = 1; + // 2 violations above: + // 'Line contains a tab character.' + // ''method def' child has incorrect indentation level 16, expected level should be 4.' + int tab4 = 1; + // 2 violations above: + // 'Line contains a tab character.' + // ''method def' child has incorrect indentation level 16, expected level should be 4.' + int tab5 = 1; + // 2 violations above: + // 'Line contains a tab character.' + // ''method def' child has incorrect indentation level 8, expected level should be 4.' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/InputIllegalTokenText.java b/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/InputIllegalTokenText.java deleted file mode 100644 index 65fed9d85dbd..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter2filebasic/rule232specialescape/InputIllegalTokenText.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.google.checkstyle.test.chapter2filebasic.rule232specialescape; - -/** - * Test for illegal tokens - */ -public class InputIllegalTokenText -{ - - public void methodWithLiterals() - { - final String ref = " <- - // Contains trailing whitespace -> - - // Name format tests - // - /** Invalid format **/ - public static final int badConstant = 2; - /** Valid format **/ - public static final int MAX_ROWS = 2; - - /** Invalid format **/ - private static int badStatic = 2; - /** Valid format **/ - private static int sNumCreated = 0; - - /** Invalid format **/ - private int badMember = 2; - /** Valid format **/ - private int mNumCreated1 = 0; - /** Valid format **/ - protected int mNumCreated2 = 0; - - /** commas are wrong **/ - private int[] mInts = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}; //warn - - /** - * Very long url: https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java - */ - public void fooMethod() {} - - /** - * Long url without wrapping: http://ftp.dlink.ru/pub/D-Link_Solutions/D-Link_Solutions_for_Business.pdf - */ - public void fooMethodLongFtp() {} - - public void fooLongStringUrl() { - String url = "https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java"; //ok - processUrl("https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java"); //ok - processUrl("some line" - + "https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java" //ok - + "+ long fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo00000000000o line"); //warn - processUrl("Some long foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo line"); //warn - String[] soooooooooooooooooooooooooooooooooooolongfooooooooooooooooooooooooooooooooooooooooooo = { //warn - "http://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java", //ok - "Some long foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo line", //warn - }; - - String fakehttps = "Some long foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo line"; //warn - - processUrl(new String[] { - "http://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java", //ok - "Some long foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo line", //warn - }); - - String s = "text" - + "text" - + "text something more.. long url name, long url name, long url name" //ok - + "other text"; - } - - /** - * - * @param url - */ - public void processUrl(String url) {} - - /** - * - * @param urls - */ - public void processUrl(String[] urls){} -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule32packagestatement/InputPackageStatement.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule32packagestatement/InputPackageStatement.java new file mode 100644 index 000000000000..333b9537e30c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule32packagestatement/InputPackageStatement.java @@ -0,0 +1,15 @@ +package com.google.checkstyle.test. // violation 'package statement should not be line-wrapped.' + chapter3filestructure.rule32packagestatement; + +/** some javadoc. */ +public class InputPackageStatement { + // Long line + // ----------------------------------------------------------------------------------------------------- + // violation above 'Line is longer than 100 characters (found 106).' + + private int[] testing = + new int[] { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 + }; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/InputAvoidStarImport.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/InputAvoidStarImport.java deleted file mode 100644 index 386dbb03fe86..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/InputAvoidStarImport.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule331nowildcard; - -import java.io.*; //warn -import java.lang.*; //warn -import java.lang.String; -import java.sql.Connection; -import java.util.List; -import java.util.List; -import java.util.Iterator; -import java.util.Enumeration; -import java.util.Arrays; -import javax.swing.JToolBar; -import javax.swing.JToggleButton; -import javax.swing.ScrollPaneLayout; -import javax.swing.BorderFactory; -import static java.io.File.listRoots; - -import static javax.swing.WindowConstants.*; //warn -import static javax.swing.WindowConstants.*; //warn -import static java.io.File.createTempFile; -import java.awt.Component; -import java.awt.Graphics2D; -import java.awt.HeadlessException; -import java.awt.Label; -import java.util.Date; -import java.util.Calendar; -import java.util.BitSet; - -class InputAvoidStarImport {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/InputNoWildcardImports.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/InputNoWildcardImports.java new file mode 100644 index 000000000000..e85cf9c90c3f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule331nowildcard/InputNoWildcardImports.java @@ -0,0 +1,70 @@ +package com.google.checkstyle.test.chapter3filestructure.rule331nowildcard; + +import static java.io.File.createTempFile; +import static java.io.File.listRoots; +import static javax.swing.WindowConstants.*; +// violation above '.* '.*' form of import should be avoided - javax.swing.WindowConstants.*.' + +import java.awt.Component; +import java.awt.Graphics2D; +import java.awt.HeadlessException; +import java.awt.Label; +import java.io.*; // violation 'Using the '.*' form of import should be avoided - java.io.*.' +import java.sql.Connection; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Calendar; +import java.util.Date; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import javax.swing.BorderFactory; +import javax.swing.JToggleButton; +import javax.swing.JToolBar; +import javax.swing.ScrollPaneLayout; + +class InputNoWildcardImports { + public static void main(String[] args) { + // Use of static imports + try { + createTempFile("temp", ".txt"); + File[] roots = listRoots(); + } catch (IOException exc) { + exc.printStackTrace(); + } + int closeOperation = EXIT_ON_CLOSE; + + // Use of java.awt classes + Component component; + Graphics2D graphics2D; + Label label = new Label(); + HeadlessException headlessException = new HeadlessException(); + + // Use of java.io classes + FileReader fileReader; + BufferedReader bufferedReader; + InputStream inputStream; + OutputStream outputStream; + + // Use of java.lang classes + String string = new String("Hello"); + Object obj = new Object(); + + // Use of java.sql classes + Connection connection; + + // Use of java.util classes + List list = Arrays.asList("One", "Two", "Three"); + BitSet bitSet = new BitSet(); + Calendar calendar = Calendar.getInstance(); + Date date = new Date(); + Enumeration enumeration; + Iterator iterator; + + // Use of javax.swing classes + JToggleButton toggleButton = new JToggleButton(); + JToolBar toolBar = new JToolBar(); + ScrollPaneLayout scrollPaneLayout = new ScrollPaneLayout(); + BorderFactory.createEmptyBorder(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputFormattedNoLineWrapping.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputFormattedNoLineWrapping.java new file mode 100644 index 000000000000..f451a6f7491b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputFormattedNoLineWrapping.java @@ -0,0 +1,25 @@ +package com.google.checkstyle.test.chapter3filestructure.rule332nolinewrap; + +// ok, long imports are allowed +import com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule.PackageStatementTest; + +/** Some javadoc. */ +public class InputFormattedNoLineWrapping { + + /** Some javadoc. */ + public void fooMethod() { + // + } + + // Long line + // -------------------------------------------------------------------------------------------------- + // violation above 'Line is longer than 100 characters (found 103).' + + private int[] testing = + new int[] { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 + }; + + PackageStatementTest packageStatementTest = new PackageStatementTest(); +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputLineLength.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputLineLength.java deleted file mode 100644 index d5f12de9a84a..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputLineLength.java +++ /dev/null @@ -1,184 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule332nolinewrap; //ok -import com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule.*; //ok -final class InputLineLength -{ - // Long line ---------------------------------------------------------------------------------------- //warn - // Contains a tab -> <- - // Contains trailing whitespace -> - - // Name format tests - // - /** Invalid format **/ - public static final int badConstant = 2; - /** Valid format **/ - public static final int MAX_ROWS = 2; - - /** Invalid format **/ - private static int badStatic = 2; - /** Valid format **/ - private static int sNumCreated = 0; - - /** Invalid format **/ - private int badMember = 2; - /** Valid format **/ - private int mNumCreated1 = 0; - /** Valid format **/ - protected int mNumCreated2 = 0; - - /** commas are wrong **/ - private int[] mInts = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, }; //warn - - // - // Accessor tests - // - /** should be private **/ - public static int sTest1; - /** should be private **/ - protected static int sTest3; - /** should be private **/ - static int sTest2; - - /** should be private **/ - int mTest1; - /** should be private **/ - public int mTest2; - - // - // Parameter name format tests - // - - /** - * @return hack - * @param badFormat1 bad format - * @param badFormat2 bad format - * @param badFormat3 bad format - * @throws java.lang.Exception abc - **/ - int test1(int badFormat1,int badFormat2, - final int badFormat3) - throws java.lang.Exception - { - return 0; - } - - /** method that is 20 lines long **/ - private void longMethod() - { - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - } - - /** constructor that is 10 lines long **/ - private InputLineLength() - { - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - } - - /** test local variables */ - private void localVariables() - { - // normal decl - int abc = 0; - int ABC = 0; - - // final decls - final int cde = 0; - final int CDE = 0; - - // decl in for loop init statement - for (int k = 0; k < 1; k++) - { - String innerBlockVariable = ""; - } - for (int I = 0; I < 1; I++) - { - String InnerBlockVariable = ""; - } - } - - /** test method pattern */ - void ALL_UPPERCASE_METHOD() - { - } - - /** test illegal constant **/ - private static final int BAD__NAME = 3; - - // A very, very long line that is OK because it matches the regexp "^.*is OK.*regexp.*$" - // long line that has a tab -> <- and would be OK if tab counted as 1 char - // tabs that count as one char because of their position -> <- -> <-, OK - - /** some lines to test the column after tabs */ - void violateColumnAfterTabs() - { - // with tab-width 8 all statements below start at the same column, - // with different combinations of ' ' and '\t' before the statement - int tab0 =1; - int tab1 =1; - int tab2 =1; - int tab3 =1; - int tab4 =1; - int tab5 =1; - } - - // MEMME: - /* MEMME: a - * MEMME: - * OOOO - */ - /* NOTHING */ - /* YES */ /* MEMME: x */ /* YES!! */ - - /** test long comments **/ - void veryLong() - { - /* - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - enough talk */ - } - - /** - * @see to lazy to document all args. Testing excessive # args - **/ - void toManyArgs(int aArg1, int aArg2, int aArg3, int aArg4, int aArg5, - int aArg6, int aArg7, int aArg8, int aArg9) - { - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapBad.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapBad.java deleted file mode 100644 index 8663ba4689b5..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapBad.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.google.checkstyle.test. //warn - chapter3filestructure.rule332nolinewrap; - -import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; //ok - -import javax.accessibility. //warn - AccessibleAttributeSequence; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; //ok - -import static java.math. //warn - BigInteger.ONE; - -public class - InputNoLineWrapBad { - - public void - fooMethod() { - final int - foo = 0; - } -} - -enum - FooFoo { -} - -interface - InterFoo {} - diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapGood.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapGood.java deleted file mode 100644 index 50b28664ecb8..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapGood.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule332nolinewrap; //ok - -import static java.math.BigInteger.ZERO; //ok - -import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; //ok -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; //ok -import javax.accessibility.AccessibleAttributeSequence; //ok - -public class InputNoLineWrapGood { - - public void fooMethod() { - // - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapping.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapping.java new file mode 100644 index 000000000000..9423476af1da --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapping.java @@ -0,0 +1,36 @@ +package com.google.checkstyle.test.chapter3filestructure.rule332nolinewrap; + +import static java.math. // violation 'import statement should not be line-wrapped.' + BigInteger.ONE; +import static java.math.BigInteger.ZERO; // ok + +// ok, long imports are allowed +import com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule.PackageStatementTest; +import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; // ok +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; // ok +import java.util.concurrent.atomic // violation 'import statement should not be line-wrapped.' + .AtomicMarkableReference; +import javax.accessibility.AccessibleAttributeSequence; // ok +import javax.accessibility. // violation 'import statement should not be line-wrapped.' + AccessibleAttributeSequence; + +/** Some javadoc. */ +public class InputNoLineWrapping { + + /** Some javadoc. */ + public void fooMethod() { + // + } + + // Long line + // -------------------------------------------------------------------------------------------------- + // violation above 'Line is longer than 100 characters (found 103).' + + private int[] testing = + new int[] { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 + }; + + PackageStatementTest packageStatementTest = new PackageStatementTest(); +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder1.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder1.java deleted file mode 100644 index a79d8682eef6..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder1.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; - -import static java.io.File.createTempFile; -import static java.awt.Button.ABORT; //warn -import static javax.swing.WindowConstants.*; -import java.awt.Button; //warn -import java.awt.Frame; -import java.awt.Dialog; //warn -import java.awt.event.ActionEvent; -import javax.swing.JComponent; -import javax.swing.JTable; -import java.io.File; //warn -import java.io.IOException; //warn -import java.io.InputStream; //warn -import java.io.Reader; //warn - -import com.google.common.base.Ascii; //warn - -public class InputCustomImportOrder1 {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder2.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder2.java deleted file mode 100644 index 3f5497a947ca..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder2.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; - -import static java.io.File.createTempFile; -import static java.awt.Button.ABORT; //warn -import static javax.swing.WindowConstants.*; - -import java.util.List; -import java.util.StringTokenizer; -import java.util.*; //warn -import java.util.concurrent.AbstractExecutorService; -import java.util.concurrent.*; //warn - -import com.google.checkstyle.test.chapter2filebasic.rule21filename.*; //warn -import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.*; //warn - -import com.google.common.reflect.*; //warn - -public class InputCustomImportOrder2 { -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder3.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder3.java deleted file mode 100644 index c2f317f4ad9b..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder3.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; - -import static java.awt.Button.ABORT; -import java.awt.Dialog; //warn -import static javax.swing.WindowConstants.*; //warn - -import com.google.checkstyle.test.chapter2filebasic.rule21filename.*; //warn -import com.google.common.reflect.*; //warn -import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.*; //warn -import java.io.File; -import static java.io.File.createTempFile; //warn -import java.util.StringTokenizer; -import java.util.*; //warn -import java.util.concurrent.AbstractExecutorService; -import java.util.concurrent.*; //warn - -public class InputCustomImportOrder3 { -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder4.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder4.java deleted file mode 100644 index aaf66e72c0bf..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder4.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; - -import static java.awt.Button.ABORT; -import static java.io.File.createTempFile; - - -import static javax.swing.WindowConstants.*; //warn - -import com.google.checkstyle.test.chapter2filebasic.rule21filename.*; -import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.*; -import com.google.common.reflect.*; -import java.util.List; - - -import java.util.StringTokenizer; //warn - -import java.util.concurrent.AbstractExecutorService; // warn - -public class InputCustomImportOrder4 { -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder5.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder5.java deleted file mode 100644 index 55aa52769e6c..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrder5.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; - -import static java.awt.Button.ABORT; -import static java.io.File.createTempFile; -// comments - - -// comments -import static javax.swing.WindowConstants.*; //warn - -// comments - -import com.google.checkstyle.test.chapter2filebasic.rule21filename.*; //warn -import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.*; -// comments - -import com.google.common.reflect.*; //warn -import java.util.List; - -// comments -import java.util.StringTokenizer; //warn -// comments - -// comments -import java.util.concurrent.AbstractExecutorService; //warn - -public class InputCustomImportOrder5 { -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderNoImports.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderNoImports.java deleted file mode 100644 index 6b3051f7c53b..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderNoImports.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; - -public class InputCustomImportOrderNoImports { -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderValid.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderValid.java deleted file mode 100644 index befffe891e75..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderValid.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; -// it is not forbidden to have extra lines (more than one) between package and import group - - -import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.containsAnnotation; -import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.getAnnotation; - -import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; -import com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck; -import com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck; -import java.util.Arrays; -import java.util.BitSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NoSuchElementException; -import javax.accessibility.Accessible; -import org.apache.commons.beanutils.converters.ArrayConverter; - -public class InputCustomImportOrderValid { -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderValid2.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderValid2.java deleted file mode 100644 index 30be0597af23..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputCustomImportOrderValid2.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; - -import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.containsAnnotation; -import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.getAnnotation; -// comments - -// comments -import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; -import com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck; -import com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck; -import java.util.Arrays; -// comments -import java.util.BitSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NoSuchElementException; -import javax.accessibility.Accessible; -import org.apache.commons.beanutils.converters.ArrayConverter; - -public class InputCustomImportOrderValid2 { -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing1.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing1.java new file mode 100644 index 000000000000..661aa36b8974 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing1.java @@ -0,0 +1,38 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.awt.Button.ABORT; +import static java.io.File.createTempFile; +import static javax.swing.WindowConstants.*; // violation '.*' form of import should be avoided' + +import com.google.common.base.Ascii; +import java.awt.*; // violation 'Using the '.*' form of import should be avoided' +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import javax.swing.*; // violation 'Using the '.*' form of import should be avoided' + +/** Some javadoc. */ +public class InputFormattedOrderingAndSpacing1 { + /** some javadoc. */ + public static void main(String[] args) { + // Use of static imports + try { + File tempFile = createTempFile("temp", ".txt"); + } catch (IOException e) { + e.printStackTrace(); + } + int abortAction = ABORT; + + Frame frame = new Frame(); + + JTable table = new JTable(); + int closeOperation = EXIT_ON_CLOSE; + + File file = new File("example.txt"); + InputStream inputStream = System.in; + Reader reader = null; + + char ascii = Ascii.BS; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing2.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing2.java new file mode 100644 index 000000000000..ea1f5337b4b2 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing2.java @@ -0,0 +1,67 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.awt.Button.ABORT; +import static java.io.File.createTempFile; +import static javax.swing.WindowConstants.*; // violation '.*' form of import should be avoided' + +import com.google.checkstyle.test.chapter2filebasic.rule21filename.*; // violation '.*' +import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.*; // violation '.*' +import com.google.common.reflect.*; // violation 'Using the '.*' form of import should be avoided' +import java.util.*; // violation 'Using the '.*' form of import should be avoided' +import java.util.List; +import java.util.StringTokenizer; +import java.util.concurrent.*; // violation 'Using the '.*' form of import should be avoided' +import java.util.concurrent.AbstractExecutorService; + +/** Some javadoc. */ +public class InputFormattedOrderingAndSpacing2 { + /** Some javadoc. */ + public static void main(String[] args) { + try { + createTempFile("temp", ".txt"); + } catch (Exception exc) { + exc.printStackTrace(); + } + int abortAction = ABORT; + int closeOperation = EXIT_ON_CLOSE; + + List list = new ArrayList<>(); + StringTokenizer tokenizer = new StringTokenizer("Hello World"); + + AbstractExecutorService abstractExecutorService = + new AbstractExecutorService() { + @Override + public void shutdown() {} + + @Override + public List shutdownNow() { + return null; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) {} + }; + ExecutorService executorService = Executors.newSingleThreadExecutor(); + + TypeToken typeToken = TypeToken.of(String.class); + + FileNameTest testing1 = new FileNameTest(); + + SourceFileStructureTest testing2 = new SourceFileStructureTest(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing3.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing3.java new file mode 100644 index 000000000000..0eaa7217fe3c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing3.java @@ -0,0 +1,83 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.awt.Button.ABORT; +import static java.io.File.createTempFile; +import static javax.swing.WindowConstants.EXIT_ON_CLOSE; + +import com.google.checkstyle.test.chapter2filebasic.rule21filename.FileNameTest; +import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.SourceFileStructureTest; +import com.google.common.reflect.ImmutableTypeToInstanceMap; +import java.awt.Dialog; +import java.io.File; +import java.util.LinkedHashMap; +import java.util.StringTokenizer; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.ThreadFactory; + +/** Some javadoc. */ +public class InputFormattedOrderingAndSpacing3 { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + int abortAction = ABORT; + int closeOperation = EXIT_ON_CLOSE; + + try { + createTempFile("temp", ".txt"); + } catch (Exception exc) { + exc.printStackTrace(); + } + + // Use of java.awt and javax.swing classes + Dialog dialog = new Dialog(new java.awt.Frame()); + + // Use of java.io classes + File file = new File("example.txt"); + + // Use of java.util classes + StringTokenizer tokenizer = new StringTokenizer("Hello World"); + LinkedHashMap map = new LinkedHashMap<>(); + + // Use of java.util.concurrent classes + ThreadFactory threadFactory = + new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r); + } + }; + AbstractExecutorService abstractExecutorService = + new AbstractExecutorService() { + @Override + public void shutdown() {} + + @Override + public java.util.List shutdownNow() { + return null; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) {} + }; + + // Use of com.google classes + FileNameTest fileNameTest = new FileNameTest(); + ImmutableTypeToInstanceMap mapInstance = ImmutableTypeToInstanceMap.builder().build(); + SourceFileStructureTest sourceFileStructureTest = new SourceFileStructureTest(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing4.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing4.java new file mode 100644 index 000000000000..62d983e43a3e --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing4.java @@ -0,0 +1,66 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.awt.Button.ABORT; +import static java.io.File.createTempFile; +import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE; + +import com.google.checkstyle.test.chapter2filebasic.rule21filename.FileNameTest; +import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.SourceFileStructureTest; +import com.google.common.reflect.Invokable; +import java.util.List; +import java.util.StringTokenizer; +import java.util.concurrent.AbstractExecutorService; + +/** Some javadoc. */ +public class InputFormattedOrderingAndSpacing4 { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + try { + createTempFile("temp", ".txt"); + } catch (Exception e) { + e.printStackTrace(); + } + int abortAction = ABORT; + int closeOperation = DO_NOTHING_ON_CLOSE; + + // Use of com.google classes + FileNameTest fileNameTest = new FileNameTest(); + SourceFileStructureTest sourceFileStructureTest = new SourceFileStructureTest(); + Invokable invokable = Invokable.from(Object.class.getDeclaredMethods()[0]); + + // Use of java.util classes + List list; + StringTokenizer tokenizer = new StringTokenizer("Hello World"); + + // Use of java.util.concurrent classes + AbstractExecutorService abstractExecutorService = + new AbstractExecutorService() { + @Override + public void shutdown() {} + + @Override + public List shutdownNow() { + return null; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) {} + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing5.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing5.java new file mode 100644 index 000000000000..a15b57d2cc2d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacing5.java @@ -0,0 +1,66 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.awt.Button.ABORT; +import static java.io.File.createTempFile; +import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE; + +import com.google.checkstyle.test.chapter2filebasic.rule21filename.InputFileName1; +import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.SourceFileStructureTest; +import com.google.common.reflect.TypeToken; +import java.util.List; +import java.util.StringTokenizer; +import java.util.concurrent.AbstractExecutorService; + +/** Some javadoc. */ +public class InputFormattedOrderingAndSpacing5 { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + int abortAction = ABORT; + try { + createTempFile("temp", ".txt"); + } catch (Exception e) { + e.printStackTrace(); + } + int closeOperation = DISPOSE_ON_CLOSE; + + // Use of com.google classes + InputFileName1 inputFileName1 = new InputFileName1(); + SourceFileStructureTest sourceFileStructureTest = new SourceFileStructureTest(); + TypeToken typeToken = TypeToken.of(String.class); + + // Use of java.util classes + List list; + StringTokenizer tokenizer = new StringTokenizer("Hello World"); + + // Use of java.util.concurrent classes + AbstractExecutorService abstractExecutorService = + new AbstractExecutorService() { + @Override + public void shutdown() {} + + @Override + public List shutdownNow() { + return null; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) {} + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingNoImports.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingNoImports.java new file mode 100644 index 000000000000..a9562970eef5 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingNoImports.java @@ -0,0 +1,4 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +/** Some javadoc. */ +public class InputFormattedOrderingAndSpacingNoImports {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingValid.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingValid.java new file mode 100644 index 000000000000..7d24ed92813d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingValid.java @@ -0,0 +1,51 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +// it is not forbidden to have extra lines (more than one) between package and import group + +import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.containsAnnotation; +import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.getAnnotation; + +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; +import com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck; +import com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NoSuchElementException; +import javax.accessibility.Accessible; +import org.apache.commons.beanutils.converters.ArrayConverter; + +/** Some javadoc. */ +public class InputFormattedOrderingAndSpacingValid { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + boolean hasAnnotation = containsAnnotation((DetailAST) new Object(), "Override"); + Object annotation = getAnnotation((DetailAST) new Object(), "Override"); + + // Use of com.puppycrawl.tools.checkstyle classes + FinalClassCheck finalClassCheck = new FinalClassCheck(); + ThrowsCountCheck throwsCountCheck = new ThrowsCountCheck(); + VisibilityModifierCheck visibilityModifierCheck = new VisibilityModifierCheck(); + + // Use of java.util classes + int[] numbers = {1, 2, 3}; + Arrays.sort(numbers); + BitSet bitSet = new BitSet(); + Map map; + Entry entry = Map.entry("key", "value"); + try { + throw new NoSuchElementException(); + } catch (NoSuchElementException e) { + e.printStackTrace(); + } + + // Use of javax.accessibility classes + Accessible accessible; + + // Use of org.apache.commons.beanutils.converters classes + ArrayConverter arrayConverter = new ArrayConverter(int[].class, null); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingValid2.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingValid2.java new file mode 100644 index 000000000000..3e17ce6b9f2a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputFormattedOrderingAndSpacingValid2.java @@ -0,0 +1,53 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.containsAnnotation; +import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.getAnnotation; + +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; +import com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck; +import com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NoSuchElementException; +import javax.accessibility.Accessible; +import org.apache.commons.beanutils.converters.ArrayConverter; + +/** Some javadoc. */ +public class InputFormattedOrderingAndSpacingValid2 { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + boolean hasAnnotation = containsAnnotation((DetailAST) new Object(), "Override"); + Object annotation = getAnnotation((DetailAST) new Object(), "Override"); + + // comments + + // Use of com.puppycrawl.tools.checkstyle classes + FinalClassCheck finalClassCheck = new FinalClassCheck(); + ThrowsCountCheck throwsCountCheck = new ThrowsCountCheck(); + VisibilityModifierCheck visibilityModifierCheck = new VisibilityModifierCheck(); + + // Use of java.util classes + int[] numbers = {1, 2, 3}; + Arrays.sort(numbers); + BitSet bitSet = new BitSet(); + Map map; + Entry entry = Map.entry("key", "value"); + try { + throw new NoSuchElementException(); + } catch (NoSuchElementException e) { + e.printStackTrace(); + } + + // comments + + // Use of javax.accessibility classes + Accessible accessible; + + // Use of org.apache.commons.beanutils.converters classes + ArrayConverter arrayConverter = new ArrayConverter(int[].class, null); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing1.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing1.java new file mode 100644 index 000000000000..986c9cef3861 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing1.java @@ -0,0 +1,53 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.io.File.createTempFile; +import static java.awt.Button.ABORT; +// violation above '.* 'java.awt.Button.ABORT' .* Should be before 'java.io.File.createTempFile'.' +import static javax.swing.WindowConstants.*; +// violation above 'Using the '.*' form of import should be avoided' +import java.awt.Button; +// violation above ''java.awt.Button' should be separated from previous import group by one line.' +import java.awt.Frame; +import java.awt.Dialog; +// violation above '.* 'java.awt.Dialog' .* Should be before 'java.awt.Frame'.' +import java.awt.event.ActionEvent; +import javax.swing.JComponent; +import javax.swing.JTable; +import java.io.File; +// violation above '.* 'java.io.File' .* Should be before 'javax.swing.JTable'.' +import java.io.IOException; +// violation above '.* 'java.io.IOException' .* Should be before 'javax.swing.JTable'.' +import java.io.InputStream; +// violation above '.* 'java.io.InputStream' .* Should be before 'javax.swing.JTable'.' +import java.io.Reader; +// violation above '.* 'java.io.Reader' .* Should be before 'javax.swing.JTable'.' + +import com.google.common.base.Ascii; +// 2 violations above: +// 'Extra separation in import group before 'com.google.common.base.Ascii'' +// '.* 'com.google.common.base.Ascii' .* Should be before 'javax.swing.JTable'.' + +/** Some javadoc. */ +public class InputOrderingAndSpacing1 { + /** some javadoc. */ + public static void main(String[] args) { + // Use of static imports + try { + File tempFile = createTempFile("temp", ".txt"); + } catch (IOException e) { + e.printStackTrace(); + } + int abortAction = ABORT; + + Frame frame = new Frame(); + + JTable table = new JTable(); + int closeOperation = EXIT_ON_CLOSE; + + File file = new File("example.txt"); + InputStream inputStream = System.in; + Reader reader = null; + + char ascii = Ascii.BS; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing2.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing2.java new file mode 100644 index 000000000000..924fd1709841 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing2.java @@ -0,0 +1,91 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.io.File.createTempFile; +import static java.awt.Button.ABORT; +// violation above '.* 'java.awt.Button.ABORT' .* Should be before 'java.io.File.createTempFile'.' +import static javax.swing.WindowConstants.*; +// violation above 'Using the '.*' form of import should be avoided' + +import java.util.List; +import java.util.StringTokenizer; +import java.util.*; +// 2 violations above: +// '.* 'java.util.*' .* Should be before 'java.util.StringTokenizer'.' +// 'Using the '.*' form of import should be avoided' +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.*; +// 2 violations above: +// '.* Should be before 'java.util.concurrent.AbstractExecutorService'.' +// 'Using the '.*' form of import should be avoided' + +import com.google.checkstyle.test.chapter2filebasic.rule21filename.*; +// 3 violations above: +// 'Extra separation in import group before .*' +// '.* Should be before 'java.util.concurrent.AbstractExecutorService'.' +// 'Using the '.*' form of import should be avoided' + +import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.*; +// 3 violations above: +// 'Extra separation in import group before .*' +// '.* Should be before 'java.util.concurrent.AbstractExecutorService'.' +// 'Using the '.*' form of import should be avoided' + +import com.google.common.reflect.*; +// 3 violations above: +// 'Extra separation in import group before 'com.google.common.reflect.*'' +// '.* Should be before 'java.util.concurrent.AbstractExecutorService'.' +// 'Using the '.*' form of import should be avoided' + +/** Some javadoc. */ +public class InputOrderingAndSpacing2 { + /** Some javadoc. */ + public static void main(String[] args) { + try { + createTempFile("temp", ".txt"); + } catch (Exception e) { + e.printStackTrace(); + } + int abortAction = ABORT; + int closeOperation = EXIT_ON_CLOSE; + + List list = new ArrayList<>(); + StringTokenizer tokenizer = new StringTokenizer("Hello World"); + + AbstractExecutorService abstractExecutorService = new AbstractExecutorService() { + @Override + public void shutdown() { + } + + @Override + public List shutdownNow() { + return null; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) { + } + }; + ExecutorService executorService = Executors.newSingleThreadExecutor(); + + TypeToken typeToken = TypeToken.of(String.class); + + FileNameTest testing1 = new FileNameTest(); + + SourceFileStructureTest testing2 = new SourceFileStructureTest(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing3.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing3.java new file mode 100644 index 000000000000..538af8b8a392 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing3.java @@ -0,0 +1,93 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.awt.Button.ABORT; +import java.awt.Dialog; +// violation above ''java.awt.Dialog' should be separated from previous import group by one line.' +import static javax.swing.WindowConstants.EXIT_ON_CLOSE; +// violation above '.*'javax.swing.WindowConstants.*' .* wrong order. Should be in the 'STATIC' .*' + +import com.google.checkstyle.test.chapter2filebasic.rule21filename.FileNameTest; +// 2 violations above: +// 'Extra separation in import group before .*' +// '.* Should be before 'java.awt.Dialog'.' +import com.google.common.reflect.ImmutableTypeToInstanceMap; +// violation above '.* Should be before 'java.awt.Dialog'.' +import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.SourceFileStructureTest; +// violation above '.* Should be before 'java.awt.Dialog'.' +import java.io.File; +import static java.io.File.createTempFile; +// violation above '.*'java.io.File.createTempFile' .* wrong order. Should be in the 'STATIC' .*' +import java.util.StringTokenizer; +import java.util.LinkedHashMap; +// violation above '.* 'java.util.LinkedHashMap' .* Should be before 'java.util.StringTokenizer'.' +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.AbstractExecutorService; +// violation above '.* Should be before 'java.util.concurrent.ThreadFactory'.' + +/** Some javadoc. */ +public class InputOrderingAndSpacing3 { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + int abortAction = ABORT; + int closeOperation = EXIT_ON_CLOSE; + + try { + createTempFile("temp", ".txt"); + } catch (Exception e) { + e.printStackTrace(); + } + + // Use of java.awt and javax.swing classes + Dialog dialog = new Dialog(new java.awt.Frame()); + + // Use of java.io classes + File file = new File("example.txt"); + + // Use of java.util classes + StringTokenizer tokenizer = new StringTokenizer("Hello World"); + LinkedHashMap map = new LinkedHashMap<>(); + + // Use of java.util.concurrent classes + ThreadFactory threadFactory = new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return new Thread(r); + } + }; + AbstractExecutorService abstractExecutorService = new AbstractExecutorService() { + @Override + public void shutdown() { + } + + @Override + public java.util.List shutdownNow() { + return null; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) { + } + }; + + // Use of com.google classes + FileNameTest fileNameTest = new FileNameTest(); + ImmutableTypeToInstanceMap mapInstance = ImmutableTypeToInstanceMap.builder().build(); + SourceFileStructureTest sourceFileStructureTest = new SourceFileStructureTest(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing4.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing4.java new file mode 100644 index 000000000000..167b0b783d09 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing4.java @@ -0,0 +1,74 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.io.File.createTempFile; +import static java.awt.Button.ABORT; +// violation above '.* 'java.awt.Button.ABORT' .* Should be before 'java.io.File.createTempFile'.' + +import static javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE; +// violation above 'Extra separation .* before 'javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE'' + +import com.google.checkstyle.test.chapter2filebasic.rule21filename.FileNameTest; +import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.SourceFileStructureTest; +import com.google.common.reflect.Invokable; +import java.util.List; + +import java.util.StringTokenizer; +// violation above 'Extra separation in import group before 'java.util.StringTokenizer'' + +import java.util.concurrent.AbstractExecutorService; +// violation above 'Extra separation .* before 'java.util.concurrent.AbstractExecutorService'' + +/** Some javadoc. */ +public class InputOrderingAndSpacing4 { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + try { + createTempFile("temp", ".txt"); + } catch (Exception e) { + e.printStackTrace(); + } + int abortAction = ABORT; + int closeOperation = DO_NOTHING_ON_CLOSE; + + // Use of com.google classes + FileNameTest fileNameTest = new FileNameTest(); + SourceFileStructureTest sourceFileStructureTest = new SourceFileStructureTest(); + Invokable invokable = Invokable.from(Object.class.getDeclaredMethods()[0]); + + // Use of java.util classes + List list; + StringTokenizer tokenizer = new StringTokenizer("Hello World"); + + // Use of java.util.concurrent classes + AbstractExecutorService abstractExecutorService = new AbstractExecutorService() { + @Override + public void shutdown() { + } + + @Override + public java.util.List shutdownNow() { + return null; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) { + } + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing5.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing5.java new file mode 100644 index 000000000000..c98ca40e1b5e --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacing5.java @@ -0,0 +1,84 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static java.awt.Button.ABORT; +import static java.io.File.createTempFile; +// comments + +// comments +import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE; +// violation above 'Extra separation .* before 'javax.swing.WindowConstants.DISPOSE_ON_CLOSE'' + +// comments + +import com.google.checkstyle.test.chapter2filebasic.rule21filename.InputFileName1; +// violation above ''com.google.checkstyle.test.*' should be separated .* by one line.' +import com.google.checkstyle.test.chapter3filestructure.rule3sourcefile.SourceFileStructureTest; +// comments + +import com.google.common.reflect.TypeToken; +// violation above 'Extra separation in import group before 'com.google.common.reflect.*'' +import java.util.List; + +// comments +import java.util.StringTokenizer; +// violation above 'Extra separation in import group before 'java.util.StringTokenizer'' +// comments + +// comments +import java.util.concurrent.AbstractExecutorService; +// violation above 'Extra separation .* before 'java.util.concurrent.AbstractExecutorService'' + +/** Some javadoc. */ +public class InputOrderingAndSpacing5 { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + int abortAction = ABORT; + try { + createTempFile("temp", ".txt"); + } catch (Exception e) { + e.printStackTrace(); + } + int closeOperation = DISPOSE_ON_CLOSE; + + // Use of com.google classes + InputFileName1 inputFileName1 = new InputFileName1(); + SourceFileStructureTest sourceFileStructureTest = new SourceFileStructureTest(); + TypeToken typeToken = TypeToken.of(String.class); + + // Use of java.util classes + List list; + StringTokenizer tokenizer = new StringTokenizer("Hello World"); + + // Use of java.util.concurrent classes + AbstractExecutorService abstractExecutorService = new AbstractExecutorService() { + @Override + public void shutdown() { + } + + @Override + public java.util.List shutdownNow() { + return null; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, java.util.concurrent.TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) { + } + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingNoImports.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingNoImports.java new file mode 100644 index 000000000000..83b5aa4da7a3 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingNoImports.java @@ -0,0 +1,4 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +/** Some javadoc. */ +public class InputOrderingAndSpacingNoImports {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingValid.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingValid.java new file mode 100644 index 000000000000..7d6012f0662f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingValid.java @@ -0,0 +1,49 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.containsAnnotation; +import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.getAnnotation; + +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; +import com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck; +import com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NoSuchElementException; +import javax.accessibility.Accessible; +import org.apache.commons.beanutils.converters.ArrayConverter; + +/** Some javadoc. */ +public class InputOrderingAndSpacingValid { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + boolean hasAnnotation = containsAnnotation((DetailAST) new Object(), "Override"); + Object annotation = getAnnotation((DetailAST) new Object(), "Override"); + + // Use of com.puppycrawl.tools.checkstyle classes + FinalClassCheck finalClassCheck = new FinalClassCheck(); + ThrowsCountCheck throwsCountCheck = new ThrowsCountCheck(); + VisibilityModifierCheck visibilityModifierCheck = new VisibilityModifierCheck(); + + // Use of java.util classes + int[] numbers = {1, 2, 3}; + Arrays.sort(numbers); + BitSet bitSet = new BitSet(); + Map map; + Entry entry = Map.entry("key", "value"); + try { + throw new NoSuchElementException(); + } catch (NoSuchElementException e) { + e.printStackTrace(); + } + + // Use of javax.accessibility classes + Accessible accessible; + + // Use of org.apache.commons.beanutils.converters classes + ArrayConverter arrayConverter = new ArrayConverter(int[].class, null); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingValid2.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingValid2.java new file mode 100644 index 000000000000..e6fcfd62f590 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule333orderingandspacing/InputOrderingAndSpacingValid2.java @@ -0,0 +1,56 @@ +package com.google.checkstyle.test.chapter3filestructure.rule333orderingandspacing; + +import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.containsAnnotation; +import static com.puppycrawl.tools.checkstyle.utils.AnnotationUtil.getAnnotation; +// comments + +// comments +import com.puppycrawl.tools.checkstyle.api.DetailAST; +import com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheck; +import com.puppycrawl.tools.checkstyle.checks.design.ThrowsCountCheck; +import com.puppycrawl.tools.checkstyle.checks.design.VisibilityModifierCheck; +import java.util.Arrays; +// comments +import java.util.BitSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NoSuchElementException; +import javax.accessibility.Accessible; +import org.apache.commons.beanutils.converters.ArrayConverter; + +/** Some javadoc. */ +public class InputOrderingAndSpacingValid2 { + /** Some javadoc. */ + public static void main(String[] args) { + // Use of static imports + boolean hasAnnotation = containsAnnotation((DetailAST) new Object(), "Override"); + Object annotation = getAnnotation((DetailAST) new Object(), "Override"); + + // comments + + // Use of com.puppycrawl.tools.checkstyle classes + FinalClassCheck finalClassCheck = new FinalClassCheck(); + ThrowsCountCheck throwsCountCheck = new ThrowsCountCheck(); + VisibilityModifierCheck visibilityModifierCheck = new VisibilityModifierCheck(); + + // Use of java.util classes + int[] numbers = {1, 2, 3}; + Arrays.sort(numbers); + BitSet bitSet = new BitSet(); + Map map; + Entry entry = Map.entry("key", "value"); + try { + throw new NoSuchElementException(); + } catch (NoSuchElementException e) { + e.printStackTrace(); + } + + // comments + + // Use of javax.accessibility classes + Accessible accessible; + + // Use of org.apache.commons.beanutils.converters classes + ArrayConverter arrayConverter = new ArrayConverter(int[].class, null); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBad1.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBad1.java index 9b4c603ff287..ae476634e918 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBad1.java +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBad1.java @@ -1,4 +1,9 @@ package com.google.checkstyle.test.chapter3filestructure.rule341onetoplevel; -class InputOneTopLevelClassBad1 {} //ok -enum FooEnum {} // warn +class InputOneTopLevelClassBad1 {} // ok + +// violation below 'Top-level class FooEnum has to reside in its own source file.' +enum FooEnum {} + +// violation below 'Top-level class FooAt has to reside in its own source file.' +@interface FooAt {} // warn diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBad2.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBad2.java index 5e442eb451ce..88bd45b63174 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBad2.java +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBad2.java @@ -1,9 +1,10 @@ package com.google.checkstyle.test.chapter3filestructure.rule341onetoplevel; -public enum InputOneTopLevelClassBad2 {} //ok +/** Some javadoc. */ +public enum InputOneTopLevelClassBad2 {} // ok -interface FooIn {} // warn +// violation below 'Top-level class FooIn has to reside in its own source file.' +interface FooIn {} +// violation below 'Top-level class FooClass has to reside in its own source file.' class FooClass {} // warn - - diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBasic.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBasic.java index 14c87159e291..bb1e7830017a 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBasic.java +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassBasic.java @@ -1,88 +1,87 @@ package com.google.checkstyle.test.chapter3filestructure.rule341onetoplevel; -public class InputOneTopLevelClassBasic -{ - public InputOneTopLevelClassBasic() throws CloneNotSupportedException - { - super.equals(new String()); - super.clone(); - } - public Object clone() throws CloneNotSupportedException - { - return super.clone(); - } +/** Some javadoc. */ +public class InputOneTopLevelClassBasic { + /** Some javadoc. */ + public InputOneTopLevelClassBasic() throws CloneNotSupportedException { + super.equals(new String()); + super.clone(); + } - public void method() throws CloneNotSupportedException - { - super.clone(); - } + /** Some javadoc. */ + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } - { - super.clone(); - } + /** Some javadoc. */ + public void method() throws CloneNotSupportedException { + super.clone(); + } + + { + super.clone(); + } } -class NoSuperClone //warn -{ - public Object clone() - { - return null; - } +// violation below 'Top-level class NoSuperClone has to reside in its own source file.' +class NoSuperClone { + public Object clone() { + return null; + } } -class InnerClone //warn -{ - public Object clone() - { - class Inner - { - public Object clone() throws CloneNotSupportedException - { - return super.clone(); - } - } - return null; +// violation below 'Top-level class InnerClone has to reside in its own source file.' +class InnerClone { + public Object clone() { + class Inner { + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } } + + return null; + } } // This could not pass as valid semantically but tests that // type arguments are ignored when checking super calls -class CloneWithTypeArguments //warn -{ - //Some code +// violation below 'Top-level class CloneWithTypeArguments has to reside in its own source file.' +class CloneWithTypeArguments { + // Some code } -class CloneWithTypeArgumentsAndNoSuper //warn -{ -} +// violation below '.* class CloneWithTypeArgumentsAndNoSuper has to reside in .* own source file.' +class CloneWithTypeArgumentsAndNoSuper {} -//Check that super keyword isn't snagged here -class MyClassWithGenericSuperMethod //warn -{ - void someMethod(java.util.List l) - { - //Some code - } +// Check that super keyword isn't snagged here +// violation below '.* class MyClassWithGenericSuperMethod has to reside in its own source file.' +class MyClassWithGenericSuperMethod { + void someMethod(java.util.List l) { + // Some code + } - /** - * Not a valid clone override. Should not get flagged. - * @param o some object - * @return a cloned Object? - */ - public static Object clone(Object o) { + /** + * Not a valid clone override. Should not get flagged. + * + * @param o some object + * @return a cloned Object? + */ + public static Object clone(Object o) { return null; - } + } } -class AnotherClass { //warn +// violation below 'Top-level class AnotherClass has to reside in its own source file.' +class AnotherClass { - /** - * Not a valid clone override. Should not get flagged. - * @param t some type - * @param a type - * @return a cloned type? - */ - public T clone(T t) { + /** + * Not a valid clone override. Should not get flagged. + * + * @param t some type + * @param a type + * @return a cloned type? + */ + public T clone(T t) { return null; - } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassGood.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassGood.java index 43a0f2dbc026..76cafaea0815 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassGood.java +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule341onetoplevel/InputOneTopLevelClassGood.java @@ -1,23 +1,24 @@ package com.google.checkstyle.test.chapter3filestructure.rule341onetoplevel; -public class InputOneTopLevelClassGood //ok -{ - public InputOneTopLevelClassGood() throws CloneNotSupportedException - { - super.equals(new String()); - super.clone(); - } - public Object clone() throws CloneNotSupportedException - { - return super.clone(); - } +/** Some javadoc. */ +public class InputOneTopLevelClassGood { // ok + /** Some javadoc. */ + public InputOneTopLevelClassGood() throws CloneNotSupportedException { + super.equals(new String()); + super.clone(); + } - public void method() throws CloneNotSupportedException - { - super.clone(); - } + /** Some javadoc. */ + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } - { - super.clone(); - } + /** Some javadoc. */ + public void method() throws CloneNotSupportedException { + super.clone(); + } + + { + super.clone(); + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadMethodsDeclarationOrder.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadMethodsDeclarationOrder.java deleted file mode 100644 index 76cdf5f399be..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadMethodsDeclarationOrder.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.rule3421overloadsplit; - -class InputOverloadMethodsDeclarationOrder -{ - public void overloadMethod(int i) - { - //some foo code - } - - public void overloadMethod(String s) - { - //some foo code - } - - public void overloadMethod(boolean b) - { - //some foo code - } - - public void fooMethod() - { - - } - - //violation because overloads never split - public void overloadMethod(String s, Boolean b, int i) //warn - { - //some foo code - } - - InputOverloadMethodsDeclarationOrder anonymous = new InputOverloadMethodsDeclarationOrder() - { - public void overloadMethod(int i) - { - //some foo code - } - - public void overloadMethod(String s) - { - //some foo code - } - - public void overloadMethod(boolean b) - { - //some foo code - } - - public void fooMethod() - { - - } - - //violation because overloads never split - public void overloadMethod(String s, Boolean b, int i) //warn - { - //some foo code - } - }; -} - -interface Fooable -{ - public abstract void foo(int i); - public abstract void foo(String s); - public abstract void noFoo(); - public abstract void foo(String s, Boolean b, int i); //warn -} - -enum FooType { - Strategy(""), - Shooter(""), - RPG(""); - - private String description; - - private FooType(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public void overloadMethod(int i) - { - //some foo code - } - - public void overloadMethod(String s) - { - //some foo code - } - - public void overloadMethod(boolean b) - { - //some foo code - } - - public void fooMethod() - { - - } - - //violation because overloads never split - public void overloadMethod(String s, Boolean b, int i) //warn - { - //some foo code - } -} - diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadsNeverSplit.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadsNeverSplit.java new file mode 100644 index 000000000000..366ac04c3da1 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadsNeverSplit.java @@ -0,0 +1,245 @@ +package com.google.checkstyle.test.chapter3filestructure.rule3421overloadsplit; + +/** Testing. */ +public class InputOverloadsNeverSplit { + + int abc; + + int bcd; + + void foo() {} + + InputOverloadsNeverSplit() {} + + InputOverloadsNeverSplit(String a) {} + + void foo2() {} + + InputOverloadsNeverSplit(int a) {} + + // violation 2 lines above 'Constructors should be grouped together.*' + + int abcd; + + InputOverloadsNeverSplit(double x) {} + + // violation 2 lines above 'Constructors should be grouped together.*' + + private enum InnerEnum1 { + one; + + int xyz; + + InnerEnum1() {} + + InnerEnum1(String f) {} + + String str; + + String str2; + + InnerEnum1(int x) {} // violation 'Constructors should be grouped together.*' + + private abstract class Inner { + Inner() {} + + int xyz; + + String neko; + + Inner(String g) {} // violation 'Constructors should be grouped together.*' + } + + InnerEnum1(double d) {} // violation 'Constructors should be grouped together.*' + } + + InputOverloadsNeverSplit(float x) {} + + // violation 2 lines above 'Constructors should be grouped together.*' + + InputOverloadsNeverSplit(long l) {} + + // violation 2 lines above 'Constructors should be grouped together.*' + + private class Inner { + Inner() {} + + Inner(String str) {} + + // Comments are allowed between constructors. + Inner(int x) {} + } + + private class Inner2 { + Inner2() {} + + Inner2(String str) {} + + int xyz; + + Inner2(int x) {} // violation 'Constructors should be grouped together.*' + + String xx; + + Inner2(double d) {} // violation 'Constructors should be grouped together.*' + + // violation below 'Constructors should be grouped together.*' + Inner2(float f) {} + } + + InputOverloadsNeverSplit(long l, double d) {} + + // violation 2 lines above 'Constructors should be grouped together.*' + + InputOverloadsNeverSplit annoynmous = + new InputOverloadsNeverSplit() { + int xyz; + + void test() {} + + void test2() {} + }; + + private enum InnerEnum2 { + ONE, + TWO, + THREE; + + void test() {} + + void test2() {} + + void test3() {} + } + + private enum InnerEnum3 { + InnerEnum3() {} + } + + private enum InnerEnum4 {} + + private class Inner3 { + void test() {} + + void test2() {} + + void test3() {} + } + + private class Inner4 { + Inner4() {} + } + + private class Inner5 {} + + /** some javadoc. */ + public void overloadMethod(int i) { + // some foo code + } + + /** some javadoc. */ + public void overloadMethod(String s) { + // some foo code + } + + /** some javadoc. */ + public void overloadMethod(boolean b) { + // some foo code + } + + /** some javadoc. */ + public void fooMethod() {} + + // violation 2 lines below 'All overloaded methods should be placed next to each other. .* '146'.' + /** some javadoc. */ + public void overloadMethod(String s, Boolean b, int i) { + // some foo code + } + + InputOverloadsNeverSplit anonymous = + new InputOverloadsNeverSplit() { + public void overloadMethod(int i) { + // some foo code + } + + public void overloadMethod(String s) { + // some foo code + } + + public void overloadMethod(boolean b) { + // some foo code + } + + public void fooMethod() {} + + // violation below 'All overloaded methods should be placed next to each other. .* '169'.' + public void overloadMethod(String s, Boolean b, int i) { + // some foo code + } + }; + + /** some javadoc. */ + public void testing() {} + + private void testing(int a) {} + + /** some javadoc. */ + public void testing(int a, int b) {} + + /** some javadoc. */ + public static void testing(String a) {} + + /** some javadoc. */ + public void testing(String a, String b) {} + + interface Fooable { + public abstract void foo(int i); + + public abstract void foo(String s); + + public abstract void noFoo(); + + public abstract void foo(String s, Boolean b, int i); + // violation above 'All overloaded methods should be placed next to each other. .* '198'.' + + } + + enum FooType { + Strategy(""), + Shooter(""), + RPG(""); + + private String description; + + private FooType(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public void overloadMethod(int i) { + // some foo code + } + + public void overloadMethod(String s) { + // some foo code + } + + public void overloadMethod(boolean b) { + // some foo code + } + + public void fooMethod() {} + + // violation below 'All overloaded methods should be placed next to each other. .* '234'.' + public void overloadMethod(String s, Boolean b, int i) { + // some foo code + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadsNeverSplitRecords.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadsNeverSplitRecords.java new file mode 100644 index 000000000000..e77af6c4d7bf --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3421overloadsplit/InputOverloadsNeverSplitRecords.java @@ -0,0 +1,113 @@ +// Java17 + +package com.google.checkstyle.test.chapter3filestructure.rule3421overloadsplit; + +/** Some javadoc. */ +public class InputOverloadsNeverSplitRecords { + /** Some javadoc. */ + public record MyRecord1(int x, int y) { + /** Some javadoc. */ + public MyRecord1(int a) { + this(a, a); + } + + void foo() {} + + void foo2() {} + + /** Some javadoc. */ + public MyRecord1 {} // violation 'Constructors should be grouped together.*' + + /** Some javadoc. */ + public MyRecord1(int a, int b, int c, int d) { + // violation above 'Constructors should be grouped together.*' + this(a + b, c + d); + } + + /** Some javadoc. */ + public MyRecord1(int x, int y, int z) { + // violation above 'Constructors should be grouped together.*' + this(x + y, z); + } + } + + class MyClass { + int xyz = 20; + + MyClass() {} + + MyClass(String s) {} + + String[] str; + + String[] str2; + + MyClass(int a) {} // violation 'Constructors should be grouped together.*' + } + + /** Some javadoc. */ + public record MyRecord2(double d) { + /** Some javadoc. */ + public MyRecord2(double a, double b, double c) { + this(a + b + c); + } + + /** Some javadoc. */ + public MyRecord2 {} + + /** Some javadoc. */ + public MyRecord2(double a, double b) { + this(a + b); + } + } + + /** Some javadoc. */ + public record MyRecord3(float f) { + /** Some javadoc. */ + public MyRecord3(float a, float b, float c) { + this(a + b + c); + } + } + + /** Some javadoc. */ + public record MyRecord4(String str) { + /** Some javadoc. */ + public MyRecord4 {} + } + + /** Some javadoc. */ + public record MyRecord5(long l) { + void test() {} + + void test2() {} + + void test3() {} + } + + /** Some javadoc. */ + public record MyRecord6(String str, int x) {} + + /** Some javadoc. */ + public void overloadMethod(int i) { + // some foo code + } + + /** Some javadoc. */ + public void overloadMethod(String s) { + // some foo code + } + + /** Some javadoc. */ + public void overloadMethod(boolean b) { + // some foo code + } + + /** Some javadoc. */ + public void fooMethod() {} + + // violation 2 lines below 'All overloaded methods should be placed next to each other. .* '101' + /** Some javadoc. */ + public void overloadMethod(String s, Boolean b, int i) { + // some foo code + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputEmptyLineSeparator.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputEmptyLineSeparator.java deleted file mode 100644 index 882e740b6266..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputEmptyLineSeparator.java +++ /dev/null @@ -1,126 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// -package com.google.checkstyle.test.chapter3filestructure.rule3sourcefile; //warn -import java.io.Serializable; //warn -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.Collections; -import com.puppycrawl.tools.checkstyle.Checker; -import com.puppycrawl.tools.checkstyle.ConfigurationLoader; - -import javax.swing.AbstractAction; - -import org.apache.commons.beanutils.locale.converters.ByteLocaleConverter; -class InputEmptyLineSeparator //warn -{ - public static final double FOO_PI = 3.1415; - private boolean flag = true; - static { //warn - //empty static initializer - } - - { - //empty instance initializer - } - - /** - * - * - * - */ - private InputEmptyLineSeparator() - { - //empty - } - - public int compareTo(InputEmptyLineSeparator aObject) - { - int number = 0; - return 0; - } - /** - * - * @param task - * @param result - * @return - */ - public static Callable callable(Runnable task, T result) // warn - { - return null; - } - - public int getBeastNumber() - { - return 666; - } - interface IntEnum { //warn - } - - class InnerClass { - - public static final double FOO_PI_INNER = 3.1415; - private boolean flagInner = true; - { //warn - //empty instance initializer - } - - private InnerClass() - { - //empty - } - - } - - class InnerClass2 { //ok - private InnerClass2() //ok - { - //empty - } - } - - class InnerClass3 { //ok - public int compareTo(InputEmptyLineSeparator aObject) //ok - { - int number = 0; - return 0; - } - - } -} - -class Class1 { //ok - private Class1() {} //ok -} -class Class2{ //warn - public int compareTo(InputEmptyLineSeparator aObject) //ok - { - int number = 0; - return 0; - } - Class2 anon = new Class2(){ //warn - public int compareTo(InputEmptyLineSeparator aObject) //ok - { - int number = 0; - return 0; - } - }; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputFormattedSourceFileStructure.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputFormattedSourceFileStructure.java new file mode 100644 index 000000000000..0714b878e717 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputFormattedSourceFileStructure.java @@ -0,0 +1,111 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// +package com.google.checkstyle.test.chapter3filestructure.rule3sourcefile; + +// violation 2 lines above ''package' should be separated from previous line.' + +import java.util.concurrent.Callable; + +class InputFormattedSourceFileStructure { + public static final double FOO_PI = 3.1415; + private boolean flag = true; + + static { + // empty static initializer + } + + { + // empty instance initializer + } + + /** Some javadoc... */ + private InputFormattedSourceFileStructure() { + // empty + } + + public int compareTo(InputFormattedSourceFileStructure obj) { + int number = 0; + return 0; + } + + /** + * Some javadoc... + * + * @param task some description.... + * @param result some description.... + * @return some description.... + */ + public static Callable callable(Runnable task, T result) { + return null; + } + + public int getBeastNumber() { + return 666; + } + + interface IntEnum {} + + class InnerClass { + + public static final double FOO_PI_INNER = 3.1415; + private boolean flagInner = true; + + { + // empty instance initializer + } + + private InnerClass() { + // empty + } + } + + class InnerClass2 { // ok + private InnerClass2() { // ok + // empty + } + } + + class InnerClass3 { // ok + public int compareTo(InputSourceFileStructure obj) { // ok + int number = 0; + return 0; + } + } +} + +// violation below 'Top-level class ExtraClass1 has to reside in its own source file.' +class ExtraClass1 { // ok + private ExtraClass1() {} // ok +} + +class ExtraClass2 { + // violation above 'Top-level class ExtraClass2 has to reside in its own source file.' + public int compareTo(InputSourceFileStructure obj) { // ok + int number = 0; + return 0; + } + + Class2 anon = + new Class2() { + public int compareTo(InputSourceFileStructure obj) { // ok + int number = 0; + return 0; + } + }; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputSourceFileStructure.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputSourceFileStructure.java new file mode 100644 index 000000000000..b93550bda150 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/InputSourceFileStructure.java @@ -0,0 +1,107 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// +// violation below ''package' should be separated from previous line.' +package com.google.checkstyle.test.chapter3filestructure.rule3sourcefile; +import java.util.concurrent.Callable; // violation ''import' should be separated from previous line.' +class InputSourceFileStructure { // violation ''CLASS_DEF' should be separated from previous line.' + public static final double FOO_PI = 3.1415; + private boolean flag = true; + static { // violation ''STATIC_INIT' should be separated from previous line.' + // empty static initializer + } + + { + // empty instance initializer + } + + /** Some javadoc... */ + private InputSourceFileStructure() { + // empty + } + + public int compareTo(InputSourceFileStructure obj) { + int number = 0; + return 0; + } + /** + * Some javadoc... + * + * @param task some description.... + * @param result some description.... + * @return some description.... + */ + public static Callable callable(Runnable task, T result) { + // violation above ''METHOD_DEF' should be separated from previous line.' + return null; + } + + public int getBeastNumber() { + return 666; + } + interface IntEnum { + // violation above ''INTERFACE_DEF' should be separated from previous line.' + } + + class InnerClass { + + public static final double FOO_PI_INNER = 3.1415; + private boolean flagInner = true; + { // violation ''INSTANCE_INIT' should be separated from previous line.' + // empty instance initializer + } + + private InnerClass() { + // empty + } + } + + class InnerClass2 { // ok + private InnerClass2() { // ok + // empty + } + } + + class InnerClass3 { // ok + public int compareTo(InputSourceFileStructure obj) { // ok + int number = 0; + return 0; + } + } +} + +// violation below 'Top-level class Class1 has to reside in its own source file.' +class Class1 { // ok + private Class1() {} // ok +} +class Class2 { + // 2 violations above: + // 'Top-level class Class2 has to reside in its own source file.' + // 'CLASS_DEF' should be separated from previous line.' + public int compareTo(InputSourceFileStructure obj) { // ok + int number = 0; + return 0; + } + Class2 anon = // violation ''VARIABLE_DEF' should be separated from previous line.' + new Class2() { + public int compareTo(InputSourceFileStructure obj) { // ok + int number = 0; + return 0; + } + }; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/package-info.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/package-info.java new file mode 100644 index 000000000000..121dcdf24b00 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule3sourcefile/package-info.java @@ -0,0 +1,20 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// +package com.google.checkstyle.test.chapter3filestructure.rule3sourcefile; +// false-negative above, ok until #17541 diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/InputLineLength.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/InputLineLength.java deleted file mode 100644 index 7f215f4ce869..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/InputLineLength.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule; // ok -import java.io.*; -final class InputLineLength -{ - // Long line ---------------------------------------------------------------------------------------- //warn - // Contains a tab -> <- - // Contains trailing whitespace -> - - // Name format tests - // - /** Invalid format **/ - public static final int badConstant = 2; - /** Valid format **/ - public static final int MAX_ROWS = 2; - - /** Invalid format **/ - private static int badStatic = 2; - /** Valid format **/ - private static int sNumCreated = 0; - - /** Invalid format **/ - private int badMember = 2; - /** Valid format **/ - private int mNumCreated1 = 0; - /** Valid format **/ - protected int mNumCreated2 = 0; - - /** commas are wrong **/ - private int[] mInts = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}; //warn - - /** - * Very long url: https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java - */ - public void fooMethod() {} - - /** - * Long url without wrapping: http://ftp.dlink.ru/pub/D-Link_Solutions/D-Link_Solutions_for_Business.pdf - */ - public void fooMethodLongFtp() {} - - public void fooLongStringUrl() { - String url = "https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java"; //ok - processUrl("https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java"); //ok - processUrl("some line" - + "https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java" //ok - + "+ long fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo00000000000o line"); //warn - processUrl("Some long foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo line"); //warn - String[] soooooooooooooooooooooooooooooooooooolongfooooooooooooooooooooooooooooooooooooooooooo = { //warn - "http://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java", //ok - "Some long foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo line", //warn - }; - - String fakehttps = "Some long foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo line"; //warn - - processUrl(new String[] { - "http://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java", //ok - "Some long foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo line", //warn - }); - - String s = "text" - + "text" - + "text something more.. long url name, long url name, long url name" //ok - + "other text"; - } - - /** - * - * @param url - */ - public void processUrl(String url) {} - - /** - * - * @param urls - */ - public void processUrl(String[] urls){} -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/InputPackageStatementLongName.java b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/InputPackageStatementLongName.java new file mode 100644 index 000000000000..c2b51834a26b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter3filestructure/toolongpackagetotestcoveragegooglesjavastylerule/InputPackageStatementLongName.java @@ -0,0 +1,3 @@ +package com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule; // ok + +final class InputPackageStatementLongName {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule411bracesareused/InputNeedBraces.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule411bracesareused/InputNeedBraces.java deleted file mode 100644 index 93673907a444..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule411bracesareused/InputNeedBraces.java +++ /dev/null @@ -1,215 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule411bracesareused; - -import java.io.*; -import javax.script.*; -import java.util.concurrent.*; -import java.nio.channels.*; -import java.awt.print.*; -import java.lang.management.*; -import javax.lang.model.element.*; - -class InputNeedBraces -{ - /** @return helper func **/ - boolean condition() - { - return false; - } - - /** Test do/while loops **/ - void testDoWhile() - { - // Valid - do { - testDoWhile(); - } - while (condition()); - - // Invalid - do testDoWhile(); while (condition()); //warn - } - - /** Test while loops **/ - void testWhile() - { - // Valid - while (condition()) { - testWhile(); - } - - // Invalid - while(condition()); //warn - while (condition()) //warn - testWhile(); - while (condition()) //warn - if (condition()) //warn - testWhile(); - } - - /** Test for loops **/ - void testFor() - { - // Valid - for (int i = 1; i < 5; i++) { - testFor(); - } - - // Invalid - for(int i = 1;i < 5;i++); //warn - for (int i = 1; i < 5; i++) //warn - testFor(); - for (int i = 1; i < 5; //warn - i++) - if (i > 2) //warn - testFor(); - } - - /** Test if constructs **/ - public void testIf() - { - // Valid - if (condition()) { - testIf(); - } - else if (condition()) { - testIf(); - } - else { - testIf(); - } - - // Invalid - if (condition()); //warn - if (condition()) //warn - testIf(); - if (condition()) //warn - testIf(); - else //warn - testIf(); - if (condition()) //warn - testIf(); - else { - testIf(); - } - if (condition()) { - testIf(); - } - else //warn - testIf(); - if (condition()) //warn - if (condition()) //warn - testIf(); - } - - void whitespaceAfterSemi() - { - //reject - int i = 1;int j = 2; - - //accept - for (;;) { - } - } - - /** Empty constructor block. **/ - public InputNeedBraces() {} - - /** Empty method block. **/ - public void emptyImplementation() {} -} - -class EmptyBlocks { - boolean flag = true; - int[] a = {1, 2, 3, 4, }; - - void foo() { - while(flag); //warn - while(flag) {} - while(flag) {/*foo*/} - do; //warn - while(flag); - do {} - while(flag); - do {/*foo*/} - while(flag); - if(flag); //warn - if(flag){} - if(flag) {/*foo*/} - if(flag); //warn - else; //warn - if(flag){} - else {} - if(flag){/*foo*/} - else {/*foo*/} - for(int i = 0; i < 10; i++); //warn - for(int i = 0; i < 10; i++) {} - for(int i = 0; i < 10; i++) {/*foo*/} - for(int b : a); //warn - for(int b : a) {} - for(int b : a) {/*foo*/} - } - - class InnerEmptyBlocks { - boolean flag = true; - int[] a = {1, 2, 3, 4, }; - - void foo() { - while(flag); //warn - while(flag) {} - while(flag) {/*foo*/} - do; //warn - while(flag); - do {} - while(flag); - do {/*foo*/} - while(flag); - if(flag); //warn - if(flag){} - if(flag) {/*foo*/} - if(flag); //warn - else; //warn - if(flag){} - else {} - if(flag){/*foo*/} - else {/*foo*/} - for(int i = 0; i < 10; i++); //warn - for(int i = 0; i < 10; i++) {} - for(int i = 0; i < 10; i++) {/*foo*/} - for(int b : a); //warn - for(int b : a) {} - for(int b : a) {/*foo*/} - } - } - - InnerEmptyBlocks anon = new InnerEmptyBlocks() { - boolean flag = true; - int[] a = {1, 2, 3, 4, }; - - void foo() { - while(flag); //warn - while(flag) {} - while(flag) {/*foo*/} - do; //warn - while(flag); - do {} - while(flag); - do {/*foo*/} - while(flag); - if(flag); //warn - if(flag){} - if(flag) {/*foo*/} - if(flag); //warn - else; //warn - if(flag){} - else {} - if(flag){/*foo*/} - else {/*foo*/} - for(int i = 0; i < 10; i++); //warn - for(int i = 0; i < 10; i++) {} - for(int i = 0; i < 10; i++) {/*foo*/} - for(int b : a); //warn - for(int b : a) {} - for(int b : a) {/*foo*/} - } - }; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule411optionalbracesusage/InputUseOfOptionalBraces.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule411optionalbracesusage/InputUseOfOptionalBraces.java new file mode 100644 index 000000000000..166b435361f3 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule411optionalbracesusage/InputUseOfOptionalBraces.java @@ -0,0 +1,311 @@ +package com.google.checkstyle.test.chapter4formatting.rule411optionalbracesusage; + +class InputUseOfOptionalBraces { + /** + * some javadoc.. + * + * @return helper func * + */ + boolean condition() { + return false; + } + + /** Test do/while loops. */ + void testDoWhile() { + // Valid + do { + testDoWhile(); + } while (condition()); + + // Invalid + // violation below ''do' construct must use '{}'s.' + do testDoWhile(); + while (condition()); + } + + /** Test while loops. */ + void testWhile() { + // Valid + while (condition()) { + testWhile(); + } + + // Invalid + // violation 2 lines below ''while' construct must use '{}'s.' + // violation 3 lines below ''while' construct must use '{}'s.' + while (condition()) + ; + while (condition()) testWhile(); + // violation 2 lines below ''while' construct must use '{}'s.' + // violation below ''if' construct must use '{}'s.' + while (condition()) if (condition()) testWhile(); + String k = "testing"; + // violation below ''if' construct must use '{}'s.' + if (k != null) k = "ss"; + } + + /** Test for loops. */ + void testFor() { + // Valid + for (int i = 1; i < 5; i++) { + testFor(); + } + + // Invalid + // violation below ''for' construct must use '{}'s.' + for (int i = 1; i < 5; i++) + ; + // violation below ''for' construct must use '{}'s.' + for (int i = 1; i < 5; i++) testFor(); + // violation 2 lines below ''for' construct must use '{}'s.' + // violation below ''if' construct must use '{}'s.' + for (int i = 1; i < 5; i++) if (i > 2) testFor(); + } + + /** Test if constructs. */ + public void testIf() { + // Valid + if (condition()) { + testIf(); + } else if (condition()) { + testIf(); + } else { + testIf(); + } + + // Invalid + // violation below ''if' construct must use '{}'s.' + if (condition()) + ; + // violation below ''if' construct must use '{}'s.' + if (condition()) testIf(); + // violation 2 lines below ''if' construct must use '{}'s.' + // violation 2 lines below ''else' construct must use '{}'s.' + if (condition()) testIf(); + else testIf(); + // violation below ''if' construct must use '{}'s.' + if (condition()) testIf(); + else { + testIf(); + } + if (condition()) { + testIf(); + // violation below ''else' construct must use '{}'s.' + } else testIf(); + // violation 2 lines below ''if' construct must use '{}'s.' + // violation below ''if' construct must use '{}'s.' + if (condition()) if (condition()) testIf(); + } + + void whitespaceAfterSemi() { + // reject + int i = 1; + int j = 2; + + // accept + for (; ; ) {} + } + + /** Empty constructor block. */ + public InputUseOfOptionalBraces() {} + + /** Empty method block. */ + public void emptyImplementation() {} + + /** Testing Lambdas. */ + static Runnable r2 = () -> String.CASE_INSENSITIVE_ORDER.equals("Hello world one!"); + + static Runnable r3 = () -> String.CASE_INSENSITIVE_ORDER.equals("Hello world one!"); + static Runnable r4 = + () -> { + String.CASE_INSENSITIVE_ORDER.equals("Hello world one!"); + }; + static Runnable r5 = () -> {}; + + class EmptyBlocks { + boolean flag = true; + int[] abc = { + 1, 2, 3, 4, + }; + + void foo() { + // violation below ''while' construct must use '{}'s.' + while (flag) + ; + while (flag) {} + while (flag) { + /*foo*/ + } + // violation below ''do' construct must use '{}'s.' + do + ; + while (flag); + do {} while (flag); + do { + /*foo*/ + } while (flag); + // violation below ''if' construct must use '{}'s.' + if (flag) + ; + if (flag) { + /*foo*/ + } + if (flag) { + /*foo*/ + } + // violation 2 lines below ''if' construct must use '{}'s.' + // violation 3 lines below ''else' construct must use '{}'s.' + if (flag) + ; + else + ; + if (flag) { + } else { + } + if (flag) { + /*foo*/ + } else { + /*foo*/ + } + // violation below ''for' construct must use '{}'s.' + for (int i = 0; i < 10; i++) + ; + for (int i = 0; i < 10; i++) {} + for (int i = 0; i < 10; i++) { + /*foo*/ + } + // violation below ''for' construct must use '{}'s.' + for (int b : abc) + ; + for (int b : abc) {} + for (int b : abc) { + /*foo*/ + } + } + + class InnerEmptyBlocks { + boolean flag = true; + int[] abc = { + 1, 2, 3, 4, + }; + + void foo() { + // violation below ''while' construct must use '{}'s.' + while (flag) + ; + while (flag) {} + while (flag) { + /*foo*/ + } + // violation below ''do' construct must use '{}'s.' + do + ; + while (flag); + do {} while (flag); + do { + /*foo*/ + } while (flag); + // violation below ''if' construct must use '{}'s.' + if (flag) + ; + if (flag) { + /*foo*/ + } + if (flag) { + /*foo*/ + } + // violation 2 lines below ''if' construct must use '{}'s.' + // violation 3 lines below ''else' construct must use '{}'s.' + if (flag) + ; + else + ; + if (flag) { + } else { + } + if (flag) { + /*foo*/ + } else { + /*foo*/ + } + // violation below ''for' construct must use '{}'s.' + for (int i = 0; i < 10; i++) + ; + for (int i = 0; i < 10; i++) {} + for (int i = 0; i < 10; i++) { + /*foo*/ + } + // violation below ''for' construct must use '{}'s.' + for (int b : abc) + ; + for (int b : abc) {} + for (int b : abc) { + /*foo*/ + } + } + } + + InnerEmptyBlocks anon = + new InnerEmptyBlocks() { + boolean flag = true; + int[] abc = { + 1, 2, 3, 4, + }; + + void foo() { + // violation below ''while' construct must use '{}'s.' + while (flag) + ; + while (flag) {} + while (flag) { + /*foo*/ + } + // violation below ''do' construct must use '{}'s.' + do + ; + while (flag); + do {} while (flag); + do { + /*foo*/ + } while (flag); + // violation below ''if' construct must use '{}'s.' + if (flag) + ; + if (flag) { + /*foo*/ + } + if (flag) { + /*foo*/ + } + // violation 2 lines below ''if' construct must use '{}'s.' + // violation 3 lines below ''else' construct must use '{}'s.' + if (flag) + ; + else + ; + if (flag) { + } else { + } + if (flag) { + /*foo*/ + } else { + /*foo*/ + } + // violation below ''for' construct must use '{}'s.' + for (int i = 0; i < 10; i++) + ; + for (int i = 0; i < 10; i++) {} + for (int i = 0; i < 10; i++) { + /*foo*/ + } + // violation below ''for' construct must use '{}'s.' + for (int b : abc) + ; + for (int b : abc) {} + for (int b : abc) { + /*foo*/ + } + } + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedLeftCurlyAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedLeftCurlyAnnotations.java new file mode 100644 index 000000000000..316d68318ccc --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedLeftCurlyAnnotations.java @@ -0,0 +1,61 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; +import java.util.ArrayList; +import java.util.List; + +@TestClassAnnotation2 +class InputFormattedLeftCurlyAnnotations { + private static final int X = 10; + + @Override + public boolean equals(Object other) { + return false; + } + + @Override + @SuppressWarnings("unused") + public int hashCode() { + int a = 10; + return 1; + } + + @Override + @SuppressWarnings({"unused", "unchecked", "static-access"}) + public String toString() { + Integer i = this.X; + List l = new ArrayList(); + return "SomeString"; + } +} + +// violation below '.* InputFormattedLeftCurlyAnnotations2 has to reside in its own source file.' +@TestClassAnnotation2 +class InputFormattedLeftCurlyAnnotations2 { + private static final int X = 10; + + @Override + public boolean equals(Object other) { + return false; + } + + @Override + @SuppressWarnings("unused") + public int hashCode() { + int a = 10; + return 1; + } + + @Override + @SuppressWarnings({"unused", "unchecked", "static-access"}) + public String toString() { + Integer i = this.X; + List l = new ArrayList(); + return "SomeString"; + } +} + +// violation below 'Top-level class TestClassAnnotation2 has to reside in its own source file.' +@Target(ElementType.TYPE) +@interface TestClassAnnotation2 {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedLeftCurlyMethod.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedLeftCurlyMethod.java new file mode 100644 index 000000000000..6938dbd9c31b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedLeftCurlyMethod.java @@ -0,0 +1,55 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +class InputFormattedLeftCurlyMethod { + InputFormattedLeftCurlyMethod() {} + + InputFormattedLeftCurlyMethod(String one) {} + + InputFormattedLeftCurlyMethod(int one) {} + + void method1() {} + + void method2() {} + + void method3() {} + + void method4() {} + + void method5(String one, String two) {} + + void method6(String one, String two) {} + + enum InputLeftCurlyMethodEnum { + CONSTANT1("hello") { + void method1() {} + + void method2() {} + + void method3() {} + + void method4() {} + + void method5(String one, String two) {} + + void method6(String one, String two) {} + }, + + CONSTANT2("hello") {}, + + CONSTANT3("hellohellohellohellohellohellohellohellohellohellohellohellohellohello") {}; + + private InputLeftCurlyMethodEnum(String value) {} + + void method1() {} + + void method2() {} + + void method3() {} + + void method4() {} + + void method5(String one, String two) {} + + void method6(String one, String two) {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedNonemptyBlocksLeftRightCurly.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedNonemptyBlocksLeftRightCurly.java new file mode 100644 index 000000000000..653a41cf7dc5 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedNonemptyBlocksLeftRightCurly.java @@ -0,0 +1,273 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +class InputFormattedNonemptyBlocksLeftRightCurly { + /** + * summary. + * + * @return helper func * + */ + boolean condition() { + return false; + } + + /** Test do/while loops. */ + void testDoWhile() { + + do { + testDoWhile(); + } while (condition()); + + do { + testDoWhile(); + } while (condition()); + } + + /** Test while loops. */ + void testWhile() { + + while (condition()) { + testWhile(); + } + + while (condition()) { + /* foo */ + } + while (condition()) { + testWhile(); + } + while (condition()) { + if (condition()) { + testWhile(); + } + } + } + + /** Test for loops. */ + void testFor() { + + for (int i = 1; i < 5; i++) { + testFor(); + } + + for (int i = 1; i < 5; i++) { + /* foo */ + } + for (int i = 1; i < 5; i++) { + testFor(); + } + for (int i = 1; i < 5; i++) { + if (i > 2) { + testFor(); + } + } + } + + /** Test if constructs. */ + public void testIf() { + + if (condition()) { + testIf(); + } else if (condition()) { + testIf(); + } else { + testIf(); + } + + if (condition()) { + /* foo */ + } + if (condition()) { + testIf(); + } + if (condition()) { + testIf(); + } else { + testIf(); + } + if (condition()) { + testIf(); + } else { + testIf(); + } + if (condition()) { + testIf(); + } else { + testIf(); + } + if (condition()) { + if (condition()) { + testIf(); + } + } + } + + void whitespaceAfterSemi() { + + int i = 1; + int j = 2; + + for (; ; ) {} + } + + /** Empty constructor block. */ + public InputFormattedNonemptyBlocksLeftRightCurly() {} + + /** Empty method block. */ + public void emptyImplementation() {} +} + +// violation below 'Top-level class EnumContainerLeft2 has to reside in its own source file.' +class EnumContainerLeft2 { + private enum Suit { + CLUBS, + HEARTS, + SPADES, + DIAMONDS + } +} + +// violation below 'Top-level class WithArraysLeft2 has to reside in its own source file.' +class WithArraysLeft2 { + String[] s1 = {""}; + String[] empty = {}; + String[] s2 = { + "foo", "foo", + }; + String[] s3 = { + "foo", "foo", + }; + String[] s4 = { + "foo", "foo", + }; + String[] s5 = {"foo", "foo"}; +} + +// violation below 'Top-level class InputRightCurlyOther22 has to reside in its own source file.' +class InputRightCurlyOther22 { + /** + * summary. + * + * @see test method * + */ + int foo() throws InterruptedException { + int x = 1; + int a = 2; + while (true) { + try { + if (x > 0) { + break; + } else if (x < 0) { + + ; + } else { + break; + } + switch (a) { + case 0: + break; + default: + break; + } + } catch (Exception e) { + break; + } + } + + synchronized (this) { + do { + x = 2; + } while (x == 2); + } + + this.wait(666); // Bizarre, but legal + + for (int k = 0; k < 1; k++) { + String innerBlockVariable = ""; + } + + if (System.currentTimeMillis() > 1000) { + return 1; + } else { + return 2; + } + } + + static { + int x = 1; + } + + /** some javadoc. */ + public enum GreetingsEnum { + HELLO, + GOODBYE + } + + void method2() { + boolean flag = true; + if (flag) { + System.identityHashCode("heh"); + flag = !flag; + } + System.identityHashCode("Xe-xe"); + + if (flag) { + System.identityHashCode("some foo"); + } + } +} + +/** + * Test input for closing brace if that brace terminates a statement or the body of a constructor. + */ +// violation below 'Top-level class FooCtor2 has to reside in its own source file.' +class FooCtor2 { + int i3; + + public FooCtor2() { + i3 = 1; + } +} + +/** Test input for closing brace if that brace terminates a statement or the body of a method. */ +// violation below 'Top-level class FooMethod2 has to reside in its own source file.' +class FooMethod2 { + public void fooMethod() { + int i = 1; + } +} + +/** + * Test input for closing brace if that brace terminates a statement or the body of a named class. + */ +// violation below 'Top-level class FooInner2 has to reside in its own source file.' +class FooInner2 { + class InnerFoo { + public void fooInnerMethod() {} + } +} + +// violation below 'Top-level class EnumContainer2 has to reside in its own source file.' +class EnumContainer2 { + private enum Suit { + CLUBS, + HEARTS, + SPADES, + DIAMONDS + } +} + +// violation below 'Top-level class WithArrays2 has to reside in its own source file.' +class WithArrays2 { + String[] test = {""}; + String[] empty = {}; + String[] s1 = { + "foo", "foo", + }; + String[] s2 = { + "foo", "foo", + }; + String[] s3 = { + "foo", "foo", + }; + String[] s4 = {"foo", "foo"}; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurly.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurly.java new file mode 100644 index 000000000000..a362195ec6e6 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurly.java @@ -0,0 +1,14 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputFormattedRightCurly { + /** some javadoc. */ + public static void main(String[] args) { + boolean after = false; + try { + /* foo */ + } finally { + after = true; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyDoWhile.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyDoWhile.java new file mode 100644 index 000000000000..0ed682f7883c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyDoWhile.java @@ -0,0 +1,85 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +import java.util.Scanner; + +/** Test input for GitHub issue #3090. https://github.com/checkstyle/checkstyle/issues/3090 . */ +public class InputFormattedRightCurlyDoWhile { + + /** some javadoc. */ + public void foo1() { + do {} while (true); + } + + /** some javadoc. */ + public void foo2() { + int i = 1; + while (i < 5) { + String.CASE_INSENSITIVE_ORDER.equals(i + " "); + i++; + } + } + + /** some javadoc. */ + public void foo3() { + int i = 1; + do { + i++; + String.CASE_INSENSITIVE_ORDER.equals(i + " "); + } while (i < 5); + } + + /** some javadoc. */ + public void foo4() { + int prog; + int user; + prog = (int) (Math.random() * 10) + 1; + Scanner input = new Scanner(System.in, "utf-8"); + if (input.hasNextInt()) { + do { + user = input.nextInt(); + if (user == prog) { + String.CASE_INSENSITIVE_ORDER.equals("Good!"); + } else { + if (user > 0 && user <= 10) { + String.CASE_INSENSITIVE_ORDER.equals("Bad! "); + if (prog < user) { + String.CASE_INSENSITIVE_ORDER.equals("My number is less than yours."); + } else { + String.CASE_INSENSITIVE_ORDER.equals("My number is greater than yours"); + } + } else { + String.CASE_INSENSITIVE_ORDER.equals("Violation!"); + } + } + } while (user != prog); + } else { + String.CASE_INSENSITIVE_ORDER.equals("Violation!"); + } + String.CASE_INSENSITIVE_ORDER.equals("Goodbye!"); + } + + /** some javadoc. */ + public void foo5() { + do {} while (true); + } + + /** some javadoc. */ + public void foo6() { + do {} while (true); + } + + /** some javadoc. */ + public void foo7() { + do {} while (true); + } + + /** some javadoc. */ + public void foo8() { + do {} while (true); + } + + /** some javadoc. */ + public void foo9() { + do {} while (true); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyDoWhile2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyDoWhile2.java new file mode 100644 index 000000000000..070119c42b50 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyDoWhile2.java @@ -0,0 +1,86 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +/** Test input for GitHub issue #3090. https://github.com/checkstyle/checkstyle/issues/3090 . */ +public class InputFormattedRightCurlyDoWhile2 { + + /** some javadoc. */ + public void foo1() { + do {} while (true); + } + + /** some javadoc. */ + public void foo2() { + int i = 1; + while (i < 5) { + String.CASE_INSENSITIVE_ORDER.equals(i + " "); + i++; + } + } + + /** some javadoc. */ + public void foo3() { + int i = 1; + do { + i++; + String.CASE_INSENSITIVE_ORDER.equals(i + " "); + } while (i < 5); + } + + /** some javadoc. */ + public void foo4() { + int prog; + int user; + prog = (int) (Math.random() * 10) + 1; + Scanner input = new Scanner(System.in, StandardCharsets.UTF_8); + if (input.hasNextInt()) { + do { + user = input.nextInt(); + if (user == prog) { + String.CASE_INSENSITIVE_ORDER.equals("Good!"); + } else { + if (user > 0 && user <= 10) { + String.CASE_INSENSITIVE_ORDER.equals("Bad! "); + if (prog < user) { + String.CASE_INSENSITIVE_ORDER.equals("My number is less than yours."); + } else { + String.CASE_INSENSITIVE_ORDER.equals("My number is greater than yours"); + } + } else { + String.CASE_INSENSITIVE_ORDER.equals("Violation!"); + } + } + } while (user != prog); + } else { + String.CASE_INSENSITIVE_ORDER.equals("Violation!"); + } + String.CASE_INSENSITIVE_ORDER.equals("Goodbye!"); + } + + /** some javadoc. */ + public void foo5() { + do {} while (true); + } + + /** some javadoc. */ + public void foo6() { + do {} while (true); + } + + /** some javadoc. */ + public void foo7() { + do {} while (true); + } + + /** some javadoc. */ + public void foo8() { + do {} while (true); + } + + /** some javadoc. */ + public void foo9() { + do {} while (true); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyOther.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyOther.java new file mode 100644 index 000000000000..bf0833f5cad4 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlyOther.java @@ -0,0 +1,173 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +class InputFormattedRightCurlyOther { + /** + * summary. + * + * @see test method * + */ + int foo() throws InterruptedException { + int x = 1; + int a = 2; + while (true) { + try { + if (x > 0) { + break; + } else if (x < 0) { + + ; + } else { + break; + } + switch (a) { + case 0: + break; + default: + break; + } + } catch (Exception e) { + break; + } + } + + synchronized (this) { + do { + x = 2; + } while (x == 2); + } + + this.wait(666); // Bizarre, but legal + + for (int k = 0; k < 1; k++) { + String innerBlockVariable = ""; + } + + if (System.currentTimeMillis() > 1000) { + return 1; + } else { + return 2; + } + } + + static { + int x = 1; + } + + public enum GreetingsEnum { + HELLO, + GOODBYE + } + + void method2() { + boolean flag = true; + if (flag) { + System.identityHashCode("heh"); + flag = !flag; + } + System.identityHashCode("Xe-xe"); + + if (flag) { + System.identityHashCode("some foo"); + } + } +} + +/** + * Test input for closing brace if that brace terminates a statement or the body of a constructor. + */ +class FooCtorAlone2 { + // violation above 'Top-level class FooCtorAlone2 has to reside in its own source file.' + int test; + + public FooCtorAlone2() { + test = 1; + } +} + +/** Test input for closing brace if that brace terminates a statement or the body of a method. */ +class FooMethodAlone2 { + // violation above 'Top-level class FooMethodAlone2 has to reside in its own source file.' + public void fooMethod() { + int i = 1; + } +} + +/** + * Test input for closing brace if that brace terminates a statement or the body of a named class. + */ +class FooInnerAlone2 { + // violation above 'Top-level class FooInnerAlone2 has to reside in its own source file.' + class InnerFoo { + public void fooInnerMethod() {} + } +} + +// violation below 'Top-level class EnumContainerAlone2 has to reside in its own source file.' +class EnumContainerAlone2 { + private enum Suit { + CLUBS, + HEARTS, + SPADES, + DIAMONDS + } +} + +// violation below 'Top-level class WithArraysAlone2 has to reside in its own source file.' +class WithArraysAlone2 { + String[] ss = {""}; + String[] empty = {}; + String[] s1 = { + "foo", "foo", + }; + String[] s2 = { + "foo", "foo", + }; + String[] s3 = { + "foo", "foo", + }; + String[] s4 = {"foo", "foo"}; +} + +// violation below 'Top-level class Interface2 has to reside in its own source file.' +class Interface2 { + public @interface TestAnnotation {} + + public @interface TestAnnotation1 { + String someValue(); + } + + public @interface TestAnnotation2 { + String someValue(); + } + + public @interface TestAnnotation3 { + String someValue(); + } + + public @interface TestAnnotation4 { + String someValue(); + } +} + +// violation below 'Top-level class TestEnum222 has to reside in its own source file.' +enum TestEnum222 {} + +// violation below 'Top-level class TestEnum12 has to reside in its own source file.' +enum TestEnum12 { + SOME_VALUE; +} + +// violation below 'Top-level class TestEnum22 has to reside in its own source file.' +enum TestEnum22 { + SOME_VALUE; +} + +// violation below 'Top-level class TestEnum32 has to reside in its own source file.' +enum TestEnum32 { + SOME_VALUE; +} + +// violation below 'Top-level class TestEnum42 has to reside in its own source file.' +enum TestEnum42 { + SOME_VALUE; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlySwitchCase.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlySwitchCase.java new file mode 100644 index 000000000000..4703dbc282bc --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlySwitchCase.java @@ -0,0 +1,59 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputFormattedRightCurlySwitchCase { + + /** some javadoc. */ + public static void method0() { + int mode = 0; + switch (mode) { + case 1: + int x = 1; + break; + default: + x = 0; + } + } + + /** some javadoc. */ + public static void method1() { + int mode = 0; + switch (mode) { + default: + int x = 0; + } + } + + /** some javadoc. */ + public static void method2() { + int mode = 0; + switch (mode) { + case 1: + int x = 1; + break; + default: + x = 0; + } + } + + /** some javadoc. */ + public static void method3() { + int mode = 0; + switch (mode) { + default: + int x = 0; + } + } + + /** some javadoc. */ + public static void method4() { + int mode = 0; + switch (mode) { + case 1: + int y = 2; + break; + default: + int x = 0; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlySwitchCasesBlocks.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlySwitchCasesBlocks.java new file mode 100644 index 000000000000..d48ec59f9225 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedRightCurlySwitchCasesBlocks.java @@ -0,0 +1,158 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputFormattedRightCurlySwitchCasesBlocks { + + /** some javadoc. */ + public static void test0() { + int mode = 0; + switch (mode) { + case 1: + { + int x = 1; + break; + } + case 2: + { + int x = 0; + break; + } + default: + { + int x = 0; + } + } + } + + /** some javadoc. */ + public static void test() { + int mode = 0; + switch (mode) { + case 1: + { + int x = 1; + break; + } + default: + int x = 0; + } + } + + /** some javadoc. */ + public static void test1() { + int k = 0; + switch (k) { + case 1: + { + int x = 1; + } + break; + case 2: + int x = 2; + break; + default: + } + } + + /** some javadoc. */ + public static void test2() { + int mode = 0; + switch (mode) { + case 1: + int x = 1; + break; + case 2: + { + break; + } + default: + { + break; + } + } + } + + /** some javadoc. */ + public static void test3() { + int k = 0; + switch (k) { + case 1: + { + int x = 1; + break; + } + case 2: + { + int x = 2; + } + break; + default: + { + int x = 2; + } + } + } + + /** some javadoc. */ + public static void test4() { + int mode = 0; + switch (mode) { + case 1: + { + int x = 1; + break; + } + default: + { + int x = 0; + } + } + } + + /** some javadoc. */ + public static void test5() { + int k = 0; + switch (k) { + case 1: + { + int x = 1; + } + break; + default: + { + int a = 2; + } + } + } + + /** some javadoc. */ + public static void test6() { + int mode = 0; + switch (mode) { + case 1: + int x = 1; + break; + case 2: + { + break; + } + default: + } + } + + /** some javadoc. */ + public static void test7() { + int k = 0; + switch (k) { + case 1: + { + int x = 1; + break; + } + default: + { + int x = 2; + } + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedTryCatchIfElse.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedTryCatchIfElse.java new file mode 100644 index 000000000000..bc48dd315e09 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedTryCatchIfElse.java @@ -0,0 +1,105 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputFormattedTryCatchIfElse { + + @interface TesterAnnotation {} + + void foo() throws Exception { + int a = 90; + boolean test = true; + + if (a == 1) { + } else { + } + + if (a == 1) { + } else { + } + + if (a == 45) {} + + if (a == 9) { + } else { + } + + if (a == 99) { + System.out.println("test"); + } else { + System.out.println("before"); + } + + try (MyResource r = new MyResource()) {} + + try (MyResource r = new MyResource()) {} + + try (MyResource r = new MyResource()) { + // violation below 'Empty catch block' + } catch (Exception expected) { + } + + try (MyResource r = new MyResource()) { + // violation below 'Empty catch block' + } catch (Exception expected) { + } + + try (MyResource r = new MyResource()) { + // violation below 'Empty catch block' + } catch (Exception expected) { + } + + try (MyResource r = new MyResource()) { + // violation below 'Empty catch block' + } catch (Exception expected) { + } + + try (MyResource r = new MyResource()) { + ; + } + + try { + /* foo */ + } catch (NullPointerException e) { + /* foo */ + } catch (Exception e) { + /* foo */ + } finally { + test = true; + } + + try { + /* foo */ + } catch (NullPointerException e) { + /* foo */ + } catch (Exception e) { + /* foo */ + } finally { + test = true; + } + + try { + /* foo */ + } catch (Exception e) { + /* foo */ + } finally { + test = true; + } + + try { + /* foo */ + } catch (Exception e) { + /* foo */ + } finally { + test = true; + } + } + + /** some javadoc. */ + public class MyResource implements AutoCloseable { + /** some javadoc. */ + @Override + public void close() throws Exception { + System.out.println("Closed MyResource"); + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedTryCatchIfElse2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedTryCatchIfElse2.java new file mode 100644 index 000000000000..3fdb37d02133 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputFormattedTryCatchIfElse2.java @@ -0,0 +1,87 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputFormattedTryCatchIfElse2 { + /** some javadoc. */ + public static void main(String[] args) { + boolean after = false; + try { + /* foo */ + } finally { + after = true; + } + + try { + /* foo */ + } catch (NullPointerException e) { + /* foo */ + } catch (Exception e) { + /* foo */ + } finally { + after = true; + } + + if (after) { + System.out.println("after"); + } else if (after) { + System.out.println("before"); + } else if (after) { + System.out.println("before"); + } else { + System.out.println("before"); + } + + if (after) { + System.out.println("after"); + } else if (after) { + } else if (after) { + System.out.println("before"); + } else if (!after) { + /* foo */ + } else { + System.out.println("before"); + } + + if (after) { + System.out.println("foo"); + } else if (false) { + System.out.println("foo"); + } else { + System.out.println("foo"); + } + + if (after) { + System.out.println("after"); + } else if (after) { + System.out.println("before"); + } else { + System.out.println("before"); + } + + if (after) { + System.out.println("after"); + } else if (after) { + System.out.println("before"); + } else if (after) { + System.out.println("before"); + } else { + System.out.println("before"); + } + + if (after) { + System.out.println("after"); + } else if (after) { + System.out.println("before"); + } else { + System.out.println("before"); + } + + if (after) { + System.out.println("after"); + } else if (after) { + System.out.println("before"); + } else { + System.out.println("before"); + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyAnnotations.java index ecf250033ddd..973d42b01a8d 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyAnnotations.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyAnnotations.java @@ -7,53 +7,61 @@ @TestClassAnnotation class InputLeftCurlyAnnotations -{ //warn + { // violation ''{' at column 3 should be on the previous line.' private static final int X = 10; + @Override - public boolean equals(Object other) - { //warn - return false; + public boolean equals( + Object other) + { // violation ''{' at column 5 should be on the previous line.' + return false; } @Override @SuppressWarnings("unused") public int hashCode() - { //warn - int a = 10; - return 1; + { // violation ''{' at column 5 should be on the previous line.' + int a = 10; + return 1; } - @Override @SuppressWarnings({"unused", "unchecked", "static-access"}) public String toString() - { //warn - Integer i = this.X; - List l = new ArrayList(); - return "SomeString"; + @Override + @SuppressWarnings({"unused", "unchecked", "static-access"}) + public String toString() + { // violation ''{' at column 5 should be on the previous line.' + Integer i = this.X; + List l = new ArrayList(); + return "SomeString"; } -} + } +// violation below '.* InputLeftCurlyAnnotations2 has to reside in its own source file.' @TestClassAnnotation class InputLeftCurlyAnnotations2 { - private static final int X = 10; - @Override - public boolean equals(Object other) { - return false; - } + private static final int X = 10; - @Override - @SuppressWarnings("unused") - public int hashCode() { - int a = 10; - return 1; - } + @Override + public boolean equals(Object other) { + return false; + } - @Override @SuppressWarnings({"unused", "unchecked", "static-access"}) public String toString() - { //warn - Integer i = this.X; - List l = new ArrayList(); - return "SomeString"; + @Override + @SuppressWarnings("unused") + public int hashCode() { + int a = 10; + return 1; + } + + @Override + @SuppressWarnings({"unused", "unchecked", "static-access"}) + public String toString() + { // violation ''{' at column 5 should be on the previous line.' + Integer i = this.X; + List l = new ArrayList(); + return "SomeString"; } } +// violation below 'Top-level class TestClassAnnotation has to reside in its own source file.' @Target(ElementType.TYPE) -@interface TestClassAnnotation { -} +@interface TestClassAnnotation {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyBraces.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyBraces.java deleted file mode 100644 index 92f0c579d144..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyBraces.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; - -class InputLeftCurlyBraces -{ //warn - /** @return helper func **/ - boolean condition() - { //warn - return false; - } - - /** Test do/while loops **/ - void testDoWhile() - { //warn - - do { - testDoWhile(); - } - while (condition()); - - - do testDoWhile(); while (condition()); - } - - /** Test while loops **/ - void testWhile() - { //warn - - while (condition()) { - testWhile(); - } - - - while(condition()); - while (condition()) - testWhile(); - while (condition()) - if (condition()) - testWhile(); - } - - /** Test for loops **/ - void testFor() - { //warn - - for (int i = 1; i < 5; i++) { - testFor(); - } - - - for(int i = 1;i < 5;i++); - for (int i = 1; i < 5; i++) - testFor(); - for (int i = 1; i < 5; - i++) - if (i > 2) - testFor(); - } - - /** Test if constructs **/ - public void testIf() - { //warn - - if (condition()) { - testIf(); - } - else if (condition()) { - testIf(); - } - else { - testIf(); - } - - - if (condition()); - if (condition()) - testIf(); - if (condition()) - testIf(); - else - testIf(); - if (condition()) - testIf(); - else { - testIf(); - } - if (condition()) { - testIf(); - } - else - testIf(); - if (condition()) - if (condition()) - testIf(); - } - - void whitespaceAfterSemi() - { //warn - - int i = 1;int j = 2; - - - for (;;) { - } - } - - /** Empty constructor block. **/ - public InputLeftCurlyBraces() {} - - /** Empty method block. **/ - public void emptyImplementation() {} -} - -class EnumContainerLeft { - private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS } // ok -} - -class WithArraysLeft { // ok - String[] s = {""}; // ok - String[] empty = {}; // ok - String[] s1 = { // ok - "foo", "foo", - }; - String[] s2 = - { // ok - "foo", "foo", - }; - String[] s3 = - { // ok - "foo", - "foo", - }; - String[] s4 = - {"foo", "foo"}; // ok -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyMethod.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyMethod.java index bf06d8094a4a..5b185cf9689b 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyMethod.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputLeftCurlyMethod.java @@ -1,82 +1,82 @@ package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; class InputLeftCurlyMethod -{ //warn - InputLeftCurlyMethod() {} //ok - InputLeftCurlyMethod(String aOne) {//ok - } - InputLeftCurlyMethod(int aOne) - { //warn - } + { // violation ''{' at column 3 should be on the previous line.' + InputLeftCurlyMethod() {} + + InputLeftCurlyMethod(String one) {} - void method1() {}//ok - void method2() {//ok + InputLeftCurlyMethod(int one) + { // violation ''{' at column 5 should be on the previous line.' } + + void method1() {} + + void method2() {} + void method3() - { //warn - } - void method4() - { //warn + { // violation ''{' at column 5 should be on the previous line.' } - void method5(String aOne, - String aTwo) - {//warn + + void method4() + { // violation ''{' at column 5 should be on the previous line.' } - void method6(String aOne, - String aTwo) {// ok + + void method5(String one, String two) + { // violation ''{' at column 5 should be on the previous line.' } -} - -enum InputLeftCurlyMethodEnum -{//warn - CONSTANT1("hello") - {//warn - void method1() {}//ok - void method2() { - }//ok - void method3() - {//warn - } - void method4() - { //warn - } - void method5(String aOne, - String aTwo) - {//warn - } - void method6(String aOne, - String aTwo) {//ok - } - }, - CONSTANT2("hello") {//ok + void method6(String one, String two) {} - }, + enum InputLeftCurlyMethodEnum + { // violation ''{' at column 7 should be on the previous line.' + CONSTANT1("hello") + { // violation ''{' at column 17 should be on the previous line.' + void method1() {} - CONSTANT3("hellohellohellohellohellohellohellohellohellohellohellohellohellohello") - {//warn - }; + void method2() {} - private InputLeftCurlyMethodEnum(String value) - {//warn + void method3() + { // violation ''{' at column 21 should be on the previous line.' + } - } + void method4() + { // violation ''{' at column 21 should be on the previous line.' + } - void method1() {}//ok - void method2() {//ok - } - void method3() - {//warn - } - void method4() - {//warn - } - void method5(String aOne, - String aTwo) - {//warn - } - void method6(String aOne, - String aTwo) {// ok - } -} + void method5(String one, String two) + { // violation ''{' at column 21 should be on the previous line.' + } + + void method6(String one, String two) {} + }, + + CONSTANT2("hello") {}, + + CONSTANT3("hellohellohellohellohellohellohellohellohellohellohellohellohellohello") + { // violation ''{' at column 17 should be on the previous line.' + }; + + private InputLeftCurlyMethodEnum(String value) + { // violation ''{' at column 9 should be on the previous line.' + } + + void method1() {} + + void method2() {} + + void method3() + { // violation ''{' at column 9 should be on the previous line.' + } + + void method4() + { // violation ''{' at column 9 should be on the previous line.' + } + + void method5(String one, String two) + { // violation ''{' at column 9 should be on the previous line.' + } + void method6(String one, String two) {} + } + } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputNonemptyBlocksLeftRightCurly.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputNonemptyBlocksLeftRightCurly.java new file mode 100644 index 000000000000..f2e7fc8673f1 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputNonemptyBlocksLeftRightCurly.java @@ -0,0 +1,306 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +class InputNonemptyBlocksLeftRightCurly + { // violation ''{' at column 3 should be on the previous line.' + /** + * summary. + * + * @return helper func * + */ + boolean condition() + { // violation ''{' at column 5 should be on the previous line.' + return false; + } + + /** Test do/while loops. */ + void testDoWhile() + { // violation ''{' at column 5 should be on the previous line.' + + do { + testDoWhile(); + } // violation ''}' at column 7 should be on the same line as the next part of .*' + while (condition()); + + do { + testDoWhile(); + } while (condition()); + } + + /** Test while loops. */ + void testWhile() + { // violation ''{' at column 5 should be on the previous line.' + + while (condition()) { + testWhile(); + } + + while (condition()) { + /* foo */ + } + while (condition()) { + testWhile(); + } + while (condition()) { + if (condition()) { + testWhile(); + } + } + } + + /** Test for loops. */ + void testFor() + { // violation ''{' at column 5 should be on the previous line.' + + for (int i = 1; i < 5; i++) { + testFor(); + } + + for (int i = 1; i < 5; i++) { + /* foo */ + } + for (int i = 1; i < 5; i++) { + testFor(); + } + for (int i = 1; i < 5; i++) { + if (i > 2) { + testFor(); + } + } + } + + /** Test if constructs. */ + public void testIf() + { // violation ''{' at column 5 should be on the previous line.' + + if (condition()) { + testIf(); + } // violation ''}' at column 7 should be on the same line as the next part of .*' + else if (condition()) { + testIf(); + } // violation ''}' at column 7 should be on the same line as the next part of .*' + else { + testIf(); + } + + if (condition()) { /* foo */ } + if (condition()) { + testIf(); + } + if (condition()) { + testIf(); + } else { + testIf(); + } + if (condition()) { + testIf(); + } else { + testIf(); + } + if (condition()) { + testIf(); + } // violation ''}' at column 7 should be on the same line as the next part of .*' + else { + testIf(); + } + if (condition()) { + if (condition()) { + testIf(); + } + } + } + + void whitespaceAfterSemi() + { // violation ''{' at column 5 should be on the previous line.' + + int i = 1; + int j = 2; + + for (; ; ) {} + } + + /** Empty constructor block. */ + public InputNonemptyBlocksLeftRightCurly() {} + + /** Empty method block. */ + public void emptyImplementation() {} + } + +// violation below 'Top-level class EnumContainerLeft has to reside in its own source file.' +class EnumContainerLeft { + private enum Suit { + CLUBS, + HEARTS, + SPADES, + DIAMONDS + } // ok +} + +// violation below 'Top-level class WithArraysLeft has to reside in its own source file.' +class WithArraysLeft { // ok + String[] s1 = {""}; // ok + String[] empty = {}; // ok + String[] s2 = { // ok + "foo", "foo", + }; + String[] s3 = { // ok + "foo", "foo", + }; + String[] s4 = { // ok + "foo", "foo", + }; + String[] s5 = {"foo", "foo"}; // ok +} + +// violation below 'Top-level class InputRightCurlyOther2 has to reside in its own source file.' +class InputRightCurlyOther2 + { // violation ''{' at column 3 should be on the previous line.' + /** + * summary. + * + * @see test method * + */ + int foo() + throws InterruptedException + { // violation ''{' at column 5 should be on the previous line.' + int x = 1; + int a = 2; + while (true) + { // violation ''{' at column 9 should be on the previous line.' + try + { // violation ''{' at column 11 should be on the previous line.' + if (x > 0) + { // violation ''{' at column 15 should be on the previous line.' + break; + } else if (x < 0) { // ok + + ; + } // violation ''}' at column 13 should be on the same line as the next part.*' + else + { // violation ''{' at column 15 should be on the previous line.' + break; + } // ok + switch (a) + { // violation ''{' at column 15 should be on the previous line.' + case 0: + break; + default: + break; + } // ok + } // violation ''}' at column 11 should be on the same line as the next part of .*' + catch (Exception e) + { // violation ''{' at column 11 should be on the previous line.' + break; + } // ok + } // ok + + synchronized (this) + { // violation ''{' at column 9 should be on the previous line.' + do + { // violation ''{' at column 11 should be on the previous line.' + x = 2; + } while (x == 2); // ok + } // ok + + this.wait(666); // Bizarre, but legal + + for (int k = 0; k < 1; k++) + { // violation ''{' at column 9 should be on the previous line.' + String innerBlockVariable = ""; + } // ok + + if (System.currentTimeMillis() > 1000) { + return 1; + } else { + return 2; + } + } // ok + + static + { // violation ''{' at column 5 should be on the previous line.' + int x = 1; + } // ok + + /** some javadoc. */ + public enum GreetingsEnum + { // violation ''{' at column 5 should be on the previous line.' + HELLO, + GOODBYE + } // ok + + void method2() + { // violation ''{' at column 5 should be on the previous line.' + boolean flag = true; + if (flag) { + System.identityHashCode("heh"); + // 2 violations 3 lines below: + // ''if' child has incorrect indentation level 6, expected level should be 8.' + // ''}' at column 21 should have line break before.' + flag = !flag; } System + .identityHashCode("Xe-xe"); + + if (flag) { System.identityHashCode("some foo"); } + // violation above ''{' at column 17 should have line break after.' + } // ok + } // ok + +/** + * Test input for closing brace if that brace terminates a statement or the body of a constructor. + */ +// violation below 'Top-level class FooCtor has to reside in its own source file.' +class FooCtor + { // violation ''{' at column 3 should be on the previous line.' + int i3; + + public FooCtor() + { // violation ''{' at column 5 should be on the previous line.' + i3 = 1; + } } // violation ''}' at column 5 should be alone on a line.' + +/** Test input for closing brace if that brace terminates a statement or the body of a method. */ +// violation below 'Top-level class FooMethod has to reside in its own source file.' +class FooMethod + { // violation ''{' at column 3 should be on the previous line.' + public void fooMethod() + { // violation ''{' at column 5 should be on the previous line.' + int i = 1; + } } // violation ''}' at column 5 should be alone on a line.' + +/** + * Test input for closing brace if that brace terminates a statement or the body of a named class. + */ +// violation below 'Top-level class FooInner has to reside in its own source file.' +class FooInner + { // violation ''{' at column 3 should be on the previous line.' + class InnerFoo + { // violation ''{' at column 5 should be on the previous line.' + public void fooInnerMethod() + { // violation ''{' at column 9 should be on the previous line.' + } + } + } // ok + +// violation below 'Top-level class EnumContainer has to reside in its own source file.' +class EnumContainer { + private enum Suit { + CLUBS, + HEARTS, + SPADES, + DIAMONDS + } // ok +} + +// violation below 'Top-level class WithArrays has to reside in its own source file.' +class WithArrays { + String[] test = {""}; // ok + String[] empty = {}; // ok + String[] s1 = { + "foo", "foo", + }; // ok + String[] s2 = { + "foo", "foo", + }; // ok + String[] s3 = { + "foo", "foo", + }; // ok + String[] s4 = {"foo", "foo"}; // ok +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurly.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurly.java new file mode 100644 index 000000000000..d227ffc05fdb --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurly.java @@ -0,0 +1,15 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputRightCurly { + /** some javadoc. */ + public static void main(String[] args) { + boolean after = false; + try { + /* foo */ + } finally { after = true; } + // 2 violations above + // ''{' at column 15 should have line break after.' + // ''}' at column 30 should be alone on a line.' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhile.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhile.java index fa3de0a0d6f3..367450de86d9 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhile.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhile.java @@ -2,92 +2,87 @@ import java.util.Scanner; -/** - * Test input for GitHub issue #3090. - * https://github.com/checkstyle/checkstyle/issues/3090 - */ +/** Test input for GitHub issue #3090. https://github.com/checkstyle/checkstyle/issues/3090 . */ public class InputRightCurlyDoWhile { - public void foo1() { - do { - } while (true); + /** some javadoc. */ + public void foo1() { + do {} while (true); + } + + /** some javadoc. */ + public void foo2() { + int i = 1; + while (i < 5) { + String.CASE_INSENSITIVE_ORDER.equals(i + " "); + i++; } - - public void foo2() { - int i = 1; - while (i < 5) { - String.CASE_INSENSITIVE_ORDER.equals(i + " "); - i++; - } - } - - public void foo3() { - int i = 1; - do { - i++; - String.CASE_INSENSITIVE_ORDER.equals(i + " "); - } while (i < 5); - } - - public void foo4() { - int prog, user; - prog = (int)(Math.random() * 10) + 1; - Scanner input = new Scanner(System.in, "utf-8"); - if( input.hasNextInt() ) { - do { - user = input.nextInt(); - if(user == prog) { - String.CASE_INSENSITIVE_ORDER.equals("Good!"); - } else { - if (user > 0 && user <= 10) { - String.CASE_INSENSITIVE_ORDER.equals("Bad! "); - if( prog < user ) { - String.CASE_INSENSITIVE_ORDER.equals("My number is less than yours."); - } else { - String.CASE_INSENSITIVE_ORDER.equals("My number is greater than yours"); - } - } else { - String.CASE_INSENSITIVE_ORDER.equals("Violation!"); - } - } - } while( user != prog ); + } + + /** some javadoc. */ + public void foo3() { + int i = 1; + do { + i++; + String.CASE_INSENSITIVE_ORDER.equals(i + " "); + } while (i < 5); + } + + /** some javadoc. */ + public void foo4() { + int prog; + int user; + prog = (int) (Math.random() * 10) + 1; + Scanner input = new Scanner(System.in, "utf-8"); + if (input.hasNextInt()) { + do { + user = input.nextInt(); + if (user == prog) { + String.CASE_INSENSITIVE_ORDER.equals("Good!"); } else { + if (user > 0 && user <= 10) { + String.CASE_INSENSITIVE_ORDER.equals("Bad! "); + if (prog < user) { + String.CASE_INSENSITIVE_ORDER.equals("My number is less than yours."); + } else { + String.CASE_INSENSITIVE_ORDER.equals("My number is greater than yours"); + } + } else { String.CASE_INSENSITIVE_ORDER.equals("Violation!"); + } } - String.CASE_INSENSITIVE_ORDER.equals("Goodbye!"); - } - - public void foo5() { - do { - } // warn - while (true); - } - - public void foo6() { - do {} // warn - while (true); - } - - public void foo7() { - do - { - - } while (true); - } - - public void foo8() { - do - - { - - } // warn - - while - - (true); - } - - public void foo9() { - do {} while (true); + } while (user != prog); + } else { + String.CASE_INSENSITIVE_ORDER.equals("Violation!"); } + String.CASE_INSENSITIVE_ORDER.equals("Goodbye!"); + } + + /** some javadoc. */ + public void foo5() { + do {} // violation ''}' at column 9 should be on the same line as the next part of .*' + while (true); + } + + /** some javadoc. */ + public void foo6() { + do {} // violation ''}' at column 9 should be on the same line as the next part of .*' + while (true); + } + + /** some javadoc. */ + public void foo7() { + do {} while (true); + } + + /** some javadoc. */ + public void foo8() { + do {} // violation ''}' at column 9 should be on the same line as the next part of .*' + while (true); + } + + /** some javadoc. */ + public void foo9() { + do {} while (true); + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhile2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhile2.java new file mode 100644 index 000000000000..771d5cea3193 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhile2.java @@ -0,0 +1,89 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +/** Test input for GitHub issue #3090. https://github.com/checkstyle/checkstyle/issues/3090 . */ +public class InputRightCurlyDoWhile2 { + + /** some javadoc. */ + public void foo1() { + do {} while (true); + } + + /** some javadoc. */ + public void foo2() { + int i = 1; + while (i < 5) { + String.CASE_INSENSITIVE_ORDER.equals(i + " "); + i++; + } + } + + /** some javadoc. */ + public void foo3() { + int i = 1; + do { + i++; + String.CASE_INSENSITIVE_ORDER.equals(i + " "); + } while (i < 5); + } + + /** some javadoc. */ + public void foo4() { + int prog; + int user; + prog = (int) (Math.random() * 10) + 1; + Scanner input = new Scanner(System.in, StandardCharsets.UTF_8); + if (input.hasNextInt()) { + do { + user = input.nextInt(); + if (user == prog) { + String.CASE_INSENSITIVE_ORDER.equals("Good!"); + } else { + if (user > 0 && user <= 10) { + String.CASE_INSENSITIVE_ORDER.equals("Bad! "); + if (prog < user) { + String.CASE_INSENSITIVE_ORDER.equals("My number is less than yours."); + } else { + String.CASE_INSENSITIVE_ORDER.equals("My number is greater than yours"); + } + } else { + String.CASE_INSENSITIVE_ORDER.equals("Violation!"); + } + } + } while (user != prog); + } else { + String.CASE_INSENSITIVE_ORDER.equals("Violation!"); + } + String.CASE_INSENSITIVE_ORDER.equals("Goodbye!"); + } + + /** some javadoc. */ + public void foo5() { + do {} // violation ''}' at column 9 should be on the same line as the next part of .*' + while (true); + } + + /** some javadoc. */ + public void foo6() { + do {} // violation ''}' at column 9 should be on the same line as the next part of .*' + while (true); + } + + /** some javadoc. */ + public void foo7() { + do {} while (true); + } + + /** some javadoc. */ + public void foo8() { + do {} // violation ''}' at column 9 should be on the same line as the next part of .*' + while (true); + } + + /** some javadoc. */ + public void foo9() { + do {} while (true); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhileAlone.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhileAlone.java deleted file mode 100644 index 423f3a730594..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyDoWhileAlone.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; - -import java.util.Scanner; - -/** - * Test input for GitHub issue #3090. - * https://github.com/checkstyle/checkstyle/issues/3090 - */ -public class InputRightCurlyDoWhileAlone { - - public void foo1() { - do { - } while (true); - } - - public void foo2() { - int i = 1; - while (i < 5) { - String.CASE_INSENSITIVE_ORDER.equals(i + " "); - i++; - } - } - - public void foo3() { - int i = 1; - do { - i++; - String.CASE_INSENSITIVE_ORDER.equals(i + " "); - } while (i < 5); - } - - public void foo4() { - int prog, user; - prog = (int)(Math.random() * 10) + 1; - Scanner input = new Scanner(System.in, "utf-8"); - if( input.hasNextInt() ) { - do { - user = input.nextInt(); - if(user == prog) { - String.CASE_INSENSITIVE_ORDER.equals("Good!"); - } else { - if (user > 0 && user <= 10) { - String.CASE_INSENSITIVE_ORDER.equals("Bad! "); - if( prog < user ) { - String.CASE_INSENSITIVE_ORDER.equals("My number is less than yours."); - } else { - String.CASE_INSENSITIVE_ORDER.equals("My number is greater than yours"); - } - } else { - String.CASE_INSENSITIVE_ORDER.equals("Violation!"); - } - } - } while( user != prog ); - } else { - String.CASE_INSENSITIVE_ORDER.equals("Violation!"); - } - String.CASE_INSENSITIVE_ORDER.equals("Goodbye!"); - } - - public void foo5() { - do { - } // ok - for alone - while (true); - } - - public void foo6() { - do {} // ok - for alone - while (true); - } - - public void foo7() { - do - { - - } while (true); - } - - public void foo8() { - do - - { - - } // ok - for alone - - while - - (true); - } - - public void foo9() { - do {} while (true); - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyOther.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyOther.java index adfe0528060b..5cbd007d8852 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyOther.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyOther.java @@ -1,145 +1,175 @@ package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; -class InputRightCurlyOther -{ - /** @see test method **/ - int foo() throws InterruptedException - { - int x = 1; - int a = 2; - while (true) - { - try - { - if (x > 0) - { - break; - } else if (x < 0) { //ok - - ; - } //warn - else - { - break; - }//ok - switch (a) - { - case 0: - break; - default: - break; - } //ok - } //warn - catch (Exception e) - { - break; - }//ok - }//ok - - synchronized (this) - { - do - { - x = 2; - } while (x == 2); //ok - }//ok - - this.wait(666 - ); // Bizarre, but legal - - for (int k = 0; k < 1; k++) - { - String innerBlockVariable = ""; - }//ok - - - if (System.currentTimeMillis() > 1000) - return 1; - else - return 2; - }//ok - - - static - { - int x = 1; - }//ok - - public enum GreetingsEnum - { - HELLO, - GOODBYE - }; //ok - - void method2() - { - boolean flag = true; - if (flag) { - System.identityHashCode("heh"); - flag = !flag; } System. //warn - identityHashCode("Xe-xe"); - - - if (flag) { System.identityHashCode("some foo"); } - } //ok -} //ok +class InputRightCurlyOther { + /** + * summary. + * + * @see test method * + */ + int foo() throws InterruptedException { + int x = 1; + int a = 2; + while (true) { + try { + if (x > 0) { + break; + } else if (x < 0) { + + ; + } // violation ''}' at column 9 should be on the same line as the next part of .*' + else { + break; + } + switch (a) { + case 0: + break; + default: + break; + } + } // violation ''}' at column 7 should be on the same line as the next part of .*' + catch (Exception e) { + break; + } + } + + synchronized (this) { + do { + x = 2; + } while (x == 2); + } + + this.wait(666); // Bizarre, but legal + + for (int k = 0; k < 1; k++) { + String innerBlockVariable = ""; + } + + if (System.currentTimeMillis() > 1000) { + return 1; + } else { + return 2; + } + } + + static { + int x = 1; + } + + public enum GreetingsEnum { + HELLO, + GOODBYE + } + + void method2() { + boolean flag = true; + if (flag) { + System.identityHashCode("heh"); + // 2 violations 3 lines below: + // ''}' at column 21 should have line break before.' + // ''method def' child has incorrect indentation level 6, expected level should be 4.' + flag = !flag; } System + .identityHashCode("Xe-xe"); + + if (flag) { + System.identityHashCode("some foo"); + } + } +} /** - * Test input for closing brace if that brace terminates - * a statement or the body of a constructor. + * Test input for closing brace if that brace terminates a statement or the body of a constructor. */ -class FooCtor -{ - int i; - public FooCtor() - { - i = 1; - }} //ok +class FooCtorAlone { + // violation above 'Top-level class FooCtorAlone has to reside in its own source file.' + int test; -/** -* Test input for closing brace if that brace terminates -* a statement or the body of a method. -*/ -class FooMethod -{ - public void fooMethod() - { - int i = 1; - }} //ok + public FooCtorAlone() { + test = 1; + } } // violation ''}' at column 3 should be alone on a line.' + +/** Test input for closing brace if that brace terminates a statement or the body of a method. */ +class FooMethodAlone { + // violation above 'Top-level class FooMethodAlone has to reside in its own source file.' + public void fooMethod() { + int i = 1; + } } // violation ''}' at column 3 should be alone on a line.' /** -* Test input for closing brace if that brace terminates -* a statement or the body of a named class. -*/ -class FooInner -{ - class InnerFoo - { - public void fooInnerMethod () - { + * Test input for closing brace if that brace terminates a statement or the body of a named class. + */ +class FooInnerAlone { + // violation above 'Top-level class FooInnerAlone has to reside in its own source file.' + class InnerFoo { + public void fooInnerMethod() {} + } +} - } - }} //ok +// violation below 'Top-level class EnumContainerAlone has to reside in its own source file.' +class EnumContainerAlone { + private enum Suit { + CLUBS, + HEARTS, + SPADES, + DIAMONDS + } +} + +// violation below 'Top-level class WithArraysAlone has to reside in its own source file.' +class WithArraysAlone { + String[] ss = {""}; + String[] empty = {}; + String[] s1 = { + "foo", "foo", + }; + String[] s2 = { + "foo", "foo", + }; + String[] s3 = { + "foo", "foo", + }; + String[] s4 = {"foo", "foo"}; +} + +// violation below 'Top-level class Interface has to reside in its own source file.' +class Interface { + public @interface TestAnnotation {} + + public @interface TestAnnotation1 { + String someValue(); + } + + public @interface TestAnnotation2 { + String someValue(); + } + + public @interface TestAnnotation3 { + String someValue(); + } + + public @interface TestAnnotation4 { + String someValue(); + } +} + +// violation below 'Top-level class TestEnum has to reside in its own source file.' +enum TestEnum {} + +// violation below 'Top-level class TestEnum1 has to reside in its own source file.' +enum TestEnum1 { + SOME_VALUE; +} + +// violation below 'Top-level class TestEnum2 has to reside in its own source file.' +enum TestEnum2 { + SOME_VALUE; +} -class EnumContainer { - private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS } // ok +// violation below 'Top-level class TestEnum3 has to reside in its own source file.' +enum TestEnum3 { + SOME_VALUE; } -class WithArrays { - String[] s = {""}; // ok - String[] empty = {}; // ok - String[] s1 = { - "foo", "foo", - }; // ok - String[] s2 = - { - "foo", "foo", - }; // ok - String[] s3 = - { - "foo", - "foo", - }; // ok - String[] s4 = - {"foo", "foo"}; // ok +// violation below 'Top-level class TestEnum4 has to reside in its own source file.' +enum TestEnum4 { + SOME_VALUE; } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyOtherAlone.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyOtherAlone.java deleted file mode 100644 index 2068a8d40bcb..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlyOtherAlone.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; - -class InputRightCurlyOtherAlone -{ - /** @see test method **/ - int foo() throws InterruptedException - { - int x = 1; - int a = 2; - while (true) - { - try - { - if (x > 0) - { - break; - } else if (x < 0) { //ok - - ; - } //ok - for alone config - else - { - break; - }//ok - switch (a) - { - case 0: - break; - default: - break; - } //ok - } //ok - for alone config - catch (Exception e) - { - break; - }//ok - }//ok - - synchronized (this) - { - do - { - x = 2; - } while (x == 2); //ok - }//ok - - this.wait(666 - ); // Bizarre, but legal - - for (int k = 0; k < 1; k++) - { - String innerBlockVariable = ""; - }//ok - - - if (System.currentTimeMillis() > 1000) - return 1; - else - return 2; - }//ok - - - static - { - int x = 1; - }//ok - - public enum GreetingsEnum - { - HELLO, - GOODBYE - }; //warn - - void method2() - { - boolean flag = true; - if (flag) { - System.identityHashCode("heh"); - flag = !flag; } System. //ok for alone config - identityHashCode("Xe-xe"); - - - if (flag) { System.identityHashCode("some foo"); } - } //ok -} //ok - -/** - * Test input for closing brace if that brace terminates - * a statement or the body of a constructor. - */ -class FooCtorAlone -{ - int i; - public FooCtorAlone() - { - i = 1; - }} //warn - -/** -* Test input for closing brace if that brace terminates -* a statement or the body of a method. -*/ -class FooMethodAlone -{ - public void fooMethod() - { - int i = 1; - }} //warn - -/** -* Test input for closing brace if that brace terminates -* a statement or the body of a named class. -*/ -class FooInnerAlone -{ - class InnerFoo - { - public void fooInnerMethod () - { - - } - }} //warn - -class EnumContainerAlone { - private enum Suit { CLUBS, HEARTS, SPADES, DIAMONDS } // warn -} - -class WithArraysAlone { - String[] s = {""}; // ok - String[] empty = {}; // ok - String[] s1 = { - "foo", "foo", - }; // ok - String[] s2 = - { - "foo", "foo", - }; // ok - String[] s3 = - { - "foo", - "foo", - }; // ok - String[] s4 = - {"foo", "foo"}; // ok -} - -class Interface { - public @interface TestAnnotation {} //warn - - public @interface TestAnnotation1 { String someValue(); } //warn - - public @interface TestAnnotation2 { - String someValue();} //warn - - public @interface TestAnnotation3 { - String someValue(); - } //ok - - public @interface TestAnnotation4 { String someValue(); - } //ok -} - -enum TestEnum {} //warn - -enum TestEnum1 { SOME_VALUE; } //warn - -enum TestEnum2 { - SOME_VALUE;} //warn - -enum TestEnum3 { - SOME_VALUE; -} - -enum TestEnum4 { SOME_VALUE; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySame.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySame.java deleted file mode 100644 index b0f9c88b5dd0..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySame.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; - -public class InputRightCurlySame { - public static void main(String[] args) { - boolean after = false; - try { - } finally { after = true; } - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySwitchCase.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySwitchCase.java new file mode 100644 index 000000000000..1600c14da51f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySwitchCase.java @@ -0,0 +1,57 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputRightCurlySwitchCase { + + /** some javadoc. */ + public static void method0() { + int mode = 0; + switch (mode) { + case 1: + int x = 1; + break; + default: + x = 0; } // violation ''}' at column 16 should be alone on a line.' + } + + /** some javadoc. */ + public static void method1() { + int mode = 0; + switch (mode) { + default: + int x = 0; } // violation ''}' at column 20 should be alone on a line.' + } + + /** some javadoc. */ + public static void method2() { + int mode = 0; + switch (mode) { + case 1: + int x = 1; + break; + default: + x = 0; + } + } + + /** some javadoc. */ + public static void method3() { + int mode = 0; + switch (mode) { + default: + int x = 0; + } + } + + /** some javadoc. */ + public static void method4() { + int mode = 0; + switch (mode) { + case 1: + int y = 2; + break; + default: + int x = 0; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySwitchCasesBlocks.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySwitchCasesBlocks.java new file mode 100644 index 000000000000..cf6f5a844305 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputRightCurlySwitchCasesBlocks.java @@ -0,0 +1,148 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputRightCurlySwitchCasesBlocks { + + /** some javadoc. */ + public static void test0() { + int mode = 0; + switch (mode) { + case 1: + { + int x = 1; + break; + } + case 2: + { + int x = 0; + break; + } + default: + { + int x = 0; + } + } + } + + /** some javadoc. */ + public static void test() { + int mode = 0; + switch (mode) { + case 1: + { + int x = 1; + break; + } default: + int x = 0; + // 2 violations 2 lines above: + // ''}' at column 9 should be alone on a line.' + // ''case' child has incorrect indentation level 8, expected level should be 6.' + } + } + + /** some javadoc. */ + public static void test1() { + int k = 0; + switch (k) { + case 1: + { + int x = 1; } // violation ''}' at column 20 should be alone on a line.' + break; + case 2: + int x = 2; + break; + default: + } + } + + /** some javadoc. */ + public static void test2() { + int mode = 0; + switch (mode) { + case 1: + int x = 1; + break; + case 2: + { + break; + } + default: + { + break; + } + } + } + + /** some javadoc. */ + public static void test3() { + int k = 0; + switch (k) { + case 1: + { + int x = 1; + break; + } + default: + { + int x = 2; } // false-negative until #14782 + } + } + + /** some javadoc. */ + public static void test4() { + int mode = 0; + switch (mode) { + case 1: { // violation ''{' at column 15 should be on a new line.' + int x = 1; // violation '.* incorrect indentation level 10, expected level should be 8.' + break; // violation '.* incorrect indentation level 10, expected level should be 8.' + // 2 violations 3 lines below: + // ''block rcurly' has incorrect indentation level 8, expected level should be 6.' + // ''}' at column 9 should be alone on a line.' + } default: + { // violation '.* incorrect indentation level 10, expected level should be 8.' + int x = 0; // violation '.* incorrect indentation .*, expected .* 8, 10.' + } // violation '.* incorrect indentation level 10, expected level should be 8.' + } + } + + /** some javadoc. */ + public static void test5() { + int k = 0; + switch (k) { + case 1: { // violation ''{' at column 15 should be on a new line.' + int x = 1; } // violation ''}' at column 20 should be alone on a line.' + break; + default: { // violation ''{' at column 16 should be on a new line.' + int a = 2; // violation '.* incorrect indentation level 2, expected level should be 8.' + } + } + } + + /** some javadoc. */ + public static void test6() { + int mode = 0; + switch (mode) { + case 1: + int x = 1; + break; + case 2: { // violation ''{' at column 15 should be on a new line.' + break; // violation '.* incorrect indentation level 10, expected level should be 8.' + } // violation '.* incorrect indentation level 8, expected level should be 6.' + default: + } + } + + /** some javadoc. */ + public static void test7() { + int k = 0; + switch (k) { + case 1: + { + int x = 1; // violation '.* incorrect indentation .* 12, expected .* following: 8, 10.' + break; // violation '.* incorrect indentation .* 12, expected .* following: 8, 10.' + } + default: { // violation ''{' at column 16 should be on a new line.' + int x = 2; } // false-negative until #14782 + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputTryCatchIfElse.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputTryCatchIfElse.java new file mode 100644 index 000000000000..aa5f873a43b7 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputTryCatchIfElse.java @@ -0,0 +1,133 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputTryCatchIfElse { + + @interface TesterAnnotation {} // ok + + void foo() throws Exception { + int a = 90; + boolean test = true; + + if (a == 1) { + } else {} + + if (a == 1) { + } else { } + // violation above 'Empty blocks should have no spaces.' + + if (a == 45) {} + + if (a == 9) {} else {} + + if (a == 99) { + System.out.println("test"); + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + else { + System.out.println("before"); + } + + try (MyResource r = new MyResource()) { } + // violation above 'Empty blocks should have no spaces.' + + try (MyResource r = new MyResource()) {} + + try (MyResource r = new MyResource()) {} catch (Exception expected) {} + // 3 violations above: + // 'WhitespaceAround: '{' is not followed by whitespace.' + // 'Empty catch block' + // ''}' at column 74 should be alone on a line.' + + try (MyResource r = new MyResource()) {} catch (Exception expected) { } + // 4 violations above: + // 'Empty blocks should have no spaces.' + // 'WhitespaceAround: '{' is not followed by whitespace.' + // 'Empty catch block' + // ''}' at column 75 should be alone on a line.' + + try (MyResource r = new MyResource()) { + } catch (Exception expected) {} + // violation above 'Empty catch block' + // violation 2 lines above ''}' at column 35 should be alone on a line.' + + try (MyResource r = new MyResource()) { + } catch (Exception expected) { } + // 3 violations above: + // 'Empty blocks should have no spaces.' + // 'Empty catch block' + // ''}' at column 36 should be alone on a line.' + + try (MyResource r = new MyResource()) { ; } + // violation above ''{' at column 43 should have line break after.' + + try { + /* foo */ + + } catch (Exception expected) {} + // 2 violations above: + // 'Empty catch block' + // ''}' at column 35 should be alone on a line.' + + try { + /* foo */ + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + catch (NullPointerException e) { + /* foo */ + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + catch (Exception e) { + /* foo */ + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + finally { + test = true; + } + + try { + /* foo */ + } catch (NullPointerException e) { + /* foo */ + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + catch (Exception e) { + /* foo */ + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + finally { + test = true; + } + + try { + /* foo */ + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + catch (Exception e) { + /* foo */ + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + finally { + test = true; + } + + try { + /* foo */ + } catch (Exception e) { + /* foo */ + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + finally { + test = true; + } + } + + /** some javadoc. */ + public class MyResource implements AutoCloseable { + /** some javadoc. */ + @Override + public void close() throws Exception { + System.out.println("Closed MyResource"); + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputTryCatchIfElse2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputTryCatchIfElse2.java new file mode 100644 index 000000000000..e91aa5e9d647 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule412nonemptyblocks/InputTryCatchIfElse2.java @@ -0,0 +1,93 @@ +package com.google.checkstyle.test.chapter4formatting.rule412nonemptyblocks; + +/** some javadoc. */ +public class InputTryCatchIfElse2 { + /** some javadoc. */ + public static void main(String[] args) { + boolean after = false; + + try { + /* foo */ + } catch (NullPointerException e) { + /* foo */ + } catch (Exception e) { + /* foo */ + } finally { + after = true; + } + + if (after) { + System.out.println("after"); + } else if (after) { + System.out.println("before"); + } else if (after) { + System.out.println("before"); + } else { + System.out.println("before"); + } + + if (after) { + System.out.println("after"); + } else if (after) {} else if (after) { + System.out.println("before"); + } else if (!after) { /* foo */ } else { + System.out.println("before"); + } + + if (after) { + System.out.println("foo"); + } else if (false) { + System.out.println("foo"); + } else { + System.out.println("foo"); + } + + if (after) { + System.out.println("after"); + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + else if (after) { + System.out.println("before"); + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + else { + System.out.println("before"); + } + + if (after) { + System.out.println("after"); + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + else if (after) { + System.out.println("before"); + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + else if (after) { + System.out.println("before"); + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + else { + System.out.println("before"); + } + + if (after) { + System.out.println("after"); + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + else if (after) { + System.out.println("before"); + } else { + System.out.println("before"); + } + + if (after) { + System.out.println("after"); + } else if (after) { + System.out.println("before"); + // violation below ''}' at column 5 should be on the same line as .* multi-block statement' + } + else { + System.out.println("before"); + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlock.java deleted file mode 100644 index ae3c27234f1e..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlock.java +++ /dev/null @@ -1,75 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// Test case file for checkstyle. -// Created: 2001 -//////////////////////////////////////////////////////////////////////////////// -package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; - -import java.io.*; -import java.awt.Dimension; -import java.awt.Color; - -class InputEmptyBlock { - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} - finally {} //warn - } - - class Inner { - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} - finally {} //warn - } - } - - Inner anon = new Inner(){ - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} - finally {} //warn - } - }; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlockBasic.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlockBasic.java deleted file mode 100644 index 65a3bbeb4f49..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlockBasic.java +++ /dev/null @@ -1,336 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// Test case file for checkstyle. -// Created: 2001 -//////////////////////////////////////////////////////////////////////////////// -package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; - -import java.io.*; -import java.awt.Dimension; -import java.awt.Color; - -class InputEmptyBlockBasic -{ - static {} //ok - - public void fooMethod() - { - InputEmptyBlockBasic r = new InputEmptyBlockBasic(); - int a = 1; - if (a == 1) {} // warn - char[] s = {'1', '2'}; - int index = 2; - if (doSideEffect() == 1) {} // warn - IO in = new IO(); - while ((r = in.read()) != null) {} // ok - for (; index < s.length && s[index] != 'x'; index++) {} // ok - if (a == 1) {} else {System.identityHashCode("a");} // warn - do {} while(a == 1); //ok - switch (a) {} //warn - int[] z = {}; // ok - } - - public int doSideEffect() - { - return 1; - } - - public void emptyMethod() {} -} - -class IO -{ - public InputEmptyBlockBasic read() - { - return new InputEmptyBlockBasic(); - } -} -class Empty {} //ok - -interface EmptyImplement {} //ok - -class WithInner -{ - static {} //ok - - public void emptyMethod() {} - - public int doSideEffect() - { - return 1; - } - - class Inner - { - private void withEmpty() - { - InputEmptyBlockBasic r = new InputEmptyBlockBasic(); - int a = 1; - if (a == 1) {} // warn - char[] s = {'1', '2'}; - int index = 2; - if (doSideEffect() == 1) {} //warn - IO in = new IO(); - while ((r = in.read()) != null) {} // ok - for (; index < s.length && s[index] != 'x'; index++) {} // ok - if (a == 1) {} else {System.identityHashCode("a");} // warn - do {} while(a == 1); //ok - switch (a) {} //warn - int[] z = {}; // ok - } - } -} - -class WithAnon -{ - interface AnonWithEmpty { - public void fooEmpty(); - } - - void method() - { - AnonWithEmpty foo = new AnonWithEmpty() { - - public void emptyMethod() {} - - public void fooEmpty() { - InputEmptyBlockBasic r = new InputEmptyBlockBasic(); - int a = 1; - if (a == 1) {} //warn - char[] s = {'1', '2'}; - int index = 2; - if (doSideEffect() == 1) {} //warn - IO in = new IO(); - while ((r = in.read()) != null) {} // ok - for (; index < s.length && s[index] != 'x'; index++) {} // ok - if (a == 1) {} else {System.identityHashCode("a");} // warn - do {} while(a == 1); //ok - switch (a) {} //warn - int[] z = {}; // ok - } - - public int doSideEffect() - { - return 1; - } - }; - } -} - -class NewClass { - - void foo() { - int a = 1; - - if (a == 1) { - System.identityHashCode("a"); - } else {} // warn - - if (a == 1) { - System.identityHashCode("a"); - } else {/*ignore*/} // OK - - if (a == 1) { - /*ignore*/ - } else { - System.identityHashCode("a"); - } // ok - - if (a == 1) { - System.identityHashCode("a"); - } else if (a != 1) { - /*ignore*/ - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - System.identityHashCode("a"); - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - /*ignore*/ - } else { - System.identityHashCode("a"); - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - /*ignore*/ - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) {} //warn - else {} //warn - - if (a == 1) {} //warn - else if (a != 1) { - /*ignore*/ - } - else {} //warn - - if (a == 1) {} //warn - else if (a != 1) {} //warn - else { - /*ignore*/ - } - } - - class NewInner { - - void foo() { - int a = 1; - - if (a == 1) { - System.identityHashCode("a"); - } else {} // warn - - if (a == 1) { - System.identityHashCode("a"); - } else {/*ignore*/} // OK - - if (a == 1) { - /*ignore*/ - } else { - System.identityHashCode("a"); - } // ok - - if (a == 1) { - System.identityHashCode("a"); - } else if (a != 1) { - /*ignore*/ - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - System.identityHashCode("a"); - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - /*ignore*/ - } else { - System.identityHashCode("a"); - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - /*ignore*/ - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) {} //warn - else {} //warn - - if (a == 1) {} //warn - else if (a != 1) { - /*ignore*/ - } - else {} //warn - - if (a == 1) {} //warn - else if (a != 1) {} //warn - else { - /*ignore*/ - } - } - - NewInner anon = new NewInner() { - - void foo() { - int a = 1; - - if (a == 1) { - System.identityHashCode("a"); - } else {} // warn - - if (a == 1) { - System.identityHashCode("a"); - } else {/*ignore*/} // OK - - if (a == 1) { - /*ignore*/ - } else { - System.identityHashCode("a"); - } // ok - - if (a == 1) { - System.identityHashCode("a"); - } else if (a != 1) { - /*ignore*/ - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - System.identityHashCode("a"); - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - /*ignore*/ - } else { - System.identityHashCode("a"); - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) { - /*ignore*/ - } else { - /*ignore*/ - } - - if (a == 1) { - /*ignore*/ - } else if (a != 1) {} //warn - else {} //warn - - if (a == 1) {} //warn - else if (a != 1) { - /*ignore*/ - } - else {} //warn - - if (a == 1) {} //warn - else if (a != 1) {} //warn - else { - /*ignore*/ - } - } - }; - } -} - -class Example { - - void doNothing() {} // ok - - void doNothingElse() { // ok - - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlockCatch.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlockCatch.java deleted file mode 100644 index ca654264d03d..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlockCatch.java +++ /dev/null @@ -1,87 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// Test case file for checkstyle. -// Created: 2001 -//////////////////////////////////////////////////////////////////////////////// -package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; - -import java.io.*; -import java.awt.Dimension; -import java.awt.Color; - -class InputEmptyBlockCatch { - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} //warn - finally {} - } - - class Inner { - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} //warn - finally {} - } - } - - Inner anon = new Inner(){ - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} //warn - finally {} - } - }; - - void foo3() { - try { - foo(); - } catch (Exception e) {} //warn - - try { - foo(); - } catch (Exception e) /*warn*/ { - - } - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlocksAndCatchBlocks.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlocksAndCatchBlocks.java new file mode 100644 index 000000000000..2fd421e4cadc --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlocksAndCatchBlocks.java @@ -0,0 +1,508 @@ +package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; + +class InputEmptyBlocksAndCatchBlocks { + static { + } + + static {} + + static { } // violation 'Empty blocks should have no spaces. .* may only be represented as {}' + + public void fooMethod() { + InputEmptyBlocksAndCatchBlocks r = new InputEmptyBlocksAndCatchBlocks(); + int a = 1; + if (a == 1) { } + // violation above 'Empty blocks should have no spaces. .* may only be represented as {}' + char[] s = {'1', '2'}; + int index = 2; + if (doSideEffect() == 1) { } + // violation above 'Empty blocks should have no spaces. .* may only be represented as {}' + Io in = new Io(); + while ((r = in.read()) != null) {} + for (; index < s.length && s[index] != 'x'; index++) {} + if (a == 1) { + } else { + System.identityHashCode("a"); + } + do {} while (a == 1); + switch (a) { + } + // violation 2 lines above 'switch without "default" clause.' + int[] z = {}; + } + + public int doSideEffect() { + return 1; + } + + public void emptyMethod() {} + + void foo() throws Exception { + int a = 90; + + if (a == 1) { + } else {} // false-negative until #15791 + + if (a == 1) { + } else { } + // violation above 'Empty blocks should have no spaces. .* may only be represented as {}' + + try (MyResource r = new MyResource()) { } + // violation above 'Empty blocks should have no spaces. .* may only be represented as {}' + try (MyResource r = new MyResource()) {} + + try (MyResource r = new MyResource()) {} catch (Exception expected) {} + // 3 violations above: + // 'WhitespaceAround: '{' is not followed by whitespace.' + // 'Empty catch block' + // ''}' at column 74 should be alone on a line.' + + try (MyResource r = new MyResource()) {} catch (Exception expected) { } + // 4 violations above: + // 'Empty blocks should have no spaces.' + // 'WhitespaceAround: '{' is not followed by whitespace.' + // 'Empty catch block' + // ''}' at column 75 should be alone on a line.' + + try (MyResource r = new MyResource()) { + + // violation below 'Empty catch block' + } catch (Exception expected) {} + // violation above ''}' at column 35 should be alone on a line.' + try (MyResource r = new MyResource()) { + + } catch (Exception expected) { } + // 3 violations above: + // 'Empty blocks should have no spaces.' + // 'Empty catch block' + // ''}' at column 36 should be alone on a line.' + + try (MyResource r = new MyResource()) {;} + // 3 violations above: + // 'WhitespaceAround: '{' is not followed by whitespace.' + // ''{' at column 43 should have line break after.' + // 'WhitespaceAround: '}' is not preceded with whitespace.' + } + + /** some. */ + public class MyResource implements AutoCloseable { + /** some. */ + @Override + public void close() throws Exception { + System.out.println("Closed MyResource"); + } + } +} + +// violation below 'Top-level class Io has to reside in its own source file.' +class Io { + public InputEmptyBlocksAndCatchBlocks read() { + return new InputEmptyBlocksAndCatchBlocks(); + } +} + +// violation below 'Top-level class Empty has to reside in its own source file.' +class Empty {} + +// violation below 'Top-level class EmptyImplement has to reside in its own source file.' +interface EmptyImplement {} + +// violation below 'Top-level class WithInner has to reside in its own source file.' +class WithInner { + static { + } + + public void emptyMethod() {} + + public int doSideEffect() { + return 1; + } + + class Inner { + private void withEmpty() { + InputEmptyBlocksAndCatchBlocks r = new InputEmptyBlocksAndCatchBlocks(); + int a = 1; + if (a == 1) { } + // violation above 'Empty blocks should have no spaces. .* may only be represented as {}' + char[] s = {'1', '2'}; + int index = 2; + if (doSideEffect() == 1) { } + // violation above 'Empty blocks should have no spaces. .* may only be represented as {}' + Io in = new Io(); + while ((r = in.read()) != null) {} + for (; index < s.length && s[index] != 'x'; index++) {} + if (a == 1) { + } else { + System.identityHashCode("a"); + } + do {} while (a == 1); + switch (a) { + } + // violation 2 lines above 'switch without "default" clause.' + int[] z = {}; + } + } +} + +// violation below 'Top-level class WithAnon has to reside in its own source file.' +class WithAnon { + interface AnonWithEmpty { + public void fooEmpty(); + } + + void method() { + AnonWithEmpty foo = + new AnonWithEmpty() { + + public void emptyMethod() {} + + public void fooEmpty() { + InputEmptyBlocksAndCatchBlocks r = new InputEmptyBlocksAndCatchBlocks(); + int a = 1; + if (a == 1) { } + // violation above 'Empty blocks should have no spaces. .* only be represented as {}' + char[] s = {'1', '2'}; + int index = 2; + if (doSideEffect() == 1) { } + // violation above 'Empty blocks should have no spaces. .* only be represented as {}' + Io in = new Io(); + while ((r = in.read()) != null) {} + for (; index < s.length && s[index] != 'x'; index++) {} + if (a == 1) { + } else { + System.identityHashCode("a"); + } + do {} while (a == 1); + switch (a) { + } + // violation 2 lines above 'switch without "default" clause.' + int[] z = {}; + } + + public int doSideEffect() { + return 1; + } + }; + } +} + +// violation below 'Top-level class NewClass has to reside in its own source file.' +class NewClass { + + void foo() { + int a = 1; + + if (a == 1) { + System.identityHashCode("a"); + } else { + } + + if (a == 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + System.identityHashCode("a"); + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + } else { + } + + if (a == 1) { + } else if (a != 1) { + /*ignore*/ + } else { + } + + if (a == 1) { + } else if (a != 1) { + } else { + /*ignore*/ + } + } + + class NewInner { + + void foo() { + int a = 1; + + if (a == 1) { + System.identityHashCode("a"); + } else { + } + + if (a == 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + System.identityHashCode("a"); + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + } else { + } + + if (a == 1) { + } else if (a != 1) { + /*ignore*/ + } else { + } + + if (a == 1) { + } else if (a != 1) { + } else { + /*ignore*/ + } + } + + NewInner anon = + new NewInner() { + + void foo() { + int a = 1; + + if (a == 1) { + System.identityHashCode("a"); + } else { + } + + if (a == 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + System.identityHashCode("a"); + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + } else { + } + + if (a == 1) { + } else if (a != 1) { + /*ignore*/ + } else { + } + + if (a == 1) { + } else if (a != 1) { + } else { + /*ignore*/ + } + } + }; + } +} + +// violation below 'Top-level class Example has to reside in its own source file.' +class Example { + + void doNothing() {} + + void doNothingElse() {} +} + +// violation below 'Top-level class TestingEmptyBlockCatch has to reside in its own source file.' +class TestingEmptyBlockCatch { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + + class Inner { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + } + + Inner anon = + new Inner() { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + }; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlocksAndCatchBlocksNoViolations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlocksAndCatchBlocksNoViolations.java new file mode 100644 index 000000000000..f70687fac43a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyBlocksAndCatchBlocksNoViolations.java @@ -0,0 +1,106 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// Test case file for checkstyle. +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; + +import java.io.IOException; + +/** some javadoc. */ +public class InputEmptyBlocksAndCatchBlocksNoViolations { + private void foo6() { + try { + throw new IOException(); + } catch (IOException expected) { // This is expected + int k = 0; + } + } + + /** some javadoc. */ + public void testTryCatch() { + try { + int y = 0; + int u = 8; + int e = u - y; + return; + } catch (Exception e) { + System.identityHashCode(e); + return; + } finally { + return; + } + } + + /** some javadoc. */ + public void testTryCatch3() { + try { + int y = 0; + int u = 8; + int e = u - y; + } catch (IllegalArgumentException e) { + System.identityHashCode(e); // some comment + return; + } catch (IllegalStateException ex) { + System.identityHashCode(ex); + return; + } + } + + /** some javadoc. */ + public void testTryCatch4() { + int y = 0; + int u = 8; + try { + int e = u - y; + } catch (IllegalArgumentException e) { + System.identityHashCode(e); + return; + } + } + + /** some javadoc. */ + public void setFormats() { + try { + int k = 4; + } catch (Exception e) { + Object k = null; + if (k != null) { + k = "ss"; + } else { + return; + } + } + } + + /** some javadoc. */ + public void testIfElse() { + if (true) { + return; + } else { + return; + } + } + + /** some javadoc. */ + public void testIfElseIfLadder() { + if (true) { + return; + } else if (false) { + return; + } else { + return; + } + } + + /** some javadoc. */ + public void testSwtichCase() { + switch (1) { + case 1: + return; + case 2: + return; + default: + return; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockNoViolations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockNoViolations.java deleted file mode 100644 index 60fbbb4cd10a..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockNoViolations.java +++ /dev/null @@ -1,77 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// Test case file for checkstyle. -//////////////////////////////////////////////////////////////////////////////// -package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; - -import java.io.IOException; - -public class InputEmptyCatchBlockNoViolations -{ - private void foo6() { - try { - throw new IOException(); - } catch (IOException expected) { // This is expected - int k = 0; - } - } - - public void testTryCatch() - { - try { - int y=0; - int u=8; - int e=u-y; - return; - } - catch (Exception e) { - System.identityHashCode(e); - return; - } - finally - { - return; - } - } - - public void testTryCatch3() - { - try { - int y=0; - int u=8; - int e=u-y; - } - catch (IllegalArgumentException e) { - System.identityHashCode(e); //some comment - return; - } - catch (IllegalStateException ex) { - System.identityHashCode(ex); - return; - } - } - - public void testTryCatch4() - { - int y=0; - int u=8; - try { - int e=u-y; - } - catch (IllegalArgumentException e) { - System.identityHashCode(e); - return; - } - } - public void setFormats() { - try { - int k = 4; - } catch (Exception e) { - Object k = null; - if (k != null) - k = "ss"; - else { - return; - } - } - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockViolationsByComment.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockViolationsByComment.java index abcb50c4fd45..2be5f0a01c5f 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockViolationsByComment.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockViolationsByComment.java @@ -2,109 +2,107 @@ import java.io.IOException; -public class InputEmptyCatchBlockViolationsByComment -{ - private void foo() { - try { - throw new RuntimeException(); - } catch (Exception expected) //ok - { - //Expected - } +/** some javadoc. */ +public class InputEmptyCatchBlockViolationsByComment { + private void foo() { + try { + throw new RuntimeException(); + } catch (Exception expected) { + // Expected } + } - private void foo1() { - try { - throw new RuntimeException(); - } catch (Exception e) //warn - {} + private void foo1() { + try { + throw new RuntimeException(); + } catch (Exception e) { + } // violation above 'Empty catch block.' + } - } + private void foo2() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException ignore) { + } // violation above 'Empty catch block.' + } - private void foo2() { - try { - throw new IOException(); - } catch (IOException | NullPointerException | ArithmeticException ignore) //warn - { - } + private void foo3() { // comment + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException e) { // This is expected } + } - private void foo3() { // comment - try { - throw new IOException(); - } catch (IOException | NullPointerException | ArithmeticException e) { //This is expected - } + private void foo4() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException e) { + /* This is expected*/ } + } - private void foo4() { - try { - throw new IOException(); - } catch (IOException | NullPointerException | ArithmeticException e) { /* This is expected*/ - } + private void foo5() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException e) { // singleline comment } + } - private void foo5() { - try { - throw new IOException(); - } catch (IOException | NullPointerException | ArithmeticException e) { // Some singleline comment - } - } - private void some() { - try { - throw new IOException(); - } catch (IOException e) //ok - { - /* ololo - * blalba - */ - } + private void some() { + try { + throw new IOException(); + } catch (IOException e) { + /* ololo + * blalba + */ } - private void some1() { - try { - throw new IOException(); - } catch (IOException e) //ok - { - /* lalala - * This is expected - */ - } + } + + private void some1() { + try { + throw new IOException(); + } catch (IOException e) { + /* lalala + * This is expected + */ } - private void some2() { - try { - throw new IOException(); - } catch (IOException e) //ok - { - /* - * This is expected - * lalala - */ - } + } + + private void some2() { + try { + throw new IOException(); + } catch (IOException e) { + /* + * This is expected + * lalala + */ } - private void some3() { - try { - throw new IOException(); - } catch (IOException e) //ok - { - // some comment - //This is expected - } + } + + private void some3() { + try { + throw new IOException(); + } catch (IOException e) { + // some comment + // This is expected } - private void some4() { - try { - throw new IOException(); - } catch (IOException e) //ok - { - //This is expected - // some comment - } + } + + private void some4() { + try { + throw new IOException(); + } catch (IOException e) { + // This is expected + // some comment } - private void some5() { - try { - throw new IOException(); - } catch (IOException e) //ok - { - /* some comment */ - //This is expected - } + } + + private void some5() { + try { + throw new IOException(); + } catch (IOException e) { + /* some comment */ + // This is expected } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockViolationsByVariableName.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockViolationsByVariableName.java index 41d1dda60ed5..632cb40c389a 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockViolationsByVariableName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchBlockViolationsByVariableName.java @@ -2,62 +2,58 @@ import java.io.IOException; -public class InputEmptyCatchBlockViolationsByVariableName -{ - private void foo() { - try { - throw new RuntimeException(); - } catch (Exception expected) //ok - { - - } +/** some javadoc. */ +public class InputEmptyCatchBlockViolationsByVariableName { + private void foo() { + try { + throw new RuntimeException(); + } catch (Exception expected) { + // ignore } - - private void foo1() { - try { - throw new RuntimeException(); - } catch (Exception e) //warn - {} - - } - - private void foo2() { - try { - throw new IOException(); - } catch (IOException | NullPointerException | ArithmeticException expected) //ok - { - } - } - - private void foo3() { // comment - try { - throw new IOException(); - } catch (IOException | NullPointerException | ArithmeticException e) //warn - { - } + } + + private void foo1() { + try { + throw new RuntimeException(); + } catch (Exception e) { + } // violation above 'Empty catch block.' + } + + private void foo2() { + try { + throw new IOException(); + // violation below 'Empty catch block.' + } catch (IOException | NullPointerException | ArithmeticException expected) { } - - private void foo4() { - try { - throw new IOException(); - } catch (IOException | NullPointerException | ArithmeticException expected) //ok - { - } - } - - private void foo5() { - try { - throw new IOException(); - } catch (IOException | NullPointerException | ArithmeticException e) //warn - { - } - } - private void some() { - try { - throw new IOException(); - } catch (IOException e) //warn - { - - } + } + + private void foo3() { // comment + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException e) { + } // violation above 'Empty catch block.' + } + + private void foo4() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException expected) { + // ignore } + } + + private void foo5() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException e) { + } // violation above 'Empty catch block.' + } + + private void some() { + try { + throw new IOException(); + } catch (IOException e) { + + } // violation 2 lines above 'Empty catch block.' + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchEmptyComment.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchEmptyComment.java new file mode 100644 index 000000000000..1c9a8f83ee5b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyCatchEmptyComment.java @@ -0,0 +1,97 @@ +package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; + +import java.io.IOException; + +/** some javadoc. */ +public class InputEmptyCatchEmptyComment { + private void foo() { + try { + throw new RuntimeException(); + // violation below 'Empty catch block' + } catch (Exception expected) { + // + } + } + + private void foo2() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException ignore) { + // ignore + } + } + + private void foo3() { // comment + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { + /**/ + } + } + + private void foo4() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { + /* */ + } + } + + private void foo5() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { // + } + } + + private void foo6() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException e) { // + } + } + + private void foo7() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException e) { + /**/ + } + } + + private void foo8() { + try { + throw new IOException(); + } catch (IOException e) { + /* no violation. */ + } + } + + private void foo9() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException e) { /* no violation. */ + } + } + + private void foo10() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { /* */ + } + } + + private void foo11() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { /**/ + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyFinallyBlocks.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyFinallyBlocks.java new file mode 100644 index 000000000000..af794768bbdd --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputEmptyFinallyBlocks.java @@ -0,0 +1,94 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// Test case file for checkstyle. +// Created: 2001 +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; + +class InputEmptyFinallyBlocks { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + + class Inner { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + } + + Inner anon = + new Inner() { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + }; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputFormattedEmptyBlocksAndCatchBlocks.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputFormattedEmptyBlocksAndCatchBlocks.java new file mode 100644 index 000000000000..b863986e5757 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputFormattedEmptyBlocksAndCatchBlocks.java @@ -0,0 +1,491 @@ +package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; + +class InputFormattedEmptyBlocksAndCatchBlocks { + static { + } + + static { + } + + static { + } + + public void fooMethod() { + InputEmptyBlocksAndCatchBlocks r = new InputEmptyBlocksAndCatchBlocks(); + int a = 1; + if (a == 1) {} + char[] s = {'1', '2'}; + int index = 2; + if (doSideEffect() == 1) {} + Io in = new Io(); + while ((r = in.read()) != null) {} + for (; index < s.length && s[index] != 'x'; index++) {} + if (a == 1) { + } else { + System.identityHashCode("a"); + } + do {} while (a == 1); + switch (a) { + } + // violation 2 lines above 'switch without "default" clause.' + int[] z = {}; + } + + public int doSideEffect() { + return 1; + } + + public void emptyMethod() {} + + void foo() throws Exception { + int a = 90; + + if (a == 1) { + } else { + } + + if (a == 1) { + } else { + } + + try (MyResource r = new MyResource()) {} + try (MyResource r = new MyResource()) {} + try (MyResource r = new MyResource()) { + // violation below 'Empty catch block.' + } catch (Exception expected) { + } + try (MyResource r = new MyResource()) { + // violation below 'Empty catch block.' + } catch (Exception expected) { + } + try (MyResource r = new MyResource()) { + // violation below 'Empty catch block.' + } catch (Exception expected) { + } + try (MyResource r = new MyResource()) { + // violation below 'Empty catch block.' + } catch (Exception expected) { + } + try (MyResource r = new MyResource()) { + ; + } + } + + /** some. */ + public class MyResource implements AutoCloseable { + /** some. */ + @Override + public void close() throws Exception { + System.out.println("Closed MyResource"); + } + } +} + +// violation below 'Top-level class ExtraIo has to reside in its own source file.' +class ExtraIo { + public InputEmptyBlocksAndCatchBlocks read() { + return new InputEmptyBlocksAndCatchBlocks(); + } +} + +// violation below 'Top-level class ExtraEmpty has to reside in its own source file.' +class ExtraEmpty {} + +// violation below 'Top-level class ExtraEmptyImplement has to reside in its own source file.' +interface ExtraEmptyImplement {} + +// violation below 'Top-level class ExtraWithInner has to reside in its own source file.' +class ExtraWithInner { + static { + } + + public void emptyMethod() {} + + public int doSideEffect() { + return 1; + } + + class Inner { + private void withEmpty() { + InputEmptyBlocksAndCatchBlocks r = new InputEmptyBlocksAndCatchBlocks(); + int a = 1; + if (a == 1) {} + char[] s = {'1', '2'}; + int index = 2; + if (doSideEffect() == 1) {} + Io in = new Io(); + while ((r = in.read()) != null) {} + for (; index < s.length && s[index] != 'x'; index++) {} + if (a == 1) { + } else { + System.identityHashCode("a"); + } + do {} while (a == 1); + switch (a) { + } + // violation 2 lines above 'switch without "default" clause.' + int[] z = {}; + } + } +} + +// violation below 'Top-level class ExtraWithAnon has to reside in its own source file.' +class ExtraWithAnon { + interface AnonWithEmpty { + public void fooEmpty(); + } + + void method() { + AnonWithEmpty foo = + new AnonWithEmpty() { + + public void emptyMethod() {} + + public void fooEmpty() { + InputEmptyBlocksAndCatchBlocks r = new InputEmptyBlocksAndCatchBlocks(); + int a = 1; + if (a == 1) {} + char[] s = {'1', '2'}; + int index = 2; + if (doSideEffect() == 1) {} + Io in = new Io(); + while ((r = in.read()) != null) {} + for (; index < s.length && s[index] != 'x'; index++) {} + if (a == 1) { + } else { + System.identityHashCode("a"); + } + do {} while (a == 1); + switch (a) { + } + // violation 2 lines above 'switch without "default" clause.' + int[] z = {}; + } + + public int doSideEffect() { + return 1; + } + }; + } +} + +// violation below 'Top-level class ExtraNewClass has to reside in its own source file.' +class ExtraNewClass { + + void foo() { + int a = 1; + + if (a == 1) { + System.identityHashCode("a"); + } else { + } + + if (a == 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + System.identityHashCode("a"); + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + } else { + } + + if (a == 1) { + } else if (a != 1) { + /*ignore*/ + } else { + } + + if (a == 1) { + } else if (a != 1) { + } else { + /*ignore*/ + } + } + + class NewInner { + + void foo() { + int a = 1; + + if (a == 1) { + System.identityHashCode("a"); + } else { + } + + if (a == 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + System.identityHashCode("a"); + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + } else { + } + + if (a == 1) { + } else if (a != 1) { + /*ignore*/ + } else { + } + + if (a == 1) { + } else if (a != 1) { + } else { + /*ignore*/ + } + } + + NewInner anon = + new NewInner() { + + void foo() { + int a = 1; + + if (a == 1) { + System.identityHashCode("a"); + } else { + } + + if (a == 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + System.identityHashCode("a"); + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + System.identityHashCode("a"); + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + System.identityHashCode("a"); + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + /*ignore*/ + } else { + /*ignore*/ + } + + if (a == 1) { + /*ignore*/ + } else if (a != 1) { + } else { + } + + if (a == 1) { + } else if (a != 1) { + /*ignore*/ + } else { + } + + if (a == 1) { + } else if (a != 1) { + } else { + /*ignore*/ + } + } + }; + } +} + +// violation below 'Top-level class ExtraExample has to reside in its own source file.' +class ExtraExample { + + void doNothing() {} + + void doNothingElse() {} +} + +// violation below '.* ExtraTestingEmptyBlockCatch has to reside in its own source file.' +class ExtraTestingEmptyBlockCatch { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + + class Inner { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + } + + Inner anon = + new Inner() { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + // violation below 'Empty catch block.' + } catch (Exception e) { + } finally { + } + } + }; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputFormattedEmptyCatchEmptyComment.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputFormattedEmptyCatchEmptyComment.java new file mode 100644 index 000000000000..9fc999ec3202 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputFormattedEmptyCatchEmptyComment.java @@ -0,0 +1,100 @@ +package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; + +import java.io.IOException; + +/** some javadoc. */ +public class InputFormattedEmptyCatchEmptyComment { + private void foo() { + try { + throw new RuntimeException(); + // violation below 'Empty catch block' + } catch (Exception expected) { + // + } + } + + private void foo2() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException ignore) { + // ignore + } + } + + private void foo3() { // comment + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { + /**/ + } + } + + private void foo4() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { + /* */ + } + } + + private void foo5() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { // + } + } + + private void foo6() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException e) { // + } + } + + private void foo7() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException e) { + /**/ + } + } + + private void foo8() { + try { + throw new IOException(); + } catch (IOException e) { + /* no violation. */ + } + } + + private void foo9() { + try { + throw new IOException(); + } catch (IOException | NullPointerException | ArithmeticException e) { + /* no violation. */ + } + } + + private void foo10() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { + /* */ + } + } + + private void foo11() { + try { + throw new IOException(); + // violation below 'Empty catch block' + } catch (IOException | NullPointerException | ArithmeticException e) { + /**/ + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputRightCurlyAloneOrEmptyNoViolations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputRightCurlyAloneOrEmptyNoViolations.java deleted file mode 100644 index 24e0b088d28d..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule413emptyblocks/InputRightCurlyAloneOrEmptyNoViolations.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule413emptyblocks; - -public class InputRightCurlyAloneOrEmptyNoViolations { - - private InputRightCurlyAloneOrEmptyNoViolations() {} //ok - - final class BrrrTests extends Object {} // ok - - void method7(int a) {} //ok - - class TestClass4 {} //ok - - enum Test {} //ok - - interface Interface {} //ok - - @interface ClassPreamble { } //ok, should be violation, as there is space - - void method2(java.util.HashSet set) { - java.util.Map map2 = new java.util.LinkedHashMap() {{ - put("Hello", "World"); - }}; //ok - - if (set.isEmpty()) { - while (true) {} //ok - } - if (!set.isEmpty()) { - do {} while (true); //ok - } else { - for (int i = 0; i < 10; i++) {} //ok - } - } - - void method8(int a) { - java.util.Map map3 = new java.util.LinkedHashMap() {{ - put("Hello", "World"); - } - - }; - } -} - -@interface TesterAnnotation {} //ok diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputClassWithChainedMethods3.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputClassWithChainedMethods3.java new file mode 100644 index 000000000000..65e68b214439 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputClassWithChainedMethods3.java @@ -0,0 +1,36 @@ +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +/** some javadoc. */ +public class InputClassWithChainedMethods3 { + + /** some javadoc. */ + public InputClassWithChainedMethods3(Object... params) {} + + /** some javadoc. */ + public static void main(String[] args) { + new InputClassWithChainedMethods3() + .getInstance("string_one") + .doNothing("string_one".trim(), "string_two"); + // violation above ''method call' child has incorrect indentation level 4, expected .* 8.' + + int length = + new InputClassWithChainedMethods3("param1", "param2").getInstance() + .doNothing("something").length(); + // violation 2 lines above ''new' has incorrect indentation level 4, expected .* 8.' + + int length2 = + new InputClassWithChainedMethods3("param1", "param2").getInstance() + .doNothing("something").length(); + // violation 2 lines above ''new' has incorrect indentation level 4, expected .* 8.' + } + + /** some javadoc. */ + public String doNothing(String something, String... uselessParams) { + return something; + } + + /** some javadoc. */ + public InputClassWithChainedMethods3 getInstance(String... uselessParams) { + return this; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFastMatcher.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFastMatcher.java index 3d3d24aa96c9..c259a20c5ee3 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFastMatcher.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFastMatcher.java @@ -1,42 +1,41 @@ package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; -public class InputFastMatcher -{ - - public boolean matches(char c) - { - // OOOO Auto-generated method stub - return false; - } - - public String replaceFrom(CharSequence sequence, CharSequence replacement) - { - // OOOO Auto-generated method stub - return null; - } - - public String collapseFrom(CharSequence sequence, char replacement) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimFrom(CharSequence s) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimLeadingFrom(CharSequence sequence) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimTrailingFrom(CharSequence sequence) - { - // OOOO Auto-generated method stub - return null; - } - +/** some javadoc. */ +public class InputFastMatcher { + + /** some javadoc. */ + public boolean matches(char c) { + // OOOO Auto-generated method stub + return false; + } + + /** some javadoc. */ + public String replaceFrom(CharSequence sequence, CharSequence replacement) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String collapseFrom(CharSequence sequence, char replacement) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimFrom(CharSequence s) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimLeadingFrom(CharSequence sequence) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimTrailingFrom(CharSequence sequence) { + // OOOO Auto-generated method stub + return null; + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFormattedClassWithChainedMethods3.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFormattedClassWithChainedMethods3.java new file mode 100644 index 000000000000..a6b094afd29e --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFormattedClassWithChainedMethods3.java @@ -0,0 +1,25 @@ +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +/** some javadoc. */ +public class InputFormattedClassWithChainedMethods3 { + /** some javadoc. */ + public InputFormattedClassWithChainedMethods3() { + + String someString = ""; + + String chained1 = doNothing(someString.concat("zyx").concat("255, 254, 253")); + + doNothing(someString.concat("zyx").concat("255, 254, 253")); + } + + /** some javadoc. */ + public static void main(String[] args) { + InputFormattedClassWithChainedMethods3 classWithChainedMethodsCorrect = + new InputFormattedClassWithChainedMethods3(); + } + + /** some javadoc. */ + public String doNothing(String something) { + return something; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFormattedIndentationCodeBlocks.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFormattedIndentationCodeBlocks.java new file mode 100644 index 000000000000..684cd07af97d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputFormattedIndentationCodeBlocks.java @@ -0,0 +1,26 @@ +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +/** Some javadoc. */ +public class InputFormattedIndentationCodeBlocks { + private static void test(int condition) { + { + System.out.println("True"); + } + } + + { + System.out.println("False"); + } + + { + System.out.println("False"); + } + + class Inner { + void test() { + { + System.out.println("True"); + } + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCodeBlocks.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCodeBlocks.java new file mode 100644 index 000000000000..dee65d6d106b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCodeBlocks.java @@ -0,0 +1,26 @@ +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +/** Some javadoc. */ +public class InputIndentationCodeBlocks { + private static void test(int condition) { + { + System.out.println("True"); + } + } + + { + System.out.println("False"); + } + + { // violation ''block lcurly' has incorrect indentation level 4, expected level should be 2.' + System.out.println("False"); // violation '.* incorrect indentation level 6, expected .* 4.' + } // violation ''block rcurly' has incorrect indentation level 4, expected level should be 2.' + + class Inner { + void test() { + { + System.out.println("True"); + } + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrect.java index 3fea081a52e7..f16e8c8c6b5a 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrect.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrect.java @@ -1,113 +1,111 @@ -package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; //indent:0 exp:0 - -import java.util.Map; //indent:0 exp:0 -import java.util.ArrayList;//indent:0 exp:0 - -public abstract class InputIndentationCorrect { //indent:0 exp:0 - - static int i; //indent:2 exp:2 - - int[] c = {1, 2, 3, //indent:2 exp:2 - 4, 5, 6}; //indent:6 exp:6 - - int b; //indent:2 exp:2 - - static { //indent:2 exp:2 - i = 0; //indent:4 exp:4 - } //indent:2 exp:2 - - { //indent:2 exp:2 - b = 2; //indent:4 exp:4 - } //indent:2 exp:2 - - private static abstract class RangesMatcher { //indent:2 exp:2 - - private static final String ZEROES = "0\u0660\u06f0" //indent:4 exp:4 - + "\u0c66\u0ce6" //indent:8 exp:8 - + "\u1c40\u1c50"; //indent:8 exp:8 - - public static final InputIndentationCorrect JAVA_LETTER_OR_DIGIT = //indent:4 exp:4 - new InputIndentationCorrect() { //indent:8 exp:8 - @Override public boolean matches(char c) { //indent:10 exp:10 - return Character.isLetterOrDigit(c); //indent:12 exp:12 - } //indent:10 exp:10 - }; //indent:8 exp:8 - - /** Matches no characters. */ //indent:4 exp:4 - public static final InputFastMatcher NONE = //indent:4 exp:4 - new InputFastMatcher() { //indent:12 exp:>=8 - @Override public boolean matches(char c) { //indent:6 exp:6 - return false; //indent:8 exp:8 - } //indent:6 exp:6 - - @Override public String replaceFrom(CharSequence seq, CharSequence repl) { //indent:6 exp:6 - checkNotNull(repl); //indent:8 exp:8 - return seq.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - - private void checkNotNull(CharSequence replacement) {} //indent:6 exp:6 - - @Override public String collapseFrom(CharSequence sequence, //indent:6 exp:6 - char replacement) { //indent:10 exp:10 - return sequence.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - - @Override //indent:6 exp:6 - public String trimTrailingFrom(CharSequence sequence) { //indent:6 exp:6 - return sequence.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean matches(char c) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public void foo() { //indent:2 exp:2 - int i = 0; //indent:4 exp:4 - for (; i < 9; i++) { //indent:4 exp:4 - if (veryLongLongLongCondition() //indent:6 exp:6 - || veryLongLongLongCondition2()) { //indent:14 exp:>=10 - someFooMethod("longString", "veryLongString", //indent:8 exp:8 - "superVeryExtraLongString"); //indent:12 exp:12 - if (veryLongLongLongCondition()) { //indent:8 exp:8 - while (veryLongLongLongCondition2() //indent:10 exp:10 - && veryLongLongLongCondition2()) { //indent:16 exp:>=14 - try { //indent:12 exp:12 - doSmth(); //indent:14 exp:14 - } catch (Exception e) { //indent:12 exp:12 - throw new AssertionError(e); //indent:14 exp:14 - } //indent:12 exp:12 - } //indent:10 exp:10 - } //indent:8 exp:8 - } //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean veryLongLongLongCondition() { //indent:2 exp:2 - if (veryLongLongLongCondition2()) { //indent:4 exp:4 - return true; //indent:6 exp:6 - } //indent:4 exp:4 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean veryLongLongLongCondition2() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public void someFooMethod(String longString, //indent:2 exp:2 - String superLongString, String exraSuperLongString) {} //indent:6 exp:6 - - public void fooThrowMethod() //indent:2 exp:2 - throws Exception { //indent:10 exp:>=6 - /* Some code*/ //indent:6 exp:6 - } //indent:2 exp:2 - - public void doSmth() { //indent:2 exp:2 - for (int h //indent:4 exp:4 - : c) { //indent:10 exp:>=8 - someFooMethod("longString", "veryLongString", //indent:6 exp:6 - "superVeryExtraLongString"); //indent:10 exp:10 - } //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +/** some javadoc. */ +public abstract class InputIndentationCorrect { + + static int i; + + static { + i = 0; + } + + int[] pqr = { + 1, 2, 3, + 4, 5, 6 + }; + int abc; + + { + abc = 2; + } + + /** some javadoc. */ + public boolean matches(char c) { + return false; + } + + /** some javadoc. */ + public void foo() { + int i = 0; + for (; i < 9; i++) { + if (veryLongLongLongCondition() || veryLongLongLongCondition2()) { + someFooMethod("longString", "veryLongString", "superVeryExtraLongString"); + if (veryLongLongLongCondition()) { + while (veryLongLongLongCondition2() && veryLongLongLongCondition2()) { + try { + doSmth(); + } catch (Exception e) { + throw new AssertionError(e); + } + } + } + } + } + } + + /** some javadoc. */ + public boolean veryLongLongLongCondition() { + return veryLongLongLongCondition2(); + } + + /** some javadoc. */ + public boolean veryLongLongLongCondition2() { + return false; + } + + /** some javadoc. */ + public void someFooMethod( + String longString, String superLongString, String exraSuperLongString) {} + + /** some javadoc. */ + public void fooThrowMethod() throws Exception { + /* Some code*/ + } + + /** some javadoc. */ + public void doSmth() { + for (int h : pqr) { + someFooMethod("longString", "veryLongString", "superVeryExtraLongString"); + } + } + + private abstract static class RangesMatcher { + + public static final InputIndentationCorrect JAVA_LETTER_OR_DIGIT = + new InputIndentationCorrect() { + @Override + public boolean matches(char c) { + return Character.isLetterOrDigit(c); + } + }; + + /** Matches no characters. */ + public static final InputFastMatcher NONE = + new InputFastMatcher() { + @Override + public boolean matches(char c) { + return false; + } + + @Override + public String replaceFrom(CharSequence seq, CharSequence repl) { + checkNotNull(repl); + return seq.toString(); + } + + private void checkNotNull(CharSequence replacement) {} + + @Override + public String collapseFrom(CharSequence sequence, char replacement) { + return sequence.toString(); + } + + @Override + public String trimTrailingFrom(CharSequence sequence) { + return sequence.toString(); + } + }; + + private static final String ZEROES = "" + ""; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectAnnotationArrayInit.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectAnnotationArrayInit.java new file mode 100644 index 000000000000..dacf946df7f8 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectAnnotationArrayInit.java @@ -0,0 +1,13 @@ +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +/** some javadoc. */ +public class InputIndentationCorrectAnnotationArrayInit { + interface MyInterface { + @AnAnnotation(values = {"Hello"}) + void works(); + + @interface AnAnnotation { + String[] values(); + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectClass.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectClass.java index ea6ad0aed79d..0531056c381e 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectClass.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectClass.java @@ -1,45 +1,33 @@ -package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; //indent:0 exp:0 - -import java.util.Iterator; //indent:0 exp:0 - -public class InputIndentationCorrectClass //indent:0 exp:0 - implements Runnable, Cloneable { //indent:4 exp:4 - - class InnerClass implements //indent:2 exp:2 - Iterable, //indent:10 exp:>=6 - Cloneable { //indent:13 exp:>=6 - @Override //indent:4 exp:4 - public Iterator iterator() { //indent:4 exp:4 - return null; //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClass2 //indent:2 exp:2 - extends //indent:7 exp:>=6 - SecondClassReturnWithVeryVeryVeryLongName { //indent:10 exp:>=6 - public InnerClass2(String string) { //indent:4 exp:4 - super(); //indent:6 exp:6 - // OOOO Auto-generated constructor stub //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 - - @Override //indent:2 exp:2 - public void run() { //indent:2 exp:2 - SecondClassWithLongLongLongLongName anon = //indent:4 exp:4 - new SecondClassWithLongLongLongLongName() { //indent:10 exp:>=8 - - }; //indent:4 exp:4 - - SecondClassWithLongLongLongLongName anon2 = new //indent:4 exp:4 - SecondClassWithLongLongLongLongName() { //indent:10 exp:>=8 - - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassWithLongLongLongLongName //indent:0 exp:0 - extends //indent:4 exp:4 - InputIndentationCorrectClass{ //indent:9 exp:>=4 - -} //indent:0 exp:0 -class SecondClassReturnWithVeryVeryVeryLongName{} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +import java.util.Iterator; + +/** some javadoc. */ +public class InputIndentationCorrectClass implements Runnable, Cloneable { + + /** some javadoc. */ + @Override + public void run() { + SecondClassWithLongLongLongLongName anon = new SecondClassWithLongLongLongLongName() {}; + + SecondClassWithLongLongLongLongName anon2 = new SecondClassWithLongLongLongLongName() {}; + } + + class InnerClass implements Iterable, Cloneable { + @Override + public Iterator iterator() { + return null; + } + } + + class InnerClass2 extends SecondClassReturnWithVeryVeryVeryLongName { + public InnerClass2(String string) { + super(); + // OOOO Auto-generated constructor stub + } + } + + class SecondClassWithLongLongLongLongName extends InputIndentationCorrectClass {} + + class SecondClassReturnWithVeryVeryVeryLongName {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectFieldAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectFieldAndParameter.java index dcdb3412d6a6..732ebb374da0 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectFieldAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectFieldAndParameter.java @@ -1,127 +1,156 @@ -package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; //indent:0 exp:0 - -class InputIndentationCorrectFieldAndParameter { //indent:0 exp:0 - - boolean flag = conditionFirst("Loooooooooooooooooong", new //indent:2 exp:2 - SecondFieldLongNam2("Loooooooooooooooooog"). //indent:6 exp:6 - getInteger(new FooFieldClass(), "Loooooooooooooooooog"), //indent:6 exp:6 - new InnerClassFoo()); //indent:6 exp:6 - - boolean secondFlag = conditionSecond(10000000000.0, new //indent:2 exp:2 - SecondFieldLongNam2("Looooooooooooo" //indent:6 exp:6 - + "oooooooooooong").getString(new FooFieldClass(), //indent:6 exp:6 - new SecondFieldLongNam2("loooooooooong"). //indent:6 exp:6 - getInteger(new FooFieldClass(), "loooooooooooooong")), "loooooooooooong") //indent:6 exp:6 - || conditionThird(2048) || conditionFourth(new //indent:6 exp:6 - SecondFieldLongNam2("Looooooooooooooo" //indent:6 exp:6 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:6 exp:6 - conditionFifth(true, new SecondFieldLongNam2(getString(2048, "Looo" //indent:6 exp:6 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:6 exp:6 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:6 exp:6 - SecondFieldLongNam2(getString(100000, "Loooooong" //indent:6 exp:6 - + "Fooooooo><"))) || conditionNoArg() //indent:6 exp:6 - || conditionNoArg() || //indent:6 exp:6 - conditionNoArg() || conditionNoArg(); //indent:6 exp:6 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondFieldLongNam2 instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - boolean flag = conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondFieldLongNam2("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooFieldClass(), "Loooooooooooooooooog"), //indent:12 exp:>=8 - new InnerClassFoo()); //indent:13 exp:>=8 - - boolean secondFlag = conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondFieldLongNam2("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooFieldClass(), //indent:11 exp:>=8 - new SecondFieldLongNam2("loooooooooong"). //indent:10 exp:>=8 - getInteger(new FooFieldClass(), "looooooooong")), "loooooooooooong") //indent:12 exp:>=8 - || conditionThird(2048) || conditionFourth(new //indent:13 exp:>=8 - SecondFieldLongNam2("Looooooooooooooo" //indent:16 exp:>=8 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:12 exp:>=8 - conditionFifth(true, new SecondFieldLongNam2(getString(2048, "Looo" //indent:11 exp:>=8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:15 exp:>=8 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:12 exp:>=8 - SecondFieldLongNam2(getString(100000, "Loooooong" //indent:12 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=8 - || conditionNoArg() || //indent:10 exp:>=8 - conditionNoArg() || conditionNoArg(); //indent:10 exp:>=8 - - FooFieldClass anonymousClass = new FooFieldClass() { //indent:4 exp:4 - boolean secondFlag = conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondFieldLongNam2("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooFieldClass(), //indent:12 exp:>=10 - new SecondFieldLongNam2("loooooooooong"). //indent:15 exp:>=10 - getInteger(new FooFieldClass(), "looooooong")), "loooooooooooong") //indent:13 exp:>=10 - || conditionThird(2048) || conditionFourth(new //indent:14 exp:>=10 - SecondFieldLongNam2("Looooooooooooooo" //indent:17 exp:>=10 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:13 exp:>=10 - conditionFifth(true, new SecondFieldLongNam2(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:16 exp:>=10 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:13 exp:>=8 - SecondFieldLongNam2(getString(100000, "Loooooong" //indent:13 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:17 exp:>=10 - || conditionNoArg() || //indent:11 exp:>=10 - conditionNoArg() || conditionNoArg(); //indent:11 exp:>=10 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondFieldLongNam2 { //indent:0 exp:0 - - public SecondFieldLongNam2(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooFieldClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooFieldClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooFieldClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondFieldLongNam2 getInstance() { //indent:2 exp:2 - return new SecondFieldLongNam2("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooFieldClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +class InputIndentationCorrectFieldAndParameter { + + boolean flag = + conditionFirst( + "Loooooooooooooooooong", + new SecondFieldLongNam2("Loooooooooooooooooog") + .getInteger(new FooFieldClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + + boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + + String getString(int someInt, String someString) { + return "String"; + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondFieldLongNam2 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + boolean flag = + conditionFirst( + "Loooooooooooooooooong", + new SecondFieldLongNam2("Loooooooooooooooooog") + .getInteger(new FooFieldClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + + boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "looooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + + FooFieldClass anonymousClass = + new FooFieldClass() { + final boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "looooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString( + 2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + }; + } + + class SecondFieldLongNam2 { + + public SecondFieldLongNam2(String string) {} + + String getString(FooFieldClass instance, int integer) { + return "String"; + } + + int getInteger(FooFieldClass instance, String string) { + return -1; + } + + boolean getBoolean(FooFieldClass instance, boolean flag) { + return false; + } + + SecondFieldLongNam2 getInstance() { + return new SecondFieldLongNam2("VeryLoooooooooo" + "oongString"); + } + } + + class FooFieldClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectForAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectForAndParameter.java index 3f252ed83d69..1a521b964f44 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectForAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectForAndParameter.java @@ -1,113 +1,126 @@ -package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; //indent:0 exp:0 - -import java.util.ArrayList; //indent:0 exp:0 -import java.util.HashMap; //indent:0 exp:0 -import java.util.Iterator; //indent:0 exp:0 -import java.util.List; //indent:0 exp:0 -import java.util.Map; //indent:0 exp:0 - -class InputIndentationCorrectForAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - for (int i = 1; i < 10; i ++) {} //indent:4 exp:4 - - for (int i = new SecondForClassWithLongName1("Loooooooooooooooooooo" //indent:4 exp:4 - + "oong").getInteger(new FooForClass(), //indent:8 exp:8 - getString(1000000000, "Loooooooooooooooong")); i < 10; i++) {} //indent:10 exp:>=8 - - for (Map.Entry entry : new SecondForClassWithLongName1("Loo" //indent:4 exp:4 - + "ooooooooooooooooooooong").getMap(new //indent:8 exp:8 - FooForClass(), 10000000, //indent:8 exp:8 - getString(10000, "Loooooooooo" //indent:8 exp:8 - + "ooooong")).entrySet()) {} //indent:8 exp:8 - - for (Map.Entry entry : new SecondForClassWithLongName1("Loo" //indent:4 exp:4 - + "ooooooooooooooooooooong").getMap(new //indent:8 exp:8 - FooForClass(), 10000000, //indent:12 exp:>=8 - getString(10000, "Loooooooooo" //indent:10 exp:>=8 - + "ooooong")).entrySet()) {} //indent:15 exp:>=8 - - for (String string : new SecondForClassWithLongName1(getString(1024 //indent:4 exp:4 - , "Looooooooooooooooooong")). //indent:8 exp:8 - getList(new FooForClass(), 1000, getString(1024, //indent:8 exp:8 - "Loooooooooooooooooooooooooooooooo" //indent:8 exp:8 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:8 exp:8 - + "oooooooooong"))) {} //indent:8 exp:8 - - for (String string : new SecondForClassWithLongName1(getString(1024 //indent:4 exp:4 - , "Looooooooooooooooooong")). //indent:8 exp:8 - getList(new FooForClass(), 1000, getString(1024, //indent:12 exp:>=8 - "Loooooooooooooooooooooooooooooooo" //indent:14 exp:>=8 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:10 exp:>=8 - + "oooooooooong"))) {} //indent:13 exp:>=8 - - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - - for (int i = 1; i < 10; i ++) {} //indent:6 exp:6 - - for (int i = new SecondForClassWithLongName1("Loooooooooooooooooooo" //indent:6 exp:6 - + "oong").getInteger(new FooForClass(), //indent:10 exp:10 - getString(1000000000, "Loooooooooooooooong")); i < 10; i++) {} //indent:12 exp:>=10 - - for (Map.Entry entry : new SecondForClassWithLongName1("Loo" //indent:6 exp:6 - + "ooooooooooooooooooooong").getMap(new //indent:10 exp:10 - FooForClass(), 10000000, //indent:10 exp:10 - getString(10000, "Loooooooooo" //indent:10 exp:10 - + "ooooong")).entrySet()) {} //indent:10 exp:10 - - for (Map.Entry entry : new SecondForClassWithLongName1("Loo" //indent:6 exp:6 - + "ooooooooooooooooooooong").getMap(new //indent:12 exp:>=10 - FooForClass(), 10000000, //indent:13 exp:>=10 - getString(10000, "Loooooooooo" //indent:18 exp:>=10 - + "ooooong")).entrySet()) {} //indent:15 exp:>=10 - - for (String string : new SecondForClassWithLongName1(getString(1024 //indent:6 exp:6 - , "Looooooooooooooooooong")). //indent:10 exp:10 - getList(new FooForClass(), 1000, getString(1024, //indent:10 exp:10 - "Loooooooooooooooooooooooooooooooo" //indent:10 exp:10 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:10 exp:10 - + "oooooooooong"))) {} //indent:10 exp:10 - - for (String string : new SecondForClassWithLongName1(getString(1024 //indent:6 exp:6 - , "Looooooooooooooooooong")). //indent:15 exp:>=10 - getList(new FooForClass(), 1000, getString(1024, //indent:13 exp:>=10 - "Loooooooooooooooooooooooooooooooo" //indent:19 exp:>=10 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:21 exp:>=10 - + "oooooooooong"))) {} //indent:10 exp:10 - } //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondForClassWithLongName1 //indent:0 exp:0 - implements Iterable{ //indent:8 exp:>=4 - - public SecondForClassWithLongName1(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - int getInteger(FooForClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - Map getMap(FooForClass instance, int integer, String string) { //indent:2 exp:2 - return new HashMap(); //indent:4 exp:4 - } //indent:2 exp:2 - - List getList(FooForClass instance, long longLong, String string) { //indent:2 exp:2 - return new ArrayList(); //indent:4 exp:4 - } //indent:2 exp:2 - - public Iterator iterator() { //indent:2 exp:2 - return null; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooForClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +class InputIndentationCorrectForAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + for (int i = 1; i < 10; i++) {} + + for (int i = + new SecondForClassWithLongName1("Loooooooooooooooooooo" + "oong") + .getInteger(new FooForClass(), getString(1000000000, "Loooooooooooooooong")); + i < 10; + i++) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + } + + class InnerClassFoo { + + void fooMethodWithIf() { + + for (int i = 1; i < 10; i++) {} + + for (int i = + new SecondForClassWithLongName1("Loooooooooooooooooooo" + "oong") + .getInteger(new FooForClass(), getString(1000000000, "Loooooooooooooooong")); + i < 10; + i++) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + } + } + + class SecondForClassWithLongName1 implements Iterable { + + public SecondForClassWithLongName1(String string) {} + + int getInteger(FooForClass instance, String string) { + return -1; + } + + Map getMap(FooForClass instance, int integer, String string) { + return new HashMap(); + } + + List getList(FooForClass instance, long longLong, String string) { + return new ArrayList(); + } + + public Iterator iterator() { + return null; + } + } + + class FooForClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectIfAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectIfAndParameter.java index 837c0b89dd35..2ff226031e44 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectIfAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectIfAndParameter.java @@ -1,144 +1,180 @@ -package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; //indent:0 exp:0 - -class InputIndentationCorrectIfAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - if (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondClassLongNam3("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:8 exp:8 - new InnerClassFoo())) {} //indent:8 exp:8 - - if (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondClassLongNam3("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooIfClass(), //indent:8 exp:8 - new SecondClassLongNam3("loooooooooong"). //indent:8 exp:8 - getInteger(new FooIfClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondClassLongNam3("Looooooooooooooo" //indent:8 exp:8 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondClassLongNam3(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooIfClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondClassLongNam3(getString(100000, "Loooooong" //indent:8 exp:8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:8 exp:8 - conditionNoArg() || conditionNoArg()) {} //indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondClassLongNam3 instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - if (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondClassLongNam3("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())) {} //indent:14 exp:>=10 - - if (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondClassLongNam3("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooIfClass(), //indent:10 exp:10 - new SecondClassLongNam3("loooooooooong"). //indent:10 exp:10 - getInteger(new FooIfClass(), "loooooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondClassLongNam3("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondClassLongNam3(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooIfClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondClassLongNam3(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()) {} //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooIfClass anonymousClass = new FooIfClass() { //indent:4 exp:4 - - void fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - if (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondClassLongNam3("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())) {} //indent:19 exp:>=12 - - if (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondClassLongNam3("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooIfClass(), //indent:12 exp:12 - new SecondClassLongNam3("loooooooooong"). //indent:12 exp:12 - getInteger(new FooIfClass(), "looooooooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondClassLongNam3("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondClassLongNam3(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooIfClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondClassLongNam3(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName) {} //indent:21 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassLongNam3 { //indent:0 exp:0 - - public SecondClassLongNam3(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooIfClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooIfClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooIfClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondClassLongNam3 getInstance() { //indent:2 exp:2 - return new SecondClassLongNam3("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooIfClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +class InputIndentationCorrectIfAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) { + /* foo */ + } + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondClassLongNam3 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooIfClass anonymousClass = + new FooIfClass() { + + void fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "looooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName) { + /* foo */ + } + } + }; + + void fooMethodWithIf() { + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) { + /* foo */ + } + } + } + + class SecondClassLongNam3 { + + public SecondClassLongNam3(String string) {} + + String getString(FooIfClass instance, int integer) { + return "String"; + } + + int getInteger(FooIfClass instance, String string) { + return -1; + } + + boolean getBoolean(FooIfClass instance, boolean flag) { + return false; + } + + SecondClassLongNam3 getInstance() { + return new SecondClassLongNam3("VeryLoooooooooo" + "oongString"); + } + } + + class FooIfClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectNewChildren.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectNewChildren.java new file mode 100644 index 000000000000..c040d1bedbc2 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectNewChildren.java @@ -0,0 +1,26 @@ +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +/** some javadoc. */ +public class InputIndentationCorrectNewChildren { + + private final StringBuffer filter = + new StringBuffer( + new CharSequence() { + @Override + public char charAt(int index) { + return 'A'; + } + + public int length() { + return 1; + } + + public CharSequence subSequence(int start, int end) { + return this; + } + + public String toString() { + return "Foo"; + } + }); +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectReturnAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectReturnAndParameter.java index 4f8a483598cc..8f17cfbcc2ad 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectReturnAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectReturnAndParameter.java @@ -1,143 +1,166 @@ -package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; //indent:0 exp:0 - -class InputIndentationCorrectReturnAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean fooMethodWithIf() { //indent:2 exp:2 - - return conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondClassLongNam4("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooReturnClass(), //indent:8 exp:8 - new SecondClassLongNam4("loooooooooong"). //indent:8 exp:8 - getInteger(new FooReturnClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondClassLongNam4("Looooooooooooooo" //indent:8 exp:8 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondClassLongNam4(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondClassLongNam4(getString(100000, "Loooooong" //indent:8 exp:8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:8 exp:8 - conditionNoArg() || conditionNoArg();//indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondClassLongNam4 instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - boolean fooMethodWithIf() { //indent:4 exp:4 - return conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondClassLongNam4("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooReturnClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo()); //indent:14 exp:>=10 - } //indent:4 exp:4 - - boolean fooReturn() { //indent:4 exp:4 - return conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondClassLongNam4("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooReturnClass(), //indent:10 exp:10 - new SecondClassLongNam4("loooooooooong"). //indent:10 exp:10 - getInteger(new FooReturnClass(), "looooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondClassLongNam4("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondClassLongNam4(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondClassLongNam4(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg(); //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooReturnClass anonymousClass = new FooReturnClass() { //indent:4 exp:4 - - boolean fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - return conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondClassLongNam4("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooReturnClass(), //indent:12 exp:12 - new SecondClassLongNam4("loooooooooong"). //indent:12 exp:12 - getInteger(new FooReturnClass(), "looooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondClassLongNam4("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondClassLongNam4(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondClassLongNam4(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName; //indent:21 exp:>=12 - } //indent:6 exp:6 - - boolean fooReturn() { //indent:6 exp:6 - return conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondClassLongNam4("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooReturnClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo()); //indent:19 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassLongNam4 { //indent:0 exp:0 - - public SecondClassLongNam4(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooReturnClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooReturnClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooReturnClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondClassLongNam4 getInstance() { //indent:2 exp:2 - return new SecondClassLongNam4("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooReturnClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +class InputIndentationCorrectReturnAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + boolean fooMethodWithIf() { + + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondClassLongNam4 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooReturnClass anonymousClass = + new FooReturnClass() { + + boolean fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "looooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName; + } + + boolean fooReturn() { + return conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam4("Loooooooooooooooooog") + .getInteger(new FooReturnClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + } + }; + + boolean fooMethodWithIf() { + return conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam4("Loooooooooooooooooog") + .getInteger(new FooReturnClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + } + + boolean fooReturn() { + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "looooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + } + } + + class SecondClassLongNam4 { + + public SecondClassLongNam4(String string) {} + + String getString(FooReturnClass instance, int integer) { + return "String"; + } + + int getInteger(FooReturnClass instance, String string) { + return -1; + } + + boolean getBoolean(FooReturnClass instance, boolean flag) { + return false; + } + + SecondClassLongNam4 getInstance() { + return new SecondClassLongNam4("VeryLoooooooooo" + "oongString"); + } + } + + class FooReturnClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectWhileDoWhileAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectWhileDoWhileAndParameter.java index a82cda948d3b..59a5b2e7b690 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectWhileDoWhileAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule42blockindentation/InputIndentationCorrectWhileDoWhileAndParameter.java @@ -1,221 +1,270 @@ -package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; //indent:0 exp:0 - -class InputIndentationCorrectWhileDoWhileAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - while (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondWhileLongNam1("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:11 exp:>=8 - new InnerClassFoo())) {} //indent:10 exp:>=8 - - do { //indent:4 exp:4 - - } while (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondWhileLongNam1("Loooooooooooooooooog"). //indent:9 exp:>=8 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:15 exp:>=8 - new InnerClassFoo())); //indent:9 exp:>=8 - - while (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondWhileLongNam1("Looooooooooooo" //indent:9 exp:>=8 - + "oooooooooooong").getString(new FooWhileClass(), //indent:8 exp:8 - new SecondWhileLongNam1("loooooooooong"). //indent:11 exp:>=8 - getInteger(new FooWhileClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:14 exp:>=8 - SecondWhileLongNam1("Looooooooooooooo" //indent:14 exp:>=8 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondWhileLongNam1( //indent:12 exp:>=8 - getString(2048, "Looo" //indent:12 exp:>=8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondWhileLongNam1(getString(100000, "Loooooong" //indent:11 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:10 exp:>=8 - conditionNoArg() || conditionNoArg()) {} //indent:10 exp:10 - - do { //indent:4 exp:4 - - } while (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondWhileLongNam1("Looooooooooooo" //indent:10 exp:>=8 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:>=8 - new SecondWhileLongNam1("loooooooooong"). //indent:8 exp:8 - getInteger(new FooWhileClass(), "loooooooong")), "loooooooooooong") //indent:13 exp:>=8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondWhileLongNam1("Looooooooooooooo" //indent:11 exp:>=8 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondWhileLongNam1(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondWhileLongNam1(getString(100000, "Loooooong" //indent:11 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:13 exp:>=8 - conditionNoArg() || conditionNoArg()); //indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondWhileLongNam1 instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - while (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondWhileLongNam1("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())) {} //indent:14 exp:>=10 - - do { //indent:6 exp:6 - /* Do something*/ //indent:8 exp:8 - } while (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondWhileLongNam1("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())); //indent:14 exp:>=10 - - while (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondWhileLongNam1("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:10 - new SecondWhileLongNam1("loooooooooong"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "loooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondWhileLongNam1("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondWhileLongNam1(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondWhileLongNam1(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()) {} //indent:14 exp:>=10 - - do { //indent:6 exp:6 - /* Do smth*/ //indent:8 exp:8 - } while (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondWhileLongNam1("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:10 - new SecondWhileLongNam1("loooooooooong"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "loooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondWhileLongNam1("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondWhileLongNam1(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondWhileLongNam1(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()); //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooWhileClass anonymousClass = new FooWhileClass() { //indent:4 exp:4 - - void fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - while (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondWhileLongNam1("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())) {} //indent:19 exp:>=12 - - do { //indent:8 exp:8 - /* Do smth*/ //indent:10 exp:10 - } while (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondWhileLongNam1("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())); //indent:19 exp:>=12 - - while (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondWhileLongNam1("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooWhileClass(), //indent:12 exp:12 - new SecondWhileLongNam1("loooooooooong"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "loooooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondWhileLongNam1("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondWhileLongNam1(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondWhileLongNam1(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName) {} //indent:21 exp:>=12 - - do { //indent:8 exp:8 - /* Do smth*/ //indent:10 exp:10 - } while (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondWhileLongNam1("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooWhileClass(), //indent:12 exp:12 - new SecondWhileLongNam1("loooooooooong"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "loooooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondWhileLongNam1("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondWhileLongNam1(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondWhileLongNam1(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName);//indent:21 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondWhileLongNam1 { //indent:0 exp:0 - - public SecondWhileLongNam1(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooWhileClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooWhileClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooWhileClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondWhileLongNam1 getInstance() { //indent:2 exp:2 - return new SecondWhileLongNam1("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooWhileClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule42blockindentation; + +class InputIndentationCorrectWhileDoWhileAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do {} while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) {} + + do {} while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()); + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondWhileLongNam1 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooWhileClass anonymousClass = + new FooWhileClass() { + + void fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do { + /* Do smth*/ + + } while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName) {} + + do { + /* Do smth*/ + + } while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName); + } + }; + + void fooMethodWithIf() { + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do { + /* Do something*/ + + } while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) {} + + do { + /* Do smth*/ + + } while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()); + } + } + + class SecondWhileLongNam1 { + + public SecondWhileLongNam1(String string) {} + + String getString(FooWhileClass instance, int integer) { + return "String"; + } + + int getInteger(FooWhileClass instance, String string) { + return -1; + } + + boolean getBoolean(FooWhileClass instance, boolean flag) { + return false; + } + + SecondWhileLongNam1 getInstance() { + return new SecondWhileLongNam1("VeryLoooooooooo" + "oongString"); + } + } + + class FooWhileClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputFormattedOneStatementPerLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputFormattedOneStatementPerLine.java new file mode 100644 index 000000000000..f789495f1783 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputFormattedOneStatementPerLine.java @@ -0,0 +1,220 @@ +package com.google.checkstyle.test.chapter4formatting.rule43onestatement; + +// Two import statements on the same line are illegal. + +/** Some javadoc. */ +public class InputFormattedOneStatementPerLine { + + /** Dummy variable to work on. */ + private int one = 0; + + /** Dummy variable to work on. */ + private int two = 0; + + /** Simple legal method. */ + public void doLegal() { + one = 1; + two = 2; + } + + /** The illegal format is used within a String. Therefor the whole method is legal. */ + public void doLegalString() { + one = 1; + two = 2; + System.identityHashCode("one = 1; two = 2"); + } + + /** Within the for-header there are 3 Statements, but this is legal. */ + public void doLegalForLoop() { + for (int i = 0, j = 0, k = 1; i < 20; i++) { // it's ok. + one = i; + } + } + + /** Simplest form of illegal layouts. */ + public void doIllegal() { + one = 1; + two = 2; + if (one == 1) { + one++; + two++; + } + if (one != 1) { + one++; + } else { + one--; + } + int n = 10; + + doLegal(); + doLegal(); + while (one == 1) { + one++; + two--; + } + } + + /** + * While theoretically being distributed over two lines, this is a sample of 2 statements on one + * line. + */ + public void doIllegal2() { + one = 1; + two = 2; + } + + class Inner { + /** Dummy variable to work on. */ + private int one = 0; + + /** Dummy variable to work on. */ + private int two = 0; + + /** Simple legal method. */ + public void doLegal() { + one = 1; + two = 2; + } + + /** Simplest form a an illegal layout. */ + public void doIllegal() { + one = 1; + two = 2; + if (one == 1) { + one++; + two++; + } + if (one != 1) { + one++; + } else { + one--; + } + int n = 10; + + doLegal(); + doLegal(); + while (one == 1) { + one++; + two--; + } + } + } + + /** Two declaration statements on the same line are illegal. */ + int aaaa; + + int bbb; + + /** Two declaration statements which are not on the same line are legal. */ + int ccc; + + int dddd; + + /** Two assignment (declaration) statements on the same line are illegal. */ + int dog = 1; + + int cow = 2; + + /** Two assignment (declaration) statements on the different lines are legal. */ + int test1 = 1; + + int test2 = 2; + + /** This method contains two object creation statements on the same line. */ + private void foo() { + // Two object creation statements on the same line are illegal. + Object obj1 = new Object(); + Object obj2 = new Object(); + } + + int blah; + + int seven = 2; + + /** Two statements on the same line (they both are distributed over two lines) are illegal. */ + int var6 = 5; + + /** Two statements on the same line (they both are distributed over two lines) are illegal. */ + private void foo2() { + toString(); + toString(); + } + + int var11 = 2; + + /** Multiline for loop statement is legal. */ + private void foo3() { + for (int n = 0, k = 1; n < 5; n++, k--) {} + } + + /** This method contains break and while loop statements. */ + private void foo4() { + int var9 = 0; + int var10 = 0; + + do { + var9++; + if (var10 > 4) { + break; // legal + } + var11++; + var9++; + } while (var11 < 7); // legal + + /* + * One statement inside for block is legal + */ + for (int i = 0; i < 10; i++) { + one = 5; + } // legal + + /* + * One statement inside for block where + * increment expression is empty is legal + */ + for (int i = 0; i < 10; ) { + one = 5; + } // legal + + /* + One statement inside for block where + increment and conditional expressions are empty + (forever loop) is legal + */ + for (int i = 0; ; ) { + one = 5; + } // legal + } + + /** Some javadoc. */ + public void foo5() { + // a "forever" loop. + for (; ; ) {} // legal + } + + /** Some javadoc. */ + public void foo6() { + // One statement inside for block is legal + for (; ; ) { + one = 5; + } // legal + } + + int var1 = 0; + int var2 = 0; + + /** One statement inside multiline for loop is legal. */ + private void foo7() { + for (int n = 0, k = 1; n < 5; n++, k--) { + var1++; + } // legal + } + + /** Two statements on the same lne inside multiline for loop are illegal. */ + private void foo8() { + for (int n = 0, k = 1; n < 5; n++, k--) { + var1++; + var2++; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine.java index bf77830bbd58..901afb7da6d8 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule43onestatement/InputOneStatementPerLine.java @@ -1,10 +1,10 @@ package com.google.checkstyle.test.chapter4formatting.rule43onestatement; -/** - * Two import statements on the same line are illegal. - */ -import java.io.EOFException; import java.io.BufferedReader; //warn +// Two import statements on the same line are illegal. +import java.io.BufferedReader; import java.io.EOFException; +// violation above 'Only one statement per line allowed.' +/** Some javadoc. */ public class InputOneStatementPerLine { /** @@ -38,7 +38,7 @@ public void doLegalString() { * Within the for-header there are 3 Statements, but this is legal. */ public void doLegalForLoop() { - for (int i = 0, j = 0, k = 1; i < 20; i++) { //it's ok. + for (int i = 0, j = 0, k = 1; i < 20; i++) { // it's ok. one = i; } } @@ -47,15 +47,23 @@ public void doLegalForLoop() { * Simplest form of illegal layouts. */ public void doIllegal() { - one = 1; two = 2; //warn + one = 1; two = 2; // violation 'Only one statement per line allowed.' if (one == 1) { - one++; two++; //warn + one++; two++; // violation 'Only one statement per line allowed.' } - if (one != 1) { one++; } else { one--; } //warn + if (one != 1) { one++; } else { one--; } + // 3 violations above: + // ''{' at column 19 should have line break after.' + // ''{' at column 35 should have line break after.' + // 'Only one statement per line allowed.' int n = 10; - doLegal(); doLegal(); //warn - while (one == 1) {one++; two--;} //warn + doLegal(); doLegal(); // violation 'Only one statement per line allowed.' + while (one == 1) { one++; two--; } + // 3 violations above: + // ''{' at column 22 should have line break after.' + // 'Only one statement per line allowed.' + // ''}' at column 38 should be alone on a line.' } @@ -65,117 +73,134 @@ public void doIllegal() { */ public void doIllegal2() { one = 1 - ; two = 2; //warn + ; two = 2; // violation 'Only one statement per line allowed.' } - class Inner - { - /** - * Dummy variable to work on. - */ - private int one = 0; - - /** - * Dummy variable to work on. - */ - private int two = 0; - - /** - * Simple legal method. - */ - public void doLegal() { - one = 1; - two = 2; - } + class Inner { + /** + * Dummy variable to work on. + */ + private int one = 0; - /** - * Simplest form a an illegal layout. - */ - public void doIllegal() { - one = 1; two = 2; //warn - if (one == 1) { - one++; two++; //warn - } - if (one != 1) { one++; } else { one--; } //warn - int n = 10; + /** + * Dummy variable to work on. + */ + private int two = 0; - doLegal(); doLegal(); //warn - while (one == 1) {one++; two--;} //warn + /** + * Simple legal method. + */ + public void doLegal() { + one = 1; + two = 2; + } + /** + * Simplest form a an illegal layout. + */ + public void doIllegal() { + one = 1; two = 2; // violation 'Only one statement per line allowed.' + if (one == 1) { + one++; two++; // violation 'Only one statement per line allowed.' } + if (one != 1) { one++; } else { one--; } + // 3 violations above: + // ''{' at column 21 should have line break after.' + // ''{' at column 37 should have line break after.' + // 'Only one statement per line allowed.' + int n = 10; + + doLegal(); doLegal(); // violation 'Only one statement per line allowed.' + while (one == 1) { + one++; two--; // violation 'Only one statement per line allowed.' + } + + } } /** * Two declaration statements on the same line are illegal. */ - int a; int b; //warn + int aaaa; int bbb; + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' /** * Two declaration statements which are not on the same line * are legal. */ - int c; - int d; + int ccc; + int dddd; /** * Two assignment (declaration) statements on the same line are illegal. */ - int e = 1; int f = 2; //warn + int dog = 1; int cow = 2; + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' /** * Two assignment (declaration) statements on the different lines * are legal. */ - int g = 1; - int h = 2; + int test1 = 1; + int test2 = 2; /** * This method contains * two object creation statements on the same line. */ private void foo() { - //Two object creation statements on the same line are illegal. - Object obj1 = new Object(); Object obj2 = new Object(); //warn + // Two object creation statements on the same line are illegal. + Object obj1 = new Object(); Object obj2 = new Object(); + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' } /** * One multiline assignment (declaration) statement * is legal. */ - int i = 1, j = 2, - k = 5; + int ijk = 1, jkl = 2, // violation 'Each variable declaration must be in its own statement.' + klm = 5; /** * One multiline assignment (declaration) statement * is legal. */ - int l = 1, - m = 2, - n = 5; + int lmn = 1, // violation 'Each variable declaration must be in its own statement.' + mnp = 2, + npq = 5; /** * One multiline assignment (declaration) statement * is legal. */ - int w = 1, - x = 2, - y = 5 - ; + int wxy = 1, // violation 'Each variable declaration must be in its own statement.' + xyzz = 2, + yys = 5 + ; /** * Two multiline assignment (declaration) statements * are illegal. */ - int o = 1, p = 2, - r = 5; int t; //warn + // 2 violations 3 lines below: + // 'Each variable declaration must be in its own statement.' + // 'Only one variable definition per line allowed.' + int abc = 1, pqr = 2, + xyz = 5; int blah; // violation 'Only one statement per line allowed.' /** * Two assignment (declaration) statement * which are not on the same lines and are legal. */ - int four = 1, - five = 5 - ; + int four = 1, // violation 'Each variable declaration must be in its own statement.' + five = 5 + ; int seven = 2; /** @@ -183,17 +208,23 @@ private void foo() { * (they both are distributed over two lines) * are illegal. */ + // 2 violations 3 lines below: + // 'Each variable declaration must be in its own statement.' + // 'Only one variable definition per line allowed.' int var1 = 5, - var4 = 5; int var2 = 6, - var3 = 5; //warn + var4 = 5; int var2 = 6, // violation 'Each variable declaration must be in its own statement.' + var3 = 5; // violation 'Only one statement per line allowed.' /** * Two statements on the same line * (they both are distributed over two lines) * are illegal. */ + // 2 violations 3 lines below: + // 'Only one variable definition per line allowed.' + // 'Each variable declaration must be in its own statement.' int var6 = 5; int var7 = 6, - var8 = 5; //warn + var8 = 5; // violation 'Only one statement per line allowed.' /** * Two statements on the same line @@ -203,28 +234,29 @@ private void foo() { private void foo2() { toString( - ); toString ( + ); toString(// violation ''method call' .* incorrect indentation level 4, expected .* 6.' - ); //warn + ); + // 2 violations above: + // ''method call rparen' has incorrect indentation level 8, expected level should be 4.' + // 'Only one statement per line allowed.' } - /** * While theoretically being distributed over two lines, this is a sample * of 2 statements on one line. */ - int var9 = 1, var10 = 5 - ; int var11 = 2; //warn - + int var9 = 1, var10 = 5 // violation 'Each variable declaration must be in its own statement.' + ; int var11 = 2; // violation 'Only one statement per line allowed.' /** * Multiline for loop statement is legal. */ private void foo3() { for (int n = 0, - k = 1; - n < 5; n++, - k--) { + k = 1; + n < 5; n++, + k--) { } } @@ -232,10 +264,11 @@ private void foo3() { /** * Two multiline statements (which are not on the same line) * are legal. + * Violations are not related to "OneStatementPerLine", but to "MultipleVariableDeclarations". */ - int var12, + int var12, // violation 'Each variable declaration must be in its own statement.' var13 = 12; - int var14 = 5, + int var14 = 5, // violation 'Each variable declaration must be in its own statement.' var15 = 6; /** @@ -245,65 +278,78 @@ private void foo4() { do { var9++; if (var10 > 4) { - break; //legal + break; // legal } var11++; var9++; - } while (var11 < 7); //legal + } while (var11 < 7); // legal - /** + /* * One statement inside for block is legal */ - for (int i = 0; i < 10; i++) one = 5; //legal + for (int i = 0; i < 10; i++) { one = 5; } // legal + // 2 violations above: + // ''{' at column 34 should have line break after.' + // ''}' at column 45 should be alone on a line.' - /** + /* * One statement inside for block where * increment expression is empty is legal */ - for (int i = 0; i < 10;) one = 5; //legal - - /** - * One statement inside for block where - * increment and conditional expressions are empty - * (forever loop) is legal + for (int i = 0; i < 10;) { one = 5; } // legal + // 2 violations above: + // ''{' at column 30 should have line break after.' + // ''}' at column 41 should be alone on a line.' + + /* + One statement inside for block where + increment and conditional expressions are empty + (forever loop) is legal */ - for (int i = 0;;) one = 5; //legal + for (int i = 0;;) { one = 5; } // legal + // 2 violations above: + // ''{' at column 23 should have line break after.' + // ''}' at column 34 should be alone on a line.' } + /** Some javadoc. */ public void foo5() { - /** - * a "forever" loop. - */ - for(;;){} //legal + // a "forever" loop. + for (;;){} // legal } + /** Some javadoc. */ public void foo6() { - /** - * One statement inside for block is legal - */ - for (;;) { one = 5; } //legal + // One statement inside for block is legal + for (;;) { + one = 5; + } // legal } /** * One statement inside multiline for loop is legal. */ private void foo7() { - for(int n = 0, - k = 1 - ; n<5 - ; - n++, k--) { var1++; } //legal - } + for (int n = 0, + k = 1 + ; n < 5 + ; + n++, k--) { + var1++; + } // legal + } /** * Two statements on the same lne * inside multiline for loop are illegal. */ private void foo8() { - for(int n = 0, - k = 1 - ; n<5 - ; - n++, k--) { var1++; var2++; } //warn + for (int n = 0, + k = 1 + ; n < 5 + ; + n++, k--) { + var1++; var2++; // violation 'Only one statement per line allowed.' } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputColumnLimit.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputColumnLimit.java new file mode 100644 index 000000000000..1513735e6a59 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputColumnLimit.java @@ -0,0 +1,199 @@ +package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; + +// ok above, longer package statements are allowed + +// ok below, longer imports are allowed +import com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule.PackageStatementTest; +import java.io.IOException; + +final class InputColumnLimit { + // Long line + // ---------------------------------------------------------------------------------------------------- + // violation above 'Line is longer than 100 characters (found 105).' + + PackageStatementTest pckgStmt = new PackageStatementTest(); + + private int[] testing = + new int[] { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 + // violation above 'Line is longer than 100 characters (found 105).' + }; + + /** + * Some javadoc. + * + * @param badFormat1 bad format + * @param badFormat2 bad format + * @param badFormat3 bad format + * @return hack + * @throws java.lang.Exception abc + */ + int test1(int badFormat1, int badFormat2, final int badFormat3) throws java.lang.Exception { + return 0; + } + + /** + * Some javadoc. + * Very long url with https: https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + */ + String https = "200 OK"; + + /** + * Some javadoc. + * Very long url with http: http://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + */ + String http = "200 OK"; + + // Very long url with ftp: ftp://ftp.example.com/areallyyyyyyyyyyyylongggggggggggggggggggggggurlllll.text + int ftp = 0; + + // violation below 'Line is longer than 100 characters (found 144).' + // Very long url with invalid href: href="www.google.com/search?hl=en&q=java+style+guide+checkstyle+check+href+length+limit&btnG=Google+Search + int invalidHref = 88; + + // Very long url with valid href: href="www.google.com/search?hl=en&q=java+style+guide+checkstyle+check+href+length+limit&btnG=Google+Search" + int validHref = 54; + + // Very long url with valid href: href = "www.google.com/search?hl=en&q=java+style+guide+checkstyle+check+href+length+limit&btnG=Google+Search" + int validHrefWithWhiteSpaces = 54; + + // violation below 'Line is longer than 100 characters (found 118).' + int aaaarealllllllllllllllllyyyyyyyyyyylllllllloooooooooooooooonnnnnnnnnnnnnnnnnggggggggggvvvvvvaarriaaabllee1 = 99; + + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + int aaaarealllllllllllllllllyyyyyyyyyyylllllllloooooooooooooooonnnnnnnnnnnnnnnnnggggggggggvvvvvvaarriaaabllee2 = 99; + // suppressed above. + + // violation below 'Line is longer than 100 characters (found 109).' + void longggggggggggggggggggggmethoooooooooooooooooooooodddddddddddddddddddddddddddddddddddddddddddddd1() {} + + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + void longggggggggggggggggggggmethoooooooooooooooooooooodddddddddddddddddddddddddddddddddddddddddddddd2() {} + // suppressed above. + + final boolean isValid = true; + final boolean isValid2 = true; + final boolean isValid3 = true; + final boolean isValid4 = true; + final boolean isValid5 = true; + + void testingNestedIf1() { + if (isValid) { + if (isValid2) { + if (isValid3) { + if (isValid4) { + if (isValid5) { + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + longggggggggggggggggggggmethoooooooooooooooooooooodddddddddddddddddddddddddddddddddddddddddddddd1(); + } + } + } + } + } + } + + void testingNestedIf2() { + if (isValid) { + if (isValid2) { + if (isValid3) { + if (isValid4) { + if (isValid5) { + // violation below 'Line is longer than 100 characters (found 114).' + longggggggggggggggggggggmethoooooooooooooooooooooodddddddddddddddddddddddddddddddddddddddddddddd2(); + } + } + } + } + } + } + + // violation below 'Line is longer than 100 characters (found 179).' + void testingParametersNames1(int areallllllyyyyyyyyyyyyyyyyyylonnnnggggggggggnameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, int anotherlongnameblahblahblah) {} + + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + void testingParametersNames2(int areallllllyyyyyyyyyyyyyyyyyylonnnnggggggggggnameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, int anotherlongnameblahblahblah) {} + // suppressed above. + + // violation below 'Line is longer than 100 characters (found 156).' + InputColumnLimit inputColumnLimit1 = (InputColumnLimit) ((Object) new com.google.checkstyle.test.chapter4formatting.rule44columnlimit.InputColumnLimit()); + + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + InputColumnLimit inputColumnLimit2 = (InputColumnLimit) ((Object) new com.google.checkstyle.test.chapter4formatting.rule44columnlimit.InputColumnLimit()); + // suppressed above. + // Above code is wrap-able, user should not use suppression for such cases + + void testing1() { + try { + throwExceptionBasedOnCondition1(); + // violation below 'Line is longer than 100 characters (found 111).' + } catch (IOException | NullPointerException | ArrayIndexOutOfBoundsException | ClassNotFoundException ex) { + System.out.println(ex.getMessage()); + } + } + + void testing2() { + try { + throwExceptionBasedOnCondition2(); + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + } catch (IOException | NullPointerException | ArrayIndexOutOfBoundsException | ClassNotFoundException ex) { + // Above code is wrap-able. User should not use suppression for such cases + System.out.println(ex.getMessage()); + } + } + + // violation 2 lines below 'Line is longer than 100 characters (found 104).' + void throwExceptionBasedOnCondition1() + throws IOException, NullPointerException, ArrayIndexOutOfBoundsException, ClassNotFoundException { + int condition = new java.util.Random().nextInt(3); + switch (condition) { + case 0: + throw new IOException("Test IOException"); + case 1: + throw new NullPointerException("Test NullPointerException"); + case 2: + throw new ArrayIndexOutOfBoundsException("Test ArrayIndexOutOfBoundsException"); + case 3: + throw new ClassNotFoundException("Test ClassNotFoundException"); + default: + } + } + + // CHECKSTYLE.SUPPRESS: LineLength for +2 lines + void throwExceptionBasedOnCondition2() + throws IOException, NullPointerException, ArrayIndexOutOfBoundsException, ClassNotFoundException { + // suppressed above. + // Above code is wrap-able. User should not use suppression for such cases + int condition = new java.util.Random().nextInt(3); + switch (condition) { + case 0: + throw new IOException("Test IOException"); + case 1: + throw new NullPointerException("Test NullPointerException"); + case 2: + throw new ArrayIndexOutOfBoundsException("Test ArrayIndexOutOfBoundsException"); + case 3: + throw new ClassNotFoundException("Test ClassNotFoundException"); + default: + } + } + + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + class LonggggggggggggggggggggggggggggClassssssssssssssssssssssssssNameeeeeeeeeeeeeeSoooooBoooooorrriinngggg1 { + // ok below, as it is suppressed. + void longggggggggggggggggggggmethooooooooooooooooooooooddddddddddddddddddddddddddddddddddddddddddddddddddddddd(int x, int y) {} + // CHECKSTYLE.SUPPRESS: LineLength for -1 lines + + // ok below, as it is suppressed. + int aaaarealllllllllllllllllyyyyyyyyyyylllllllloooooooooooooooonnnnnnnnnnnnnnnnnggggggggggvvvvvvaarriaaablleeeeeeeeeeee = 99; + // CHECKSTYLE.SUPPRESS: LineLength for -1 lines + } + + // violation below 'Line is longer than 100 characters (found 112).' + class LonggggggggggggggggggggggggggggClassssssssssssssssssssssssssNameeeeeeeeeeeeeeSoooooBoooooorrriinngggg2 { + // violation below 'Line is longer than 100 characters (found 131).' + void longggggggggggggggggggggmethooooooooooooooooooooooddddddddddddddddddddddddddddddddddddddddddddddddddddddd(int x, int y) {} + + // violation below 'Line is longer than 100 characters (found 129).' + int aaaarealllllllllllllllllyyyyyyyyyyylllllllloooooooooooooooonnnnnnnnnnnnnnnnnggggggggggvvvvvvaarriaaablleeeeeeeeeeee = 99; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputColumnLimitEdgeCase.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputColumnLimitEdgeCase.java new file mode 100644 index 000000000000..55f87192d03f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputColumnLimitEdgeCase.java @@ -0,0 +1,26 @@ +package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; + +/** some javadoc. */ +public class InputColumnLimitEdgeCase { + void testMethod1() { + String s3 = + "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical"; + // violation above 'Line is longer than 100 characters (found 114)' + + String s1 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical + """ + + getSampleTest(); + + String s2 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical\ + """; + } + + /** some javadoc. */ + String getSampleTest() { + return "String"; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedColumnLimit.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedColumnLimit.java new file mode 100644 index 000000000000..a183493114eb --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedColumnLimit.java @@ -0,0 +1,247 @@ +package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; + +// ok above, longer package statements are allowed + +// ok below, longer imports are allowed +import com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule.PackageStatementTest; +import java.io.IOException; + +final class InputFormattedColumnLimit { + // Long line + // ---------------------------------------------------------------------------------------------------- + // violation above 'Line is longer than 100 characters (found 105).' + + PackageStatementTest pckgStmt = new PackageStatementTest(); + + private int[] testing = + new int[] { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27 + }; + + /** + * Some javadoc. + * + * @param badFormat1 bad format + * @param badFormat2 bad format + * @param badFormat3 bad format + * @return hack + * @throws java.lang.Exception abc + */ + int test1(int badFormat1, int badFormat2, final int badFormat3) throws java.lang.Exception { + return 0; + } + + /** + * Some javadoc. Very long url with https: + * https://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + */ + String https = "200 OK"; + + /** + * Some javadoc. Very long url with http: + * http://github.com/checkstyle/checkstyle/blob/master/src/main/java/com/puppycrawl/tools/checkstyle/checks/AvoidEscapedUnicodeCharactersCheck.java + */ + String http = "200 OK"; + + // Very long url with ftp: + // ftp://ftp.example.com/areallyyyyyyyyyyyylongggggggggggggggggggggggurlllll.text + int ftp = 0; + + // violation 2 lines below 'Line is longer than 100 characters (found 111).' + // Very long url with invalid href: + // href="www.google.com/search?hl=en&q=java+style+guide+checkstyle+check+href+length+limit&btnG=Google+Search + int invalidHref = 88; + + // Very long url with valid href: + // href="www.google.com/search?hl=en&q=java+style+guide+checkstyle+check+href+length+limit&btnG=Google+Search" + int validHref = 54; + + // violation 2 lines below 'Line is longer than 100 characters (found 107).' + // Very long url with valid href: href = + // "www.google.com/search?hl=en&q=java+style+guide+checkstyle+check+href+length+limit&btnG=Google+Search" + int validHrefWithWhiteSpaces = 54; + + // violation 2 lines below 'Line is longer than 100 characters (found 114).' + int + aaaarealllllllllllllllllyyyyyyyyyyylllllllloooooooooooooooonnnnnnnnnnnnnnnnnggggggggggvvvvvvaarriaaabllee1 = + 99; + + // CHECKSTYLE.SUPPRESS: LineLength for +2 lines + int + aaaarealllllllllllllllllyyyyyyyyyyylllllllloooooooooooooooonnnnnnnnnnnnnnnnnggggggggggvvvvvvaarriaaabllee2 = + 99; + + // suppressed above. + + // violation 2 lines below 'Line is longer than 100 characters (found 108).' + void + longggggggggggggggggggggmethoooooooooooooooooooooodddddddddddddddddddddddddddddddddddddddddddddd1() {} + + // CHECKSTYLE.SUPPRESS: LineLength for +2 lines + void + longggggggggggggggggggggmethoooooooooooooooooooooodddddddddddddddddddddddddddddddddddddddddddddd2() {} + + // suppressed above. + + final boolean isValid = true; + final boolean isValid2 = true; + final boolean isValid3 = true; + final boolean isValid4 = true; + final boolean isValid5 = true; + + void testingNestedIf1() { + if (isValid) { + if (isValid2) { + if (isValid3) { + if (isValid4) { + if (isValid5) { + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + longggggggggggggggggggggmethoooooooooooooooooooooodddddddddddddddddddddddddddddddddddddddddddddd1(); + } + } + } + } + } + } + + void testingNestedIf2() { + if (isValid) { + if (isValid2) { + if (isValid3) { + if (isValid4) { + if (isValid5) { + // violation below 'Line is longer than 100 characters (found 114).' + longggggggggggggggggggggmethoooooooooooooooooooooodddddddddddddddddddddddddddddddddddddddddddddd2(); + } + } + } + } + } + } + + // violation 3 lines below 'Line is longer than 100 characters (found 118).' + void testingParametersNames1( + int + areallllllyyyyyyyyyyyyyyyyyylonnnnggggggggggnameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, + int anotherlongnameblahblahblah) {} + + // CHECKSTYLE.SUPPRESS: LineLength for +3 lines + void testingParametersNames2( + int + areallllllyyyyyyyyyyyyyyyyyylonnnnggggggggggnameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, + int anotherlongnameblahblahblah) {} + + // suppressed above. + + InputColumnLimit inputColumnLimit1 = + (InputColumnLimit) + ((Object) + new com.google.checkstyle.test.chapter4formatting.rule44columnlimit + .InputColumnLimit()); + + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + InputColumnLimit inputColumnLimit2 = + (InputColumnLimit) + ((Object) + new com.google.checkstyle.test.chapter4formatting.rule44columnlimit + .InputColumnLimit()); + + // suppressed above. + // Above code is wrap-able, user should not use suppression for such cases + + void testing1() { + try { + throwExceptionBasedOnCondition1(); + } catch (IOException + | NullPointerException + | ArrayIndexOutOfBoundsException + | ClassNotFoundException ex) { + System.out.println(ex.getMessage()); + } + } + + void testing2() { + try { + throwExceptionBasedOnCondition2(); + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + } catch (IOException + | NullPointerException + | ArrayIndexOutOfBoundsException + | ClassNotFoundException ex) { + // Above code is wrap-able. User should not use suppression for such cases + System.out.println(ex.getMessage()); + } + } + + void throwExceptionBasedOnCondition1() + throws IOException, + NullPointerException, + ArrayIndexOutOfBoundsException, + ClassNotFoundException { + int condition = new java.util.Random().nextInt(3); + switch (condition) { + case 0: + throw new IOException("Test IOException"); + case 1: + throw new NullPointerException("Test NullPointerException"); + case 2: + throw new ArrayIndexOutOfBoundsException("Test ArrayIndexOutOfBoundsException"); + case 3: + throw new ClassNotFoundException("Test ClassNotFoundException"); + default: + } + } + + // CHECKSTYLE.SUPPRESS: LineLength for +2 lines + void throwExceptionBasedOnCondition2() + throws IOException, + NullPointerException, + ArrayIndexOutOfBoundsException, + ClassNotFoundException { + // suppressed above. + // Above code is wrap-able. User should not use suppression for such cases + int condition = new java.util.Random().nextInt(3); + switch (condition) { + case 0: + throw new IOException("Test IOException"); + case 1: + throw new NullPointerException("Test NullPointerException"); + case 2: + throw new ArrayIndexOutOfBoundsException("Test ArrayIndexOutOfBoundsException"); + case 3: + throw new ClassNotFoundException("Test ClassNotFoundException"); + default: + } + } + + // CHECKSTYLE.SUPPRESS: LineLength for +1 lines + class LonggggggggggggggggggggggggggggClassssssssssssssssssssssssssNameeeeeeeeeeeeeeSoooooBoooooorrriinngggg1 { + // ok below, as it is suppressed. + void + longggggggggggggggggggggmethooooooooooooooooooooooddddddddddddddddddddddddddddddddddddddddddddddddddddddd( + int x, int y) {} + + // CHECKSTYLE.SUPPRESS: LineLength for -3 lines + + // ok below, as it is suppressed. + // violation 4 lines below '.* indentation should be the same level as line 231.' + int + aaaarealllllllllllllllllyyyyyyyyyyylllllllloooooooooooooooonnnnnnnnnnnnnnnnnggggggggggvvvvvvaarriaaablleeeeeeeeeeee = + 99; + // CHECKSTYLE.SUPPRESS: LineLength for -2 lines + } + + // violation below 'Line is longer than 100 characters (found 112).' + class LonggggggggggggggggggggggggggggClassssssssssssssssssssssssssNameeeeeeeeeeeeeeSoooooBoooooorrriinngggg2 { + // violation 2 lines below 'Line is longer than 100 characters (found 114).' + void + longggggggggggggggggggggmethooooooooooooooooooooooddddddddddddddddddddddddddddddddddddddddddddddddddddddd( + int x, int y) {} + + // violation 2 lines below 'Line is longer than 100 characters (found 125).' + int + aaaarealllllllllllllllllyyyyyyyyyyylllllllloooooooooooooooonnnnnnnnnnnnnnnnnggggggggggvvvvvvaarriaaablleeeeeeeeeeee = + 99; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedColumnLimitEdgeCase.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedColumnLimitEdgeCase.java new file mode 100644 index 000000000000..1e73215bb58e --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedColumnLimitEdgeCase.java @@ -0,0 +1,26 @@ +package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; + +/** some javadoc. */ +public class InputFormattedColumnLimitEdgeCase { + void testMethod1() { + String s3 = + "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece" + + " of classical"; + + String s1 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical + """ + + getSampleTest(); + + String s2 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical\ + """; + } + + /** some javadoc. */ + String getSampleTest() { + return "String"; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedTextBlockColumnLimit.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedTextBlockColumnLimit.java new file mode 100644 index 000000000000..26b0b92b5f56 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputFormattedTextBlockColumnLimit.java @@ -0,0 +1,64 @@ +package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; + +/** somejavadoc. */ +public class InputFormattedTextBlockColumnLimit { + static final String SAMPLE = + """ + locationId,label,regionId,regionLabel,vendorId,vendorLabel,address,address2,city,stateProvinceCode,zipCode,countryCode,latitude,longitude + ST001,Station 001,ZONE1,Zone 1,CP1,Competitor 1,123 Street,Unit 2,Houston,TX,77033,US,29.761496813335178,-95.53049214204984 + ST002,Station 002,ZONE2,,CP2,,668 Street,Unit 23,San Jose,CA,95191,US,37.35102477242508,-121.9209934020318 + """; + + /** somejavadoc. */ + public static void main(String[] args) { + String textBlock = + """ + This STRing will exceed the column limit of 100 but checktyle will not show many error because it is allowed + Random String + google config allows text block to exceed limit of 100 line length. it improves readability and stuff. + same is true for this line also. same is true for this line as well. same is true for this line too. + one more Random String. + """; + + String textblock2 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """; + + String textblock3 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """; + + String textblock4 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """ + + getSampleTest(); + + String textblock5 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """ + + "end."; + + String textblock6 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """ + + getSampleTest(); + + String textblock7 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC\ + """; + + String normalString = + "a very long string is heavy to parse and takes so much processing power. it is not ideal" + + " to make long strings"; + } + + public static String getSampleTest() { + return "sampleTest"; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputLineLength.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputLineLength.java deleted file mode 100644 index 10b58219e00f..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputLineLength.java +++ /dev/null @@ -1,211 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; //ok -import com.google.checkstyle.test.chapter3filestructure.toolongpackagetotestcoveragegooglesjavastylerule.*; //ok -final class InputLineLength -{ - // Long line ---------------------------------------------------------------------------------------- //warn - // Contains a tab -> <- - // Contains trailing whitespace -> - - // Name format tests - // - /** Invalid format **/ - public static final int badConstant = 2; - /** Valid format **/ - public static final int MAX_ROWS = 2; - - /** Invalid format **/ - private static int badStatic = 2; - /** Valid format **/ - private static int sNumCreated = 0; - - /** Invalid format **/ - private int badMember = 2; - /** Valid format **/ - private int mNumCreated1 = 0; - /** Valid format **/ - protected int mNumCreated2 = 0; - - /** commas are wrong **/ - private int[] mInts = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, }; //warn - - // - // Accessor tests - // - /** should be private **/ - public static int sTest1; - /** should be private **/ - protected static int sTest3; - /** should be private **/ - static int sTest2; - - /** should be private **/ - int mTest1; - /** should be private **/ - public int mTest2; - - // - // Parameter name format tests - // - - /** - * @return hack - * @param badFormat1 bad format - * @param badFormat2 bad format - * @param badFormat3 bad format - * @throws java.lang.Exception abc - **/ - int test1(int badFormat1,int badFormat2, - final int badFormat3) - throws java.lang.Exception - { - return 0; - } - - /** method that is 20 lines long **/ - private void longMethod() - { - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - } - - /** constructor that is 10 lines long **/ - private InputLineLength() - { - // a line - // a line - // a line - // a line - // a line - // a line - // a line - // a line - } - - /** test local variables */ - private void localVariables() - { - // normal decl - int abc = 0; - int ABC = 0; - - // final decls - final int cde = 0; - final int CDE = 0; - - // decl in for loop init statement - for (int k = 0; k < 1; k++) - { - String innerBlockVariable = ""; - } - for (int I = 0; I < 1; I++) - { - String InnerBlockVariable = ""; - } - } - - /** test method pattern */ - void ALL_UPPERCASE_METHOD() - { - } - - /** test illegal constant **/ - private static final int BAD__NAME = 3; - - // A very, very long line that is OK because it matches the regexp "^.*is OK.*regexp.*$" - // long line that has a tab -> <- and would be OK if tab counted as 1 char - // tabs that count as one char because of their position -> <- -> <-, OK - - /** some lines to test the column after tabs */ - void violateColumnAfterTabs() - { - // with tab-width 8 all statements below start at the same column, - // with different combinations of ' ' and '\t' before the statement - int tab0 =1; - int tab1 =1; - int tab2 =1; - int tab3 =1; - int tab4 =1; - int tab5 =1; - } - - // MEMME: - /* MEMME: a - * MEMME: - * OOOO - */ - /* NOTHING */ - /* YES */ /* MEMME: x */ /* YES!! */ - - /** test long comments **/ - void veryLong() - { - /* - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - blah blah blah blah - enough talk */ - } - - /** - * @see to lazy to document all args. Testing excessive # args - **/ - void toManyArgs(int aArg1, int aArg2, int aArg3, int aArg4, int aArg5, - int aArg6, int aArg7, int aArg8, int aArg9) - { - } -} - -/** Test class for variable naming in for each clauses. */ -class InputSimple2 -{ - /** Some more Javadoc. */ - public void doSomething() - { - //"O" should be named "o" - for (Object O : new java.util.ArrayList()) - { - - } - } -} - -/** Test enum for member naming check */ -enum MyEnum1 -{ - /** ABC constant */ - ABC, - - /** XYZ constant */ - XYZ; - - /** Should be mSomeMember */ - private int someMember; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputTextBlockColumnLimit.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputTextBlockColumnLimit.java new file mode 100644 index 000000000000..a54ff7954149 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule44columnlimit/InputTextBlockColumnLimit.java @@ -0,0 +1,57 @@ +package com.google.checkstyle.test.chapter4formatting.rule44columnlimit; + +/** somejavadoc. */ +public class InputTextBlockColumnLimit { + static final String SAMPLE = """ + locationId,label,regionId,regionLabel,vendorId,vendorLabel,address,address2,city,stateProvinceCode,zipCode,countryCode,latitude,longitude + ST001,Station 001,ZONE1,Zone 1,CP1,Competitor 1,123 Street,Unit 2,Houston,TX,77033,US,29.761496813335178,-95.53049214204984 + ST002,Station 002,ZONE2,,CP2,,668 Street,Unit 23,San Jose,CA,95191,US,37.35102477242508,-121.9209934020318 + """; + + /** somejavadoc. */ + public static void main(String[] args) { + String textBlock = """ + This STRing will exceed the column limit of 100 but checktyle will not show many error because it is allowed + Random String + google config allows text block to exceed limit of 100 line length. it improves readability and stuff. + same is true for this line also. same is true for this line as well. same is true for this line too. + one more Random String. + """; + + String textblock2 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """; + + String textblock3 = """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """; + + String textblock4 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """ + getSampleTest(); + + String textblock5 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """ + "end."; + + String textblock6 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC. + """ + + getSampleTest(); + + String textblock7 = + """ + Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC"""; + + String normalString = "a very long string is heavy to parse and takes so much processing power. it is not ideal to make long strings"; + // false negative above, ok until #17707 + } + + public static String getSampleTest() { + return "sampleTest"; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedIllegalLineBreakAroundLambda.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedIllegalLineBreakAroundLambda.java new file mode 100644 index 000000000000..8922bad7463c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedIllegalLineBreakAroundLambda.java @@ -0,0 +1,71 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +import java.util.ArrayList; + +/** some javadoc. */ +public class InputFormattedIllegalLineBreakAroundLambda { + + private interface MyLambdaInterface { + int foo(int a, int b); + } + + void test() { + MyLambdaInterface div = + (a, b) -> { + if (b != 0) { + return a / b; + } + return 0; + }; + + MyLambdaInterface div2 = + (ab, bc) -> { + if (ab != 0) { + return ab / 2; + } + return 0; + }; + + MyLambdaInterface div3 = + (ab, bc) -> { + if (ab != 0) { + return ab / 2; + } + return 0; + }; + } + + void test2(int day) { + ArrayList list = new ArrayList<>(); + list.stream().map(x -> x.toString()); + + String dayString = + switch (day) { + case 1 -> "one day of the week"; + case 2 -> "two day of the week"; + case 3 -> "third day of the week"; + default -> throw new IllegalArgumentException(); + }; + } + + void test3(TransactionStatus transaction) { + String status = + switch (transaction) { + case TransactionIsComplete -> "ok done"; + case NotValidTryAgain -> + "Please Enter the valid value. Try again this time with valid value"; + case CouldNotBeginTheProcess -> "Please try again after some time. Downtime."; + case ErrorInProcessingTryAgain -> + "Please try again after some time. you made a mistake or there is something wrong."; + default -> throw new IllegalArgumentException(""); + }; + } + + /** some javadoc. */ + public enum TransactionStatus { + NotValidTryAgain, + ErrorInProcessingTryAgain, + TransactionIsComplete, + CouldNotBeginTheProcess + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedLambdaBodyWrap.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedLambdaBodyWrap.java new file mode 100644 index 000000000000..1e2c02164af9 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedLambdaBodyWrap.java @@ -0,0 +1,67 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +import java.util.Arrays; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; + +/** Some javdoc. */ +public class InputFormattedLambdaBodyWrap { + + private List names = Arrays.asList("Alice", "Bob", "Charlie"); + + private BiFunction add = (a, b) -> a + b; + + private Supplier getMessage = () -> "Hello, world!"; + + private void printNames() { + names.forEach(name -> System.out.println(name)); + } + + private void runTask() { + Runnable runTask = + () -> { + System.out.println("Starting task"); + System.out.println("Task completed"); + }; + } + + private void executeNestedLambda() { + Function, Integer> applyFunc = f -> f.apply(5); + System.out.println(applyFunc.apply(x -> x * x)); + } + + private void sumOfSquares() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + int sum = numbers.stream().filter(n -> n % 2 == 1).mapToInt(n -> n * n).sum(); + } + + private void showComplexNestedLambda() { + // terminology: () - parentheses, [] - brackets, {} - braces + // Code below is definitely "unbraced expression" and it is single (but not a single-line), + // fact that is parentheses-ed is still definition of single. + // Multiple expressions will imply curly braces and `;`. + // so case below is ok + Function> createAdder = x -> (y -> x + y); + } + + private void foo() { + BiFunction r = + (String label, Long value) -> { + return value; + }; + + java.util.function.Predicate predicate = + str -> { + return str.isEmpty(); + }; + + Function> s = + (String label) -> { + return (a, b) -> { + return a + " " + b; + }; + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedMethodParamPad.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedMethodParamPad.java new file mode 100644 index 000000000000..bf9a2f93eea2 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedMethodParamPad.java @@ -0,0 +1,137 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +import java.util.HashMap; +import java.util.Map; + +class InputFormattedMethodParamPad { + class Inner { + void testGenerics1() { + Comparable c = new String(); + Map map = new HashMap(); + boolean flag = false; + + int init = 9; + } + } + + Inner anon = + new Inner() { + void testGenerics1() { + Comparable c = new String(); + Map map = new HashMap(); + boolean flag = false; + int init = 9; + } + }; +} + +// violation below 'Top-level class ExtraAsInput1 has to reside in its own source file.' +class ExtraAsInput1 { + int abc = 0; + String string = "string"; + double pi = 3.1415; +} + +// violation below 'Top-level class ExtraTernary2 has to reside in its own source file.' +class ExtraTernary2 { + void foo() { + boolean flag = true; + int i2 = flag == true ? 1 : 2; + int i3 = flag == true ? 1 : 2; + } +} + +// violation below 'Top-level class ExtraAssignClass3 has to reside in its own source file.' +class ExtraAssignClass3 { + void foo() { + int i = 0; + int j = 0; + i += 1; + j += 2; + i -= 1; + j -= 2; + i /= 1; + j /= 2; + i *= 1; + j *= 2; + i %= 1; + j %= 2; + i ^= 1; + j ^= 2; + i |= 1; + j |= 2; + i &= 1; + j &= 2; + i >>= 1; + j >>= 2; + i >>>= 1; + j >>>= 2; + i <<= 1; + j <<= 2; + } + + class InnerClass { + void foo() { + int i = 0; + int j = 0; + i += 1; + j += 2; + i -= 1; + j -= 2; + i /= 1; + j /= 2; + i *= 1; + j *= 2; + i %= 1; + j %= 2; + i ^= 1; + j ^= 2; + i |= 1; + j |= 2; + i &= 1; + j &= 2; + i >>= 1; + j >>= 2; + i >>>= 1; + j >>>= 2; + i <<= 1; + j <<= 2; + } + } + + InnerClass anon = + new InnerClass() { + void foo() { + int i = 0; + int j = 0; + i += 1; + j += 2; + i -= 1; + j -= 2; + i /= 1; + j /= 2; + i *= 1; + j *= 2; + i %= 1; + j %= 2; + i ^= 1; + j ^= 2; + i |= 1; + j |= 2; + i &= 1; + j &= 2; + i >>= 1; + j >>= 2; + i >>>= 1; + j >>>= 2; + i <<= 1; + j <<= 2; + } + }; + + enum TestEnum { + FIRST() {}, + + SECOND() {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedNoWrappingAfterRecordName.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedNoWrappingAfterRecordName.java new file mode 100644 index 000000000000..0b00f2070f40 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedNoWrappingAfterRecordName.java @@ -0,0 +1,60 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +/** Some javadoc. */ +public record InputFormattedNoWrappingAfterRecordName(String name) { + record Multi(String main, Record rec) { + private static boolean isSent(Object obj) { + int value = 0; + if (obj instanceof Integer i) { + value = i; + } + return value > 10; + } + } + + record Multi2() { + Multi2(String s1, String s2, String s3) { + this(); + } + } + + record Multi3(Integer i, Integer node) { + public static void main(String... args) { + System.out.println("works!"); + } + } + + record Multi4() { + void foo() {} + } + + record Multi5() { + private static final Multi obj = new Multi("my string", new Multi4()); + } + + record Multi6() { + + public static final Multi obj = new Multi("hello", new Multi4()); + } + + class MyTestClass { + private final Multi obj = new Multi("my string", new Multi4()); + } + + /** + * Maps the ports. + * + * @param from the from param + */ + record Mapping(String from) { + + /** + * The constructor for Mapping. + * + * @param from The source + */ + Mapping(String from) { + this.from = from; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedNoWrappingAfterRecordName2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedNoWrappingAfterRecordName2.java new file mode 100644 index 000000000000..0cda847b535d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedNoWrappingAfterRecordName2.java @@ -0,0 +1,72 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +/** Some javadoc. */ +public class InputFormattedNoWrappingAfterRecordName2 { + + @interface InSize { + int limit(); + } + + @InSize(limit = 2) + record MyRecord(String main, Record rec) { + private static boolean isSent(Object obj) { + int value = 0; + if (obj instanceof Integer i) { + value = i; + } + return value > 10; + } + } + + record Multi2() { + + @InSize(limit = 2) + public Multi2(String s1, String s2, String s3) { + this(); + } + } + + record Multi3(Integer i, Integer node) { + public static void main(String... args) { + System.out.println("works!"); + } + } + + record Multi4() { + + @InSize(limit = 2) + void foo() {} + } + + record Multi5() { + private static final MyRecord object = new MyRecord("my string", new Multi4()); + } + + record Multi6() { + + public static final MyRecord obj = new MyRecord("hello", new Multi4()); + } + + class MyTestClass { + private final MyRecord obj = new MyRecord("my string", new Multi4()); + } + + /** + * Maps the ports. + * + * @param from the from param + */ + @InSize(limit = 2) + record Mapping(String from) { + + /** + * The constructor for Mapping. + * + * @param from The source + */ + @InSize(limit = 3) + Mapping(String from) { + this.from = from; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedOperatorWrap.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedOperatorWrap.java new file mode 100644 index 000000000000..b7d7e62058e5 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedOperatorWrap.java @@ -0,0 +1,206 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +class InputFormattedOperatorWrap { + void test() { + int x = 1 + 2 - 3 - 4; + x = x + 2; + boolean y = true && false; + y = true && false; + y = false && true; + /* Note: The three tests below will be used when issue #3381 is closed */ + Arrays.sort(null, String::compareToIgnoreCase); + Arrays.sort(null, String::compareToIgnoreCase); + Arrays.sort(null, String::compareToIgnoreCase); + } + + void testAssignment() { + int x = 0; + int y = 0; + } + + void testGenerics1() { + Comparable c = new String(); + Map map = new HashMap(); + + boolean flag = false; + + int init = 9; + + for (Map.Entry entry : map.entrySet()) { + int i = flag == true ? 1 : 2; + } + + if (init != 9) { + /* ignore */ + } + + while (init == 10) {} + + if (init > 10) { + /* ignore */ + } + + while (init < 10 || !flag) {} + } + + class Inner { + void testGenerics1() { + Comparable c = new String(); + Map map = new HashMap(); + boolean flag = false; + + int init = 9; + + for (Map.Entry entry : map.entrySet()) { + int i = flag == true ? 1 : 2; + } + + if (init != 9) { + /* ignore */ + } + + while (init == 10) {} + + if (init > 10) { + /* ignore */ + } + + while (init < 10 || !flag) {} + } + } + + Inner anon = + new Inner() { + void testGenerics1() { + Comparable c = new String(); + Map map = new HashMap(); + boolean flag = false; + int init = 9; + + for (Map.Entry entry : map.entrySet()) { + int i = flag == true ? 1 : 2; + } + + if (init != 9) { + /* ignore */ + } + + while (init == 10) {} + + if (init > 10) { + /* ignore */ + } + + while (init < 10 || !flag) {} + } + }; + + class AsInput { + int abc = 0; + String string = "string"; + double pi = 3.1415; + } + + class Ternary { + void foo() { + boolean flag = true; + int i = flag == true ? 1 : 2; + int i2 = flag == true ? 1 : 2; + int i3 = flag == true ? 1 : 2; + } + } + + class AssignClass { + void foo() { + int i = 0; + int j = 0; + i += 1; + j += 2; + i -= 1; + j -= 2; + i /= 1; + j /= 2; + i *= 1; + j *= 2; + i %= 1; + j %= 2; + i ^= 1; + j ^= 2; + i |= 1; + j |= 2; + i &= 1; + j &= 2; + i >>= 1; + j >>= 2; + i >>>= 1; + j >>>= 2; + i <<= 1; + j <<= 2; + } + + class InnerClass { + void foo() { + int i = 0; + int j = 0; + i += 1; + j += 2; + i -= 1; + j -= 2; + i /= 1; + j /= 2; + i *= 1; + j *= 2; + i %= 1; + j %= 2; + i ^= 1; + j ^= 2; + i |= 1; + j |= 2; + i &= 1; + j &= 2; + i >>= 1; + j >>= 2; + i >>>= 1; + j >>>= 2; + i <<= 1; + j <<= 2; + } + } + + InnerClass anon = + new InnerClass() { + void foo() { + int i = 0; + int j = 0; + i += 1; + j += 2; + i -= 1; + j -= 2; + i /= 1; + j /= 2; + i *= 1; + j *= 2; + i %= 1; + j %= 2; + i ^= 1; + j ^= 2; + i |= 1; + j |= 2; + i &= 1; + j &= 2; + i >>= 1; + j >>= 2; + i >>>= 1; + j >>>= 2; + i <<= 1; + j <<= 2; + } + }; + + void testWrapBeforeOperator() {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrap.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrap.java new file mode 100644 index 000000000000..21fa0f581d8a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrap.java @@ -0,0 +1,41 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +/** Some javadoc. */ +public class InputFormattedSeparatorWrap { + /** Some javadoc. */ + public void goodCase() { + int i = 0; + String s = "ffffooooString"; + s.isEmpty(); + s.isEmpty(); + + foo(i, s); + } + + /** Some javadoc. */ + public static void foo(int i, String s) {} +} + +// violation below 'Top-level class ExtraBadCase has to reside in its own source file.' +class ExtraBadCase { + + public void goodCase(int... foo) { + int i = 0; + + String s = "ffffooooString"; + boolean b = s.isEmpty(); + foo(i, s); + int[] j; + } + + public static String foo(int i, String s) { + String maxLength = "123"; + int truncationLength = 1; + CharSequence seq = null; + Object truncationIndicator = null; + return new StringBuilder(maxLength) + .append(seq, 0, truncationLength) + .append(truncationIndicator) + .toString(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapArrayDeclarator.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapArrayDeclarator.java new file mode 100644 index 000000000000..97445afc000f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapArrayDeclarator.java @@ -0,0 +1,8 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +class InputFormattedSeparatorWrapArrayDeclarator { + + protected int[] arrayDeclarationWithGoodWrapping = new int[] {1, 2}; + + protected int[] arrayDeclarationWithBadWrapping = new int[] {1, 2}; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapComma.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapComma.java new file mode 100644 index 000000000000..408ee420b69b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapComma.java @@ -0,0 +1,43 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +/** Some javadoc. */ +public class InputFormattedSeparatorWrapComma { + /** Some javadoc. */ + public void goodCase() { + int i = 0; + String s = "ffffooooString"; + s.isEmpty(); + s.isEmpty(); + + foo(i, s); + } + + /** Some javadoc. */ + public static void foo(int i, String s) {} +} + +// violation below 'Top-level class ExtraBadCaseComma has to reside in its own source file.' +class ExtraBadCaseComma { + + /** Some javadoc. */ + public void goodCase(int... foo) { + int i = 0; + + String s = "ffffooooString"; + boolean b = s.isEmpty(); + foo(i, s); + int[] j; + } + + /** Some javadoc. */ + public static String foo(int i, String s) { + String maxLength = "123"; + int truncationLength = 1; + CharSequence seq = null; + Object truncationIndicator = null; + return new StringBuilder(maxLength) + .append(seq, 0, truncationLength) + .append(truncationIndicator) + .toString(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapEllipsis.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapEllipsis.java new file mode 100644 index 000000000000..1bedbc460353 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapEllipsis.java @@ -0,0 +1,8 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +class InputFormattedSeparatorWrapEllipsis { + + public void testMethodWithGoodWrapping(String... parameters) {} + + public void testMethodWithBadWrapping(String... parameters) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapMethodRef.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapMethodRef.java new file mode 100644 index 000000000000..1d14b2a01727 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputFormattedSeparatorWrapMethodRef.java @@ -0,0 +1,21 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +import java.util.Arrays; + +/** Some javdoc. */ +public class InputFormattedSeparatorWrapMethodRef { + + void goodCase() { + String[] stringArray = { + "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" + }; + Arrays.sort(stringArray, String::compareToIgnoreCase); + } + + void badCase() { + String[] stringArray = { + "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" + }; + Arrays.sort(stringArray, String::compareToIgnoreCase); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputIllegalLineBreakAroundLambda.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputIllegalLineBreakAroundLambda.java new file mode 100644 index 000000000000..c0a5e37b8afd --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputIllegalLineBreakAroundLambda.java @@ -0,0 +1,80 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +import java.util.ArrayList; + +/** some javadoc. */ +public class InputIllegalLineBreakAroundLambda { + + private interface MyLambdaInterface { + int foo(int a, int b); + } + + void test() { + MyLambdaInterface div = (a, b) + -> { // illegal line break before lambda, ok until #17253 + if (b != 0) { + return a / b; + } + return 0; + }; + + // violation 2 lines below ''{' at column 7 should be on the previous line.' + MyLambdaInterface div2 = (ab, bc) -> + { + if (ab != 0) { + return ab / 2; + } + return 0; + }; + + MyLambdaInterface div3 = (ab, bc) -> { + if (ab != 0) { + return ab / 2; + } + return 0; + }; + } + + void test2(int day) { + ArrayList list = new ArrayList<>(); + list.stream() + .map(x + -> x.toString()); // illegal line break before lambda, ok until #17253 + + String dayString = switch (day) { + case 1 + -> "one day of the week"; // illegal line break before lambda, ok until #17253 + case 2 + -> // illegal line break before lambda, ok until #17253 + "two day of the week"; + case 3 -> // ok because text following '->' is unbraced. + "third day of the week"; + default -> // ok because text following '->' is unbraced. + throw new IllegalArgumentException(); + }; + } + + void test3(TransactionStatus transaction) { + String status = switch (transaction) { + case TransactionIsComplete -> "ok done"; + case NotValidTryAgain + -> // illegal line break before lambda, ok until #17253 + "Please Enter the valid value. Try again this time with valid value"; + case CouldNotBeginTheProcess -> + "Please try again after some time. Downtime."; + case ErrorInProcessingTryAgain + -> "Please try again after some time. you made a mistake or there is something wrong."; + // illegal line break before lambda above, ok until #17253 + default -> + throw new IllegalArgumentException(""); + }; + } + + /** some javadoc. */ + public enum TransactionStatus { + NotValidTryAgain, + ErrorInProcessingTryAgain, + TransactionIsComplete, + CouldNotBeginTheProcess + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputLambdaBodyWrap.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputLambdaBodyWrap.java new file mode 100644 index 000000000000..3eaa35d7c145 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputLambdaBodyWrap.java @@ -0,0 +1,88 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +import java.util.Arrays; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; + +/** Some javdoc. */ +public class InputLambdaBodyWrap { + + private List names = Arrays.asList("Alice", "Bob", "Charlie"); + + private BiFunction add = (a, b) -> a + b; + + private Supplier getMessage = + () -> + + "Hello, world!"; + + private void printNames() { + names.forEach(name -> System.out.println(name)); + } + + private void runTask() { + Runnable runTask = () + -> { + System.out.println("Starting task"); + System.out.println("Task completed"); + }; + } + + private void executeNestedLambda() { + Function, Integer> applyFunc = f -> f.apply(5); + System.out.println( + applyFunc.apply( + x -> + x * x)); + } + + private void sumOfSquares() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + int sum = + numbers.stream() + .filter(n -> n % 2 == 1) + .mapToInt( + n -> + n * n) + .sum(); + } + + private void showComplexNestedLambda() { + // terminology: () - parentheses, [] - brackets, {} - braces + // Code below is definitely "unbraced expression" and it is single (but not a single-line), + // fact that is parentheses-ed is still definition of single. + // Multiple expressions will imply curly braces and `;`. + // so case below is ok + Function> createAdder = + x -> + (y -> + x + y); + } + + private void foo() { + BiFunction r = + (String label, Long value) -> { + return value; + }; + + // violation 3 lines below ''{' at column 11 should be on the previous line.' + java.util.function.Predicate predicate = str + -> + { + return str.isEmpty(); + }; + + // violation 3 lines below ''{' at column 11 should be on the previous line.' + Function> s = + (String label) -> + { + return (a, b) -> + { + return a + " " + b; + }; + }; + // violation 4 lines above ''{' at column 15 should be on the previous line.' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputMethodParamPad.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputMethodParamPad.java index 1326477d75cb..4037cf663013 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputMethodParamPad.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputMethodParamPad.java @@ -3,360 +3,201 @@ import java.util.HashMap; import java.util.Map; -class InputMethodParamPad -{ - void test() - { - int x = 1 + - 2 - - 3 - - - 4; - x = x + 2; - boolean y = true - && - false; - y = true && - false; - y = false - && true; +class InputMethodParamPad { + class Inner { + void testGenerics1 + () { // violation ''(' should be on the previous line.' + Comparable + < + String + > + c = new String(); + Map map = new HashMap(); + boolean flag = false; + + int init = 9; } + } - void testAssignment() - { - int x - = 0; - int y = - 0; - } - - < - T extends Comparable & - java.io.Serializable - > - void testGenerics1() - { - Comparable - < - String - > - c = new String(); - Map map = new HashMap(); - - boolean flag = false; - - int init = 9; - - /*ok*/ for (Map.Entry entry : - map.entrySet()) - { - int i = flag == true ? - 1 : 2; - } - - if (init != - 9) - { - - } - - while (init == - 10) - { - - } - - if (init > - 10) - { - - } else {} - - while (init < 10 || - !flag) { - - } - } - - class Inner { - void testGenerics1 - () //warn - { - Comparable - < - String - > - c = new String(); - Map map = new HashMap(); - boolean flag = false; - - int init = 9; - - /*ok*/ for (Map.Entry entry : - map.entrySet()) - { - int i = flag == true ? - 1 : 2; - } - - if (init != - 9) - { - - } - - while (init == - 10) - { - - } - - if (init > - 10) - { - - } else {} - - while (init < 10 || - !flag) { - - } - } - } - - Inner anon = new Inner - (){ //warn + Inner anon = new Inner + () { + // 2 violations above: + // ''new lparen' has incorrect indentation level 6, expected level should be 2.' + // ''(' should be on the previous line.' void testGenerics1 - () //warn - { - Comparable - < - String - > - c = new String(); - Map map = new HashMap(); - boolean flag = false; - int init = 9; - - /*ok*/ for (Map.Entry entry : - map.entrySet()) - { - int i = flag == true ? - 1 : 2; - } - - if (init != - 9) - { - - } - - while (init == - 10) - { - - } - - if (init > - 10) - { - - } else {} - - while (init < 10 || - !flag) { - - } + () { // violation ''(' should be on the previous line.' + Comparable + < + String + > + c = new String(); + Map map = new HashMap(); + boolean flag = false; + int init = 9; } - }; + }; } +// violation below 'Top-level class AsInput1 has to reside in its own source file.' class AsInput1 { - int abc = 0; - String string - = "string"; - double PI = // ok - 3.1415; + int abc = 0; + String string + = "string"; + double pi = + 3.1415; } +// violation below 'Top-level class Ternary2 has to reside in its own source file.' class Ternary2 { - void foo() { - boolean flag = true; - int i = flag == true ? - 1 : - 2; - int i2 = flag == true - ? - 1 - : - 2; - int i3 = flag == true - ? 1 - : 2; - - } + void foo() { + boolean flag = true; + int i2 = flag == true + ? + 1 + : + 2; + int i3 = flag == true + ? 1 + : 2; + } } +// violation below 'Top-level class AssignClass3 has to reside in its own source file.' class AssignClass3 { + void foo() { + int i = 0; + int j = 0; + i += + 1; + j + += 2; + i -= + 1; + j + -= 2; + i /= + 1; + j + /= 2; + i *= + 1; + j + *= 2; + i %= + 1; + j + %= 2; + i ^= + 1; + j + ^= 2; + i |= + 1; + j + |= 2; + i &= + 1; + j + &= 2; + i >>= + 1; + j + >>= 2; + i >>>= + 1; + j + >>>= 2; + i <<= + 1; + j + <<= 2; + } + + class InnerClass { void foo() { - int i = 0; - int j = 0; - i += - 1; - j - += 2; - i -= - 1; - j - -= 2; - i /= - 1; - j - /= 2; - i *= - 1; - j - *= 2; - i %= - 1; - j - %= 2; - i ^= - 1; - j - ^= 2; - i |= - 1; - j - |= 2; - i &= - 1; - j - &= 2; - i >>= - 1; - j - >>= 2; - i >>>= - 1; - j - >>>= 2; - i <<= - 1; - j - <<= 2; - } - - class InnerClass { - void foo() { - int i = 0; - int j = 0; - i += - 1; - j - += 2; - i -= - 1; - j - -= 2; - i /= - 1; - j - /= 2; - i *= - 1; - j - *= 2; - i %= - 1; - j - %= 2; - i ^= - 1; - j - ^= 2; - i |= - 1; - j - |= 2; - i &= - 1; - j - &= 2; - i >>= - 1; - j - >>= 2; - i >>>= - 1; - j - >>>= 2; - i <<= - 1; - j - <<= 2; - } + int i = 0; + int j = 0; + i += 1; + j += 2; + i -= 1; + j -= 2; + i /= 1; + j /= 2; + i *= 1; + j *= 2; + i %= 1; + j %= 2; + i ^= 1; + j ^= 2; + i |= 1; + j |= 2; + i &= 1; + j &= 2; + i >>= 1; + j >>= 2; + i >>>= 1; + j >>>= 2; + i <<= 1; + j <<= 2; } + } - InnerClass anon = new InnerClass() { + InnerClass anon = + new InnerClass() { void foo() { - int i = 0; - int j = 0; - i += - 1; - j - += 2; - i -= - 1; - j - -= 2; - i /= - 1; - j - /= 2; - i *= - 1; - j - *= 2; - i %= - 1; - j - %= 2; - i ^= - 1; - j - ^= 2; - i |= - 1; - j - |= 2; - i &= - 1; - j - &= 2; - i >>= - 1; - j - >>= 2; - i >>>= - 1; - j - >>>= 2; - i <<= - 1; - j - <<= 2; + int i = 0; + int j = 0; + i += + 1; + j + += 2; + i -= + 1; + j + -= 2; + i /= + 1; + j + /= 2; + i *= + 1; + j + *= 2; + i %= + 1; + j + %= 2; + i ^= + 1; + j + ^= 2; + i |= + 1; + j + |= 2; + i &= + 1; + j + &= 2; + i >>= + 1; + j + >>= 2; + i >>>= + 1; + j + >>>= 2; + i <<= + 1; + j + <<= 2; } - }; + }; - enum TestEnum { - FIRST () // warn - { - }, + enum TestEnum { + FIRST () {}, // violation ''(' is preceded with whitespace.' - SECOND - () // warn - { - } - } + SECOND + () {} // violation ''(' should be on the previous line.' + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordName.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordName.java new file mode 100644 index 000000000000..42af96afddde --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordName.java @@ -0,0 +1,71 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +/** Some javadoc. */ +public record InputNoWrappingAfterRecordName (String name) { + // violation above ''(' is preceded with whitespace' + record Multi (String main, Record rec) { // violation ''(' is preceded with whitespace' + private static boolean isSent (Object obj) { // violation ''(' is preceded with whitespace' + int value = 0; + if (obj instanceof Integer i) { + value = i; + } + return value > 10; + } + } + + record Multi2 () { // violation ''(' is preceded with whitespace' + Multi2 (String s1, String s2, String s3) { // violation ''(' is preceded with whitespace' + this (); // violation ''(' is preceded with whitespace' + } + } + + record Multi3 (Integer i, Integer node) { // violation ''(' is preceded with whitespace' + public static void main (String... args) { // violation ''(' is preceded with whitespace' + System.out.println("works!"); + } + } + + record Multi4 () { // violation ''(' is preceded with whitespace' + void foo (){} // violation ''(' is preceded with whitespace' + } + + record Multi5() { + private static final Multi obj = + new Multi ("my string", new Multi4()); // violation ''(' is preceded with whitespace' + } + + // violation 2 lines below ''(' has incorrect indentation level 2, expected level should be 6.' + record Multi6 + () { + // violation above ''(' should be on the previous line.' + + // violation 2 lines below ''(' has incorrect indentation level 4, expected level should be 8.' + public static final Multi obj = new Multi + ("hello", new Multi4 // violation ''(' should be on the previous line.' + ()); + // violation above ''(' has incorrect indentation level 4, expected level should be 8.' + // violation 2 lines above ''(' should be on the previous line.' + } + + class MyTestClass { + private final Multi obj = + new Multi ("my string", new Multi4()); // violation ''(' is preceded with whitespace' + } + + /** + * Maps the ports. + * + * @param from the from param + */ + record Mapping (String from) { // violation ''(' is preceded with whitespace' + + /** + * The constructor for Mapping. + * + * @param from The source + */ + Mapping (String from) { // violation ''(' is preceded with whitespace' + this.from = from; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordName2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordName2.java new file mode 100644 index 000000000000..5e5ece76cfbd --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordName2.java @@ -0,0 +1,82 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +/** Some javadoc. */ +public class InputNoWrappingAfterRecordName2 { + + @interface InSize { + int limit(); + } + + @InSize(limit = 2) + record MyRecord(String main, Record rec) { + private static boolean isSent(Object obj) { + int value = 0; + if (obj instanceof Integer i) { + value = i; + } + return value > 10; + } + } + + record Multi2 () { // violation ''(' is preceded with whitespace' + + @InSize(limit = 2) + public Multi2 (String s1, String s2, String s3) { // violation ''(' is preceded with whitespace' + this (); // violation ''(' is preceded with whitespace' + } + } + + record Multi3 (Integer i, Integer node) { // violation ''(' is preceded with whitespace' + public static void main (String... args) { // violation ''(' is preceded with whitespace' + System.out.println("works!"); + } + } + + record Multi4 () { // violation ''(' is preceded with whitespace' + + @InSize(limit = 2) + void foo (){} // violation ''(' is preceded with whitespace' + } + + record Multi5() { + private static final MyRecord object = + new MyRecord ("my string", new Multi4()); // violation ''(' is preceded with whitespace' + } + + // violation 2 lines below ''(' has incorrect indentation level 2, expected level should be 6.' + record Multi6 + () { + // violation above ''(' should be on the previous line.' + + // violation 2 lines below ''(' has incorrect indentation level 4, expected level should be 8.' + public static final MyRecord obj = new MyRecord + ("hello", new Multi4 // violation ''(' should be on the previous line.' + ()); + // violation above ''(' has incorrect indentation level 4, expected level should be 8.' + // violation 2 lines above ''(' should be on the previous line.' + } + + class MyTestClass { + private final MyRecord obj = + new MyRecord ("my string", new Multi4()); // violation ''(' is preceded with whitespace' + } + + /** + * Maps the ports. + * + * @param from the from param + */ + @InSize(limit = 2) + record Mapping (String from) { // violation ''(' is preceded with whitespace' + + /** + * The constructor for Mapping. + * + * @param from The source + */ + @InSize(limit = 3) + Mapping (String from) { // violation ''(' is preceded with whitespace' + this.from = from; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordNameCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordNameCorrect.java new file mode 100644 index 000000000000..291c2e6b5639 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputNoWrappingAfterRecordNameCorrect.java @@ -0,0 +1,38 @@ +package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; + +/** Some javadoc. */ +public record InputNoWrappingAfterRecordNameCorrect(String name) { + record Multi(String string, Record rec) { + private boolean inRecord(Object obj) { + int value = 0; + if (obj instanceof Integer i) { + value = i; + } + return value > 10; + } + } + + record Multi2() { + Multi2(String s1, String s2, String s3) { + this(); + } + } + + record Multi3(Integer i, int node) { + public static void main(String... args) { + System.out.println("works!"); + } + } + + record Multi4() { + void foo() {} + } + + record Multi5() { + public static Multi5 object = new Multi5(); + } + + class MyTestClass { + private final Multi obj = new Multi("my string", new Multi4()); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputOperatorWrap.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputOperatorWrap.java index 828b597a075c..6e70ebfcd8ae 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputOperatorWrap.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputOperatorWrap.java @@ -4,357 +4,316 @@ import java.util.HashMap; import java.util.Map; -class InputOperatorWrap -{ - void test() - { - /*warn*/int x = 1 + - /*warn*/ 2 - +class InputOperatorWrap { + void test() { + int x = 1 + // violation ''\+' should be on a new line.' + 2 - // violation ''-' should be on a new line.' 3 - 4; - x = x + 2; - boolean y = true - && - false; - /*warn*/ y = true && - false; - y = false - && true; - /* Note: The three tests below will be used when issue #3381 is closed */ - Arrays.sort(null, String - :: - compareToIgnoreCase); - Arrays.sort(null, String:: /*(warn)*/ - compareToIgnoreCase); - Arrays.sort(null, String - ::compareToIgnoreCase); + x = x + 2; + boolean y = true + && + false; + y = true && // violation ''&&' should be on a new line.' + false; + y = false + && true; + /* Note: The three tests below will be used when issue #3381 is closed */ + Arrays.sort(null, String + // violation below ''::' should be on a new line.' + :: + compareToIgnoreCase); + Arrays.sort(null, String:: // violation ''::' should be on a new line.' + compareToIgnoreCase); + Arrays.sort(null, String + ::compareToIgnoreCase); + } + + void testAssignment() { + int x + = 0; + int y = + 0; + } + + + void testGenerics1() { + Comparable + < + String + > + c = new String(); + Map map = new HashMap(); + + boolean flag = false; + + int init = 9; + + for (Map.Entry entry : + map.entrySet()) { + int i = flag == true ? // violation ''?' should be on a new line.' + 1 : 2; } - void testAssignment() - { - int x - = 0; - int y = - 0; - } + if (init != // violation ''!=' should be on a new line.' + 9) { /* ignore */ } - < - T extends Comparable & - java.io.Serializable - > - void testGenerics1() - { - Comparable - < - String - > - c = new String(); - Map map = new HashMap(); + while (init == // violation ''==' should be on a new line.' + 10) { } // violation 'Empty blocks should have no spaces. .* only be represented as {}' - boolean flag = false; + if (init > // violation ''>' should be on a new line.' + 10) { /* ignore */ } - int init = 9; + while (init < 10 || // violation ''\|\|' should be on a new line.' + !flag) { } // violation 'Empty blocks should have no spaces. .* only be represented as {}' + } - /*ok*/ for (Map.Entry entry : - map.entrySet()) - { - /*warn*/int i = flag == true ? - 1 : 2; - } + class Inner { + void testGenerics1() { + Comparable + < + String + > + c = new String(); + Map map = new HashMap(); + boolean flag = false; - /*warn*/ if (init != - 9) - { + int init = 9; - } + for (Map.Entry entry : + map.entrySet()) { + int i = flag == true ? // violation ''?' should be on a new line.' + 1 : 2; + } - /*warn*/ while (init == - 10) - { + if (init != // violation ''!=' should be on a new line.' + 9) { /* ignore */ } - } + while (init == // violation ''==' should be on a new line.' + 10) { } // violation 'Empty blocks should have no spaces. .* only be represented as {}' - /*warn*/ if (init > - 10) - { + if (init > // violation ''>' should be on a new line.' + 10) { /* ignore */ } - } else {} - - /*warn*/ while (init < 10 || - !flag) { - - } + while (init < 10 || // violation ''\|\|' should be on a new line.' + !flag) {} } - - class Inner { - void testGenerics1 - () - { - Comparable - < - String - > - c = new String(); - Map map = new HashMap(); - boolean flag = false; - - int init = 9; - - /*ok*/ for (Map.Entry entry : - map.entrySet()) - { - /*warn*/int i = flag == true ? - 1 : 2; - } - - /*warn*/ if (init != - 9) - { - - } - - /*warn*/ while (init == - 10) - { - - } - - /*warn*/ if (init > - 10) - { - - } else {} - - /*warn*/ while (init < 10 || - !flag) { - - } + } + + Inner anon = + new Inner() { + void testGenerics1() { + Comparable + < + String + > + c = new String(); + Map map = new HashMap(); + boolean flag = false; + int init = 9; + + for (Map.Entry entry : + map.entrySet()) { + int i = flag == true ? // violation ''?' should be on a new line.' + 1 : 2; + } + + if (init != // violation ''!=' should be on a new line.' + 9) { /* ignore */ } + + while (init == // violation ''==' should be on a new line.' + 10) { } // violation 'Empty blocks should have no spaces.* only be represented as {}' + + if (init > // violation ''>' should be on a new line.' + 10) { /* ignore */ } + + while (init < 10 || // violation ''\|\|' should be on a new line.' + !flag) {} } - } - - Inner anon = new Inner - (){ - void testGenerics1 - () - { - Comparable - < - String - > - c = new String(); - Map map = new HashMap(); - boolean flag = false; - int init = 9; - - /*ok*/ for (Map.Entry entry : - map.entrySet()) - { - /*warn*/int i = flag == true ? - 1 : 2; - } - - /*warn*/ if (init != - 9) - { - - } - - /*warn*/ while (init == - 10) - { - - } + }; - /*warn*/ if (init > - 10) - { - - } else {} - - /*warn*/ while (init < 10 || - !flag) { - - } - } - }; -} - -class AsInput { + class AsInput { int abc = 0; String string - = "string"; - double PI = // ok + = "string"; + double pi = 3.1415; -} + } -class Ternary { + class Ternary { void foo() { - boolean flag = true; - /*warn*/int i = flag == true ? - 1 : - 2; - int i2 = flag == true - ? - 1 - : - 2; - int i3 = flag == true - ? 1 - : 2; - + boolean flag = true; + int i = flag == true ? // violation ''?' should be on a new line.' + 1 : + 2; + int i2 = flag == true + ? + 1 + : + 2; + int i3 = flag == true + ? 1 + : 2; } -} + } -class AssignClass { + class AssignClass { void foo() { + int i = 0; + int j = 0; + i += + 1; + j + += 2; + i -= + 1; + j + -= 2; + i /= + 1; + j + /= 2; + i *= + 1; + j + *= 2; + i %= + 1; + j + %= 2; + i ^= + 1; + j + ^= 2; + i |= + 1; + j + |= 2; + i &= + 1; + j + &= 2; + i >>= + 1; + j + >>= 2; + i >>>= + 1; + j + >>>= 2; + i <<= + 1; + j + <<= 2; + } + + class InnerClass { + void foo() { int i = 0; int j = 0; i += 1; j - += 2; + += 2; i -= 1; j - -= 2; + -= 2; i /= 1; j - /= 2; + /= 2; i *= 1; j - *= 2; + *= 2; i %= 1; j - %= 2; + %= 2; i ^= 1; j - ^= 2; + ^= 2; i |= 1; j - |= 2; + |= 2; i &= 1; j - &= 2; + &= 2; i >>= 1; j - >>= 2; + >>= 2; i >>>= 1; j - >>>= 2; + >>>= 2; i <<= 1; j - <<= 2; - } - - class InnerClass { - void foo() { - int i = 0; - int j = 0; - i += - 1; - j - += 2; - i -= - 1; - j - -= 2; - i /= - 1; - j - /= 2; - i *= - 1; - j - *= 2; - i %= - 1; - j - %= 2; - i ^= - 1; - j - ^= 2; - i |= - 1; - j - |= 2; - i &= - 1; - j - &= 2; - i >>= - 1; - j - >>= 2; - i >>>= - 1; - j - >>>= 2; - i <<= - 1; - j <<= 2; - } + } } - InnerClass anon = new InnerClass() { - void foo() { - int i = 0; - int j = 0; - i += - 1; - j - += 2; - i -= - 1; - j - -= 2; - i /= - 1; - j - /= 2; - i *= - 1; - j - *= 2; - i %= - 1; - j - %= 2; - i ^= - 1; - j - ^= 2; - i |= - 1; - j - |= 2; - i &= - 1; - j - &= 2; - i >>= - 1; - j - >>= 2; - i >>>= - 1; - j - >>>= 2; - i <<= - 1; - j - <<= 2; - } - }; + InnerClass anon = + new InnerClass() { + void foo() { + int i = 0; + int j = 0; + i += + 1; + j + += 2; + i -= + 1; + j + -= 2; + i /= + 1; + j + /= 2; + i *= + 1; + j + *= 2; + i %= + 1; + j + %= 2; + i ^= + 1; + j + ^= 2; + i |= + 1; + j + |= 2; + i &= + 1; + j + &= 2; + i >>= + 1; + j + >>= 2; + i >>>= + 1; + j + >>>= 2; + i <<= + 1; + j + <<= 2; + } + }; + + + void testWrapBeforeOperator() {} + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrap.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrap.java index 773508fab006..0a02cc5e663e 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrap.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrap.java @@ -1,45 +1,46 @@ package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; +/** Some javadoc. */ public class InputSeparatorWrap { - public void goodCase() - { - int i = 0; - String s = "ffffooooString"; - s - .isEmpty(); //ok - s.isEmpty(); + /** Some javadoc. */ + public void goodCase() { + int i = 0; + String s = "ffffooooString"; + s + .isEmpty(); + s.isEmpty(); - foo(i, - s); //ok - } - public static void foo(int i, String s) - { + foo(i, + s); + } - } + /** Some javadoc. */ + public static void foo(int i, String s) {} } -class badCase { +// violation below 'Top-level class BadCase has to reside in its own source file.' +class BadCase { - public void goodCase(int... aFoo) - { - int i = 0; + public void goodCase(int... foo) { + int i = 0; - String s = "ffffooooString"; - /*warn*/boolean b = s. + String s = "ffffooooString"; + // violation below ''.' should be on a new line.' + boolean b = s. isEmpty(); - foo(i - ,s); - int[] j; - } - public static String foo(int i, String s) - { - String maxLength = "123"; - int truncationLength = 1; - CharSequence seq = null; - Object truncationIndicator = null; - return new StringBuilder(maxLength ) - .append(seq, 0, truncationLength ) - .append(truncationIndicator) - .toString(); - } + foo(i + , s); // violation '',' should be on the previous line.' + int[] j; + } + + public static String foo(int i, String s) { + String maxLength = "123"; + int truncationLength = 1; + CharSequence seq = null; + Object truncationIndicator = null; + return new StringBuilder(maxLength) + .append(seq, 0, truncationLength) + .append(truncationIndicator) + .toString(); + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapArrayDeclarator.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapArrayDeclarator.java index acbcdd9b895c..1d46fee10d7a 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapArrayDeclarator.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapArrayDeclarator.java @@ -2,11 +2,8 @@ class InputSeparatorWrapArrayDeclarator { - protected int[] arrayDeclarationWithGoodWrapping = new int[ - ] {1, 2}; // ok - - protected int[] arrayDeclarationWithBadWrapping = new int - [] {1, 2}; // warn + protected int[] arrayDeclarationWithGoodWrapping = new int[] {1, 2}; + protected int[] arrayDeclarationWithBadWrapping = new int + [] {1, 2}; // violation ''\[' should be on the previous line.' } - diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapComma.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapComma.java index ed3f009af35d..95ec54d6dd78 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapComma.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapComma.java @@ -1,45 +1,46 @@ package com.google.checkstyle.test.chapter4formatting.rule451wheretobreak; +/** Some javadoc. */ public class InputSeparatorWrapComma { - public void goodCase() - { - int i = 0; - String s = "ffffooooString"; - s - .isEmpty(); //ok - s.isEmpty(); + /** Some javadoc. */ + public void goodCase() { + int i = 0; + String s = "ffffooooString"; + s.isEmpty(); + s.isEmpty(); - foo(i, - s); //ok - } - public static void foo(int i, String s) - { + foo(i, s); + } - } + /** Some javadoc. */ + public static void foo(int i, String s) {} } -class badCaseComma { +// violation below 'Top-level class BadCaseComma has to reside in its own source file.' +class BadCaseComma { - public void goodCase(int... aFoo) - { - int i = 0; + /** Some javadoc. */ + public void goodCase(int... foo) { + int i = 0; - String s = "ffffooooString"; - boolean b = s. + String s = "ffffooooString"; + // violation below ''.' should be on a new line.' + boolean b = s. isEmpty(); - foo(i - ,s); //warn - int[] j; - } - public static String foo(int i, String s) - { - String maxLength = "123"; - int truncationLength = 1; - CharSequence seq = null; - Object truncationIndicator = null; - return new StringBuilder(maxLength ) - .append(seq, 0, truncationLength ) - .append(truncationIndicator) - .toString(); - } + foo(i + , s); // violation '',' should be on the previous line.' + int[] j; + } + + /** Some javadoc. */ + public static String foo(int i, String s) { + String maxLength = "123"; + int truncationLength = 1; + CharSequence seq = null; + Object truncationIndicator = null; + return new StringBuilder(maxLength) + .append(seq, 0, truncationLength) + .append(truncationIndicator) + .toString(); + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapEllipsis.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapEllipsis.java index d9620466890d..e4d23e5d1612 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapEllipsis.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapEllipsis.java @@ -2,15 +2,8 @@ class InputSeparatorWrapEllipsis { - public void testMethodWithGoodWrapping(String... // ok - parameters) { - - } - - public void testMethodWithBadWrapping(String - ...parameters) { // warn - - } + public void testMethodWithGoodWrapping(String... parameters) {} + public void testMethodWithBadWrapping(String + ... parameters) {} // violation ''...' should be on the previous line.' } - diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapMethodRef.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapMethodRef.java index af314afdd04d..6178bb4329fc 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapMethodRef.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule451wheretobreak/InputSeparatorWrapMethodRef.java @@ -2,19 +2,23 @@ import java.util.Arrays; +/** Some javdoc. */ public class InputSeparatorWrapMethodRef { - void goodCase() { - String[] stringArray = { "Barbara", "James", "Mary", "John", - "Patricia", "Robert", "Michael", "Linda" }; - Arrays.sort(stringArray, String - ::compareToIgnoreCase); - } + void goodCase() { + String[] stringArray = { + "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" + }; + Arrays.sort(stringArray, String::compareToIgnoreCase); + } - void badCase() { - String[] stringArray = { "Barbara", "James", "Mary", "John", - "Patricia", "Robert", "Michael", "Linda" }; - /*warn*/ Arrays.sort(stringArray, String:: - compareToIgnoreCase); - } + void badCase() { + String[] stringArray = { + "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" + }; + Arrays.sort( + stringArray, + String:: // violation ''::' should be on a new line.' + compareToIgnoreCase); + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputClassWithChainedMethods2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputClassWithChainedMethods2.java new file mode 100644 index 000000000000..0048bee26681 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputClassWithChainedMethods2.java @@ -0,0 +1,36 @@ +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +/** some javadoc. */ +public class InputClassWithChainedMethods2 { + + /** some javadoc. */ + public InputClassWithChainedMethods2(Object... params) {} + + /** some javadoc. */ + public static void main(String[] args) { + new InputClassWithChainedMethods2() + .getInstance("string_one") + .doNothing("string_one".trim(), "string_two"); + // violation above ''method call' child has incorrect indentation level 4, expected .* 8.' + + int length = + new InputClassWithChainedMethods2("param1", "param2").getInstance() + .doNothing("something").length(); + // violation 2 lines above ''new' has incorrect indentation level 4, expected .* 8.' + + int length2 = + new InputClassWithChainedMethods2("param1", "param2").getInstance() + .doNothing("something").length(); + // violation 2 lines above ''new' has incorrect indentation level 4, expected .* 8.' + } + + /** some javadoc. */ + public String doNothing(String something, String... uselessParams) { + return something; + } + + /** some javadoc. */ + public InputClassWithChainedMethods2 getInstance(String... uselessParams) { + return this; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputFastMatcher.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputFastMatcher.java index 6e0908b3bdc6..78715fc369a3 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputFastMatcher.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputFastMatcher.java @@ -1,42 +1,41 @@ package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; -public class InputFastMatcher -{ - - public boolean matches(char c) - { - // OOOO Auto-generated method stub - return false; - } - - public String replaceFrom(CharSequence sequence, CharSequence replacement) - { - // OOOO Auto-generated method stub - return null; - } - - public String collapseFrom(CharSequence sequence, char replacement) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimFrom(CharSequence s) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimLeadingFrom(CharSequence sequence) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimTrailingFrom(CharSequence sequence) - { - // OOOO Auto-generated method stub - return null; - } - +/** some javadoc. */ +public class InputFastMatcher { + + /** some javadoc. */ + public boolean matches(char c) { + // OOOO Auto-generated method stub + return false; + } + + /** some javadoc. */ + public String replaceFrom(CharSequence sequence, CharSequence replacement) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String collapseFrom(CharSequence sequence, char replacement) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimFrom(CharSequence s) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimLeadingFrom(CharSequence sequence) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimTrailingFrom(CharSequence sequence) { + // OOOO Auto-generated method stub + return null; + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputFormattedClassWithChainedMethods2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputFormattedClassWithChainedMethods2.java new file mode 100644 index 000000000000..b254aeae63e1 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputFormattedClassWithChainedMethods2.java @@ -0,0 +1,25 @@ +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +/** some javadoc. */ +public class InputFormattedClassWithChainedMethods2 { + /** some javadoc. */ + public InputFormattedClassWithChainedMethods2() { + + String someString = ""; + + String chained1 = doNothing(someString.concat("zyx").concat("255, 254, 253")); + + doNothing(someString.concat("zyx").concat("255, 254, 253")); + } + + /** some javadoc. */ + public static void main(String[] args) { + InputFormattedClassWithChainedMethods2 classWithChainedMethodsCorrect = + new InputFormattedClassWithChainedMethods2(); + } + + /** some javadoc. */ + public String doNothing(String something) { + return something; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrect.java index b0c9a627cac5..f7faeca5a865 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrect.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrect.java @@ -1,113 +1,111 @@ -package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; //indent:0 exp:0 - -import java.util.Map; //indent:0 exp:0 -import java.util.ArrayList;//indent:0 exp:0 - -public abstract class InputIndentationCorrect { //indent:0 exp:0 - - static int i; //indent:2 exp:2 - - int[] c = {1, 2, 3, //indent:2 exp:2 - 4, 5, 6}; //indent:6 exp:6 - - int b; //indent:2 exp:2 - - static { //indent:2 exp:2 - i = 0; //indent:4 exp:4 - } //indent:2 exp:2 - - { //indent:2 exp:2 - b = 2; //indent:4 exp:4 - } //indent:2 exp:2 - - private static abstract class RangesMatcher { //indent:2 exp:2 - - private static final String ZEROES = "0\u0660\u06f0" //indent:4 exp:4 - + "\u0c66\u0ce6" //indent:8 exp:8 - + "\u1c40\u1c50"; //indent:8 exp:8 - - public static final InputIndentationCorrect JAVA_LETTER_OR_DIGIT = //indent:4 exp:4 - new InputIndentationCorrect() { //indent:8 exp:8 - @Override public boolean matches(char c) { //indent:10 exp:10 - return Character.isLetterOrDigit(c); //indent:12 exp:12 - } //indent:10 exp:10 - }; //indent:8 exp:8 - - /** Matches no characters. */ //indent:4 exp:4 - public static final InputFastMatcher NONE = //indent:4 exp:4 - new InputFastMatcher() { //indent:12 exp:>=8 - @Override public boolean matches(char c) { //indent:6 exp:6 - return false; //indent:8 exp:8 - } //indent:6 exp:6 - - @Override public String replaceFrom(CharSequence seq, CharSequence repl) { //indent:6 exp:6 - checkNotNull(repl); //indent:8 exp:8 - return seq.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - - private void checkNotNull(CharSequence replacement) {} //indent:6 exp:6 - - @Override public String collapseFrom(CharSequence sequence, //indent:6 exp:6 - char replacement) { //indent:10 exp:10 - return sequence.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - - @Override //indent:6 exp:6 - public String trimTrailingFrom(CharSequence sequence) { //indent:6 exp:6 - return sequence.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean matches(char c) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public void foo() { //indent:2 exp:2 - int i = 0; //indent:4 exp:4 - for (; i < 9; i++) { //indent:4 exp:4 - if (veryLongLongLongCondition() //indent:6 exp:6 - || veryLongLongLongCondition2()) { //indent:14 exp:>=10 - someFooMethod("longString", "veryLongString", //indent:8 exp:8 - "superVeryExtraLongString"); //indent:12 exp:12 - if (veryLongLongLongCondition()) { //indent:8 exp:8 - while (veryLongLongLongCondition2() //indent:10 exp:10 - && veryLongLongLongCondition2()) { //indent:16 exp:>=14 - try { //indent:12 exp:12 - doSmth(); //indent:14 exp:14 - } catch (Exception e) { //indent:12 exp:12 - throw new AssertionError(e); //indent:14 exp:14 - } //indent:12 exp:12 - } //indent:10 exp:10 - } //indent:8 exp:8 - } //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean veryLongLongLongCondition() { //indent:2 exp:2 - if (veryLongLongLongCondition2()) { //indent:4 exp:4 - return true; //indent:6 exp:6 - } //indent:4 exp:4 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean veryLongLongLongCondition2() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public void someFooMethod(String longString, //indent:2 exp:2 - String superLongString, String exraSuperLongString) {} //indent:6 exp:6 - - public void fooThrowMethod() //indent:2 exp:2 - throws Exception { //indent:10 exp:>=6 - /* Some code*/ //indent:6 exp:6 - } //indent:2 exp:2 - - public void doSmth() { //indent:2 exp:2 - for (int h //indent:4 exp:4 - : c) { //indent:10 exp:>=8 - someFooMethod("longString", "veryLongString", //indent:6 exp:6 - "superVeryExtraLongString"); //indent:10 exp:10 - } //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +/** some javadoc. */ +public abstract class InputIndentationCorrect { + + static int i; + + static { + i = 0; + } + + int[] pqr = { + 1, 2, 3, + 4, 5, 6 + }; + int abc; + + { + abc = 2; + } + + /** some javadoc. */ + public boolean matches(char c) { + return false; + } + + /** some javadoc. */ + public void foo() { + int i = 0; + for (; i < 9; i++) { + if (veryLongLongLongCondition() || veryLongLongLongCondition2()) { + someFooMethod("longString", "veryLongString", "superVeryExtraLongString"); + if (veryLongLongLongCondition()) { + while (veryLongLongLongCondition2() && veryLongLongLongCondition2()) { + try { + doSmth(); + } catch (Exception e) { + throw new AssertionError(e); + } + } + } + } + } + } + + /** some javadoc. */ + public boolean veryLongLongLongCondition() { + return veryLongLongLongCondition2(); + } + + /** some javadoc. */ + public boolean veryLongLongLongCondition2() { + return false; + } + + /** some javadoc. */ + public void someFooMethod( + String longString, String superLongString, String exraSuperLongString) {} + + /** some javadoc. */ + public void fooThrowMethod() throws Exception { + /* Some code*/ + } + + /** some javadoc. */ + public void doSmth() { + for (int h : pqr) { + someFooMethod("longString", "veryLongString", "superVeryExtraLongString"); + } + } + + private abstract static class RangesMatcher { + + public static final InputIndentationCorrect JAVA_LETTER_OR_DIGIT = + new InputIndentationCorrect() { + @Override + public boolean matches(char c) { + return Character.isLetterOrDigit(c); + } + }; + + /** Matches no characters. */ + public static final InputFastMatcher NONE = + new InputFastMatcher() { + @Override + public boolean matches(char c) { + return false; + } + + @Override + public String replaceFrom(CharSequence seq, CharSequence repl) { + checkNotNull(repl); + return seq.toString(); + } + + private void checkNotNull(CharSequence replacement) {} + + @Override + public String collapseFrom(CharSequence sequence, char replacement) { + return sequence.toString(); + } + + @Override + public String trimTrailingFrom(CharSequence sequence) { + return sequence.toString(); + } + }; + + private static final String ZEROES = "" + ""; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectAnnotationArrayInit.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectAnnotationArrayInit.java new file mode 100644 index 000000000000..8b85c83bd72b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectAnnotationArrayInit.java @@ -0,0 +1,13 @@ +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +/** some javadoc. */ +public class InputIndentationCorrectAnnotationArrayInit { + interface MyInterface { + @AnAnnotation(values = {"Hello"}) + void works(); + + @interface AnAnnotation { + String[] values(); + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectClass.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectClass.java index 54baa77ca9b0..0d95326d3dc0 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectClass.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectClass.java @@ -1,44 +1,33 @@ -package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; //indent:0 exp:0 - -import java.util.Iterator; //indent:0 exp:0 - -public class InputIndentationCorrectClass //indent:0 exp:0 - implements Runnable, Cloneable { //indent:4 exp:4 - - class InnerClass implements //indent:2 exp:2 - Iterable, //indent:10 exp:>=6 - Cloneable { //indent:13 exp:>=6 - @Override //indent:4 exp:4 - public Iterator iterator() { //indent:4 exp:4 - return null; //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClass2 //indent:2 exp:2 - extends //indent:7 exp:>=6 - SecondClassWithLongLongLongLongName { //indent:10 exp:>=6 - public InnerClass2(String string) { //indent:4 exp:4 - super(); //indent:6 exp:6 - // OOOO Auto-generated constructor stub //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 - - @Override //indent:2 exp:2 - public void run() { //indent:2 exp:2 - SecondClassWithLongLongLongLongName anon = //indent:4 exp:4 - new SecondClassWithLongLongLongLongName() { //indent:10 exp:>=8 - - }; //indent:4 exp:4 - - SecondClassWithLongLongLongLongName anon2 = new //indent:4 exp:4 - SecondClassWithLongLongLongLongName() { //indent:10 exp:>=8 - - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassWithLongLongLongLongName //indent:0 exp:0 - extends //indent:4 exp:4 - InputIndentationCorrectClass{ //indent:9 exp:>=4 - -} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +import java.util.Iterator; + +/** some javadoc. */ +public class InputIndentationCorrectClass implements Runnable, Cloneable { + + /** some javadoc. */ + @Override + public void run() { + SecondClassWithLongLongLongLongName anon = new SecondClassWithLongLongLongLongName() {}; + + SecondClassWithLongLongLongLongName anon2 = new SecondClassWithLongLongLongLongName() {}; + } + + class InnerClass implements Iterable, Cloneable { + @Override + public Iterator iterator() { + return null; + } + } + + class InnerClass2 extends SecondClassReturnWithVeryVeryVeryLongName { + public InnerClass2(String string) { + super(); + // OOOO Auto-generated constructor stub + } + } + + class SecondClassWithLongLongLongLongName extends InputIndentationCorrectClass {} + + class SecondClassReturnWithVeryVeryVeryLongName {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectFieldAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectFieldAndParameter.java index 49f29828ac66..bb81ea3704bf 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectFieldAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectFieldAndParameter.java @@ -1,127 +1,156 @@ -package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; //indent:0 exp:0 - -class InputIndentationCorrectFieldAndParameter { //indent:0 exp:0 - - boolean flag = conditionFirst("Loooooooooooooooooong", new //indent:2 exp:2 - SecondFieldWithName("Loooooooooooooooooog"). //indent:6 exp:6 - getInteger(new FooFieldClass(), "Loooooooooooooooooog"), //indent:6 exp:6 - new InnerClassFoo()); //indent:6 exp:6 - - boolean secondFlag = conditionSecond(10000000000.0, new //indent:2 exp:2 - SecondFieldWithName("Looooooooooooo" //indent:6 exp:6 - + "oooooooooooong").getString(new FooFieldClass(), //indent:6 exp:6 - new SecondFieldWithName("loooooooooong"). //indent:6 exp:6 - getInteger(new FooFieldClass(), "loooooooooooooong")), "loooooooooooong") //indent:6 exp:6 - || conditionThird(2048) || conditionFourth(new //indent:6 exp:6 - SecondFieldWithName("Looooooooooooooo" //indent:6 exp:6 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:6 exp:6 - conditionFifth(true, new SecondFieldWithName(getString(2048, "Looo" //indent:6 exp:6 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:6 exp:6 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:6 exp:6 - SecondFieldWithName(getString(100000, "Loooooong" //indent:6 exp:6 - + "Fooooooo><"))) || conditionNoArg() //indent:6 exp:6 - || conditionNoArg() || //indent:6 exp:6 - conditionNoArg() || conditionNoArg(); //indent:6 exp:6 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondFieldWithName instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - boolean flag = conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondFieldWithName("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooFieldClass(), "Loooooooooooooooooog"), //indent:12 exp:>=8 - new InnerClassFoo()); //indent:13 exp:>=8 - - boolean secondFlag = conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondFieldWithName("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooFieldClass(), //indent:11 exp:>=8 - new SecondFieldWithName("loooooooooong"). //indent:10 exp:>=8 - getInteger(new FooFieldClass(), "looooooooong")), "loooooooooooong") //indent:12 exp:>=8 - || conditionThird(2048) || conditionFourth(new //indent:13 exp:>=8 - SecondFieldWithName("Looooooooooooooo" //indent:16 exp:>=8 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:12 exp:>=8 - conditionFifth(true, new SecondFieldWithName(getString(2048, "Looo" //indent:11 exp:>=8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:15 exp:>=8 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:12 exp:>=8 - SecondFieldWithName(getString(100000, "Loooooong" //indent:12 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=8 - || conditionNoArg() || //indent:10 exp:>=8 - conditionNoArg() || conditionNoArg(); //indent:10 exp:>=8 - - FooFieldClass anonymousClass = new FooFieldClass() { //indent:4 exp:4 - boolean secondFlag = conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondFieldWithName("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooFieldClass(), //indent:12 exp:>=10 - new SecondFieldWithName("loooooooooong"). //indent:15 exp:>=10 - getInteger(new FooFieldClass(), "looooooong")), "loooooooooooong") //indent:13 exp:>=10 - || conditionThird(2048) || conditionFourth(new //indent:14 exp:>=10 - SecondFieldWithName("Looooooooooooooo" //indent:17 exp:>=10 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:13 exp:>=10 - conditionFifth(true, new SecondFieldWithName(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:16 exp:>=10 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:13 exp:>=8 - SecondFieldWithName(getString(100000, "Loooooong" //indent:13 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:17 exp:>=10 - || conditionNoArg() || //indent:11 exp:>=10 - conditionNoArg() || conditionNoArg(); //indent:11 exp:>=10 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondFieldWithName { //indent:0 exp:0 - - public SecondFieldWithName(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooFieldClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooFieldClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooFieldClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondFieldWithName getInstance() { //indent:2 exp:2 - return new SecondFieldWithName("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooFieldClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +class InputIndentationCorrectFieldAndParameter { + + boolean flag = + conditionFirst( + "Loooooooooooooooooong", + new SecondFieldLongNam2("Loooooooooooooooooog") + .getInteger(new FooFieldClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + + boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + + String getString(int someInt, String someString) { + return "String"; + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondFieldLongNam2 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + boolean flag = + conditionFirst( + "Loooooooooooooooooong", + new SecondFieldLongNam2("Loooooooooooooooooog") + .getInteger(new FooFieldClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + + boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "looooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + + FooFieldClass anonymousClass = + new FooFieldClass() { + final boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "looooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString( + 2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + }; + } + + class SecondFieldLongNam2 { + + public SecondFieldLongNam2(String string) {} + + String getString(FooFieldClass instance, int integer) { + return "String"; + } + + int getInteger(FooFieldClass instance, String string) { + return -1; + } + + boolean getBoolean(FooFieldClass instance, boolean flag) { + return false; + } + + SecondFieldLongNam2 getInstance() { + return new SecondFieldLongNam2("VeryLoooooooooo" + "oongString"); + } + } + + class FooFieldClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectForAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectForAndParameter.java index a9ce244565cc..7ac31e6039d4 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectForAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectForAndParameter.java @@ -1,113 +1,126 @@ -package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; //indent:0 exp:0 - -import java.util.ArrayList; //indent:0 exp:0 -import java.util.HashMap; //indent:0 exp:0 -import java.util.Iterator; //indent:0 exp:0 -import java.util.List; //indent:0 exp:0 -import java.util.Map; //indent:0 exp:0 - -class InputIndentationCorrectForAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - for (int i = 1; i < 10; i ++) {} //indent:4 exp:4 - - for (int i = new SecondForClassWithLongName("Loooooooooooooooooooo" //indent:4 exp:4 - + "oong").getInteger(new FooForClass(), //indent:8 exp:8 - getString(1000000000, "Loooooooooooooooong")); i < 10; i++) {} //indent:10 exp:>=8 - - for (Map.Entry entry : new SecondForClassWithLongName("Loo" //indent:4 exp:4 - + "ooooooooooooooooooooong").getMap(new //indent:8 exp:8 - FooForClass(), 10000000, //indent:8 exp:8 - getString(10000, "Loooooooooo" //indent:8 exp:8 - + "ooooong")).entrySet()) {} //indent:8 exp:8 - - for (Map.Entry entry : new SecondForClassWithLongName("Loo" //indent:4 exp:4 - + "ooooooooooooooooooooong").getMap(new //indent:8 exp:8 - FooForClass(), 10000000, //indent:12 exp:>=8 - getString(10000, "Loooooooooo" //indent:10 exp:>=8 - + "ooooong")).entrySet()) {} //indent:15 exp:>=8 - - for (String string : new SecondForClassWithLongName(getString(1024 //indent:4 exp:4 - , "Looooooooooooooooooong")). //indent:8 exp:8 - getList(new FooForClass(), 1000, getString(1024, //indent:8 exp:8 - "Loooooooooooooooooooooooooooooooo" //indent:8 exp:8 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:8 exp:8 - + "oooooooooong"))) {} //indent:8 exp:8 - - for (String string : new SecondForClassWithLongName(getString(1024 //indent:4 exp:4 - , "Looooooooooooooooooong")). //indent:8 exp:8 - getList(new FooForClass(), 1000, getString(1024, //indent:12 exp:>=8 - "Loooooooooooooooooooooooooooooooo" //indent:14 exp:>=8 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:10 exp:>=8 - + "oooooooooong"))) {} //indent:13 exp:>=8 - - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - - for (int i = 1; i < 10; i ++) {} //indent:6 exp:6 - - for (int i = new SecondForClassWithLongName("Loooooooooooooooooooo" //indent:6 exp:6 - + "oong").getInteger(new FooForClass(), //indent:10 exp:10 - getString(1000000000, "Loooooooooooooooong")); i < 10; i++) {} //indent:12 exp:>=10 - - for (Map.Entry entry : new SecondForClassWithLongName("Loo" //indent:6 exp:6 - + "ooooooooooooooooooooong").getMap(new //indent:10 exp:10 - FooForClass(), 10000000, //indent:10 exp:10 - getString(10000, "Loooooooooo" //indent:10 exp:10 - + "ooooong")).entrySet()) {} //indent:10 exp:10 - - for (Map.Entry entry : new SecondForClassWithLongName("Loo" //indent:6 exp:6 - + "ooooooooooooooooooooong").getMap(new //indent:12 exp:>=10 - FooForClass(), 10000000, //indent:13 exp:>=10 - getString(10000, "Loooooooooo" //indent:18 exp:>=10 - + "ooooong")).entrySet()) {} //indent:15 exp:>=10 - - for (String string : new SecondForClassWithLongName(getString(1024 //indent:6 exp:6 - , "Looooooooooooooooooong")). //indent:10 exp:10 - getList(new FooForClass(), 1000, getString(1024, //indent:10 exp:10 - "Loooooooooooooooooooooooooooooooo" //indent:10 exp:10 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:10 exp:10 - + "oooooooooong"))) {} //indent:10 exp:10 - - for (String string : new SecondForClassWithLongName(getString(1024 //indent:6 exp:6 - , "Looooooooooooooooooong")). //indent:15 exp:>=10 - getList(new FooForClass(), 1000, getString(1024, //indent:13 exp:>=10 - "Loooooooooooooooooooooooooooooooo" //indent:19 exp:>=10 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:21 exp:>=10 - + "oooooooooong"))) {} //indent:10 exp:10 - } //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondForClassWithLongName //indent:0 exp:0 - implements Iterable{ //indent:8 exp:>=4 - - public SecondForClassWithLongName(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - int getInteger(FooForClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - Map getMap(FooForClass instance, int integer, String string) { //indent:2 exp:2 - return new HashMap(); //indent:4 exp:4 - } //indent:2 exp:2 - - List getList(FooForClass instance, long longLong, String string) { //indent:2 exp:2 - return new ArrayList(); //indent:4 exp:4 - } //indent:2 exp:2 - - public Iterator iterator() { //indent:2 exp:2 - return null; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooForClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +class InputIndentationCorrectForAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + for (int i = 1; i < 10; i++) {} + + for (int i = + new SecondForClassWithLongName1("Loooooooooooooooooooo" + "oong") + .getInteger(new FooForClass(), getString(1000000000, "Loooooooooooooooong")); + i < 10; + i++) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + } + + class InnerClassFoo { + + void fooMethodWithIf() { + + for (int i = 1; i < 10; i++) {} + + for (int i = + new SecondForClassWithLongName1("Loooooooooooooooooooo" + "oong") + .getInteger(new FooForClass(), getString(1000000000, "Loooooooooooooooong")); + i < 10; + i++) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + } + } + + class SecondForClassWithLongName1 implements Iterable { + + public SecondForClassWithLongName1(String string) {} + + int getInteger(FooForClass instance, String string) { + return -1; + } + + Map getMap(FooForClass instance, int integer, String string) { + return new HashMap(); + } + + List getList(FooForClass instance, long longLong, String string) { + return new ArrayList(); + } + + public Iterator iterator() { + return null; + } + } + + class FooForClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectIfAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectIfAndParameter.java index 101e49676c19..eddeb3421313 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectIfAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectIfAndParameter.java @@ -1,144 +1,180 @@ -package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; //indent:0 exp:0 - -class InputIndentationCorrectIfAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - if (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondClassLongNam8("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:8 exp:8 - new InnerClassFoo())) {} //indent:8 exp:8 - - if (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondClassLongNam8("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooIfClass(), //indent:8 exp:8 - new SecondClassLongNam8("loooooooooong"). //indent:8 exp:8 - getInteger(new FooIfClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondClassLongNam8("Looooooooooooooo" //indent:8 exp:8 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondClassLongNam8(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooIfClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondClassLongNam8(getString(100000, "Loooooong" //indent:8 exp:8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:8 exp:8 - conditionNoArg() || conditionNoArg()) {} //indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondClassLongNam8 instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - if (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondClassLongNam8("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())) {} //indent:14 exp:>=10 - - if (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondClassLongNam8("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooIfClass(), //indent:10 exp:10 - new SecondClassLongNam8("loooooooooong"). //indent:10 exp:10 - getInteger(new FooIfClass(), "loooooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondClassLongNam8("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondClassLongNam8(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooIfClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondClassLongNam8(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()) {} //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooIfClass anonymousClass = new FooIfClass() { //indent:4 exp:4 - - void fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - if (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondClassLongNam8("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())) {} //indent:19 exp:>=12 - - if (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondClassLongNam8("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooIfClass(), //indent:12 exp:12 - new SecondClassLongNam8("loooooooooong"). //indent:12 exp:12 - getInteger(new FooIfClass(), "loooooo ooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondClassLongNam8("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondClassLongNam8(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooIfClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondClassLongNam8(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName) {} //indent:21 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassLongNam8 { //indent:0 exp:0 - - public SecondClassLongNam8(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooIfClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooIfClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooIfClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondClassLongNam8 getInstance() { //indent:2 exp:2 - return new SecondClassLongNam8("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooIfClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +class InputIndentationCorrectIfAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) { + /* foo */ + } + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondClassLongNam3 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooIfClass anonymousClass = + new FooIfClass() { + + void fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "looooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName) { + /* foo */ + } + } + }; + + void fooMethodWithIf() { + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) { + /* foo */ + } + } + } + + class SecondClassLongNam3 { + + public SecondClassLongNam3(String string) {} + + String getString(FooIfClass instance, int integer) { + return "String"; + } + + int getInteger(FooIfClass instance, String string) { + return -1; + } + + boolean getBoolean(FooIfClass instance, boolean flag) { + return false; + } + + SecondClassLongNam3 getInstance() { + return new SecondClassLongNam3("VeryLoooooooooo" + "oongString"); + } + } + + class FooIfClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectNewChildren.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectNewChildren.java new file mode 100644 index 000000000000..eee5fa7eb5ce --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectNewChildren.java @@ -0,0 +1,26 @@ +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +/** some javadoc. */ +public class InputIndentationCorrectNewChildren { + + private final StringBuffer filter = + new StringBuffer( + new CharSequence() { + @Override + public char charAt(int index) { + return 'A'; + } + + public int length() { + return 1; + } + + public CharSequence subSequence(int start, int end) { + return this; + } + + public String toString() { + return "Foo"; + } + }); +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectReturnAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectReturnAndParameter.java index b2436fa9b646..72dacaceec41 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectReturnAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectReturnAndParameter.java @@ -1,143 +1,166 @@ -package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; //indent:0 exp:0 - -class InputIndentationCorrectReturnAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean fooMethodWithIf() { //indent:2 exp:2 - - return conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondClassLongName("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooReturnClass(), //indent:8 exp:8 - new SecondClassLongName("loooooooooong"). //indent:8 exp:8 - getInteger(new FooReturnClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondClassLongName("Looooooooooooooo" //indent:8 exp:8 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondClassLongName(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondClassLongName(getString(100000, "Loooooong" //indent:8 exp:8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:8 exp:8 - conditionNoArg() || conditionNoArg();//indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondClassLongName instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - boolean fooMethodWithIf() { //indent:4 exp:4 - return conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondClassLongName("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooReturnClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo()); //indent:14 exp:>=10 - } //indent:4 exp:4 - - boolean fooReturn() { //indent:4 exp:4 - return conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondClassLongName("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooReturnClass(), //indent:10 exp:10 - new SecondClassLongName("loooooooooong"). //indent:10 exp:10 - getInteger(new FooReturnClass(), "looooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondClassLongName("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondClassLongName(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondClassLongName(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg(); //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooReturnClass anonymousClass = new FooReturnClass() { //indent:4 exp:4 - - boolean fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - return conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondClassLongName("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooReturnClass(), //indent:12 exp:12 - new SecondClassLongName("loooooooooong"). //indent:12 exp:12 - getInteger(new FooReturnClass(), "looooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondClassLongName("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondClassLongName(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondClassLongName(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName; //indent:21 exp:>=12 - } //indent:6 exp:6 - - boolean fooReturn() { //indent:6 exp:6 - return conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondClassLongName("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooReturnClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo()); //indent:19 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassLongName { //indent:0 exp:0 - - public SecondClassLongName(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooReturnClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooReturnClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooReturnClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondClassLongName getInstance() { //indent:2 exp:2 - return new SecondClassLongName("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooReturnClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +class InputIndentationCorrectReturnAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + boolean fooMethodWithIf() { + + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondClassLongNam4 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooReturnClass anonymousClass = + new FooReturnClass() { + + boolean fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "looooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName; + } + + boolean fooReturn() { + return conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam4("Loooooooooooooooooog") + .getInteger(new FooReturnClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + } + }; + + boolean fooMethodWithIf() { + return conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam4("Loooooooooooooooooog") + .getInteger(new FooReturnClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + } + + boolean fooReturn() { + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "looooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + } + } + + class SecondClassLongNam4 { + + public SecondClassLongNam4(String string) {} + + String getString(FooReturnClass instance, int integer) { + return "String"; + } + + int getInteger(FooReturnClass instance, String string) { + return -1; + } + + boolean getBoolean(FooReturnClass instance, boolean flag) { + return false; + } + + SecondClassLongNam4 getInstance() { + return new SecondClassLongNam4("VeryLoooooooooo" + "oongString"); + } + } + + class FooReturnClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectWhileDoWhileAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectWhileDoWhileAndParameter.java index 6c4bb492181e..8bc42ddf8bd6 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectWhileDoWhileAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule452indentcontinuationlines/InputIndentationCorrectWhileDoWhileAndParameter.java @@ -1,221 +1,270 @@ -package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; //indent:0 exp:0 - -class InputIndentationCorrectWhileDoWhileAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - while (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondWhileLongName("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:11 exp:>=8 - new InnerClassFoo())) {} //indent:10 exp:>=8 - - do { //indent:4 exp:4 - - } while (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondWhileLongName("Loooooooooooooooooog"). //indent:9 exp:>=8 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:15 exp:>=8 - new InnerClassFoo())); //indent:9 exp:>=8 - - while (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondWhileLongName("Looooooooooooo" //indent:9 exp:>=8 - + "oooooooooooong").getString(new FooWhileClass(), //indent:8 exp:8 - new SecondWhileLongName("loooooooooong"). //indent:11 exp:>=8 - getInteger(new FooWhileClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:14 exp:>=8 - SecondWhileLongName("Looooooooooooooo" //indent:14 exp:>=8 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondWhileLongName( //indent:12 exp:>=8 - getString(2048, "Looo" //indent:12 exp:>=8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondWhileLongName(getString(100000, "Loooooong" //indent:11 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:10 exp:>=8 - conditionNoArg() || conditionNoArg()) {} //indent:10 exp:10 - - do { //indent:4 exp:4 - - } while (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondWhileLongName("Looooooooooooo" //indent:10 exp:>=8 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:>=8 - new SecondWhileLongName("loooooooooong"). //indent:8 exp:8 - getInteger(new FooWhileClass(), "loooooooong")), "loooooooooooong") //indent:13 exp:>=8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondWhileLongName("Looooooooooooooo" //indent:11 exp:>=8 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondWhileLongName(getString(100000, "Loooooong" //indent:11 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:13 exp:>=8 - conditionNoArg() || conditionNoArg()); //indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondWhileLongName instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - while (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondWhileLongName("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())) {} //indent:14 exp:>=10 - - do { //indent:6 exp:6 - /* Do something*/ //indent:8 exp:8 - } while (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondWhileLongName("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())); //indent:14 exp:>=10 - - while (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondWhileLongName("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:10 - new SecondWhileLongName("loooooooooong"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "loooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondWhileLongName("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondWhileLongName(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()) {} //indent:14 exp:>=10 - - do { //indent:6 exp:6 - /* Do smth*/ //indent:8 exp:8 - } while (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondWhileLongName("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:10 - new SecondWhileLongName("loooooooooong"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "loooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondWhileLongName("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondWhileLongName(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()); //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooWhileClass anonymousClass = new FooWhileClass() { //indent:4 exp:4 - - void fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - while (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondWhileLongName("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())) {} //indent:19 exp:>=12 - - do { //indent:8 exp:8 - /* Do smth*/ //indent:10 exp:10 - } while (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondWhileLongName("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())); //indent:19 exp:>=12 - - while (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondWhileLongName("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooWhileClass(), //indent:12 exp:12 - new SecondWhileLongName("loooooooooong"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "loooooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondWhileLongName("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondWhileLongName(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName) {} //indent:21 exp:>=12 - - do { //indent:8 exp:8 - /* Do smth*/ //indent:10 exp:10 - } while (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondWhileLongName("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooWhileClass(), //indent:12 exp:12 - new SecondWhileLongName("loooooooooong"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "loooooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondWhileLongName("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondWhileLongName(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName);//indent:21 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondWhileLongName { //indent:0 exp:0 - - public SecondWhileLongName(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooWhileClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooWhileClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooWhileClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondWhileLongName getInstance() { //indent:2 exp:2 - return new SecondWhileLongName("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooWhileClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule452indentcontinuationlines; + +class InputIndentationCorrectWhileDoWhileAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do {} while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) {} + + do {} while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()); + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondWhileLongNam1 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooWhileClass anonymousClass = + new FooWhileClass() { + + void fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do { + /* Do smth*/ + + } while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName) {} + + do { + /* Do smth*/ + + } while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName); + } + }; + + void fooMethodWithIf() { + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do { + /* Do something*/ + + } while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) {} + + do { + /* Do smth*/ + + } while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()); + } + } + + class SecondWhileLongNam1 { + + public SecondWhileLongNam1(String string) {} + + String getString(FooWhileClass instance, int integer) { + return "String"; + } + + int getInteger(FooWhileClass instance, String string) { + return -1; + } + + boolean getBoolean(FooWhileClass instance, boolean flag) { + return false; + } + + SecondWhileLongNam1 getInstance() { + return new SecondWhileLongNam1("VeryLoooooooooo" + "oongString"); + } + } + + class FooWhileClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputEmptyLineSeparator.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputEmptyLineSeparator.java deleted file mode 100644 index b7a91285f463..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputEmptyLineSeparator.java +++ /dev/null @@ -1,126 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// -package com.google.checkstyle.test.chapter4formatting.rule461verticalwhitespace; //warn -import java.io.Serializable; //warn -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.Collections; -import com.puppycrawl.tools.checkstyle.Checker; -import com.puppycrawl.tools.checkstyle.ConfigurationLoader; - -import javax.swing.AbstractAction; - -import org.apache.commons.beanutils.locale.converters.ByteLocaleConverter; -class InputEmptyLineSeparator //warn -{ - public static final double FOO_PI = 3.1415; - private boolean flag = true; - static { //warn - //empty static initializer - } - - { - //empty instance initializer - } - - /** - * - * - * - */ - private InputEmptyLineSeparator() - { - //empty - } - - public int compareTo(InputEmptyLineSeparator aObject) - { - int number = 0; - return 0; - } - /** - * - * @param task - * @param result - * @return - */ - public static Callable callable(Runnable task, T result) // warn - { - return null; - } - - public int getBeastNumber() - { - return 666; - } - interface IntEnum { //warn - } - - class InnerClass { - - public static final double FOO_PI_INNER = 3.1415; - private boolean flagInner = true; - { //warn - //empty instance initializer - } - - private InnerClass() - { - //empty - } - - } - - class InnerClass2 { //ok - private InnerClass2() //ok - { - //empty - } - } - - class InnerClass3 { //ok - public int compareTo(InputEmptyLineSeparator aObject) //ok - { - int number = 0; - return 0; - } - - } -} - -class Clazz { //ok - private Clazz() {} //ok -} -class Class2{ //warn - public int compareTo(InputEmptyLineSeparator aObject) //ok - { - int number = 0; - return 0; - } - Class2 anon = new Class2(){ //warn - public int compareTo(InputEmptyLineSeparator aObject) //ok - { - int number = 0; - return 0; - } - }; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputEmptyLineSeparator3.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputEmptyLineSeparator3.java new file mode 100644 index 000000000000..7c06f9dc063d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputEmptyLineSeparator3.java @@ -0,0 +1,27 @@ +/* +EmptyLineSeparator +allowNoEmptyLineBetweenFields = (default)false +allowMultipleEmptyLines = false +allowMultipleEmptyLinesInsideClassMembers = (default)true +tokens = (default)PACKAGE_DEF, IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF, \ + STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF, RECORD_DEF, \ + COMPACT_CTOR_DEF + + +*/ + + + + +package com.google.checkstyle.test.chapter4formatting.rule461verticalwhitespace; //violation ''package' has more than 1 empty lines before' + + + + +public class InputEmptyLineSeparator3 { +// violation above ''CLASS_DEF' has more than 1 empty lines before.' + + + String s = "Hello"; // violation ''VARIABLE_DEF' has more than 1 empty lines before.' + +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputFormattedEmptyLineSeparator3.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputFormattedEmptyLineSeparator3.java new file mode 100644 index 000000000000..9c0b4295e168 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputFormattedEmptyLineSeparator3.java @@ -0,0 +1,21 @@ +/* +EmptyLineSeparator +allowNoEmptyLineBetweenFields = (default)false +allowMultipleEmptyLines = false +allowMultipleEmptyLinesInsideClassMembers = (default)true +tokens = (default)PACKAGE_DEF, IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF, \ + STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF, RECORD_DEF, \ + COMPACT_CTOR_DEF + + +*/ + +package com.google.checkstyle.test.chapter4formatting.rule461verticalwhitespace; + +// violation above ''package' has more than 1 empty lines before.' + +public class InputFormattedEmptyLineSeparator3 { + // violation above ''CLASS_DEF' has more than 1 empty lines before.' + + String s = "Hello"; // violation ''VARIABLE_DEF' has more than 1 empty lines before.' +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputFormattedVerticalWhitespace.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputFormattedVerticalWhitespace.java new file mode 100644 index 000000000000..d62c53e6b721 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputFormattedVerticalWhitespace.java @@ -0,0 +1,109 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule461verticalwhitespace; + +import java.util.concurrent.Callable; + +class InputFormattedVerticalWhitespace { + public static final double FOO_PI = 3.1415; + private boolean flag = true; + + static { + // empty static initializer + } + + { + // empty instance initializer + } + + /** Some javadoc. */ + private InputFormattedVerticalWhitespace() { + // empty + } + + public int compareTo(InputFormattedVerticalWhitespace obj) { + int number = 0; + return 0; + } + + /** + * Some javadoc. + * + * @param task some description. + * @param result some description. + * @return some description. + */ + public static Callable callable(Runnable task, T result) { + + return null; + } + + public int getBeastNumber() { + return 666; + } + + interface IntEnum {} + + class InnerClass { + + public static final double FOO_PI_INNER = 3.1415; + private boolean flagInner = true; + + { + // empty instance initializer + } + + private InnerClass() { + // empty + } + } + + class InnerClass2 { + private InnerClass2() { + // empty + } + } + + class InnerClass3 { + public int compareTo(InputFormattedVerticalWhitespace obj) { + int number = 0; + return 0; + } + } + + class Clazz { + private Clazz() {} + } + + class Class2 { + public int compareTo(InputFormattedVerticalWhitespace obj) { + int number = 0; + return 0; + } + + Class2 anon = + new Class2() { + public int compareTo(InputFormattedVerticalWhitespace obj) { + int number = 0; + return 0; + } + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputVerticalWhitespace.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputVerticalWhitespace.java new file mode 100644 index 000000000000..77ae887756ec --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule461verticalwhitespace/InputVerticalWhitespace.java @@ -0,0 +1,102 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// +// violation below ''package' should be separated from previous line.' +package com.google.checkstyle.test.chapter4formatting.rule461verticalwhitespace; +import java.util.concurrent.Callable; // violation ''import' should be separated from previous line.' +class InputVerticalWhitespace { // violation ''CLASS_DEF' should be separated from previous line.' + public static final double FOO_PI = 3.1415; + private boolean flag = true; + static { // violation ''STATIC_INIT' should be separated from previous line.' + // empty static initializer + } + + { + // empty instance initializer + } + + /** Some javadoc. */ + private InputVerticalWhitespace() { + // empty + } + + public int compareTo(InputVerticalWhitespace obj) { + int number = 0; + return 0; + } + /** + * Some javadoc. + * + * @param task some description. + * @param result some description. + * @return some description. + */ + public static Callable callable(Runnable task, T result) { + // violation above ''METHOD_DEF' should be separated from previous line.' + return null; + } + + public int getBeastNumber() { + return 666; + } + interface IntEnum { // violation ''INTERFACE_DEF' should be separated from previous line.' + } + + class InnerClass { + + public static final double FOO_PI_INNER = 3.1415; + private boolean flagInner = true; + { // violation ''INSTANCE_INIT' should be separated from previous line.' + // empty instance initializer + } + + private InnerClass() { + // empty + } + } + + class InnerClass2 { + private InnerClass2() { + // empty + } + } + + class InnerClass3 { + public int compareTo(InputVerticalWhitespace obj) { + int number = 0; + return 0; + } + } + + class Clazz { + private Clazz() {} + } + class Class2 { // violation ''CLASS_DEF' should be separated from previous line.' + public int compareTo(InputVerticalWhitespace obj) { + int number = 0; + return 0; + } + Class2 anon = // violation ''VARIABLE_DEF' should be separated from previous line.' + new Class2() { + public int compareTo(InputVerticalWhitespace obj) { + int number = 0; + return 0; + } + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedGenericWhitespace.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedGenericWhitespace.java new file mode 100644 index 000000000000..cf153b4d1993 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedGenericWhitespace.java @@ -0,0 +1,54 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +class InputFormattedGenericWhitespace + implements Comparable, Serializable { + InputFormattedGenericWhitespace(List things, int i) {} + + public InputFormattedGenericWhitespace(List things) {} + + public static Callable callable(Runnable task, T result) { + return null; + } + + public static Callable callable2(Runnable task, T result) { + Map, Integer> x = new HashMap, Integer>(); + for (final Map.Entry, Integer> entry : x.entrySet()) { + entry.getValue(); + } + Class[] parameterClasses = new Class[0]; + return null; + } + + void meth() { + List x = new ArrayList(); + List> y = new ArrayList>(); + List a = new ArrayList(); + List> b = new ArrayList>(); + } + + public int compareTo(InputFormattedGenericWhitespace obj) { + return 0; + } + + public int getConstructor(Class... parameterTypes) { + Collections.emptySet(); + Collections.emptySet(); + return 666; + } + + public interface IntEnum {} + + public static class IntEnumValueType & IntEnum> {} + + public static class IntEnumValueType2 & IntEnum> {} + + public static class IntEnumValueType3 & IntEnum> {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedGenericWhitespaceEndsTheLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedGenericWhitespaceEndsTheLine.java new file mode 100644 index 000000000000..f82769268d49 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedGenericWhitespaceEndsTheLine.java @@ -0,0 +1,9 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputFormattedGenericWhitespaceEndsTheLine { + /** some javadoc. */ + public boolean returnsGenericObjectAtEndOfLine(Object otherObject) { + return otherObject instanceof Enum; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedMethodParamPad2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedMethodParamPad2.java new file mode 100644 index 000000000000..33b6504bda37 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedMethodParamPad2.java @@ -0,0 +1,57 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.util.Vector; + +/** Test input for MethodDefPadCheck. */ +public class InputFormattedMethodParamPad2 { + /** some javadoc. */ + public InputFormattedMethodParamPad2() { + super(); + } + + /** some javadoc. */ + public InputFormattedMethodParamPad2(int param) { + super(); + } + + /** some javadoc. */ + public void method() {} + + /** some javadoc. */ + public void method(int param) {} + + /** some javadoc. */ + public void method(double param) { + // invoke constructor + InputFormattedMethodParamPad2 pad = new InputFormattedMethodParamPad2(); + pad = new InputFormattedMethodParamPad2(); + pad = new InputFormattedMethodParamPad2(); + + // call method + method(); + method(); + } + + /** some javadoc. */ + public void dottedCalls() { + this.method(); + this.method(); + this.method(); + + InputFormattedMethodParamPad2 p = new InputFormattedMethodParamPad2(); + p.method(); + p.method(); + p.method(); + + Integer.parseInt("0"); + Integer.parseInt("0"); + Integer.parseInt("0"); + } + + /** some javadoc. */ + public void newArray() { + int[] a = new int[] {0, 1}; + Vector v = new Vector(); + Vector v1 = new Vector(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeAnnotations.java new file mode 100644 index 000000000000..20cb18fab514 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeAnnotations.java @@ -0,0 +1,46 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** some javadoc. */ +public class InputFormattedNoWhitespaceBeforeAnnotations { + + @Target(ElementType.TYPE_USE) + @interface NonNull {} + + @Target(ElementType.TYPE_USE) + @interface AnnoType {} + + @Target(ElementType.TYPE_USE) + @interface NonNull2 {} + + @NonNull int @AnnoType [] @NonNull2 [] fiel1; + @NonNull int @AnnoType [] @NonNull2 [] field2; + + /** some javadoc. */ + public void foo(final char @NonNull [] param) {} + + // @NonNull int @NonNull ... field3; // non-compilable + // @NonNull int @NonNull... field4; // non-compilable + + /** some javadoc. */ + public void foo1(final char[] param) {} + + /** some javadoc. */ + public void foo2(final char[] param) {} + + /** some javadoc. */ + public void foo3(final char @NonNull [] param) {} + + /** some javadoc. */ + public void foo4(final char @NonNull [] param) {} + + void test1(String... param) {} + + void test2(String... param) {} + + void test3(String @NonNull ... param) {} + + void test4(String @NonNull ... param) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeCaseDefaultColon.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeCaseDefaultColon.java new file mode 100644 index 000000000000..1fd991bc226b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeCaseDefaultColon.java @@ -0,0 +1,15 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputFormattedNoWhitespaceBeforeCaseDefaultColon { + { + switch (1) { + case 1: + break; + case 2: + break; + default: + break; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeColonOfLabel.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeColonOfLabel.java new file mode 100644 index 000000000000..824556653426 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeColonOfLabel.java @@ -0,0 +1,16 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputFormattedNoWhitespaceBeforeColonOfLabel { + + { + label1: + for (int i = 0; i < 10; i++) {} + } + + /** some javadoc. */ + public void foo() { + label2: + while (true) {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeEllipsis.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeEllipsis.java new file mode 100644 index 000000000000..90cf46028484 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeEllipsis.java @@ -0,0 +1,61 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** some javadoc. */ +public class InputFormattedNoWhitespaceBeforeEllipsis { + + @Target(ElementType.TYPE_USE) + @interface NonNull {} + + @Target(ElementType.TYPE_USE) + @interface B {} + + @Target(ElementType.TYPE_USE) + @interface C {} + + @Target(ElementType.TYPE_USE) + @interface Size { + int max(); + } + + // @NonNull int @NonNull ... field3; // non-compilable + // @NonNull int @NonNull... field4; // non-compilable + + /** some javadoc. */ + void test1(String... param) {} + + /** some javadoc. */ + void test2(String... param) {} + + /** some javadoc. */ + void test3(String @NonNull ... param) {} + + /** some javadoc. */ + void test4(String @NonNull ... param) {} + + /** some javadoc. */ + void test5(String[]... param) {} + + /** some javadoc. */ + void test6(String[]... param) {} + + /** some javadoc. */ + void test7(String @NonNull []... param) {} + + /** some javadoc. */ + void test8(String @NonNull []... param) {} + + void test9(String @Size(max = 10) ... names) {} + + void test10(String @Size(max = 10) ... names) {} + + void test11(@NonNull String @C [] @B ... arg) {} + + void test12(@NonNull String @C []... arg) {} + + void test13(@NonNull String[] @B ... arg) {} + + void test14(String[] @B ... arg) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeEmptyForLoop.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeEmptyForLoop.java new file mode 100644 index 000000000000..310d5d54766c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedNoWhitespaceBeforeEmptyForLoop.java @@ -0,0 +1,24 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputFormattedNoWhitespaceBeforeEmptyForLoop { + + /** some javadoc. */ + public static void foo() { + for (; ; ) { // ok + break; + } + for (int x = 0; ; ) { // ok + break; + } + for (int x = 0; ; ) { + break; + } + for (int x = 0; x < 10; ) { // ok + break; + } + for (int x = 0; x < 10; ) { + break; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedParenPad.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedParenPad.java new file mode 100644 index 000000000000..91f5ddb2febe --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedParenPad.java @@ -0,0 +1,239 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; + +/** some javadoc. */ +public class InputFormattedParenPad { + boolean fooo = this.bar((true && false) && true); + + String foo() { + return ((Object) bar((1 > 2) ? ((3 < 4) ? false : true) : ((1 == 1) ? false : true))) + .toString(); + } + + /** some javadoc. */ + @MyAnnotation + public boolean bar(boolean a) { + assert (true); + return true; + } + + class ParenPadNoSpace { + ParenPadNoSpace() { + this(0); + } + + ParenPadNoSpace(int i) { + super(); + } + + @SuppressWarnings("") + void method(boolean status) { + try (Writer writer = new StringWriter()) { + do { + writer.append("a"); + } while (status); + } catch (IOException e) { + while (status) { + for (int i = 0; i < (long) (2 * (4 / 2)); i++) { + if (i > 2) { + synchronized (this) { + switch (i) { + case 3: + case (4): + case 5: + break; + default: + } + } + } + } + } + } + } + } + + class ParenPadSpaceLeft { + ParenPadSpaceLeft() { + this(0); + } + + ParenPadSpaceLeft(int i) { + super(); + } + + @SuppressWarnings("") + void method(boolean status) { + try (Writer writer = new StringWriter()) { + do { + writer.append("a"); + } while (status); + } catch (IOException e) { + while (status) { + for (int i = 0; i < (long) (2 * (4 / 2)); i++) { + if (i > 2) { + synchronized (this) { + switch (i) { + case 3: + case (4): + case 5: + break; + default: + } + } + } + } + } + } + } + } + + class ParenPadSpaceRight { + ParenPadSpaceRight() { + this(0); + } + + ParenPadSpaceRight(int i) { + super(); + } + + @SuppressWarnings("") + void method(boolean status) { + try (Writer writer = new StringWriter()) { + do { + writer.append("a"); + } while (status); + } catch (IOException e) { + while (status) { + for (int i = 0; i < (long) (2 * (4 / 2)); i++) { + if (i > 2) { + synchronized (this) { + switch (i) { + case 3: + case (4): + case 5: + break; + default: + } + } + } + } + } + } + } + } + + enum MyEnum { + SOME_CONSTANT() { + final int testing = 2 * (4 / 2); + }; + + private Object exam; + + private static String getterName(Exception t) { + if (t instanceof ClassNotFoundException) { + return ((ClassNotFoundException) t).getMessage(); + } else { + return "?"; + } + } + + /** some javadoc. */ + public void myMethod() { + String s = "test"; + Object o = s; + ((String) o).length(); + ((String) o).length(); + } + + /** some javadoc. */ + public void crisRon() { + Object leo = "messi"; + Object ibra = leo; + ((String) leo).compareTo((String) ibra); + Math.random(); + } + + /** some javadoc. */ + public void intStringConv() { + Object a = 5; + Object b = "string"; + int w = Integer.parseInt((String) a); + int x = Integer.parseInt((String) a); + double y = Double.parseDouble((String) a); + float z = Float.parseFloat((String) a); + String d = ((String) b); + } + + /** some javadoc. */ + public int something(Object o) { + if (o == null || !(o instanceof Float)) { + return -1; + } + return Integer.valueOf(22).compareTo((Integer) o); + } + + private void launch(Integer number) { + String myInt = (number.toString() + '\0'); + boolean result = number == 123; + } + + /** some javadoc. */ + public String testing() { + return (this.exam != null) ? ((Enum) this.exam).name() : null; + } + + Object stringReturnValue(Object result) { + if (result instanceof String) { + result = ((String) result).length(); + } + return result; + } + + private void except() { + java.util.ArrayList arrlist = new java.util.ArrayList(5); + arrlist.add(20); + arrlist.add(15); + arrlist.add(30); + arrlist.add(45); + try { + (arrlist).remove(2); + } catch (IndexOutOfBoundsException x) { + x.getMessage(); + } + org.junit.Assert.assertThat("123", org.hamcrest.CoreMatchers.is("123")); + org.junit.Assert.assertThat("Help! Integers don't work", 0, org.hamcrest.CoreMatchers.is(1)); + } + + private void tryWithResources() throws Exception { + try (AutoCloseable a = null) { + /* foo */ + } + try (AutoCloseable a = null; + AutoCloseable b = null) { + /* foo */ + } + try (AutoCloseable a = null; + AutoCloseable b = null) { + /* foo */ + } + try (AutoCloseable a = null; + AutoCloseable b = null) { + /* foo */ + } + try (AutoCloseable a = null) { + /* foo */ + } + try (AutoCloseable a = null; + AutoCloseable b = null) { + /* foo */ + } + } + } + + @interface MyAnnotation { + String someField() default "Hello world"; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterBad.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterBad.java new file mode 100644 index 000000000000..9630b594b4a6 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterBad.java @@ -0,0 +1,82 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputFormattedWhitespaceAfterBad { + /** some javadoc. */ + public void check1(int x, int y) { + // violation below ''for' construct must use '{}'s.' + for (int a = 1, b = 2; a < 5; a++, b--) + ; + while (x == 0) { + int a = 0; + int b = 1; + } + do { + System.out.println("Testing"); + } while (x == 0 || y == 2); + } + + /** some javadoc. */ + public void check2(final int a, final int b) { + if ((float) a == 0.0) { + System.out.println("true"); + } else { + System.out.println("false"); + } + } + + /** some javadoc. */ + public void check3(int... a) { + Runnable r2 = () -> String.valueOf("Hello world two!"); + switch (a[0]) { + default: + break; + } + } + + /** some javadoc. */ + public void check4() throws java.io.IOException { + try (java.io.InputStream ignored = System.in; ) { + /* foo */ + } + } + + /** some javadoc. */ + public void check5() { + try { + /* foo */ + } finally { + /* foo */ + } + try { + /* foo */ + } catch (Exception e) { + /* foo */ + } finally { + /* foo */ + } + } + + /** some javadoc. */ + public void check6() { + try { + /* foo */ + } catch (Exception e) { + /* foo */ + } + } + + /** some javadoc. */ + public void check7() { + synchronized (this) { + } + + synchronized (this) { + } + } + + /** some javadoc. */ + public String check8() { + return ("a" + "b"); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterDoubleSlashes.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterDoubleSlashes.java new file mode 100644 index 000000000000..813938989d21 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterDoubleSlashes.java @@ -0,0 +1,34 @@ +///////////////////////////////////////////////////////////////////////////////////////// +// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// +///////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputFormattedWhitespaceAfterDoubleSlashes { + String googleCheck = "Google"; // google + + /** somejavadoc. */ + public void foo1() { + int pro1 = 0; // the main variable + + int pro2 = 1; // the secondary variable + + int[] pro3 = {1, 2}; // [] should be preceded by datatype + + String pro4 = "Multiple whitespaces"; // multiple whitespaces + + /*ignore*/ + String pro5 = "//"; // no problem + + /*byte order mark ok*/ + + int pro6 = 0; // ///////////////////////////// odd comment with a lot of slashes + + /// // odd comment noone uses + + int pro7 = 0; // + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterGood.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterGood.java new file mode 100644 index 000000000000..85da38cda012 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAfterGood.java @@ -0,0 +1,83 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputFormattedWhitespaceAfterGood { + + int xyz; // multiple space between content and double slash. + int abc; // multiple space between double slash and comment's text. + int pqr; // testing both. + + /** some javadoc. */ + public void check1(int x, int y) { + // violation below ''for' construct must use '{}'s.' + for (int a = 1, b = 2; a < 5; a++, b--) + ; + while (x == 0) { + int a = 0; + int b = 1; + } + do { + System.out.println("Testing"); + } while (x == 0 || y == 2); + } + + /** some javadoc. */ + public void check2(final int a, final int b) { + if ((float) a == 0.0) { + System.out.println("true"); + } else { + System.out.println("false"); + } + } + + /** some javadoc. */ + public void check3(int... a) { + Runnable r2 = () -> String.valueOf("Hello world two!"); + switch (a[0]) { + default: + break; + } + } + + /** some javadoc. */ + public void check4() throws java.io.IOException { + try (java.io.InputStream ignored = System.in) { + /* foo */ + } + try { + /* foo. */ + } catch (Exception e) { + /* foo. */ + } + } + + /** some javadoc. */ + public void check5() { + + try { + /* foo. */ + } catch (Exception e) { + /* foo. */ + } + } + + /** some javadoc. */ + public void check6() { + try { + /* foo. */ + } catch (Exception e) { + /* foo. */ + } + } + + /** some javadoc. */ + public void check7() { + synchronized (this) { + } + } + + /** some javadoc. */ + public String check8() { + return ("a" + "b"); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundArrow.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundArrow.java new file mode 100644 index 000000000000..acd3da07843f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundArrow.java @@ -0,0 +1,105 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.awt.event.ActionEvent; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import javax.swing.JCheckBox; + +/** some javadoc. */ +public class InputFormattedWhitespaceAroundArrow { + static { + new JCheckBox() + .addActionListener( + (final ActionEvent e) -> { + test3(); + }); + } + + void foo1(Object o) { + switch (o) { + case String s when (s.equals("a")) -> {} + case String s2 -> {} + default -> {} + } + } + + /** method. */ + void test(Object o, Object o2, int y) { + switch (o) { + case String s when (s.equals("a")) -> {} + case Point(int x, int xy) when !(x >= 0 && y >= 0) -> {} + default -> {} + } + int x = + switch (o) { + case String s -> { + switch (o2) { + case Integer i when i == 0 -> { + if (y == 0) { + System.out.println(0); + } + } + default -> {} + } + yield 3; + } + default -> 3; + }; + } + + int test2(int k, Object o1) { + Predicate predicate = value -> (value != null); + Object b = ((VoidPredicate) () -> o1 instanceof String s).get(); + new LinkedList() + .stream() + .map( + t -> { + return t * 2; + }) + .filter( + t -> { + return false; + }); + return k * 2; + } + + static void test3() { + ArrayList boolList = new ArrayList(Arrays.asList(false, true, false)); + List filtered = + boolList.stream() + .filter( + statement -> { + if (!statement) { + return true; + } else { + return false; + } + }) + .collect(Collectors.toList()); + Object result = + boolList.stream() + .filter(statement -> false) + .findFirst() + .orElseThrow(() -> new IllegalStateException("big problem")); + } + + /** some javadoc. */ + record Point(int x, int y) {} + + /** some javadoc. */ + public interface Predicate { + /** some javadoc. */ + boolean test(Object value); + } + + /** some javadoc. */ + public interface VoidPredicate { + /** some javadoc. */ + public boolean get(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundBasic.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundBasic.java new file mode 100644 index 000000000000..93bbbd09d18a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundBasic.java @@ -0,0 +1,232 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/* + * Bug 806242 (NoWhitespaceBeforeCheck violation with an interface). + * + * @author o_sukhodolsky + * @version 1.0 + */ + +/** Class for testing whitespace issues. violation missing author tag. */ +class InputFormattedWhitespaceAroundBasic { + private final int var1 = 1; + private final int var2 = 1; + + /** Should be ok. */ + private final int var3 = 1; + + /** skip blank lines between comment and code, should be ok. */ + private final int var4 = 1; + + int xyz; // multiple space between content and double slash. + int abc; // multiple space between double slash and comment's text. + int pqr; // testing both. + + /** bug 806243 (NoWhitespaceBeforeCheck violation for anonymous inner class). */ + private int test; + + private int i4; + private int i5; + private int i6; + + /** method. */ + void method1() { + final int a = 1; + int b = 1; + b = 1; + b += 1; + b -= -1 + (+b); + b = b++ + b--; + b = ++b - --b; + } + + /** method. */ + void method2() { + synchronized (this) { + } + try { + /* foo */ + } catch (RuntimeException e) { + /* foo */ + } + } + + /** test WS after void return. */ + private void fastExit() { + boolean complicatedStuffNeeded = true; + if (!complicatedStuffNeeded) { + // should not complain about missing WS after return + } else { + // do complicated stuff + } + } + + /** + * test WS after non void return. + * + * @return 2 + */ + private int nonVoid() { + if (true) { + return (2); + } else { + return 2; // this is ok + } + } + + /** test casts. */ + private void testCasts() { + Object o = (Object) new Object(); + o = (Object) o; + o = (Object) o; + o = (Object) o; + } + + /** test questions. */ + private void testQuestions() { + + boolean b = (1 == 2) ? false : true; + } + + /** star test. */ + private void starTest() { + int x = 2 * 3 * 4; + } + + /** boolean test. */ + private void boolTest() { + boolean a = true; + boolean x = !a; + int z = ~1 + ~2; + } + + /** division test. */ + private void divTest() { + int a = 4 % 2; + int b = 4 % 2; + int c = 4 % 2; + int d = 4 % 2; + int e = 4 / 2; + int f = 4 / 2; + int g = 4 / 2; + } + + /** + * summary. + * + * @return dot test * + */ + private String dotTest() { + Object o = new Object(); + o.toString(); + o.toString(); + o.toString(); + return o.toString(); + } + + /** assert statement test. */ + public void assertTest() { + + assert true; + + assert true : "Whups"; + + // evil colons, should be OK + assert "OK".equals(null) ? false : true : "Whups"; + + // missing WS around assert + assert (true); + + // missing WS around colon + assert true : "Whups"; + } + + /** another check. */ + void donBradman(Runnable run) { + donBradman( + new Runnable() { + public void run() {} + }); + + final Runnable r = + new Runnable() { + public void run() {} + }; + } + + /** rfe 521323, detect whitespace before ';'. */ + void rfe521323() { + doStuff(); + for (int i = 0; i < 5; i++) {} + } + + /** bug 806243 (NoWhitespaceBeforeCheck violation for anonymous inner class). */ + void bug806243() { + Object o = + new InputFormattedWhitespaceAroundBasic() { + private int test; + }; + } + + void doStuff() {} + + interface Foo { + void foo(); + } + + /** + * Avoid Whitespace violations in for loop. + * + * @author lkuehne + * @version 1.0 + */ + class SpecialCasesInForLoop { + void forIterator() { + // avoid conflict between WhiteSpaceAfter ';' and ParenPad(nospace) + for (int i = 0; i++ < 5; ) { + // ^ no whitespace + } + + // bug 895072 + // avoid conflict between ParenPad(space) and NoWhiteSpace before ';' + int i = 0; + for (; i < 5; i++) { + // ^ whitespace + } + for (int anInt : getSomeInts()) { + // Should be ignored + } + } + + int[] getSomeInts() { + int i = 2 / 3; + return null; + } + + void forColon() { + int[] ll = new int[10]; + for (int x : ll) {} + for (int x : ll) {} + for (int x : ll) {} + for (int x : ll) {} + } + } + + /** Operators mentioned in Google Coding Standards 2016-07-12. */ + class NewGoogleOperators { + NewGoogleOperators() { + Runnable l; + + l = () -> {}; + l = () -> {}; + l = () -> {}; + l = () -> {}; + + java.util.Arrays.sort(null, String::compareToIgnoreCase); + java.util.Arrays.sort(null, String::compareToIgnoreCase); + + new Object().toString(); + new Object().toString(); + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundEmptyTypesAndCycles.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundEmptyTypesAndCycles.java new file mode 100644 index 000000000000..da07af09b6d9 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundEmptyTypesAndCycles.java @@ -0,0 +1,22 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.util.function.Function; +import java.util.function.Supplier; + +class InputFormattedWhitespaceAroundEmptyTypesAndCycles { + + private void foo() { + int i = 0; + String[][] x = {{"foo"}}; + for (int first = 0; first < 5; first++) {} // ok + int j = 0; + while (j == 1) {} // ok + do {} while (i == 1); // ok + } + + enum EmptyFooEnum {} // ok + + interface SupplierFunction extends Function, T> {} // ok + + class EmptyFoo {} // ok +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundGenerics.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundGenerics.java new file mode 100644 index 000000000000..2716c33ec17a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundGenerics.java @@ -0,0 +1,35 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.util.Collection; +import java.util.Map; + +// we need these interfaces for generics +// violation below 'Top-level class Foo3 has to reside in its own source file.' +interface Foo3 {} + +// violation below 'Top-level class Foo22 has to reside in its own source file.' +interface Foo22 {} + +/** some javadoc. */ +public class InputFormattedWhitespaceAroundGenerics {} + +// No whitespace after commas +// violation below 'Top-level class BadCommas2 has to reside in its own source file.' +class BadCommas2> { + private final java.util.Hashtable test = new java.util.Hashtable(); +} + +// violation below 'Top-level class Wildcard2 has to reside in its own source file.' +class Wildcard2 { + public static void foo(Collection collection) { + // A statement is important in this method to flush out any + // issues with parsing the wildcard in the signature + collection.size(); + } + + public static void foo2(Collection collection) { + // A statement is important in this method to flush out any + // issues with parsing the wildcard in the signature + collection.size(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundWhen.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundWhen.java new file mode 100644 index 000000000000..b39a9651bf3c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceAroundWhen.java @@ -0,0 +1,72 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +class InputFormattedWhitespaceAroundWhen { + + /** method. */ + void test(Object o) { + switch (o) { + case Integer i when (i == 0) -> {} + case String s when (s.equals("a")) -> {} + case Point(int x, int y) when !(x >= 0 && y >= 0) -> {} + default -> {} + } + + switch (o) { + case Point(int x, int y) when (x < 9 && y >= 0) -> {} + case Point(int x, int y) when (x >= 0 && y >= 0) -> {} + case Point(int x, int y) when !(x >= 0 && y >= 0) -> {} + default -> {} + } + } + + /** method. */ + void test2(Object o) { + + switch (o) { + case Integer i when (i == 0) -> {} + case String s when (s.equals("a")) -> {} + case Point(int x, int y) when (x >= 0 && y >= 0) -> {} + default -> {} + } + + switch (o) { + case Integer i when i == 0 -> {} + case String s when s.equals("a") -> {} + case Point(int x, int y) when x >= 0 && y >= 0 -> {} + default -> {} + } + } + + void emptySwitchStatements() { + switch ('a') { + case 'e' -> System.out.println("e"); + case 'i' -> System.out.println("i"); + case 'o' -> System.out.println("o"); + default -> {} + } + switch ('a') { + case 'e' -> System.out.println("e"); + case 'i' -> System.out.println("i"); + case 'o' -> System.out.println("o"); + case 'p' -> { + // some comment + } + default -> {} + } + switch ('a') { + case 'e' -> System.out.println("e"); + case 'i' -> System.out.println("i"); + case 'o' -> System.out.println("o"); + case 'p' -> { + System.out.println("o"); + } + default -> { + System.out.println("default"); + } + } + } + + record Point(int x, int y) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceBeforeLeftCurlyOfEmptyBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceBeforeLeftCurlyOfEmptyBlock.java new file mode 100644 index 000000000000..a876413ab27f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceBeforeLeftCurlyOfEmptyBlock.java @@ -0,0 +1,44 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputFormattedWhitespaceBeforeLeftCurlyOfEmptyBlock { + + InputFormattedWhitespaceBeforeLeftCurlyOfEmptyBlock instance = + new InputFormattedWhitespaceBeforeLeftCurlyOfEmptyBlock() {}; + + InputFormattedWhitespaceBeforeLeftCurlyOfEmptyBlock() {} + + void method() {} + + class Class {} + + interface Interface {} + + @interface Annotation {} + + enum Enum {} + + record Record() {} + + /** some javadoc. */ + public static void main(String... args) { + + boolean b = System.currentTimeMillis() < 0; + + while (b) {} + + for (int i = 1; i > 1; i++) {} + + do {} while (b); + + Runnable noop = () -> {}; + } + + static { + } + + record Record2(String str) { + + public Record2 {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceInsideArrayInitializer.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceInsideArrayInitializer.java new file mode 100644 index 000000000000..ee474cf232a1 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputFormattedWhitespaceInsideArrayInitializer.java @@ -0,0 +1,31 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** Some javadoc. */ +public class InputFormattedWhitespaceInsideArrayInitializer { + + public final ColorPicker[] color1 = {ColorPicker.Black}; + public final ColorPicker[] color2 = {ColorPicker.White}; + public final ColorPicker[] color3 = {ColorPicker.White, ColorPicker.Black}; + + public final ColorPicker[][] color4 = {{ColorPicker.Black, ColorPicker.Midori}}; + public final ColorPicker[][] color5 = {{ColorPicker.Black, ColorPicker.Midori}}; + + public final ColorPicker[][] color6 = {{ColorPicker.Black, ColorPicker.Midori}}; + + public ColorPicker[][] color7 = { + {ColorPicker.Yellow, ColorPicker.Orange}, // false-negative, ok until #3203 + }; + + public ColorPicker[][][] color8 = { + {{ColorPicker.Black, ColorPicker.White, ColorPicker.Yellow}, {ColorPicker.Black}, {}} + }; + + /** Some javadoc. */ + public enum ColorPicker { + Black, + White, + Yellow, + Orange, + Midori + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespace.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespace.java index 1f58f18f2da7..ce43d98e66d5 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespace.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespace.java @@ -2,64 +2,86 @@ import java.io.Serializable; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; -import java.util.Collections; -class InputGenericWhitespace implements Comparable, Serializable -{ - void meth() - { - List x = new ArrayList(); - List> y = new ArrayList>(); - List < Integer > a = new ArrayList < Integer > (); // warn - List < List < Integer > > b = new ArrayList < List < Integer > > (); // warn - } - public int compareTo(InputGenericWhitespace aObject) - { - return 0; - } +class InputGenericWhitespace implements Comparable, Serializable { + InputGenericWhitespace(List things, int i) {} - public static Callable callable(Runnable task, T result) - { - return null; - } + public InputGenericWhitespace(List things) {} - public staticCallable callable2(Runnable task, T result) // warn - { - Map, Integer> x = new HashMap, Integer>(); - for (final Map.Entry, Integer> entry : x.entrySet()) { - entry.getValue(); - } - Class[] parameterClasses = new Class[0]; - return null; - } - public int getConstructor(Class... parameterTypes) - { - Collections.emptySet(); - Collections. emptySet(); // warn - return 666; - } + public static Callable callable(Runnable task, T result) { + return null; + } - InputGenericWhitespace(List things, int i) - { + // 2 violations 3 lines below: + // ''\<' is not preceded with whitespace.' + // ''\>' should followed by whitespace.' + public staticCallable callable2(Runnable task, T result) { + Map, Integer> x = new HashMap, Integer>(); + for (final Map.Entry, Integer> entry : x.entrySet()) { + entry.getValue(); } + Class[] parameterClasses = new Class[0]; + return null; + } - public InputGenericWhitespace(List things) - { - } + void meth() { + List x = new ArrayList(); + List> y = new ArrayList>(); + List < Integer > a = new ArrayList < Integer >(); + // 6 violations above: + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\>' is preceded with whitespace.' + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\>' is preceded with whitespace.' + List < List < Integer > > b = new ArrayList < List < Integer > >(); + // 14 violations above: + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\>' is followed by whitespace.' + // ''\>' is preceded with whitespace.' + // ''\>' is preceded with whitespace.' + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\>' is followed by whitespace.' + // ''\>' is preceded with whitespace.' + // ''\>' is preceded with whitespace.' + } - public interface IntEnum { - } + public int compareTo(InputGenericWhitespace obj) { + return 0; + } - public static class IntEnumValueType & IntEnum> { - } + public int getConstructor(Class... parameterTypes) { + Collections.emptySet(); + Collections. emptySet(); + // 2 violations above: + // ''\<' is preceded with whitespace.' + // ''\>' is followed by whitespace.' + return 666; + } - public static class IntEnumValueType2& IntEnum> { // warn - } + public interface IntEnum {} - public static class IntEnumValueType3 & IntEnum> { // warn - } + public static class IntEnumValueType & IntEnum> {} + + public static class IntEnumValueType2& IntEnum> { + // 2 violations above: + // ''&' is not preceded with whitespace.' + // ''&' is not preceded with whitespace.' + } + + public static class IntEnumValueType3 & IntEnum> { + // violation above ''\>' is followed by whitespace.' + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespaceEndsTheLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespaceEndsTheLine.java index ace8dcd7daa4..8aca09152c73 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespaceEndsTheLine.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputGenericWhitespaceEndsTheLine.java @@ -1,7 +1,9 @@ package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; +/** some javadoc. */ public class InputGenericWhitespaceEndsTheLine { - public boolean returnsGenericObjectAtEndOfLine(Object otherObject) { - return otherObject instanceof Enum; - } + /** some javadoc. */ + public boolean returnsGenericObjectAtEndOfLine(Object otherObject) { + return otherObject instanceof Enum; + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputMethodParamPad.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputMethodParamPad.java deleted file mode 100644 index 059314709b5f..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputMethodParamPad.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; -import java.util.Vector; -/** Test input for MethodDefPadCheck */ -public class InputMethodParamPad -{ - public InputMethodParamPad() - { - super(); - } - - public InputMethodParamPad (int aParam) // warn - { - super (); // warn - } - - public void method() - { - } - - public void method (int aParam) // warn - { - } - - public void - method(double aParam) - { - // invoke constructor - InputMethodParamPad pad = new InputMethodParamPad(); - pad = new InputMethodParamPad (); // warn - pad = new - InputMethodParamPad(); - - // call method - method(); - method (); // warn - } - - public void dottedCalls() - { - this.method(); - this.method (); // warn - this. - method(); - - InputMethodParamPad p = new InputMethodParamPad(); - p.method(); - p.method (); // warn - p. - method(); - - java.lang.Integer.parseInt("0"); - java.lang.Integer.parseInt ("0"); // warn - java.lang.Integer. - parseInt("0"); - } - - public void newArray() - { - int[] a = new int[]{0, 1}; - java.util.Vector v = new java.util.Vector(); - java.util.Vector v1 = new Vector(); - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputMethodParamPad2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputMethodParamPad2.java new file mode 100644 index 000000000000..8f46ec7289be --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputMethodParamPad2.java @@ -0,0 +1,61 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.util.Vector; + +/** Test input for MethodDefPadCheck. */ +public class InputMethodParamPad2 { + /** some javadoc. */ + public InputMethodParamPad2() { + super(); + } + + /** some javadoc. */ + public InputMethodParamPad2 (int param) { // violation ''(' is preceded with whitespace.' + super (); // violation ''(' is preceded with whitespace.' + } + + /** some javadoc. */ + public void method() {} + + /** some javadoc. */ + public void method (int param) {} // violation ''(' is preceded with whitespace.' + + /** some javadoc. */ + public void method(double param) { + // invoke constructor + InputMethodParamPad2 pad = new InputMethodParamPad2(); + pad = new InputMethodParamPad2 (); // violation ''(' is preceded with whitespace.' + pad = new + InputMethodParamPad2(); + + // call method + method(); + method (); // violation ''(' is preceded with whitespace.' + } + + /** some javadoc. */ + public void dottedCalls() { + this.method(); + this.method (); // violation ''(' is preceded with whitespace.' + this + .method(); + + InputMethodParamPad2 p = new InputMethodParamPad2(); + p.method(); + p.method (); // violation ''(' is preceded with whitespace.' + p + .method(); + + java.lang.Integer.parseInt("0"); + java.lang.Integer.parseInt ("0"); // violation ''(' is preceded with whitespace.' + java.lang.Integer + .parseInt("0"); + } + + /** some javadoc. */ + public void newArray() { + int[] a = new int[]{0, 1}; + java.util.Vector v = new java.util.Vector(); + java.util.Vector v1 = new Vector(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeAnnotations.java new file mode 100644 index 000000000000..e322e76c195c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeAnnotations.java @@ -0,0 +1,54 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +/** some javadoc. */ +public class InputNoWhitespaceBeforeAnnotations { + + @Target(ElementType.TYPE_USE) + @interface NonNull {} + + @Target(ElementType.TYPE_USE) + @interface AnnoType {} + + @Target(ElementType.TYPE_USE) + @interface NonNull2 {} + + @NonNull int @AnnoType[] @NonNull2[] field1; + // 2 violations above: + // ''AnnoType' is not followed by whitespace' + // ''NonNull2' is not followed by whitespace' + + @NonNull int @AnnoType [] @NonNull2 [] field2; + + @NonNull int @AnnoType [] @NonNull2[] field3; + // violation above ''NonNull2' is not followed by whitespace' + + // @NonNull int @NonNull ... field3; // non-compilable + // @NonNull int @NonNull... field4; // non-compilable + + /** some javadoc. */ + public void foo(final char @NonNull [] param) {} + + /** some javadoc. */ + public void foo1(final char[] param) {} + + /** some javadoc. */ + public void foo2(final char[] param) {} + + /** some javadoc. */ + public void foo3(final char @NonNull[] param) {} + // violation above ''NonNull' is not followed by whitespace' + + /** some javadoc. */ + public void foo4(final char @NonNull [] param) {} + + void test1(String... param) {} + + void test2(String... param) {} + + void test3(String @NonNull ... param) {} + + void test4(String @NonNull ... param) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeCaseDefaultColon.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeCaseDefaultColon.java new file mode 100644 index 000000000000..1a3481e02060 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeCaseDefaultColon.java @@ -0,0 +1,15 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputNoWhitespaceBeforeCaseDefaultColon { + { + switch (1) { + case 1 : // violation '':' is preceded with whitespace.' + break; + case 2: + break; + default : // violation '':' is preceded with whitespace.' + break; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeColonOfLabel.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeColonOfLabel.java new file mode 100644 index 000000000000..aa28c9ee2919 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeColonOfLabel.java @@ -0,0 +1,18 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputNoWhitespaceBeforeColonOfLabel { + + { + label1 : // violation '':' is preceded with whitespace.' + for (int i = 0; i < 10; i++) { + } + } + + /** some javadoc. */ + public void foo() { + label2: + while (true) { + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEllipsis.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEllipsis.java new file mode 100644 index 000000000000..ccb5653d3838 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEllipsis.java @@ -0,0 +1,69 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +// +/** some javadoc. */ +public class InputNoWhitespaceBeforeEllipsis { + + @Target(ElementType.TYPE_USE) + @interface NonNull {} + + @Target(ElementType.TYPE_USE) + @interface B {} + + @Target(ElementType.TYPE_USE) + @interface C {} + + @Target(ElementType.TYPE_USE) + @interface Size { + int max(); + } + // @NonNull int @NonNull ... field3; // non-compilable + // @NonNull int @NonNull... field4; // non-compilable + + /** some javadoc. */ + void test1(String... param) {} + + /** some javadoc. */ + void test2(String ... param) {} // violation ''...' is preceded with whitespace.' + + /** some javadoc. */ + void test3(String @NonNull ... param) {} + + /** some javadoc. */ + void test4(String @NonNull... param) {} + // violation above ''NonNull' is not followed by whitespace' + + /** some javadoc. */ + void test5(String[]... param) {} + + /** some javadoc. */ + void test6(String[] ... param) {} // violation ''...' is preceded with whitespace.' + + /** some javadoc. */ + void test7(String @NonNull[]... param) {} + // violation above ''NonNull' is not followed by whitespace' + + /** some javadoc. */ + void test8(String @NonNull[] ... param) {} + // 2 violations above: + // ''NonNull' is not followed by whitespace' + // ''...' is preceded with whitespace.' + + void test9(String @Size(max = 10) ... names) {} + + void test10(String @Size(max = 10)... names) {} + // violation above '')' is not followed by whitespace' + + void test11(@NonNull String @C [] @B ... arg) {} + + void test12(@NonNull String @C [] ... arg) {} + // violation above ''...' is preceded with whitespace' + + void test13(@NonNull String [] @B ... arg) {} + + void test14( String [] @B ... arg) {} + // violation above ''(' is followed by whitespace' +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEmptyForLoop.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEmptyForLoop.java index c6d72ef4e57f..0b0cac55627f 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEmptyForLoop.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputNoWhitespaceBeforeEmptyForLoop.java @@ -1,22 +1,24 @@ package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; +/** some javadoc. */ public class InputNoWhitespaceBeforeEmptyForLoop { - public static void f() { - for (; ; ) { // ok - break; - } - for (int x = 0; ; ) { // ok - break; - } - for (int x = 0 ; ; ) { // warning - break; - } - for (int x = 0; x < 10; ) { // ok - break; - } - for (int x = 0; x < 10 ; ) { // warning - break; - } + /** some javadoc. */ + public static void foo() { + for (; ; ) { // ok + break; } + for (int x = 0; ; ) { // ok + break; + } + for (int x = 0 ; ; ) { // violation '';' is preceded with whitespace.' + break; + } + for (int x = 0; x < 10; ) { // ok + break; + } + for (int x = 0; x < 10 ; ) { // violation '';' is preceded with whitespace.' + break; + } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputParenPad.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputParenPad.java index f2ee15f7d1e2..16e6ffde9dc3 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputParenPad.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputParenPad.java @@ -4,220 +4,354 @@ import java.io.StringWriter; import java.io.Writer; -public class InputParenPad -{ - class ParenPadNoSpace { - ParenPadNoSpace() { - this(0); - } +/** some javadoc. */ +public class InputParenPad { + boolean fooo = this.bar(( true && false ) && true); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' - ParenPadNoSpace(int i) { - super(); - } + String foo() { + return ( (Object // violation ''(' is followed by whitespace.' + ) + bar( ( 1 > 2 ) ? + // 4 violations above: + // ''(' is followed by whitespace.' + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // ''?' should be on a new line.' + ( ( 3 < 4 ) ? false : true ) : + // 4 violations above: + // ''(' is followed by whitespace.' + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' + ( ( 1 == 1 ) ? false : true) ) ).toString(); + // 5 violations above: + // ''(' is followed by whitespace.' + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' + } + + /** some javadoc. */ + @MyAnnotation + public boolean bar(boolean a) { + assert ( true ); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + return true; + } + + class ParenPadNoSpace { + ParenPadNoSpace() { + this(0); + } - @SuppressWarnings("") - void method(boolean status) { - try (Writer writer = new StringWriter()) { - do { - writer.append("a"); - } while (status); - } catch (IOException e) { - while (status) { - for (int i = 0; i < (long) (2 * (4 / 2)); i++) { - if (i > 2) { - synchronized (this) { - switch (i) { - case 3: - case (4): - case 5: - break; - } - } - } - } + ParenPadNoSpace(int i) { + super(); + } + + @SuppressWarnings("") + void method(boolean status) { + try (Writer writer = new StringWriter()) { + do { + writer.append("a"); + } while (status); + } catch (IOException e) { + while (status) { + for (int i = 0; i < (long) (2 * (4 / 2)); i++) { + if (i > 2) { + synchronized (this) { + switch (i) { + case 3: + case (4): + case 5: + break; + default: } + } } + } } + } } + } - class ParenPadSpaceLeft { - ParenPadSpaceLeft( ) { // warning - this( 0); // warning - } + class ParenPadSpaceLeft { + ParenPadSpaceLeft( ) { + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + this( 0); // violation ''(' is followed by whitespace.' + } - ParenPadSpaceLeft( int i) { // warning - super( ); // warning - } + ParenPadSpaceLeft( int i) { // violation ''(' is followed by whitespace.' + super( ); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + } - @SuppressWarnings( "") // warning - void method( boolean status) { // warning - try ( Writer writer = new StringWriter( )) { // warning - do { - writer.append("a"); - } while ( status); // warning - } catch ( IOException e) { // warning - while ( status) { // warning - for ( int i = 0; i < ( long) ( 2 * ( 4 / 2)); i++) { // warning - if ( i > 2) { // warning - synchronized ( this) { // warning - switch ( i) { // warning - case 3: - case ( 4): // warning - case 5: - break; - } - } - } - } + @SuppressWarnings( "") // violation ''(' is followed by whitespace.' + void method( boolean status) { // violation ''(' is followed by whitespace.' + try ( Writer writer = new StringWriter( )) { + // 3 violations above: + // ''(' is followed by whitespace.' + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + do { + writer.append("a"); + } while ( status); // violation ''(' is followed by whitespace.' + } catch ( IOException e) { // violation ''(' is followed by whitespace.' + while ( status) { // violation ''(' is followed by whitespace.' + for ( int i = 0; i < ( long) ( 2 * ( 4 / 2)); i++) { + // 3 violations above: + // ''(' is followed by whitespace.' + // ''(' is followed by whitespace.' + // ''(' is followed by whitespace.' + if ( i > 2) { // violation ''(' is followed by whitespace.' + synchronized ( this) { // violation ''(' is followed by whitespace.' + switch ( i) { // violation ''(' is followed by whitespace.' + case 3: + case ( 4): // violation ''(' is followed by whitespace.' + case 5: + break; + default: } + } } + } } + } } + } - class ParenPadSpaceRight { - ParenPadSpaceRight( ) { // warning - this(0 ); // warning - } + class ParenPadSpaceRight { + ParenPadSpaceRight( ) { + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + this(0 ); // violation '')' is preceded with whitespace.' + } - ParenPadSpaceRight(int i ) { // warning - super( ); // warning - } + ParenPadSpaceRight(int i ) { // violation '')' is preceded with whitespace.' + super( ); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + } - @SuppressWarnings("" ) // warning - void method(boolean status ) { // warning - try (Writer writer = new StringWriter( ) ) { // warning - do { - writer.append("a" ); // warning - } while (status ); // warning - } catch (IOException e ) { // warning - while (status ) { // warning - for (int i = 0; i < (long ) (2 * (4 / 2 ) ); i++ ) { // warning - if (i > 2 ) { // warning - synchronized (this ) { // warning - switch (i ) { // warning - case 3: - case (4 ): // warning - case 5: - break; - } - } - } - } + @SuppressWarnings("" ) // violation '')' is preceded with whitespace.' + void method(boolean status ) { // violation '')' is preceded with whitespace.' + try (Writer writer = new StringWriter( ) ) { + // 3 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' + do { + writer.append("a" ); // violation '')' is preceded with whitespace.' + } while (status ); // violation '')' is preceded with whitespace.' + } catch (IOException e ) { // violation '')' is preceded with whitespace.' + while (status ) { // violation '')' is preceded with whitespace.' + for (int i = 0; i < (long ) (2 * (4 / 2 ) ); i++ ) { + // 3 violations above: + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' + if (i > 2 ) { // violation '')' is preceded with whitespace.' + synchronized (this ) { // violation '')' is preceded with whitespace.' + switch (i ) { // violation '')' is preceded with whitespace.' + case 3: + case (4 ): // violation '')' is preceded with whitespace.' + case 5: + break; + default: } + } } + } } + } } + } - String foo() { - return ( (Object // warning - ) bar( ( 1 > 2 ) ? // warning - ( ( 3 < 4 )? false : true ) : // warning - ( ( 1 == 1 ) ? false : true) ) ).toString(); // warning - } - @MyAnnotation - public boolean bar(boolean a) { - assert ( true ); // warning - return true; - } + enum MyEnum { + SOME_CONSTANT( ) { + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + final int testing = 2 * (4 / 2); + }; - boolean fooo = this.bar(( true && false ) && true); // warning -} -@interface MyAnnotation { - String someField( ) default "Hello world"; // warning -} + private Object exam; -enum MyEnum { - SOME_CONSTANT( ) { // warning - int i = (int) (2 * (4 / 2) - ); - }; + private static String getterName( Exception t) { // violation ''(' is followed by whitespace.' + if (t instanceof ClassNotFoundException ) { // violation '')' is preceded with whitespace.' + return ( (ClassNotFoundException) t ).getMessage(); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + } else { + return "?"; + } + } + /** some javadoc. */ public void myMethod() { - String s = "test"; - Object o = s; - ((String)o).length(); - ( (String)o ).length(); // warning + String s = "test"; + Object o = s; + ((String) o).length(); + ( (String) o ).length(); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' } + /** some javadoc. */ public void crisRon() { - Object leo = "messi"; - Object ibra = leo; - ((String)leo).compareTo( (String)ibra ); // warning - Math.random(); + Object leo = "messi"; + Object ibra = leo; + ((String) leo).compareTo( (String) ibra ); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + Math.random(); } + /** some javadoc. */ public void intStringConv() { - Object a = 5; - Object b = "string"; - int w = Integer.parseInt((String)a); - int x = Integer.parseInt( (String)a); // warning - double y = Double.parseDouble((String)a ); // warning - float z = Float.parseFloat( (String)a ); // warning - String d = ((String)b); - } - - public int something( Object o ) { // warning - if ( o == null || !( o instanceof Float ) ) { // warning - return -1; - } - return Integer.valueOf( 22 ).compareTo( (Integer) o ); // warning + Object a = 5; + Object b = "string"; + int w = Integer.parseInt((String) a); + int x = Integer.parseInt( (String) a); // violation ''(' is followed by whitespace.' + double y = Double.parseDouble((String) a ); // violation '')' is preceded with whitespace.' + float z = Float.parseFloat( (String) a ); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + String d = ((String) b); } - private void launch(Integer number ) { // warning - String myInt = ( number.toString() + '\0' ); // warning - boolean result = false; - if (number == 123) - result = true; + /** some javadoc. */ + public int something( Object o ) { + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + if ( o == null || !( o instanceof Float ) ) { + // 4 violations above: + // ''(' is followed by whitespace.' + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' + return -1; + } + return Integer.valueOf( 22 ).compareTo( (Integer) o ); + // 4 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' } - private static String getterName( Exception t) { // warning - if (t instanceof ClassNotFoundException ) { // warning - return ( (ClassNotFoundException) t ).getMessage(); // warning - } - else { - return "?"; - } + private void launch(Integer number ) { // violation '')' is preceded with whitespace.' + String myInt = ( number.toString() + '\0' ); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + boolean result = number == 123; } - private Object exam; - + /** some javadoc. */ public String testing() { - return ( this.exam != null ) // warning - ? ( ( Enum )this.exam ).name() // warning - : null; + return ( this.exam != null ) + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + ? ( ( Enum ) this.exam ).name() + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + : null; } - Object stringReturnValue( Object result ) { // warning - if ( result instanceof String ) { // warning - result = ( (String) result ).length(); // warning - } - return result; + Object stringReturnValue( Object result ) { + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + if ( result instanceof String ) { + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + result = ( (String) result ).length(); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + } + return result; } - - private void except() { - java.util.ArrayList arrlist = new java.util.ArrayList( 5 ); // warning - arrlist.add( 20); // warning - arrlist.add(15 ); // warning - arrlist.add( 30 ); // warning - arrlist.add(45); - try { - ( arrlist ).remove( 2); // warning - } catch ( IndexOutOfBoundsException x ) { // warning - x.getMessage(); - } - org.junit.Assert.assertThat( "123", org.hamcrest.CoreMatchers.is( "123" ) ); // warning - org.junit.Assert.assertThat( "Help! Integers don't work", // warning - 0, org.hamcrest.CoreMatchers.is( 1 ) ); // warning + java.util.ArrayList arrlist = new java.util.ArrayList( 5 ); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + arrlist.add( 20); // violation ''(' is followed by whitespace.' + arrlist.add(15 ); // violation '')' is preceded with whitespace.' + arrlist.add( 30 ); + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + arrlist.add(45); + try { + ( arrlist ).remove( 2); + // 3 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // ''(' is followed by whitespace.' + } catch ( IndexOutOfBoundsException x ) { + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + x.getMessage(); + } + org.junit.Assert.assertThat( "123", org.hamcrest.CoreMatchers.is( "123" ) ); + // 4 violations above: + // ''(' is followed by whitespace.' + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' + org.junit.Assert.assertThat( "Help! Integers don't work", + // violation above ''(' is followed by whitespace.' + 0, org.hamcrest.CoreMatchers.is( 1 ) ); + // 3 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + // '')' is preceded with whitespace.' } private void tryWithResources() throws Exception { - try (AutoCloseable a = null) {} // ok - try (AutoCloseable a = null; AutoCloseable b = null) {} // ok - try (AutoCloseable a = null; AutoCloseable b = null; ) {} // ok - try (AutoCloseable a = null; AutoCloseable b = null; ) {} // ok - try (AutoCloseable a = null ) {} // warning - try (AutoCloseable a = null; AutoCloseable b = null ) {} // warning + try (AutoCloseable a = null) {} + try (AutoCloseable a = null; + AutoCloseable b = null) {} + try (AutoCloseable a = null; + AutoCloseable b = null) {} + try (AutoCloseable a = null; + AutoCloseable b = null) {} + try (AutoCloseable a = null ) {} + // violation above '')' is preceded with whitespace.' + try (AutoCloseable a = null; + AutoCloseable b = null ) {} + // violation above '')' is preceded with whitespace.' } + } + + @interface MyAnnotation { + String someField( ) default "Hello world"; + // 2 violations above: + // ''(' is followed by whitespace.' + // '')' is preceded with whitespace.' + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterBad.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterBad.java new file mode 100644 index 000000000000..f452b5cc8a97 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterBad.java @@ -0,0 +1,130 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputWhitespaceAfterBad { + /** some javadoc. */ + public void check1(int x,int y) { // violation '',' is not followed by whitespace.' + for(int a = 1,b = 2;a < 5;a++,b--) + ; + // 7 violations 2 lines above: + // ''for' construct must use '{}'s.' + // ''for' is not followed by whitespace.' + // ''for' is not followed by whitespace.' + // '',' is not followed by whitespace.' + // '';' is not followed by whitespace.' + // '';' is not followed by whitespace.' + // '',' is not followed by whitespace.' + while(x == 0) { + // 2 violations above: + // ''while' is not followed by whitespace.' + // ''while' is not followed by whitespace.' + int a = 0,b = 1; + // 2 violations above: + // 'Each variable declaration must be in its own statement.' + // '',' is not followed by whitespace.' + } + do{ + // 3 violations above: + // ''do' is not followed by whitespace.' + // ''do' is not followed by whitespace.' + // ''{' is not preceded with whitespace.' + System.out.println("Testing"); + } while(x == 0 || y == 2); + // 2 violations above: + // ''while' is not followed by whitespace.' + // ''while' is not followed by whitespace.' + } + + /** some javadoc. */ + public void check2(final int a,final int b) { // violation '',' is not followed by whitespace.' + if((float)a == 0.0) { + // 3 violations above: + // ''if' is not followed by whitespace.' + // ''if' is not followed by whitespace.' + // ''typecast' is not followed by whitespace.' + System.out.println("true"); + } else{ + // 3 violations above: + // ''else' is not followed by whitespace.' + // ''else' is not followed by whitespace.' + // ''{' is not preceded with whitespace.' + System.out.println("false"); + } + } + + /** some javadoc. */ + public void check3(int...a) { // violation ''...' is not followed by whitespace.' + Runnable r2 = () ->String.valueOf("Hello world two!"); + // 2 violations above: + // ''->' is not followed by whitespace.' + // ''->' is not followed by whitespace.' + switch(a[0]) { + // 2 violations above: + // ''switch' is not followed by whitespace.' + // ''switch' is not followed by whitespace.' + default: + break; + } + } + + /** some javadoc. */ + public void check4() throws java.io.IOException { + try(java.io.InputStream ignored = System.in;) {} + // 2 violations above: + // ''try' is not followed by whitespace.' + // ''try' is not followed by whitespace.' + } + + /** some javadoc. */ + public void check5() { + try { + /* foo */ + } finally{ + // 3 violations above: + // ''finally' is not followed by whitespace.' + // ''finally' is not followed by whitespace.' + // ''{' is not preceded with whitespace.' + } + try { + /* foo */ + } catch (Exception e) { + /* foo */ + } finally{ + // 3 violations above: + // ''finally' is not followed by whitespace.' + // ''finally' is not followed by whitespace.' + // ''{' is not preceded with whitespace.' + } + } + + /** some javadoc. */ + public void check6() { + try { + /* foo */ + } catch(Exception e) { + // 2 violations above: + // ''catch' is not followed by whitespace.' + // ''catch' is not followed by whitespace.' + } + } + + /** some javadoc. */ + public void check7() { + synchronized(this) { + // 2 violations above: + // ''synchronized' is not followed by whitespace.' + // ''synchronized' is not followed by whitespace.' + } + + synchronized (this) { + } + } + + /** some javadoc. */ + public String check8() { + return("a" + "b"); + // 2 violations above: + // ''return' is not followed by whitespace.' + // ''return' is not followed by whitespace.' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterDoubleSlashes.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterDoubleSlashes.java new file mode 100644 index 000000000000..d87ec7439a13 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterDoubleSlashes.java @@ -0,0 +1,38 @@ +///////////////////////////////////////////////////////////////////////////////////////// +// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +// +///////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputWhitespaceAfterDoubleSlashes { + String googleCheck = "Google"; //google + // violation above ''//' must be followed by a whitespace.' + + /** somejavadoc. */ + public void foo1() { + int pro1 = 0; //the main variable + // violation above ''//' must be followed by a whitespace.' + + // violation below '';' is not followed by whitespace.' + int pro2 = 1;// the secondary variable + + int[] pro3 = {1, 2}; //[] should be preceded by datatype + // violation above ''//' must be followed by a whitespace.' + + String pro4 = "Multiple whitespaces"; // multiple whitespaces + + /*ignore*/ + String pro5 = "//"; // no problem + + /*byte order mark ok*/ + + int pro6 = 0; /////////////////////////////// odd comment with a lot of slashes + + /// // odd comment noone uses + + int pro7 = 0; // + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterDoubleSlashesCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterDoubleSlashesCorrect.java new file mode 100644 index 000000000000..5bbc7457514a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterDoubleSlashesCorrect.java @@ -0,0 +1,27 @@ +///////////////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code and other text files for adherence to a set of rules. +///////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputWhitespaceAfterDoubleSlashesCorrect { + String googleCheck = "Google"; // google + + /** somejavadoc. */ + public void foo1() { + int pro1 = 0; // the main variable + + int pro2 = 1; // the secondary variable + + int[] pro3 = {1, 2}; // [] should be preceded by datatype + + String pro4 = "Multiple whitespaces"; // multiple whitespaces + + String pro5 = "//"; // no problem + + /////////////////////////////// odd indentation comment + + /// // odd indentation comment + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterGood.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterGood.java new file mode 100644 index 000000000000..05ab05d2587f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterGood.java @@ -0,0 +1,80 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputWhitespaceAfterGood { + + int xyz; // multiple space between content and double slash. + int abc; // multiple space between double slash and comment's text. + int pqr; // testing both. + + /** some javadoc. */ + public void check1(int x, int y) { + // violation below ''for' construct must use '{}'s.' + for (int a = 1, b = 2; a < 5; a++, b--) + ; + while (x == 0) { + int a = 0, b = 1; // violation 'Each variable declaration must be in its own statement.' + } + do { + System.out.println("Testing"); + } while (x == 0 || y == 2); + } + + /** some javadoc. */ + public void check2(final int a, final int b) { + if ((float) a == 0.0) { + System.out.println("true"); + } else { + System.out.println("false"); + } + } + + /** some javadoc. */ + public void check3(int... a) { + Runnable r2 = () -> String.valueOf("Hello world two!"); + switch (a[0]) { + default: + break; + } + } + + /** some javadoc. */ + public void check4() throws java.io.IOException { + try (java.io.InputStream ignored = System.in) {} + try { + /* foo. */ + } catch (Exception e) { + /* foo. */ + } + } + + /** some javadoc. */ + public void check5() { + + try { + /* foo. */ + } catch (Exception e) { + /* foo. */ + } + } + + /** some javadoc. */ + public void check6() { + try { + /* foo. */ + } catch (Exception e) { + /* foo. */ + } + } + + /** some javadoc. */ + public void check7() { + synchronized (this) { + } + } + + /** some javadoc. */ + public String check8() { + return ("a" + "b"); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundArrow.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundArrow.java new file mode 100644 index 000000000000..28c3998d2473 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundArrow.java @@ -0,0 +1,119 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.awt.event.ActionEvent; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import javax.swing.JCheckBox; + +/** some javadoc. */ +public class InputWhitespaceAroundArrow { + static { + // violation below ''->' is not preceded with whitespace.' + new JCheckBox().addActionListener((final ActionEvent e)-> { + test3(); + }); + } + + void foo1(Object o) { + switch (o) { + case String s when (s.equals("a")) -> {} + case String s2 -> { + } + default -> {} + } + } + + /** method. */ + void test(Object o, Object o2, int y) { + switch (o) { + case String s when ( + s.equals("a"))-> // violation ''->' is not preceded with whitespace.' + { + } + case Point(int x, int xy) when !(x >= 0 && y >= 0) -> {} + default-> // violation ''->' is not preceded with whitespace.' + {} + } + + int x = switch (o) { + case String s -> { + switch (o2) { + case Integer i when i == 0-> { // violation ''->' is not preceded with whitespace.' + if (y == 0) { + System.out.println(0); + } + } + default -> {} + } + yield 3; + } + default -> 3; + }; + } + + int test2(int k, Object o1) { + Predicate predicate = value ->(value != null); + // 2 violations above: + // ''->' is not followed by whitespace.' + // 'WhitespaceAround: '->' is not followed by whitespace. .*' + Object b = ((VoidPredicate) ()->o1 instanceof String s).get(); + // 3 violations above: + // ''->' is not followed by whitespace.' + // 'WhitespaceAround: '->' is not followed by whitespace. .*' + // 'WhitespaceAround: '->' is not preceded with whitespace.' + // 3 violations 5 lines below: + // ''->' is not followed by whitespace.' + // ''->' is not followed by whitespace. .*' + // ''{' is not preceded with whitespace.' + new LinkedList().stream() + .map(t ->{ + return t * 2; + } + ) + .filter(t -> { + return false; + }); + return k * 2; + } + + static void test3() { + ArrayList boolList = new ArrayList(Arrays.asList(false, true, false)); + // violation 2 lines below 'WhitespaceAround: '->' is not preceded with whitespace.' + List filtered = boolList.stream() + .filter(statement-> { + if (!statement) { + return true; + } else { + return false; + } + }) + .collect(Collectors.toList()); + Object result = boolList.stream().filter( + // violation below 'WhitespaceAround: '->' is not preceded with whitespace.' + statement-> false).findFirst() + .orElseThrow(() ->new IllegalStateException("big problem")); + // 2 violations above: + // ''->' is not followed by whitespace.' + // 'WhitespaceAround: '->' is not followed by whitespace. .*' + } + + /** some javadoc. */ + record Point(int x, int y) {} + + /** some javadoc. */ + public interface Predicate { + /** some javadoc. */ + boolean test(Object value); + } + + /** some javadoc. */ + public interface VoidPredicate { + /** some javadoc. */ + public boolean get(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundArrowCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundArrowCorrect.java new file mode 100644 index 000000000000..0e1aa663d88b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundArrowCorrect.java @@ -0,0 +1,115 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +import java.awt.event.ActionEvent; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; +import javax.swing.JCheckBox; + +/** some javadoc. */ +public class InputWhitespaceAroundArrowCorrect { + static { + new JCheckBox() + .addActionListener( + (final ActionEvent e) -> { + test3(); + }); + } + + /** some javadoc. */ + void foo1(Object o) { + switch (o) { + case String s when (s.equals("a")) -> {} + case String s2 -> {} + default -> {} + } + } + + /** method. */ + void test(Object o, Object o2, int y) { + switch (o) { + case String s when (s.equals("a")) -> {} + case Point(int x, int xy) when !(x >= 0 && xy >= 0) -> {} + default -> {} + } + + int x = + switch (o) { + case String s -> { + switch (o2) { + case Integer newInt when newInt == 0 -> { + if (y == 0) { + System.out.println(0); + } + } + default -> {} + } + yield 3; + } + default -> 3; + }; + } + + /** some javadoc. */ + int test2(int k, Object o1) { + Predicate predicate = value -> (value != null); + + Object b = ((VoidPredicate) () -> o1 instanceof String s).get(); + + List ints = new LinkedList(); + + ints.stream() + .map( + t -> { + return t * 2; + }) + .filter( + t -> { + return false; + }); + return k * 2; + } + + /** some javadoc. */ + static void test3() { + ArrayList boolList = new ArrayList(Arrays.asList(false, true, false, false)); + + List filtered = + boolList.stream() + .filter( + statement -> { + if (!statement) { + return true; + } else { + return false; + } + }) + .collect(Collectors.toList()); + + Object result = + boolList.stream() + .filter(statement -> false) + .findFirst() + .orElseThrow(() -> new IllegalStateException("big problem")); + } + + /** some javadoc. */ + record Point(int x, int y) {} + + /** some javadoc. */ + public interface Predicate { + + /** some javadoc. */ + boolean test(Object value); + } + + /** some javadoc. */ + public interface VoidPredicate { + /** some javadoc. */ + public boolean get(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundBasic.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundBasic.java index fa80e962a19c..1050493f5559 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundBasic.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundBasic.java @@ -1,260 +1,250 @@ package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; -/** - * Class for testing whitespace issues. - * violation missing author tag - **/ -class InputWhitespaceAroundBasic -{ - /** warn **/ - private int mVar1= 1; // warn - /** warn **/ - private int mVar2 =1; // warn - /** Should be ok **/ - private int mVar3 = 1; - - /** method **/ - void method1() - { - final int a = 1; - int b= 1; // warn - b= 1; // warn - b +=1; // warn - b -=- 1 + (+ b); // warn - b = b ++ + b --; // ok - b = ++ b - -- b; // ok - } - - /** method **/ - void method2() - { - synchronized(this) { //warn - } - try {//warn - } - catch (RuntimeException e) {//warn - } - } - - /** - skip blank lines between comment and code, - should be ok - **/ - - - private int mVar4 = 1; - - - /** test WS after void return */ - private void fastExit() - { - boolean complicatedStuffNeeded = true; - if( !complicatedStuffNeeded) //warn - { - return; // should not complain about missing WS after return - } - else - { - // do complicated stuff - } - } - - - /** test WS after non void return - @return 2 - */ - private int nonVoid() - { - if ( true ) - { - return(2); // //warn - } - else - { - return 2; // this is ok - } - } - - /** test casts **/ - private void testCasts() - { - Object o = (Object) new Object(); // ok - o = (Object)o; // ok - o = ( Object ) o; // ok - o = (Object) - o; // ok - } - - /** test questions **/ - private void testQuestions() - { - - boolean b = (1 ==2) ? false : true; //warn - } - - /** star test **/ - private void starTest() - { - int x = 2 * 3* 4; //warn - } - - /** boolean test **/ - private void boolTest() - { - boolean a = true; - boolean x = ! a; - int z = ~1 + ~ 2; - } - - /** division test **/ - private void divTest() - { - int a = 4 % 2; - int b = 4% 2;//warn - int c = 4 %2;//warn - int d = 4% 2;//warn - int e = 4 / 2; - int f = 4/ 2;//warn - int g = 4 /2;//warn - - } - - /** @return dot test **/ - private java .lang. String dotTest() - { - Object o = new java.lang.Object(); - o. - toString(); - o - .toString(); - o . toString(); - return o.toString(); - } - - /** assert statement test */ - public void assertTest() - { - // OK - assert true; - - // OK - assert true : "Whups"; - - // evil colons, should be OK - assert "OK".equals(null) ? false : true : "Whups"; - - // missing WS around assert - assert(true);//warn - - // missing WS around colon - assert true: "Whups";//warn - } - - /** another check */ - void donBradman(Runnable aRun) - { - donBradman(new Runnable() { - public void run() { - } - }); - - final Runnable r = new Runnable() { - public void run() { - } - }; - } - - /** rfe 521323, detect whitespace before ';' */ - void rfe521323() - { - doStuff() ; - // ^ whitespace - for (int i = 0 ; i < 5; i++) { - // ^ whitespace - } - } - - - /** bug 806243 (NoWhitespaceBeforeCheck violation for anonymous inner class) */ - private int i ; - // ^ whitespace - private int i1, i2, i3 ; - // ^ whitespace - private int i4, i5, i6; - - /** bug 806243 (NoWhitespaceBeforeCheck violation for anonymous inner class) */ - void bug806243() - { - Object o = new InputWhitespaceAroundBasic() { - private int j ; - // ^ whitespace - }; - } - - void doStuff() { - } -} - -/** +/* * Bug 806242 (NoWhitespaceBeforeCheck violation with an interface). + * * @author o_sukhodolsky * @version 1.0 */ -interface IFoo -{ - void foo() ; - // ^ whitespace -} -/** - * Avoid Whitespace violations in for loop. - * @author lkuehne - * @version 1.0 - */ -class SpecialCasesInForLoop -{ - void forIterator() - { - // avoid conflict between WhiteSpaceAfter ';' and ParenPad(nospace) - for (int i = 0; i++ < 5;) { +/** Class for testing whitespace issues. violation missing author tag. */ +class InputWhitespaceAroundBasic { + private final int var1= 1; // violation ''=' is not preceded with whitespace.' + private final int var2 =1; // violation ''=' is not followed by whitespace.' + + /** Should be ok. */ + private final int var3 = 1; + + /** skip blank lines between comment and code, should be ok. */ + private final int var4 = 1; + + int xyz; // multiple space between content and double slash. + int abc; // multiple space between double slash and comment's text. + int pqr; // testing both. + + /** bug 806243 (NoWhitespaceBeforeCheck violation for anonymous inner class). */ + private int test; + + private int i4, i5, i6; + // violation above 'Each variable declaration must be in its own statement.' + + /** method. */ + void method1() { + final int a = 1; + int b= 1; // violation ''=' is not preceded with whitespace.' + b= 1; // violation ''=' is not preceded with whitespace.' + b +=1; // violation ''\+=' is not followed by whitespace.' + b -=- 1 + (+ b); // violation ''-=' is not followed by whitespace.' + b = b++ + b--; + b = ++ b - -- b; + } + + /** method. */ + void method2() { + synchronized(this) { + // 2 violations above: + // ''synchronized' is not followed by whitespace.' + // ''synchronized' is not followed by whitespace.' + } + try{ + // 3 violations above: + // ''try' is not followed by whitespace.' + // ''try' is not followed by whitespace.' + // ''{' is not preceded with whitespace.' + } catch (RuntimeException e) {// violation ''{' is not followed by whitespace.' + } + } + + /** test WS after void return. */ + private void fastExit() { + boolean complicatedStuffNeeded = true; + // 2 violations 3 lines below: + // ''if' is not followed by whitespace.' + // ''if' is not followed by whitespace.' + if(!complicatedStuffNeeded) { + // should not complain about missing WS after return + } else { + // do complicated stuff + } + } + + /** + * test WS after non void return. + * + * @return 2 + */ + private int nonVoid() { + if (true) { + return(2); + // 2 violations above: + // ''return' is not followed by whitespace.' + // ''return' is not followed by whitespace.' + } else { + return 2; // this is ok + } + } + + /** test casts. */ + private void testCasts() { + Object o = (Object) new Object(); + o = (Object) o; + o = ( Object ) o; + o = (Object) + o; + } + + /** test questions. */ + private void testQuestions() { + + boolean b = (1 ==2) ? false : true; // violation ''==' is not followed by whitespace.' + } + + /** star test. */ + private void starTest() { + int x = 2 * 3* 4; // violation ''*' is not preceded with whitespace.' + } + + /** boolean test. */ + private void boolTest() { + boolean a = true; + boolean x = !a; + int z = ~1 + ~2; + } + + /** division test. */ + private void divTest() { + int a = 4 % 2; + int b = 4% 2; // violation ''%' is not preceded with whitespace.' + int c = 4 %2; // violation ''%' is not followed by whitespace.' + int d = 4% 2; // violation ''%' is not preceded with whitespace.' + int e = 4 / 2; + int f = 4/ 2; // violation ''/' is not preceded with whitespace.' + int g = 4 /2; // violation ''/' is not followed by whitespace.' + } + + /** + * summary. + * + * @return dot test * + */ + private java.lang.String dotTest() { + Object o = new java.lang.Object(); + o.toString(); + o.toString(); + o.toString(); + return o.toString(); + } + + /** assert statement test. */ + public void assertTest() { + + assert true; + + + assert true : "Whups"; + + // evil colons, should be OK + assert "OK".equals(null) ? false : true : "Whups"; + + // missing WS around assert + assert(true); // violation ''assert' is not followed by whitespace.' + + // missing WS around colon + assert true: "Whups"; // violation '':' is not preceded with whitespace.' + } + + /** another check. */ + void donBradman(Runnable run) { + donBradman( + new Runnable() { + public void run() {} + }); + + final Runnable r = + new Runnable() { + public void run() {} + }; + } + + /** rfe 521323, detect whitespace before ';'. */ + void rfe521323() { + doStuff(); + for (int i = 0; i < 5; i++) {} + } + + /** bug 806243 (NoWhitespaceBeforeCheck violation for anonymous inner class). */ + void bug806243() { + Object o = + new InputWhitespaceAroundBasic() { + private int test; + }; + } + + void doStuff() {} + + interface Foo { + void foo(); + } + + /** + * Avoid Whitespace violations in for loop. + * + * @author lkuehne + * @version 1.0 + */ + class SpecialCasesInForLoop { + void forIterator() { + // avoid conflict between WhiteSpaceAfter ';' and ParenPad(nospace) + for (int i = 0; i++ < 5; ) { // ^ no whitespace - } + } - // bug 895072 - // avoid conflict between ParenPad(space) and NoWhiteSpace before ';' - int i = 0; - for ( ; i < 5; i++ ) { - // ^ whitespace - } - for (int anInt : getSomeInts()) { - //Should be ignored - } + // bug 895072 + // avoid conflict between ParenPad(space) and NoWhiteSpace before ';' + int i = 0; + for (; i < 5; i++) { + // ^ whitespace + } + for (int anInt : getSomeInts()) { + // Should be ignored + } } int[] getSomeInts() { - int i = (int) ( 2 / 3 ); - return null; - } -} - -/** - * Operators mentioned in Google Coding Standards 2016-07-12 - */ -class NewGoogleOperators -{ - NewGoogleOperators() - { - Runnable l; - - l = ()-> { }; //warn - l = () ->{ }; //warn - l = () -> { }; //ok - l = () -> {}; //ok - - java.util.Arrays.sort(null, String :: compareToIgnoreCase); - java.util.Arrays.sort(null, String::compareToIgnoreCase); - - new Object().toString(); - new Object() . toString(); - } + int i = 2 / 3; + return null; + } + + void forColon() { + int[] ll = new int[10]; + for (int x:ll) {} + // 2 violations above: + // '':' is not followed by whitespace.' + // '':' is not preceded with whitespace.' + for (int x :ll) {} // violation '':' is not followed by whitespace.' + for (int x: ll) {} // violation '':' is not preceded with whitespace.' + for (int x : ll) {} + } + } + + /** Operators mentioned in Google Coding Standards 2016-07-12. */ + class NewGoogleOperators { + NewGoogleOperators() { + Runnable l; + + l = ()-> {}; // violation ''->' is not preceded with whitespace.' + l = () ->{}; + // 2 violations above: + // ''->' is not followed by whitespace.' + // ''->' is not followed by whitespace.' + l = () -> {}; + l = () -> {}; + + java.util.Arrays.sort(null, String::compareToIgnoreCase); + java.util.Arrays.sort(null, String::compareToIgnoreCase); + + new Object().toString(); + new Object().toString(); + } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundEmptyTypesAndCycles.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundEmptyTypesAndCycles.java index f07d3e920e0c..f47e24dccc3b 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundEmptyTypesAndCycles.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundEmptyTypesAndCycles.java @@ -3,21 +3,20 @@ import java.util.function.Function; import java.util.function.Supplier; -class InputWhitespaceAroundEmptyTypesAndCycles -{ - private void foo() - { - int i = 0; - String[][] x = { {"foo"} }; - for (int first = 0; first < 5; first++) {} //ok - int j = 0; - while (j == 1) {} //ok - do {} while (i == 1); //ok - } -} +class InputWhitespaceAroundEmptyTypesAndCycles { + + private void foo() { + int i = 0; + String[][] x = {{"foo"}}; + for (int first = 0; first < 5; first++) {} // ok + int j = 0; + while (j == 1) {} // ok + do {} while (i == 1); // ok + } -interface SupplierFunction extends Function, T> {} //ok + enum EmptyFooEnum {} // ok -class EmptyFoo {} //ok + interface SupplierFunction extends Function, T> {} // ok -enum EmptyFooEnum {} //ok + class EmptyFoo {} // ok +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundGenerics.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundGenerics.java index f7c7a8a0fa69..0df2dfb5ca5a 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundGenerics.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundGenerics.java @@ -3,35 +3,54 @@ import java.util.Collection; import java.util.Map; -public class InputWhitespaceAroundGenerics -{ - -} +// we need these interfaces for generics +// violation below 'Top-level class Foo has to reside in its own source file.' +interface Foo {} -//No whitespace after commas -class BadCommas < A,B,C extends Map < A,String > > //warn -{ - private java.util.Hashtable < Integer, D > p = //warn - new java.util.Hashtable < Integer, D > (); //warn -} +// violation below 'Top-level class Foo2 has to reside in its own source file.' +interface Foo2 {} -class Wildcard -{ - public static void foo(Collection < ? extends Wildcard[] > collection) { //warn - // A statement is important in this method to flush out any - // issues with parsing the wildcard in the signature - collection.size(); - } +/** some javadoc. */ +public class InputWhitespaceAroundGenerics {} - public static void foo2(Collection collection) { - // A statement is important in this method to flush out any - // issues with parsing the wildcard in the signature - collection.size(); - } +// No whitespace after commas +// violation below 'Top-level class BadCommas has to reside in its own source file.' +class BadCommas < A, B, C extends Map < A, String > > { + // 7 violations above: + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\>' is followed by whitespace.' + // ''\>' is preceded with whitespace.' + // ''\>' is preceded with whitespace.' + private final java.util.Hashtable < Integer, Foo > test = + // 3 violations above: + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\>' is preceded with whitespace.' + new java.util.Hashtable < Integer, Foo >(); + // 3 violations above: + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\>' is preceded with whitespace.' } -// we need these interfaces for generics -interface D { -} -interface E { +// violation below 'Top-level class Wildcard has to reside in its own source file.' +class Wildcard { + public static void foo(Collection < ? extends Wildcard[] > collection) { + // 3 violations above: + // ''\<' is followed by whitespace.' + // ''\<' is preceded with whitespace.' + // ''\>' is preceded with whitespace.' + // A statement is important in this method to flush out any + // issues with parsing the wildcard in the signature + collection.size(); + } + + public static void foo2(Collection collection) { + // A statement is important in this method to flush out any + // issues with parsing the wildcard in the signature + collection.size(); + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundWhen.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundWhen.java new file mode 100644 index 000000000000..36184782dbbc --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAroundWhen.java @@ -0,0 +1,126 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +class InputWhitespaceAroundWhen { + + /** method. */ + void test(Object o) { + switch (o) { + case Integer i when(i == 0) -> + { + } + // 2 violations 3 lines above: + // ''when' is not followed by whitespace.' + // ''when' is not followed by whitespace.' + case String s when( + // 2 violations above: + // ''when' is not followed by whitespace' + // ''when' is not followed by whitespace' + s.equals("a")) -> + { + } + case Point(int x, int y) when!(x >= 0 && y >= 0) -> + { + } + // 2 violations 3 lines above: + // ''when' is not followed by whitespace.' + // ''when' is not followed by whitespace.' + default -> + { + } + } + + switch (o) { + case Point(int x, int y)when (x < 9 && y >= 0) -> + { + } // violation 2 lines above ''when' is not preceded with whitespace.' + case Point(int x, int y)when(x >= 0 && y >= 0) -> + { + } + // 3 violations 3 lines above: + // ''when' is not followed by whitespace.' + // ''when' is not followed by whitespace.' + // ''when' is not preceded with whitespace.' + case Point(int x, int y)when!(x >= 0 && y >= 0) -> + { + } + // 3 violations 3 lines above: + // ''when' is not followed by whitespace.' + // ''when' is not followed by whitespace.' + // ''when' is not preceded with whitespace.' + default -> + { + } + } + } + + /** method. */ + void test2(Object o) { + + switch (o) { + case Integer i when (i == 0) -> + { + } + case String s when (s.equals("a")) -> + { + } + case Point(int x, int y) when (x >= 0 && y >= 0) -> + { + } + default -> + { + } + } + + switch (o) { + case Integer i when i == 0 -> + { + } + case String s when s.equals("a") -> + { + } + case Point(int x, int y) when x >= 0 && y >= 0 -> + { + } + default -> + { + } + } + } + + void emptySwitchStatements() { + switch ('a') { + case 'e' -> System.out.println("e"); + case 'i' -> System.out.println("i"); + case 'o' -> System.out.println("o"); + default -> { + // some comment + } + } + switch ('a') { + case 'e' -> System.out.println("e"); + case 'i' -> System.out.println("i"); + case 'o' -> System.out.println("o"); + case 'p' -> { + // some comment + } + default -> {} + } + switch ('a') { + case 'e' -> System.out.println("e"); + case 'i' -> System.out.println("i"); + case 'o' -> System.out.println("o"); + case 'p' -> { + System.out.println("o"); + } + default -> + { + System.out.println("default"); + } + } + } + + record Point(int x, int y) { + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceBeforeLeftCurlyOfEmptyBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceBeforeLeftCurlyOfEmptyBlock.java new file mode 100644 index 000000000000..e6f16e2391fe --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceBeforeLeftCurlyOfEmptyBlock.java @@ -0,0 +1,51 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** some javadoc. */ +public class InputWhitespaceBeforeLeftCurlyOfEmptyBlock { + + InputWhitespaceBeforeLeftCurlyOfEmptyBlock instance = + new InputWhitespaceBeforeLeftCurlyOfEmptyBlock(){}; // ok until #17715 + + // violation below 'WhitespaceAround: '{' is not preceded with whitespace.' + InputWhitespaceBeforeLeftCurlyOfEmptyBlock(){} + + void method(){} // ok until #17715 + + class Class{} // ok until #17715 + + interface Interface{} // ok until #17715 + + @interface Annotation{} // ok until #17715 + + enum Enum{} // ok until #17715 + + record Record(){} // ok until #17715 + + /** some javadoc. */ + public static void main(String... args) { + + boolean b = System.currentTimeMillis() < 0; + + while (b){} // ok until #17715 + + for (int i = 1; i > 1; i++){} // ok until #17715 + + do{} while (b); + // 2 violations above: + // ''do' is not followed by whitespace.' + // 'WhitespaceAround: 'do' is not followed by whitespace. *' + + Runnable noop = () ->{}; + // 2 violations above: + // ''->' is not followed by whitespace.' + // 'WhitespaceAround: '->' is not followed by whitespace. *' + } + + static{} // ok until #17715 + + record Record2(String str) { + + public Record2{} // violation 'WhitespaceAround: '{' is not preceded with whitespace.' + + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceInsideArrayInitializer.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceInsideArrayInitializer.java new file mode 100644 index 000000000000..3b120a4c79e5 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceInsideArrayInitializer.java @@ -0,0 +1,41 @@ +package com.google.checkstyle.test.chapter4formatting.rule462horizontalwhitespace; + +/** Some javadoc. */ +public class InputWhitespaceInsideArrayInitializer { + + // false-negative below, ok until #3203 + public final ColorPicker[] color1 = { ColorPicker.Black}; + + // false-negative below, ok until #3203 + public final ColorPicker[] color2 = {ColorPicker.White }; + + // false-negative below, ok until #3203 + public final ColorPicker[] color3 = { ColorPicker.White, ColorPicker.Black }; + + // false-negative below, ok until #3203 + public final ColorPicker[][] color4 = { {ColorPicker.Black, ColorPicker.Midori} }; + + // 2 false-negatives below, ok until #3203 + public final ColorPicker[][] color5 = { { ColorPicker.Black, ColorPicker.Midori } }; + + // false-negative below, ok until #3203 + public final ColorPicker[][] color6 = {{ ColorPicker.Black, ColorPicker.Midori }}; + + public ColorPicker[][] color7 = { + { ColorPicker.Yellow, ColorPicker.Orange }, // false-negative, ok until #3203 + }; + + // false-negative below, ok until #3203 + public ColorPicker[][][] color8 = { + { {ColorPicker.Black, ColorPicker.White, ColorPicker.Yellow}, {ColorPicker.Black}, {} } + }; + + /** Some javadoc. */ + public enum ColorPicker { + Black, + White, + Yellow, + Orange, + Midori + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputFormattedOneVariablePerDeclaration.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputFormattedOneVariablePerDeclaration.java new file mode 100644 index 000000000000..72b6b04bff14 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputFormattedOneVariablePerDeclaration.java @@ -0,0 +1,95 @@ +package com.google.checkstyle.test.chapter4formatting.rule4821onevariableperline; + +/** Some javadoc. */ +public class InputFormattedOneVariablePerDeclaration { + int mnp, efg; // violation 'Each variable declaration must be in its own statement.' + int i1; + int j1; + + void method1() { + String str, str1; // violation 'Each variable declaration must be in its own statement.' + java.lang.Object obj; + Object obj1; + } + + // second definition is wrapped + // line of VARIABLE_DEF is not the same as first line of the definition + java.lang.String string; + java.lang.String[] strings; + // both definitions are wrapped + java.lang.String string1; + java.lang.String[] strings1; + + void method2() { + for (int i = 0, j = 0; i < 10; i++, j--) { // ok + } + + for (int i = 0; i < 4; i++) {} + } + + class Inner { + int xyz, qwe; // violation 'Each variable declaration must be in its own statement.' + int i1; + int j1; + + void method1() { + String str, str1; + // violation above 'Each variable declaration must be in its own statement.' + java.lang.Object obj; + Object obj1; + } + + // second definition is wrapped + // line of VARIABLE_DEF is not the same as first line of the definition + java.lang.String string; + java.lang.String[] strings; + // both definitions are wrapped + java.lang.String string1; + java.lang.String[] strings1; + + void method2() { + for (int i = 0, j = 0; i < 10; i++, j--) { // ok + } + + for (int i = 0; i < 4; i++) {} + } + + Inner anon = + new Inner() { + int abc, pqr; // violation 'Each variable declaration must be in its own statement.' + int i1; + int j1; + + void method1() { + String str, str1; + // violation above 'Each variable declaration must be in its own statement.' + java.lang.Object obj; + Object obj1; + } + + // second definition is wrapped + // line of VARIABLE_DEF is not the same as first line of the definition + java.lang.String string; + java.lang.String[] strings; + // both definitions are wrapped + java.lang.String string1; + java.lang.String[] strings1; + + void method2() { + for (int i = 0, j = 0; i < 10; i++, j--) { // ok + } + + for (int i = 0; i < 4; i++) {} + } + }; + } + + class Suppress { + @SuppressWarnings("unused") + // violation above 'Each variable declaration must be in its own statement.' + long q1, q2, q3; + @SuppressWarnings("unused") + long q4, q5, q6; + // violation 2 lines above 'Each variable declaration must be in its own statement.' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputMultipleVariableDeclarations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputMultipleVariableDeclarations.java deleted file mode 100644 index bc34d3489085..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputMultipleVariableDeclarations.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule4821onevariableperline; - -public class InputMultipleVariableDeclarations -{ - int i, j; //warn - int i1; int j1; //warn - - void method1() { - String str, str1; //warn - java.lang.Object obj; Object obj1; //warn - } - // second definition is wrapped - // line of VARIABLE_DEF is not the same as first line of the definition - java.lang.String string; java.lang.String //warn - strings[]; - //both definitions is wrapped - java.lang. //warn - String string1; java.lang.String - strings1[]; - - void method2() { - for (int i=0, j=0; i < 10; i++, j--) { //ok - } - - for(int i=0; i<4;i++) { - - } - } - - class Inner { - int i, j; //warn - int i1; int j1; //warn - - void method1() { - String str, str1; //warn - java.lang.Object obj; Object obj1; //warn - } - // second definition is wrapped - // line of VARIABLE_DEF is not the same as first line of the definition - java.lang.String string; java.lang.String //warn - strings[]; - //both definitions is wrapped - java.lang. //warn - String string1; java.lang.String - strings1[]; - - void method2() { - for (int i=0, j=0; i < 10; i++, j--) { //ok - } - - for(int i=0; i<4;i++) { - - } - } - Inner anon = new Inner() - { - int i, j; //warn - int i1; int j1; //warn - - void method1() { - String str, str1; //warn - java.lang.Object obj; Object obj1; //warn - } - // second definition is wrapped - // line of VARIABLE_DEF is not the same as first line of the definition - java.lang.String string; java.lang.String //warn - strings[]; - //both definitions is wrapped - java.lang. //warn - String string1; java.lang.String - strings1[]; - - void method2() { - for (int i=0, j=0; i < 10; i++, j--) { //ok - } - - for(int i=0; i<4;i++) { - - } - } - }; - } -} - -class Suppress { - @SuppressWarnings("unused") //warn - long q1, q2, q3; - - @SuppressWarnings("unused") long q4, q5, q6; //warn -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputOneVariablePerDeclaration.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputOneVariablePerDeclaration.java new file mode 100644 index 000000000000..ee44e962f255 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4821onevariableperline/InputOneVariablePerDeclaration.java @@ -0,0 +1,117 @@ +package com.google.checkstyle.test.chapter4formatting.rule4821onevariableperline; + +/** Some javadoc. */ +public class InputOneVariablePerDeclaration { + int mnp, efg; // violation 'Each variable declaration must be in its own statement.' + int i1; int j1; + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' + + void method1() { + String str, str1; // violation 'Each variable declaration must be in its own statement.' + java.lang.Object obj; Object obj1; + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' + } + + // second definition is wrapped + // line of VARIABLE_DEF is not the same as first line of the definition + // violation below 'Only one variable definition per line allowed.' + java.lang.String string; java.lang.String[] + strings; + // both definitions are wrapped + // violation below 'Only one variable definition per line allowed.' + java.lang + .String string1; java.lang.String[] + strings1; + + void method2() { + for (int i = 0, j = 0; i < 10; i++, j--) { // ok + } + + for (int i = 0; i < 4; i++) {} + } + + class Inner { + int xyz, qwe; // violation 'Each variable declaration must be in its own statement.' + int i1; int j1; + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' + + void method1() { + String str, str1; + // violation above 'Each variable declaration must be in its own statement.' + java.lang.Object obj; Object obj1; + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' + } + + // second definition is wrapped + // line of VARIABLE_DEF is not the same as first line of the definition + // violation below 'Only one variable definition per line allowed.' + java.lang.String string; java.lang.String[] + strings; + // both definitions are wrapped + // violation below 'Only one variable definition per line allowed.' + java.lang + .String string1; java.lang.String[] + strings1; + + void method2() { + for (int i = 0, j = 0; i < 10; i++, j--) { // ok + } + + for (int i = 0; i < 4; i++) {} + } + + Inner anon = + new Inner() { + int abc, pqr; // violation 'Each variable declaration must be in its own statement.' + int i1; int j1; + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' + + void method1() { + String str, str1; + // violation above 'Each variable declaration must be in its own statement.' + java.lang.Object obj; Object obj1; + // 2 violations above: + // 'Only one variable definition per line allowed.' + // 'Only one statement per line allowed.' + } + + // second definition is wrapped + // line of VARIABLE_DEF is not the same as first line of the definition + // violation below 'Only one variable definition per line allowed.' + java.lang.String string; java.lang.String[] + strings; + // both definitions are wrapped + // violation below 'Only one variable definition per line allowed.' + java.lang + .String string1; java.lang.String[] + strings1; + // violation 2 lines above '.* incorrect indentation .*, expected .*: 10, 12, 14.' + + void method2() { + for (int i = 0, j = 0; i < 10; i++, j--) { // ok + } + + for (int i = 0; i < 4; i++) {} + } + }; + } + + class Suppress { + @SuppressWarnings("unused") + // violation above 'Each variable declaration must be in its own statement.' + long q1, q2, q3; + + @SuppressWarnings("unused") long q4, q5, q6; + // violation above 'Each variable declaration must be in its own statement.' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4822declaredwhenneeded/InputDeclaredWhenNeeded.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4822declaredwhenneeded/InputDeclaredWhenNeeded.java new file mode 100644 index 000000000000..7a2821f3f743 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4822declaredwhenneeded/InputDeclaredWhenNeeded.java @@ -0,0 +1,753 @@ +package com.google.checkstyle.test.chapter4formatting.rule4822declaredwhenneeded; + +import java.util.Calendar; +import java.util.Locale; +import java.util.TimeZone; + +/** Some javadoc. */ +public class InputDeclaredWhenNeeded { + + private static int test1 = 0; + + static { + int b = 0; + int d = 0; + { + d = ++b; + } + } + + static { + int c = 0; + int a = 3; + int b = 2; + { + a = a + b; + c = b; + } + { + c--; + } + a = 7; + } + + static { + int a = -1; + int b = 2; + b++; + int c = --b; + a = b; // DECLARATION OF VARIABLE 'a' SHOULD BE HERE (distance = 2) + } + + /** Some javadoc. */ + public InputDeclaredWhenNeeded(int test1) { + int temp = -1; + this.test1 = test1; + temp = test1; // DECLARATION OF VARIABLE 'temp' SHOULD BE HERE (distance = 2) + } + + /** Some javadoc. */ + public boolean testMethod() { + int temp = 7; + new InputDeclaredWhenNeeded(2); + String.valueOf(temp); // DECLARATION OF VARIABLE 'temp' SHOULD BE HERE (distance = 2) + boolean result = false; + String str = ""; + if (test1 > 1) { + str = "123"; + result = true; + } + return result; + } + + /** Some javadoc. */ + public void testMethod2() { + int count; + int a = 3; + int b = 2; + { + a = a + b - 5 + 2 * a; + count = b; // DECLARATION OF VARIABLE 'count' SHOULD BE HERE (distance = 2) + } + } + + /** Some javadoc. */ + public void testMethod3() { + int count; + // violation above 'Distance between variable 'count' .* first usage is 4, but allowed 3.*' + int a = 3; + int b = 3; + a = a + b; + b = a + a; + testMethod2(); + count = b; // DECLARATION OF VARIABLE 'count' SHOULD BE HERE (distance = 4) + } + + /** Some javadoc. */ + public void testMethod4(int arg) { + int d = 0; + for (int i = 0; i < 10; i++) { + d++; + if (i > 5) { + d += arg; + } + } + + String[] ar = {"1", "2"}; + for (String st : ar) { + System.identityHashCode(st); + } + } + + /** Some javadoc. */ + public void testMethod5() { + int arg = 7; + boolean b = true; + boolean bb = false; + if (b) { + if (!bb) { + b = false; + } + } + testMethod4(arg); // DECLARATION OF VARIABLE 'arg' SHOULD BE HERE (distance = 2) + } + + /** Some javadoc. */ + public void testMethod6() { + int blockNumWithSimilarVar = 3; + int dist = 0; + int index = 0; + int block = 0; + + if (blockNumWithSimilarVar <= 1) { + do { + dist++; + if (block > 4) { + break; + } + index++; + block++; + } while (index < 7); + } else { + while (index < 8) { + dist += block; + index++; + block++; + } + } + } + + /** Some javadoc. */ + public boolean testMethod7(int a) { + boolean res; + switch (a) { + case 1: + res = true; + break; + default: + res = false; + } + return res; + } + + /** Some javadoc. */ + public void testMethod8() { + int b = 0; + int c = 0; + int m = 0; + int n = 0; + { + c++; + b++; + } + { + n++; // DECLARATION OF VARIABLE 'n' SHOULD BE HERE (distance = 2) + m++; // DECLARATION OF VARIABLE 'm' SHOULD BE HERE (distance = 3) + b++; + } + } + + /** Some javadoc. */ + public void testMethod9() { + boolean result = false; + boolean b1 = true; + boolean b2 = false; + if (b1) { + if (!b2) { + result = true; + } + result = true; + } + } + + /** Some javadoc. */ + public boolean testMethod10() { + boolean result; + try { + result = true; + } catch (Exception e) { + result = false; + } finally { + result = false; + } + return result; + } + + /** Some javadoc. */ + public void testMethod11() { + int a = 0; + int b = 10; + boolean result; + try { + b--; + } catch (Exception e) { + b++; + result = false; // DECLARATION OF VARIABLE 'result' SHOULD BE HERE (distance = 2) + } finally { + a++; + } + } + + /** Some javadoc. */ + public void testMethod12() { + boolean result = false; + boolean b3 = true; + boolean b1 = true; + boolean b2 = false; + if (b1) { + if (b3) { + if (!b2) { + result = true; + } + result = true; + } + } + } + + /** Some javadoc. */ + public void testMethod13() { + int i = 9; + int j = 6; + int g = i + 8; + int k = j + 10; + } + + /** Some javadoc. */ + public void testMethod14() { + Session s = openSession(); + Transaction t = s.beginTransaction(); + // violation above 'Distance between variable 't' .* first usage is 5, but allowed 3.' + A a = new A(); + E d1 = new E(); + C1 c = new C1(); + E d2 = new E(); + a.setForward(d1); + d1.setReverse(a); + c.setForward(d2); // DECLARATION OF VARIABLE 'c' SHOULD BE HERE (distance = 3) + // DECLARATION OF VARIABLE 'd2' SHOULD BE HERE (distance = 3) + d2.setReverse(c); + Serializable aid = s.save(a); + Serializable d2id = s.save(d2); + t.commit(); // DECLARATION OF VARIABLE 't' SHOULD BE HERE (distance = 5) + s.close(); + } + + /** Some javadoc. */ + public boolean isCheckBoxEnabled(int path) { + String model = ""; + if (true) { + for (int index = 0; index < path; ++index) { + int nodeIndex = model.codePointAt(path); + if (model.contains("")) { + return false; + } + } + } else { + int nodeIndex = model.codePointAt(path); + if (model.contains("")) { + return false; + } + } + return true; + } + + /** Some javadoc. */ + public Object readObject(String in) throws Exception { + String startDay = new String(""); + String endDay = new String(""); + return new String(startDay + endDay); + } + + /** Some javadoc. */ + public int[] getSelectedIndices() { + int[] sel = new int[5]; + String model = ""; + int a = 0; + a++; + for (int index = 0; index < 5; ++index) { + sel[index] = Integer.parseInt(model.valueOf(a)); // DECLARATION OF VARIABLE 'sel' + // SHOULD BE HERE (distance = 2) + // DECLARATION OF VARIABLE 'model' + // SHOULD BE HERE (distance = 2) + } + return sel; + } + + /** Some javadoc. */ + public void testMethod15() { + String confDebug = ""; + if (!confDebug.equals("") && !confDebug.equals("null")) { + LogLog.warn("The \"" + "\" attribute is deprecated."); + LogLog.warn("Use the \"" + "\" attribute instead."); + LogLog.setInternalDebugging(confDebug, true); + } + + int i = 0; + int k = 7; + boolean b = false; + for (; i < k; i++) { + b = true; + k++; + } + + int sw; + switch (i) { + case 0: + k++; + sw = 0; // DECLARATION OF VARIABLE 'sw' SHOULD BE HERE (distance = 2) + break; + case 1: + b = false; + break; + default: + b = true; + } + + int wh = 0; + b = true; + do { + k--; + i++; + } while (wh > 0); // DECLARATION OF VARIABLE 'wh' SHOULD BE HERE (distance = 2) + + if (wh > 0) { + k++; + } else if (!b) { + i++; + } else { + i--; + } + } + + /** Some javadoc. */ + public void testMethod16() { + int wh = 1; + int i = 0; + int k = 7; + if (i > 0) { + k++; + } else if (wh > 0) { + i++; + } else { + i--; + } + } + + /** Some javadoc. */ + protected JmenuItem createSubMenuItem(LogLevel level) { + final JmenuItem result = new JmenuItem(level.toString()); + final LogLevel logLevel = level; + result.setMnemonic(level.toString().charAt(0)); + result.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + showLogLevelColorChangeDialog(result, logLevel); + // DECLARATION OF VARIABLE 'logLevel', SHOULD BE HERE (distance = 2) + } + }); + + return result; + } + + /** Some javadoc. */ + public static Color darker(Color color, double fraction) { + int red = (int) Math.round(color.getRed() * (1.0 - fraction)); + int green = (int) Math.round(color.getGreen() * (1.0 - fraction)); + int blue = (int) Math.round(color.getBlue() * (1.0 - fraction)); + + if (red < 0) { + red = 0; + } else if (red > 255) { + red = 255; + } + if (green < 0) { // DECLARATION OF VARIABLE 'green' SHOULD BE HERE (distance = 2) + green = 0; + } else if (green > 255) { + green = 255; + } + if (blue < 0) { // DECLARATION OF VARIABLE 'blue' SHOULD BE HERE (distance = 3) + // blue = 0; + } + + int alpha = color.getAlpha(); + + return new Color(red, green, blue, alpha); + } + + /** Some javadoc. */ + public void testFinal() { + AuthUpdateTask task = null; + final long intervalMs = 30 * 60000L; + Object authCheckUrl = null; + Object authInfo = null; + task = + new AuthUpdateTask( + authCheckUrl, + authInfo, + new IauthListener() { + @Override + public void authTokenChanged(String cookie, String token) { + fireAuthTokenChanged(cookie, token); + } + }); + + Timer timer = new Timer("Auth Guard", true); + timer.schedule(task, intervalMs / 2, intervalMs); // DECLARATION OF VARIABLE 'intervalMs' + // SHOULD BE HERE (distance = 2) + } + + /** Some javadoc. */ + public void testForCycle() { + int filterCount = 0; + for (int i = 0; i < 10; i++, filterCount++) { + int abc = 0; + System.identityHashCode(abc); + + for (int j = 0; j < 10; j++) { + abc = filterCount; + System.identityHashCode(abc); + } + } + } + + /** Some javadoc. */ + public void testIssue321() { + Option srcDdlFile = OptionBuilder.create("f"); + Option logDdlFile = OptionBuilder.create("o"); + Option help = OptionBuilder.create("h"); + + Options options = new Options(); + options.something(); + options.something(); + options.something(); + options.something(); + options.addOption(srcDdlFile, logDdlFile, help); // distance=1 + } + + /** Some javadoc. */ + public void testIssue322() { + int mm = Integer.parseInt("2"); + long timeNow = 0; + Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault()); + cal.setTimeInMillis(timeNow); + cal.set(Calendar.SECOND, 0); + cal.set(Calendar.MILLISECOND, 0); + cal.set(Calendar.HOUR_OF_DAY, mm); + cal.set(Calendar.MINUTE, mm); // distance=1 + } + + /** Some javadoc. */ + public void testIssue323(MyObject[] objects) { + Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault()); + for (int i = 0; i < objects.length; i++) { + objects[i].setEnabled(true); + objects[i].setColor(0x121212); + objects[i].setUrl("http://google.com"); + objects[i].setSize(789); + objects[i].setCalendar(cal); // distance=1 + } + } + + /** Some javadoc. */ + public String testIssue324(boolean flag) { + StringBuilder builder = new StringBuilder(); + builder.append("flag is "); + builder.append(flag); + final String line = ""; + if (flag) { + builder.append("line of AST is:"); + builder.append("\n"); + builder.append(String.valueOf(line)); // distance=1 + builder.append("\n"); + } + return builder.toString(); + } + + /** Some javadoc. */ + public void testIssue325() { + Option a = null; + Option b = null; + Option c = null; + boolean isCnull = isNull(c); // distance=1 + boolean isBnull = isNull(b); // distance=1 + boolean isAnull = isNull(a); // distance=1 + } + + /** Some javadoc. */ + public void testIssue326() { + Option aopt = null; + Option bopt = null; + Option copt = null; + isNull(copt); // distance = 1 + isNull(bopt); // distance = 2 + isNull(aopt); // distance = 3 + } + + /** Some javadoc. */ + public void testIssue327() { + String line = "abc"; + OtherWriter.write(line); + line.charAt(1); + Builder.append(line); + test(line, line, line); + } + + /** Some javadoc. */ + public void testIssue328(Writer w1, Writer w2, Writer w3) { + String l1 = "1"; + + w3.write(l1); // distance=3 + } + + /** Some javadoc. */ + public void testIssue329() { + Options options = new Options(); + Option myOption = null; + // violation above 'Distance between variable 'myOption' .* usage is 7, but allowed 3.' + options.addBindFile(null); + options.addBindFile(null); + options.addBindFile(null); + options.addBindFile(null); + options.addBindFile(null); + System.identityHashCode("message"); + myOption.setArgName("abc"); // distance=7 + } + + /** Some javadoc. */ + public void testIssue3210() { + Options options = new Options(); + Option myOption = null; + // violation above 'Distance between variable 'myOption' .* usage is 6, but allowed 3.' + options.addBindFile(null); + options.addBindFile(null); + options.addBindFile(null); + options.addBindFile(null); + options.addBindFile(null); + myOption.setArgName("q"); // distance=6 + } + + /** Some javadoc. */ + public int testIssue3211(String toDir) throws Exception { + int count = 0; + // violation above 'Distance between variable 'count' .* first usage is 4, but allowed 3.' + String[] files = {}; + + System.identityHashCode("Data archival started"); + files.notify(); + System.identityHashCode("sss"); + + if (files == null || files.length == 0) { + System.identityHashCode("No files on a remote site"); + } else { + System.identityHashCode("Files on remote site: " + files.length); + + for (String ftpFile : files) { + if (files.length == 0) { + "".concat(""); + ftpFile.concat(files[2]); + count++; + } + } + } + + System.lineSeparator(); + + return count; + } + + private Session openSession() { + return null; + } + + class Session { + + public Transaction beginTransaction() { + return null; + } + + public void close() {} + + public Serializable save(E d2) { + return null; + } + + public Serializable save(A a) { + return null; + } + } + + class Transaction { + + public void commit() {} + } + + class A { + + public void setForward(E d1) {} + } + + class E { + + public void setReverse(C1 c) {} + + public void setReverse(A a) {} + } + + class C1 { + + public void setForward(E d2) {} + } + + class Serializable {} + + class JmenuItem { + + public JmenuItem(String string) {} + + public void addActionListener(ActionListener actionListener) {} + + public void setMnemonic(char charAt) {} + } + + class LogLevel {} + + class ActionListener {} + + class ActionEvent {} + + private void showLogLevelColorChangeDialog(JmenuItem j, LogLevel l) {} + + static class Color { + + public Color(int red, int green, int blue, int alpha) {} + + public double getRed() { + return 0; + } + + public int getAlpha() { + return 0; + } + + public double getBlue() { + return 0; + } + + public double getGreen() { + return 0; + } + } + + class AuthUpdateTask { + + public AuthUpdateTask(Object authCheckUrl, Object authInfo, IauthListener authListener) {} + } + + interface IauthListener { + + void authTokenChanged(String cookie, String token); + } + + void fireAuthTokenChanged(String s, String s1) {} + + class Timer { + + public Timer(String string, boolean b) {} + + public void schedule(AuthUpdateTask authUpdateTask, long l, long intervalMs) {} + } + + class Option { + + public void setArgName(String string) {} + } + + boolean isNull(Option o) { + return false; + } + + class Writer { + + public void write(String l3) {} + } + + class Options { + + public void addBindFile(Object object) {} + + public void addOption(Option srcDdlFile, Option logDdlFile, Option help) {} + + public void something() {} + } + + class TreeMapNode { + + public TreeMapNode(String label, double d, DefaultValue defaultValue) {} + + public TreeMapNode(String label) {} + } + + class DefaultValue { + + public DefaultValue(double d) {} + } + + static class LogLog { + + public static void warn(String string) {} + + public static void setInternalDebugging(String confDebug, boolean b) {} + } + + static class OptionBuilder { + + public static Option create(String string) { + return null; + } + } + + class MyObject { + + public void setEnabled(boolean b) {} + + public void setCalendar(Calendar cal) {} + + public void setSize(int i) {} + + public void setUrl(String string) {} + + public void setColor(int i) {} + } + + static class OtherWriter { + + public static void write(String line) {} + } + + void test(String s, String s1, String s2) {} + + static class Builder { + + public static void append(String line) {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4822variabledistance/InputVariableDeclarationUsageDistanceCheck.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4822variabledistance/InputVariableDeclarationUsageDistanceCheck.java deleted file mode 100644 index a40cebc136e1..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4822variabledistance/InputVariableDeclarationUsageDistanceCheck.java +++ /dev/null @@ -1,806 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule4822variabledistance; -import java.util.*; -public class InputVariableDeclarationUsageDistanceCheck { - - private static int test1 = 0; - - static { - int b = 0; - int d = 0; - { - d = ++b; - } - } - - static { - int c = 0; - int a = 3; - int b = 2; - { - a = a + b; - c = b; - } - { - c--; - } - a = 7; - } - - static { - int a = -1; - int b = 2; - b++; - int c = --b; - a = b; // DECLARATION OF VARIABLE 'a' SHOULD BE HERE (distance = 2) - } - - public InputVariableDeclarationUsageDistanceCheck(int test1) { - int temp = -1; - this.test1 = test1; - temp = test1; // DECLARATION OF VARIABLE 'temp' SHOULD BE HERE (distance = 2) - } - - public boolean testMethod() { - int temp = 7; - new InputVariableDeclarationUsageDistanceCheck(2); - String.valueOf(temp); // DECLARATION OF VARIABLE 'temp' SHOULD BE HERE (distance = 2) - boolean result = false; - String str = ""; - if (test1 > 1) { - str = "123"; - result = true; - } - return result; - } - - public void testMethod2() { - int count; - int a = 3; - int b = 2; - { - a = a - + b - - 5 - + 2 - * a; - count = b; // DECLARATION OF VARIABLE 'count' SHOULD BE HERE (distance = 2) - } - } - - public void testMethod3() { - int count; //warn - int a = 3; - int b = 3; - a = a + b; - b = a + a; - testMethod2(); - count = b; // DECLARATION OF VARIABLE 'count' SHOULD BE HERE (distance = 4) - } - - public void testMethod4(int arg) { - int d = 0; - for (int i = 0; i < 10; i++) { - d++; - if (i > 5) { - d += arg; - } - } - - String ar[] = { "1", "2" }; - for (String st : ar) { - System.identityHashCode(st); - } - } - - public void testMethod5() { - int arg = 7; - boolean b = true; - boolean bb = false; - if (b) - if (!bb) - b = false; - testMethod4(arg); // DECLARATION OF VARIABLE 'arg' SHOULD BE HERE (distance = 2) - } - - public void testMethod6() { - int blockNumWithSimilarVar = 3; - int dist = 0; - int index = 0; - int block = 0; - - if (blockNumWithSimilarVar <= 1) { - do { - dist++; - if (block > 4) { - break; - } - index++; - block++; - } while (index < 7); - } else { - while (index < 8) { - dist += block; - index++; - block++; - } - } - } - - public boolean testMethod7(int a) { - boolean res; - switch (a) { - case 1: - res = true; - break; - default: - res = false; - } - return res; - } - - public void testMethod8() { - int b = 0; - int c = 0; - int m = 0; - int n = 0; - { - c++; - b++; - } - { - n++; // DECLARATION OF VARIABLE 'n' SHOULD BE HERE (distance = 2) - m++; // DECLARATION OF VARIABLE 'm' SHOULD BE HERE (distance = 3) - b++; - } - } - - public void testMethod9() { - boolean result = false; - boolean b1 = true; - boolean b2 = false; - if (b1) { - if (!b2) { - result = true; - } - result = true; - } - } - - public boolean testMethod10() { - boolean result; - try { - result = true; - } catch (Exception e) { - result = false; - } finally { - result = false; - } - return result; - } - - public void testMethod11() { - int a = 0; - int b = 10; - boolean result; - try { - b--; - } catch (Exception e) { - b++; - result = false; // DECLARATION OF VARIABLE 'result' SHOULD BE HERE (distance = 2) - } finally { - a++; - } - } - - public void testMethod12() { - boolean result = false; - boolean b3 = true; - boolean b1 = true; - boolean b2 = false; - if (b1) { - if (b3) { - if (!b2) { - result = true; - } - result = true; - } - } - } - - public void testMethod13() { - int i = 9; - int j = 6; - int g = i + 8; - int k = j + 10; - } - - public void testMethod14() { - Session s = openSession(); - Transaction t = s.beginTransaction(); //warn - A a = new A(); - E d1 = new E(); - C1 c = new C1(); - E d2 = new E(); - a.setForward(d1); - d1.setReverse(a); - c.setForward(d2); // DECLARATION OF VARIABLE 'c' SHOULD BE HERE (distance = 3) - // DECLARATION OF VARIABLE 'd2' SHOULD BE HERE (distance = 3) - d2.setReverse(c); - Serializable aid = s.save(a); - Serializable d2id = s.save(d2); - t.commit(); // DECLARATION OF VARIABLE 't' SHOULD BE HERE (distance = 5) - s.close(); - } - - public boolean isCheckBoxEnabled(int path) { - String model = ""; - if (true) { - for (int index = 0; index < path; ++index) { - int nodeIndex = model.codePointAt(path); - if (model.contains("")) { - return false; - } - } - } else { - int nodeIndex = model.codePointAt(path); - if (model.contains("")) { - return false; - } - } - return true; - } - - public Object readObject(String in) throws Exception { - String startDay = new String(""); - String endDay = new String(""); - return new String(startDay + endDay); - } - - public int[] getSelectedIndices() { - int[] sel = new int[5]; - String model = ""; - int a = 0; - a++; - for (int index = 0; index < 5; ++index) { - sel[index] = Integer.parseInt(model.valueOf(a)); // DECLARATION OF VARIABLE 'sel' - // SHOULD BE HERE (distance = 2) - // DECLARATION OF VARIABLE 'model' - // SHOULD BE HERE (distance = 2) - } - return sel; - } - - public void testMethod15() { - String confDebug = ""; - if (!confDebug.equals("") && !confDebug.equals("null")) { - LogLog.warn("The \"" + "\" attribute is deprecated."); - LogLog.warn("Use the \"" + "\" attribute instead."); - LogLog.setInternalDebugging(confDebug, true); - } - - int i = 0; - int k = 7; - boolean b = false; - for (; i < k; i++) { - b = true; - k++; - } - - int sw; - switch (i) { - case 0: - k++; - sw = 0; // DECLARATION OF VARIABLE 'sw' SHOULD BE HERE (distance = 2) - break; - case 1: - b = false; - break; - default: - b = true; - } - - int wh = 0; - b = true; - do { - k--; - i++; - } while (wh > 0); // DECLARATION OF VARIABLE 'wh' SHOULD BE HERE (distance = 2) - - if (wh > 0) { - k++; - } else if (!b) { - i++; - } else { - i--; - } - } - - public void testMethod16() { - int wh = 1, i = 4, k = 0; - if (i > 0) { - k++; - } else if (wh > 0) { - i++; - } else { - i--; - } - } - - protected JMenuItem createSubMenuItem(LogLevel level) { - final JMenuItem result = new JMenuItem(level.toString()); - final LogLevel logLevel = level; - result.setMnemonic(level.toString().charAt(0)); - result.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - showLogLevelColorChangeDialog(result, logLevel); // DECLARATION OF VARIABLE 'logLevel' - // SHOULD BE HERE (distance = 2) - } - }); - - return result; - - } - - public static Color darker(Color color, double fraction) { - int red = (int) Math.round(color.getRed() * (1.0 - fraction)); - int green = (int) Math.round(color.getGreen() * (1.0 - fraction)); - int blue = (int) Math.round(color.getBlue() * (1.0 - fraction)); - - if (red < 0) { - red = 0; - } else if (red > 255) { - red = 255; - } - if (green < 0) { // DECLARATION OF VARIABLE 'green' SHOULD BE HERE (distance = 2) - green = 0; - } else if (green > 255) { - green = 255; - } - if (blue < 0) { // DECLARATION OF VARIABLE 'blue' SHOULD BE HERE (distance = 3) - // blue = 0; - } - - int alpha = color.getAlpha(); - - return new Color(red, green, blue, alpha); - } - - public void testFinal() { - AuthUpdateTask task = null; - final long intervalMs = 30 * 60000L; - Object authCheckUrl = null, authInfo = null; - task = new AuthUpdateTask(authCheckUrl, authInfo, new IAuthListener() { - @Override - public void authTokenChanged(String cookie, String token) { - fireAuthTokenChanged(cookie, token); - } - }); - - Timer timer = new Timer("Auth Guard", true); - timer.schedule(task, intervalMs / 2, intervalMs); // DECLARATION OF VARIABLE 'intervalMs' - // SHOULD BE HERE (distance = 2) - } - - public void testForCycle() { - int filterCount = 0; - for (int i = 0; i < 10; i++, filterCount++) { - int abc = 0; - System.identityHashCode(abc); - - for (int j = 0; j < 10; j++) { - abc = filterCount; - System.identityHashCode(abc); - } - } - } - - public void testIssue32_1() - { - Option srcDdlFile = OptionBuilder.create("f"); - Option logDdlFile = OptionBuilder.create("o"); - Option help = OptionBuilder.create("h"); - - Options options = new Options(); - options.something(); - options.something(); - options.something(); - options.something(); - options.addOption(srcDdlFile, logDdlFile, help); // distance=1 - } - - public void testIssue32_2() - { - int mm = Integer.parseInt("2"); - long timeNow = 0; - Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault()); - cal.setTimeInMillis(timeNow); - cal.set(Calendar.SECOND, 0); - cal.set(Calendar.MILLISECOND, 0); - cal.set(Calendar.HOUR_OF_DAY, mm); - cal.set(Calendar.MINUTE, mm); // distance=1 - } - - public void testIssue32_3(MyObject[] objects) { - Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault()); - for(int i=0; i=8 - - int length = new ClassWithChainedMethods("param1", //indent:4 exp:4 - "param2").getInstance() //indent:32 exp:>=8 - .doNothing("nothing") //indent:4 exp:>=8 warn - .length(); //indent:4 exp:>=8 warn - - int length2 = //indent:4 exp:4 - new ClassWithChainedMethods("param1","param2") //indent:4 exp:>=8 warn - .getInstance() //indent:8 exp:8 - .doNothing("nothing") //indent:8 exp:8 - .length(); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/ClassWithChainedMethodsCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/ClassWithChainedMethodsCorrect.java deleted file mode 100644 index 7f80141778c4..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/ClassWithChainedMethodsCorrect.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0 - -public class ClassWithChainedMethodsCorrect { //indent:0 exp:0 - public ClassWithChainedMethodsCorrect() { //indent:2 exp:2 - - String someString = ""; //indent:4 exp:4 - - String chained1 = //indent:4 exp:4 - doNothing( //indent:8 exp:8 - someString //indent:12 exp:12 - .concat("zyx" //indent:16 exp:16 - ) //indent:16 exp:16 - .concat("255, 254, 253" //indent:16 exp:16 - ) //indent:16 exp:16 - ); //indent:8 exp:8 - - doNothing( //indent:4 exp:4 - someString //indent:8 exp:8 - .concat("zyx" //indent:12 exp:12 - ) //indent:12 exp:12 - .concat("255, 254, 253" //indent:12 exp:12 - ) //indent:12 exp:12 - ); //indent:4 exp:4 - - } //indent:2 exp:2 - - public String doNothing(String something) { //indent:2 exp:2 - return something; //indent:4 exp:4 - } //indent:2 exp:2 - - public static void main(String[] args) { //indent:2 exp:2 - ClassWithChainedMethodsCorrect classWithChainedMethodsCorrect = //indent:4 exp:4 - new ClassWithChainedMethodsCorrect(); //indent:8 exp:8 - } //indent:2 exp:2 - -} //indent:0 exp:0 diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultiline.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultiline.java new file mode 100644 index 000000000000..7fcb4ff0d874 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultiline.java @@ -0,0 +1,58 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** some annotation. */ +@InputAnnotationArrayInitMultiline.AnnotList({ + @InputAnnotationArrayInitMultiline.Annot( + "hello-Goodbye world in one very long and lengthy string in annoation array"), + @InputAnnotationArrayInitMultiline.Annot( + "suppressUnnecessaryWarningsByCheckstyleIndentationCheck Annotation"), + @InputAnnotationArrayInitMultiline.Annot( + "this property is lineWrappingIndenation of Indentation Check") +}) +@ComponentScan( + basePackages = "io.camunda.operate", + excludeFilters = { + @ComponentScan.Filter( + type = FilterType.REGEX, + pattern = "io\\.camunda\\.operate\\.zeebeimport\\..*"), + @ComponentScan.Filter( + type = FilterType.REGEX, + pattern = "io\\.camunda\\.operate\\.webapp\\..*") + } +) +public class InputAnnotationArrayInitMultiline { + + @interface Annot { + String value() default ""; + + String[] values() default {"Hello", "Checkstyle"}; + } + + @interface AnnotList { + InputAnnotationArrayInitMultiline.Annot[] value(); + } +} + +// violation below 'Top-level class FilterType has to reside in its own source file.' +enum FilterType { + REGEX, + ANNOTATION, + ASSIGNABLE_TYPE +} + +// violation below 'Top-level class ComponentScan has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ComponentScan { + String[] basePackages() default {}; + + Filter[] excludeFilters() default {}; + + @interface Filter { + FilterType type(); + + String pattern(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultiline2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultiline2.java new file mode 100644 index 000000000000..363f28cf45bf --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultiline2.java @@ -0,0 +1,109 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +// violation below 'Top-level class TagNameAndDescriptionNew has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface TagNameAndDescriptionNew { + String name(); + + String description() default ""; + + ExternalDocumentation externalDocs() default @ExternalDocumentation; +} + +// violation below 'Top-level class ExternalDocumentation has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ExternalDocumentation { + String description() default ""; + + String url() default ""; +} + +// violation below 'Top-level class OperationFinal has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface OperationFinal { + String summary() default ""; +} + +// violation below 'Top-level class ApiResponses has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ApiResponses { + ApiResponse[] value(); +} + +// violation below 'Top-level class ApiResponse has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ApiResponse { + String responseCode(); + + String description() default ""; + + ContentSchema[] content() default {}; +} + +// violation below 'Top-level class ContentSchema has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ContentSchema { + String mediaType() default ""; + + SchemaStatus schema() default @SchemaStatus; +} + +// violation below 'Top-level class SchemaStatus has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface SchemaStatus { + Class implementation() default Void.class; +} + +// violation below 'Top-level class ResponseStatus has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ResponseStatus { + HttpStatus value(); +} + +// violation below 'Top-level class HttpStatus has to reside in its own source file.' +enum HttpStatus { + OK, + NOT_FOUND, + INTERNAL_SERVER_ERROR +} + +// violation below 'Top-level class CustomResponseDto has to reside in its own source file.' +class CustomResponseDto {} + +// violation below 'Top-level class ErrorDto has to reside in its own source file.' +class ErrorDto {} + +/** some javadoc. */ +@TagNameAndDescriptionNew( + name = "${something1.something2.something3}", + description = "Endpoint for blah blah blah activities", + externalDocs = @ExternalDocumentation( + description = "Consuming something from the queue", + url = "https://google.com" + ) +) +public interface InputAnnotationArrayInitMultiline2 { + + /** some javadoc. */ + @OperationFinal(summary = "Retrieves something for verifying something") + @ResponseStatus(HttpStatus.OK) + @ApiResponses(value = { + @ApiResponse( + responseCode = "500", + description = "Internal server error occurred", + content = { + @ContentSchema( + mediaType = "application/json", + schema = @SchemaStatus(implementation = ErrorDto.class) + ) + } + ) + }) + ResponseEntity getAnswer(); +} + +// violation below 'Top-level class ResponseEntity has to reside in its own source file.' +class ResponseEntity {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultilineCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultilineCorrect.java new file mode 100644 index 000000000000..578a75cf19c9 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputAnnotationArrayInitMultilineCorrect.java @@ -0,0 +1,26 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some annotation. */ +@InputAnnotationArrayInitMultilineCorrect.AnnotList({ + @InputAnnotationArrayInitMultilineCorrect.Annot( + "hello-Goodbye world in one very long and lengthy string in annoation array"), + @InputAnnotationArrayInitMultilineCorrect.Annot( + "suppressUnnecessaryWarningsByCheckstyleIndentationCheck Annotation"), + @InputAnnotationArrayInitMultilineCorrect.Annot( + "this property is lineWrappingIndenation of Indentation Check") +}) +public class InputAnnotationArrayInitMultilineCorrect { + int testMethod1(int val) { + return val + 1; + } + + @interface Annot { + String value() default ""; + + String[] values() default {"Hello", "Checkstyle"}; + } + + @interface AnnotList { + InputAnnotationArrayInitMultilineCorrect.Annot[] value(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputCatchParametersOnNewLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputCatchParametersOnNewLine.java new file mode 100644 index 000000000000..9940f6978783 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputCatchParametersOnNewLine.java @@ -0,0 +1,69 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputCatchParametersOnNewLine { + + /** some test Method. */ + public void test1() { + try { + System.out.println("try0"); + } catch (NullPointerException | IllegalArgumentException expected) { + // ignore + } + } + + void test2() { + try { + System.out.println("try"); + } catch ( + @SuppressWarnings("PMD.AvoidCatchingGenericException") + Exception e) { + java.util.logging.Logger.getAnonymousLogger().severe(e.toString()); + } + + try { + System.out.println("try1"); + } catch ( + @SuppressWarnings("suppression") + Exception e) { + java.util.logging.Logger.getAnonymousLogger().severe(e.toString()); + } + } + + void test3() { + try { + System.out.println("try"); + } catch ( + @SuppressWarnings("") + Exception e) { + java.util.logging.Logger.getAnonymousLogger().severe(e.toString()); + } + } + + void test4() { + try { + System.out.println("try"); + } catch (NullPointerException | IllegalArgumentException expected) { + // ignore + } + } + + private static String test5() { + final String simplePropertyUpdateScript = """ + s + """; + return (""" + def newInstance = params.instance; + def existingInstance = ctx._source; + """ // violation '.* incorrect indentation level 6, expected .* 8.' + + simplePropertyUpdateScript); + } + + void test2Incorrect(boolean result) { + int collect = result + ? 0 : // violation '.* incorrect indentation level 6, expected .* 8.' + 1; // violation '.* incorrect indentation level 6, expected .* 8.' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputClassWithChainedMethods.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputClassWithChainedMethods.java new file mode 100644 index 000000000000..adbcfecf3275 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputClassWithChainedMethods.java @@ -0,0 +1,34 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputClassWithChainedMethods { + + /** some javadoc. */ + public InputClassWithChainedMethods(Object... params) {} + + /** some javadoc. */ + public static void main(String[] args) { + new InputClassWithChainedMethods() + .getInstance("string_one") + .doNothing("string_one".trim(), "string_two"); + // violation above ''method call' child has incorrect indentation level 4, expected .* 8.' + + String test = + new InputClassWithChainedMethods("param1", "param2").getInstance().doNothing("nothing"); + // violation above ''new' has incorrect indentation level 4, expected .* 8.' + + String test2 = + new InputClassWithChainedMethods("param1", "param2").getInstance().doNothing("nothing"); + // violation above ''new' has incorrect indentation level 4, expected .* 8.' + } + + /** some javadoc. */ + public String doNothing(String something, String... uselessParams) { + return something; + } + + /** some javadoc. */ + public InputClassWithChainedMethods getInstance(String... uselessParams) { + return this; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputClassWithChainedMethodsCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputClassWithChainedMethodsCorrect.java new file mode 100644 index 000000000000..9bd31e1baa06 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputClassWithChainedMethodsCorrect.java @@ -0,0 +1,25 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputClassWithChainedMethodsCorrect { + /** some javadoc. */ + public InputClassWithChainedMethodsCorrect() { + + String someString = ""; + + String chained1 = doNothing(someString.concat("zyx").concat("255, 254, 253")); + + doNothing(someString.concat("zyx").concat("255, 254, 253")); + } + + /** some javadoc. */ + public static void main(String[] args) { + InputClassWithChainedMethodsCorrect classWithChainedMethodsCorrect = + new InputClassWithChainedMethodsCorrect(); + } + + /** some javadoc. */ + public String doNothing(String something) { + return something; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFastMatcher.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFastMatcher.java index 6d3e561ca622..891788e885cd 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFastMatcher.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFastMatcher.java @@ -1,42 +1,41 @@ package com.google.checkstyle.test.chapter4formatting.rule4841indentation; -public class InputFastMatcher -{ - - public boolean matches(char c) - { - // OOOO Auto-generated method stub - return false; - } - - public String replaceFrom(CharSequence sequence, CharSequence replacement) - { - // OOOO Auto-generated method stub - return null; - } - - public String collapseFrom(CharSequence sequence, char replacement) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimFrom(CharSequence s) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimLeadingFrom(CharSequence sequence) - { - // OOOO Auto-generated method stub - return null; - } - - public String trimTrailingFrom(CharSequence sequence) - { - // OOOO Auto-generated method stub - return null; - } - +/** some javadoc. */ +public class InputFastMatcher { + + /** some javadoc. */ + public boolean matches(char c) { + // OOOO Auto-generated method stub + return false; + } + + /** some javadoc. */ + public String replaceFrom(CharSequence sequence, CharSequence replacement) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String collapseFrom(CharSequence sequence, char replacement) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimFrom(CharSequence s) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimLeadingFrom(CharSequence sequence) { + // OOOO Auto-generated method stub + return null; + } + + /** some javadoc. */ + public String trimTrailingFrom(CharSequence sequence) { + // OOOO Auto-generated method stub + return null; + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedAnnotationArrayInitMultiline.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedAnnotationArrayInitMultiline.java new file mode 100644 index 000000000000..3bae3916b222 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedAnnotationArrayInitMultiline.java @@ -0,0 +1,57 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** some annotation. */ +@InputAnnotationArrayInitMultiline.AnnotList({ + @InputAnnotationArrayInitMultiline.Annot( + "hello-Goodbye world in one very long and lengthy string in annoation array"), + @InputAnnotationArrayInitMultiline.Annot( + "suppressUnnecessaryWarningsByCheckstyleIndentationCheck Annotation"), + @InputAnnotationArrayInitMultiline.Annot( + "this property is lineWrappingIndenation of Indentation Check") +}) +@ComponentShow( + basePackages = "io.camunda.operate", + excludeFilters = { + @ComponentShow.Filter( + type = FilterClass.REGEX, + pattern = "io\\.camunda\\.operate\\.zeebeimport\\..*"), + @ComponentShow.Filter( + type = FilterClass.REGEX, + pattern = "io\\.camunda\\.operate\\.webapp\\..*") + }) +public class InputFormattedAnnotationArrayInitMultiline { + + @interface Annot { + String value() default ""; + + String[] values() default {"Hello", "Checkstyle"}; + } + + @interface AnnotList { + InputAnnotationArrayInitMultiline.Annot[] value(); + } +} + +// violation below 'Top-level class FilterClass has to reside in its own source file.' +enum FilterClass { + REGEX, + ANNOTATION, + ASSIGNABLE_TYPE +} + +// violation below 'Top-level class ComponentShow has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ComponentShow { + String[] basePackages() default {}; + + Filter[] excludeFilters() default {}; + + @interface Filter { + FilterClass type(); + + String pattern(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedAnnotationArrayInitMultiline2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedAnnotationArrayInitMultiline2.java new file mode 100644 index 000000000000..bfc8a76b6a70 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedAnnotationArrayInitMultiline2.java @@ -0,0 +1,107 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +// violation below 'Top-level class TagNameAndDescription has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface TagNameAndDescription { + String name(); + + String description() default ""; + + OptionalCase externalDocs() default @OptionalCase; +} + +// violation below 'Top-level class OptionalCase has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface OptionalCase { + String description() default ""; + + String url() default ""; +} + +// violation below 'Top-level class Operation has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface Operation { + String summary() default ""; +} + +// violation below 'Top-level class ApiResponsesOne has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ApiResponsesOne { + ApiResponsesTwo[] value(); +} + +// violation below 'Top-level class ApiResponsesTwo has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ApiResponsesTwo { + String responseCode(); + + String description() default ""; + + ContentSchemaOne[] content() default {}; +} + +// violation below 'Top-level class ContentSchemaOne has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ContentSchemaOne { + String mediaType() default ""; + + SchemaStatusShow schema() default @SchemaStatusShow; +} + +// violation below 'Top-level class SchemaStatusShow has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface SchemaStatusShow { + Class implementation() default Void.class; +} + +// violation below 'Top-level class ResponseValueShow has to reside in its own source file.' +@Retention(RetentionPolicy.RUNTIME) +@interface ResponseValueShow { + DummyHttp value(); +} + +// violation below 'Top-level class DummyHttp has to reside in its own source file.' +enum DummyHttp { + OK, + NOT_FOUND, + INTERNAL_SERVER_ERROR +} + +// violation below 'Top-level class ResponseDot has to reside in its own source file.' +class ResponseDot {} + +// violation below 'Top-level class ErrorDot has to reside in its own source file.' +class ErrorDot {} + +/** some javadoc. */ +@TagNameAndDescription( + name = "${something1.something2.something3}", + description = "Endpoint for blah blah blah activities", + externalDocs = + @OptionalCase( + description = "Consuming something from the queue", + url = "https://google.com")) +public interface InputFormattedAnnotationArrayInitMultiline2 { + + /** some javadoc. */ + @Operation(summary = "Retrieves something for verifying something") + @ResponseValueShow(DummyHttp.OK) + @ApiResponsesOne( + value = { + @ApiResponsesTwo( + responseCode = "500", + description = "Internal server error occurred", + content = { + @ContentSchemaOne( + mediaType = "application/json", + schema = @SchemaStatusShow(implementation = ErrorDot.class)) + }) + }) + ResponseExitCode getAnswer(); +} + +// violation below 'Top-level class ResponseExitCode has to reside in its own source file.' +class ResponseExitCode {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedCatchParametersOnNewLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedCatchParametersOnNewLine.java new file mode 100644 index 000000000000..a6f3b0b188a3 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedCatchParametersOnNewLine.java @@ -0,0 +1,68 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputFormattedCatchParametersOnNewLine { + + /** some test Method. */ + public void test1() { + try { + System.out.println("try0"); + } catch (NullPointerException | IllegalArgumentException expected) { + // ignore + } + } + + void test2() { + try { + System.out.println("try"); + } catch ( + @SuppressWarnings("PMD.AvoidCatchingGenericException") + Exception e) { + java.util.logging.Logger.getAnonymousLogger().severe(e.toString()); + } + + try { + System.out.println("try1"); + } catch ( + @SuppressWarnings("suppression") + Exception e) { + java.util.logging.Logger.getAnonymousLogger().severe(e.toString()); + } + } + + void test3() { + try { + System.out.println("try"); + } catch ( + @SuppressWarnings("") + Exception e) { + java.util.logging.Logger.getAnonymousLogger().severe(e.toString()); + } + } + + void test4() { + try { + System.out.println("try"); + } catch (NullPointerException | IllegalArgumentException expected) { + // ignore + } + } + + private static String test5() { + final String simplePropertyUpdateScript = + """ + s + """; + return (""" + def newInstance = params.instance; + def existingInstance = ctx._source; + """ // violation '.* incorrect indentation level 4, expected .* 8.' + + simplePropertyUpdateScript); + } + + void test2Incorrect(boolean result) { + int collect = result ? 0 : 1; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedClassWithChainedMethods.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedClassWithChainedMethods.java new file mode 100644 index 000000000000..81ea0c2bf28c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedClassWithChainedMethods.java @@ -0,0 +1,35 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputFormattedClassWithChainedMethods { + + /** some javadoc. */ + public InputFormattedClassWithChainedMethods(Object... params) {} + + /** some javadoc. */ + public static void main(String[] args) { + new InputFormattedClassWithChainedMethods() + .getInstance("string_one") + .doNothing("string_one".trim(), "string_two"); + + String test = + new InputFormattedClassWithChainedMethods("param1", "param2") + .getInstance() + .doNothing("nothing"); + + String test2 = + new InputFormattedClassWithChainedMethods("param1", "param2") + .getInstance() + .doNothing("nothing"); + } + + /** some javadoc. */ + public String doNothing(String something, String... uselessParams) { + return something; + } + + /** some javadoc. */ + public InputFormattedClassWithChainedMethods getInstance(String... uselessParams) { + return this; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLambdaAndChildOnTheSameLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLambdaAndChildOnTheSameLine.java new file mode 100644 index 000000000000..cf554826d300 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLambdaAndChildOnTheSameLine.java @@ -0,0 +1,85 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.lang.reflect.Proxy; + +/** some javadoc. */ +public class InputFormattedLambdaAndChildOnTheSameLine { + + enum A { + A1, + A2, + A3, + A4, + A5 + } + + enum B { + B1, + B2, + B3, + B4, + B5 + } + + enum R { + R1, + R2; + + boolean isOk() { + return this == R2; + } + } + + boolean testMethod1(A a, B b, R r) { + return switch (a) { + case A1 -> + switch (b) { + case B1, B2 -> true; + case B3 -> r != R.R1; + case B4 -> false; + case B5 -> throw new IllegalStateException("Unexpected: " + b); + }; + case A2, A3 -> + switch (b) { + case B1 -> r.isOk(); + case B2, B3 -> false; + case B4 -> true; + case B5 -> throw new RuntimeException("Test: " + b); + }; + case A4 -> false; + case A5 -> throw new IllegalArgumentException("Bad A: " + a); + }; + } + + void testMethod2() { + var service = + (CharSequence) + Proxy.newProxyInstance( + InputFormattedLambdaAndChildOnTheSameLine.class.getClassLoader(), + new Class[] {CharSequence.class}, + (proxy, method, methodArgs) -> + switch (method.getName()) { + case "hashCode" -> 123456789; + case "equals" -> methodArgs[0] == proxy; + case "toString" -> "FakeInstanceServiceA"; + default -> throw new IllegalArgumentException(method.getName()); + }); + } + + void testMethod3() { + var service = + (CharSequence) + Proxy.newProxyInstance( + InputFormattedLambdaAndChildOnTheSameLine.class.getClassLoader(), + new Class[] {CharSequence.class}, + (proxy, method, methodArgs) -> + switch (method.getName()) { + case "hashCode" -> 123456789; + case "equals" -> methodArgs[0] == proxy; + case "toString" -> "FakeInstanceServiceA"; + default -> throw new IllegalArgumentException(method.getName()); + }); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLambdaChild.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLambdaChild.java new file mode 100644 index 000000000000..bb53f6eaa7e0 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLambdaChild.java @@ -0,0 +1,69 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + +/** some javadoc. */ +public class InputFormattedLambdaChild { + String testMethod1(List operations) { + return operations.stream() + .map( + op -> + switch (op) { + case 1 -> "test"; + default -> "TEST"; + }) + .findFirst() + .orElse("defaultValue"); + } + + String testMethod2(List operations) { + return operations.stream() + .map( + op -> + switch (op) { + case 1 -> "test"; + default -> "TEST"; + }) + .findFirst() + .orElse("defaultValue"); + } + + void main(String[] args) { + group( + (Function) + x -> + switch (x) { + default: + yield x; + }, + (Function) + x -> + switch (x) { + default: + yield x; + }); + } + + List getThrowsTrees(Object input) { + return getBlockTags( + input, + kind -> + switch (kind) { + case "EXCEPTION", "THROWS" -> true; + default -> false; + }, + String.class); + } + + void group(Function f1, Function f2) { + // Dummy method to test syntax/indentation + } + + List getBlockTags(Object input, Predicate filter, Class type) { + return List.of(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLineBreakAfterLeftCurlyOfBlockInSwitch.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLineBreakAfterLeftCurlyOfBlockInSwitch.java new file mode 100644 index 000000000000..cf0add0c0fb5 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedLineBreakAfterLeftCurlyOfBlockInSwitch.java @@ -0,0 +1,40 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputFormattedLineBreakAfterLeftCurlyOfBlockInSwitch { + + void testMethod1(int month) { + int result = + switch (month) { + case 1, 6, 7 -> { + System.out.println("try"); + yield 1; + } + case 2, 9, 10, 11, 12 -> { + yield 2; + } + case 3, 5, 4, 8 -> { + yield month << 2; + } + default -> 0; + }; + } + + void testMethod2(int number) { + switch (number) { + case 0, 1 -> System.out.println("0"); + case 2 -> handleTwoWithAnExtremelyLongMethodCallThatWouldNotFitOnTheSameLine(); + default -> { + handleSurprisingNumber(number); + } + } + } + + private static int handleSurprisingNumber(int number) { + return number; + } + + private int handleTwoWithAnExtremelyLongMethodCallThatWouldNotFitOnTheSameLine() { + return 0; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedNewKeywordChildren.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedNewKeywordChildren.java new file mode 100644 index 000000000000..13074eb50083 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedNewKeywordChildren.java @@ -0,0 +1,75 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Optional; + +/** some data. */ +public class InputFormattedNewKeywordChildren { + + static { + try { + Class.forName("org.postgresql.Driver"); + } catch (ClassNotFoundException e) { + throw new IllegalStateException( + "Please check if you have proper PostgreSQL JDBC Driver jar on the classpath", e); + } + } + + static { + try { + Class.forName("org.postgresql.Driver"); + } catch (ClassNotFoundException e) { + throw new IllegalStateException( + "Please check if you have proper PostgreSQL JDBC Driver jar on the classpath", e); + } + } + + /** some data. */ + public Object foo() { + return Optional.empty() + .orElseThrow( + () -> + new IllegalArgumentException( + "Something wrong 1, something wrong 2, something wrong 3")); + } + + /** some data. */ + public void foo2() throws IOException { + BufferedReader bf = + new BufferedReader( + new InputStreamReader(System.in) { + int anInt = 0; + }); + } + + /** some data. */ + public Object foo4(int data) { + return Optional.empty() + .orElseThrow( + () -> + new IllegalArgumentException( + "something wrong 1, something wrong 2, something wrong 3")); + } + + /** some data. */ + public Object foo5(int data) { + return Optional.empty() + .orElseThrow( + () -> + new IllegalArgumentException( + "something wrong 1, something wrong 2, something wrong 3")); + } + + /** some data. */ + public void createExpressionIssue(Object invocation, String toBeRemovedExpression) { + throw new IllegalArgumentException( + "The expression " + + toBeRemovedExpression + + ", which creates argument of the invocation " + + invocation + + " cannot be removed." + + " Override method `canRemoveExpression` to customize this behavior."); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSingleSwitchStatementWithoutCurly.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSingleSwitchStatementWithoutCurly.java new file mode 100644 index 000000000000..170eec3f1304 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSingleSwitchStatementWithoutCurly.java @@ -0,0 +1,45 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputFormattedSingleSwitchStatementWithoutCurly { + void testCorrectIndentation(int obj) { + switch (obj) { + case 0 -> System.out.println("Test"); + case 1 -> System.out.println("TEST"); + case 2 -> { + System.out.println("Test"); + } + default -> System.out.println("test"); + } + } + + void testIncorrectIndentation(int obj) { + switch (obj) { + case 1 -> System.out.println("Test"); + case 2 -> System.out.println("Test"); + default -> System.out.println("test"); + } + } + + void testMixedCases(int obj) { + switch (obj) { + case 1 -> System.out.println("TEST"); + case 2 -> System.out.println("Test"); + case 3 -> System.out.println("Test"); + case 4 -> { + System.out.println("Test"); + System.out.println("Another statement"); + } + default -> System.out.println("test"); + } + } + + private boolean testLineWrapping(int x, int y, int z) { + return switch (x) { + case 1 -> true; + case 2 -> x != y && y != 5; + case 3 -> y != 4 && z != 2 && y != z; + default -> false; + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSwitchOnStartOfTheLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSwitchOnStartOfTheLine.java new file mode 100644 index 000000000000..f81b7e01723f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSwitchOnStartOfTheLine.java @@ -0,0 +1,47 @@ +// Java17 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputFormattedSwitchOnStartOfTheLine { + String testMethod1(int i) { + String s = + switch (i) { + case 1 -> "one"; + case 2 -> "two"; + default -> "zero"; + }; + return s; + } + + void testMethod2(int month) { + int result = + switch (month) { + case 1, 6, 7 -> 3; + case 2, 9, 10, 11, 12 -> 1; + case 3, 5, 4, 8 -> { + yield month * 4; + } + default -> 0; + }; + } + + void testMethod3Invalid(int num) { + int odd = + switch (num) { + case 1, 3, 7 -> 1; + case 2, 4, 6 -> 2; + default -> 0; + }; + } + + String testMethod4Invalid(int i) { + String s = + switch (i) { + case 1 -> "one"; + case 2 -> "two"; + default -> "zero"; + }; + return s; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSwitchWrappingIndentation.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSwitchWrappingIndentation.java new file mode 100644 index 000000000000..381059409526 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputFormattedSwitchWrappingIndentation.java @@ -0,0 +1,51 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.util.List; + +/** some javadoc. */ +public class InputFormattedSwitchWrappingIndentation { + String testMethod1(int i) { + String name = ""; + name = + switch (i) { + case 1 -> "one"; + case 2 -> "two"; + default -> "zero"; + }; + return name; + } + + String testMethod2(int x, int y) { + return switch (x) { + case 1 -> + switch (y) { + case 2 -> "test"; + default -> "inner default"; + }; + default -> "outer default"; + }; + } + + String testMethod3(List operations) { + return operations.stream() + .map( + op -> + switch (op) { + case 1 -> "test"; + default -> "TEST"; + }) + .findFirst() + .orElse("defaultValue"); + } + + String testMethod4Invalid(int x, int y) { + return switch (x) { + case 1 -> + switch (y) { + case 2 -> "test"; + default -> "inner default"; + }; + default -> "outer default"; + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrect.java index d4e25edeb993..384784e0c576 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrect.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrect.java @@ -1,113 +1,111 @@ -package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0 - -import java.util.Map; //indent:0 exp:0 -import java.util.ArrayList;//indent:0 exp:0 - -public abstract class InputIndentationCorrect { //indent:0 exp:0 - - static int i; //indent:2 exp:2 - - int[] c = {1, 2, 3, //indent:2 exp:2 - 4, 5, 6}; //indent:6 exp:6 - - int b; //indent:2 exp:2 - - static { //indent:2 exp:2 - i = 0; //indent:4 exp:4 - } //indent:2 exp:2 - - { //indent:2 exp:2 - b = 2; //indent:4 exp:4 - } //indent:2 exp:2 - - private static abstract class RangesMatcher { //indent:2 exp:2 - - private static final String ZEROES = "0\u0660\u06f0" //indent:4 exp:4 - + "\u0c66\u0ce6" //indent:8 exp:8 - + "\u1c40\u1c50"; //indent:8 exp:8 - - public static final InputIndentationCorrect JAVA_LETTER_OR_DIGIT = //indent:4 exp:4 - new InputIndentationCorrect() { //indent:8 exp:8 - @Override public boolean matches(char c) { //indent:10 exp:10 - return Character.isLetterOrDigit(c); //indent:12 exp:12 - } //indent:10 exp:10 - }; //indent:8 exp:8 - - /** Matches no characters. */ //indent:4 exp:4 - public static final InputFastMatcher NONE = //indent:4 exp:4 - new InputFastMatcher() { //indent:12 exp:>=8 - @Override public boolean matches(char c) { //indent:6 exp:6 - return false; //indent:8 exp:8 - } //indent:6 exp:6 - - @Override public String replaceFrom(CharSequence seq, CharSequence repl) { //indent:6 exp:6 - checkNotNull(repl); //indent:8 exp:8 - return seq.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - - private void checkNotNull(CharSequence replacement) {} //indent:6 exp:6 - - @Override public String collapseFrom(CharSequence sequence, //indent:6 exp:6 - char replacement) { //indent:10 exp:10 - return sequence.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - - @Override //indent:6 exp:6 - public String trimTrailingFrom(CharSequence sequence) { //indent:6 exp:6 - return sequence.toString(); //indent:8 exp:8 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean matches(char c) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public void foo() { //indent:2 exp:2 - int i = 0; //indent:4 exp:4 - for (; i < 9; i++) { //indent:4 exp:4 - if (veryLongLongLongCondition() //indent:6 exp:6 - || veryLongLongLongCondition2()) { //indent:14 exp:>=10 - someFooMethod("longString", "veryLongString", //indent:8 exp:8 - "superVeryExtraLongString"); //indent:12 exp:12 - if (veryLongLongLongCondition()) { //indent:8 exp:8 - while (veryLongLongLongCondition2() //indent:10 exp:10 - && veryLongLongLongCondition2()) { //indent:16 exp:>=14 - try { //indent:12 exp:12 - doSmth(); //indent:14 exp:14 - } catch (Exception e) { //indent:12 exp:12 - throw new AssertionError(e); //indent:14 exp:14 - } //indent:12 exp:12 - } //indent:10 exp:10 - } //indent:8 exp:8 - } //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean veryLongLongLongCondition() { //indent:2 exp:2 - if (veryLongLongLongCondition2()) { //indent:4 exp:4 - return true; //indent:6 exp:6 - } //indent:4 exp:4 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public boolean veryLongLongLongCondition2() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - public void someFooMethod(String longString, //indent:2 exp:2 - String superLongString, String exraSuperLongString) {} //indent:6 exp:6 - - public void fooThrowMethod() //indent:2 exp:2 - throws Exception { //indent:10 exp:>=6 - /* Some code*/ //indent:6 exp:6 - } //indent:2 exp:2 - - public void doSmth() { //indent:2 exp:2 - for (int h //indent:4 exp:4 - : c) { //indent:10 exp:>=8 - someFooMethod("longString", "veryLongString", //indent:6 exp:6 - "superVeryExtraLongString"); //indent:10 exp:10 - } //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public abstract class InputIndentationCorrect { + + static int i; + + static { + i = 0; + } + + int[] pqr = { + 1, 2, 3, + 4, 5, 6 + }; + int abc; + + { + abc = 2; + } + + /** some javadoc. */ + public boolean matches(char c) { + return false; + } + + /** some javadoc. */ + public void foo() { + int i = 0; + for (; i < 9; i++) { + if (veryLongLongLongCondition() || veryLongLongLongCondition2()) { + someFooMethod("longString", "veryLongString", "superVeryExtraLongString"); + if (veryLongLongLongCondition()) { + while (veryLongLongLongCondition2() && veryLongLongLongCondition2()) { + try { + doSmth(); + } catch (Exception e) { + throw new AssertionError(e); + } + } + } + } + } + } + + /** some javadoc. */ + public boolean veryLongLongLongCondition() { + return veryLongLongLongCondition2(); + } + + /** some javadoc. */ + public boolean veryLongLongLongCondition2() { + return false; + } + + /** some javadoc. */ + public void someFooMethod( + String longString, String superLongString, String exraSuperLongString) {} + + /** some javadoc. */ + public void fooThrowMethod() throws Exception { + /* Some code*/ + } + + /** some javadoc. */ + public void doSmth() { + for (int h : pqr) { + someFooMethod("longString", "veryLongString", "superVeryExtraLongString"); + } + } + + private abstract static class RangesMatcher { + + public static final InputIndentationCorrect JAVA_LETTER_OR_DIGIT = + new InputIndentationCorrect() { + @Override + public boolean matches(char c) { + return Character.isLetterOrDigit(c); + } + }; + + /** Matches no characters. */ + public static final InputFastMatcher NONE = + new InputFastMatcher() { + @Override + public boolean matches(char c) { + return false; + } + + @Override + public String replaceFrom(CharSequence seq, CharSequence repl) { + checkNotNull(repl); + return seq.toString(); + } + + private void checkNotNull(CharSequence replacement) {} + + @Override + public String collapseFrom(CharSequence sequence, char replacement) { + return sequence.toString(); + } + + @Override + public String trimTrailingFrom(CharSequence sequence) { + return sequence.toString(); + } + }; + + private static final String ZEROES = "" + ""; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectAnnotationArrayInit.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectAnnotationArrayInit.java new file mode 100644 index 000000000000..77d5d96cea15 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectAnnotationArrayInit.java @@ -0,0 +1,13 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputIndentationCorrectAnnotationArrayInit { + interface MyInterface { + @AnAnnotation(values = {"Hello"}) + void works(); + + @interface AnAnnotation { + String[] values(); + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectClass.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectClass.java index 44ec5fd31fcb..2b857d5000fa 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectClass.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectClass.java @@ -1,50 +1,33 @@ -package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; -import java.util.Iterator; //indent:0 exp:0 +import java.util.Iterator; -public class InputIndentationCorrectClass //indent:0 exp:0 - implements Runnable, Cloneable { //indent:4 exp:4 +/** some javadoc. */ +public class InputIndentationCorrectClass implements Runnable, Cloneable { - class InnerClass implements //indent:2 exp:2 - Iterable, //indent:10 exp:>=6 - Cloneable { //indent:13 exp:>=6 - @Override //indent:4 exp:4 - public Iterator iterator() { //indent:4 exp:4 - return null; //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 + /** some javadoc. */ + @Override + public void run() { + SecondClassWithLongLongLongLongName anon = new SecondClassWithLongLongLongLongName() {}; - class InnerClass2 //indent:2 exp:2 - extends //indent:7 exp:>=6 - SecondClassReturnWithVeryVeryVeryLongName { //indent:10 exp:>=6 - public InnerClass2(String string) { //indent:4 exp:4 - super(); //indent:6 exp:6 - // OOOO Auto-generated constructor stub //indent:6 exp:6 - } //indent:4 exp:4 - } //indent:2 exp:2 + SecondClassWithLongLongLongLongName anon2 = new SecondClassWithLongLongLongLongName() {}; + } - @Override //indent:2 exp:2 - public void run() { //indent:2 exp:2 - SecondClassWithLongLongLongLongName anon = //indent:4 exp:4 - new SecondClassWithLongLongLongLongName() { //indent:10 exp:>=8 + class InnerClass implements Iterable, Cloneable { + @Override + public Iterator iterator() { + return null; + } + } - }; //indent:4 exp:4 + class InnerClass2 extends SecondClassReturnWithVeryVeryVeryLongName { + public InnerClass2(String string) { + super(); + // OOOO Auto-generated constructor stub + } + } - SecondClassWithLongLongLongLongName anon2 = new //indent:4 exp:4 - SecondClassWithLongLongLongLongName() { //indent:10 exp:>=8 + class SecondClassWithLongLongLongLongName extends InputIndentationCorrectClass {} - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassWithLongLongLongLongName //indent:0 exp:0 - extends //indent:4 exp:4 - InputIndentationCorrectClass{ //indent:9 exp:>=4 - -} //indent:0 exp:0 - -class SecondClassReturnWithVeryVeryVeryLongName //indent:0 exp:0 - extends //indent:4 exp:4 - InputIndentationCorrectClass{ //indent:9 exp:>=4 - -} //indent:0 exp:0 + class SecondClassReturnWithVeryVeryVeryLongName {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectFieldAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectFieldAndParameter.java index 57ce5967e034..7f8277f6bf40 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectFieldAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectFieldAndParameter.java @@ -1,127 +1,156 @@ -package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0 - -class InputIndentationCorrectFieldAndParameter { //indent:0 exp:0 - - boolean flag = conditionFirst("Loooooooooooooooooong", new //indent:2 exp:2 - SecondFieldLongName("Loooooooooooooooooog"). //indent:6 exp:6 - getInteger(new FooFieldClass(), "Loooooooooooooooooog"), //indent:6 exp:6 - new InnerClassFoo()); //indent:6 exp:6 - - boolean secondFlag = conditionSecond(10000000000.0, new //indent:2 exp:2 - SecondFieldLongName("Looooooooooooo" //indent:6 exp:6 - + "oooooooooooong").getString(new FooFieldClass(), //indent:6 exp:6 - new SecondFieldLongName("loooooooooong"). //indent:6 exp:6 - getInteger(new FooFieldClass(), "loooooooooooooong")), "loooooooooooong") //indent:6 exp:6 - || conditionThird(2048) || conditionFourth(new //indent:6 exp:6 - SecondFieldLongName("Looooooooooooooo" //indent:6 exp:6 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:6 exp:6 - conditionFifth(true, new SecondFieldLongName(getString(2048, "Looo" //indent:6 exp:6 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:6 exp:6 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:6 exp:6 - SecondFieldLongName(getString(100000, "Loooooong" //indent:6 exp:6 - + "Fooooooo><"))) || conditionNoArg() //indent:6 exp:6 - || conditionNoArg() || //indent:6 exp:6 - conditionNoArg() || conditionNoArg(); //indent:6 exp:6 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondFieldLongName instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - boolean flag = conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondFieldLongName("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooFieldClass(), "Loooooooooooooooooog"), //indent:12 exp:>=8 - new InnerClassFoo()); //indent:13 exp:>=8 - - boolean secondFlag = conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondFieldLongName("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooFieldClass(), //indent:11 exp:>=8 - new SecondFieldLongName("loooooooooong"). //indent:10 exp:>=8 - getInteger(new FooFieldClass(), "looooooooong")), "loooooooooooong") //indent:12 exp:>=8 - || conditionThird(2048) || conditionFourth(new //indent:13 exp:>=8 - SecondFieldLongName("Looooooooooooooo" //indent:16 exp:>=8 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:12 exp:>=8 - conditionFifth(true, new SecondFieldLongName(getString(2048, "Looo" //indent:11 exp:>=8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:15 exp:>=8 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:12 exp:>=8 - SecondFieldLongName(getString(100000, "Loooooong" //indent:12 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=8 - || conditionNoArg() || //indent:10 exp:>=8 - conditionNoArg() || conditionNoArg(); //indent:10 exp:>=8 - - FooFieldClass anonymousClass = new FooFieldClass() { //indent:4 exp:4 - boolean secondFlag = conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondFieldLongName("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooFieldClass(), //indent:12 exp:>=10 - new SecondFieldLongName("loooooooooong"). //indent:15 exp:>=10 - getInteger(new FooFieldClass(), "looooooong")), "loooooooooooong") //indent:13 exp:>=10 - || conditionThird(2048) || conditionFourth(new //indent:14 exp:>=10 - SecondFieldLongName("Looooooooooooooo" //indent:17 exp:>=10 - + "ooooooooooooong").getBoolean(new FooFieldClass(), false)) || //indent:13 exp:>=10 - conditionFifth(true, new SecondFieldLongName(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:16 exp:>=10 - new FooFieldClass(), true)) || conditionSixth(false, new //indent:13 exp:>=8 - SecondFieldLongName(getString(100000, "Loooooong" //indent:13 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:17 exp:>=10 - || conditionNoArg() || //indent:11 exp:>=10 - conditionNoArg() || conditionNoArg(); //indent:11 exp:>=10 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondFieldLongName { //indent:0 exp:0 - - public SecondFieldLongName(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooFieldClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooFieldClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooFieldClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondFieldLongName getInstance() { //indent:2 exp:2 - return new SecondFieldLongName("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooFieldClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +class InputIndentationCorrectFieldAndParameter { + + boolean flag = + conditionFirst( + "Loooooooooooooooooong", + new SecondFieldLongNam2("Loooooooooooooooooog") + .getInteger(new FooFieldClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + + boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + + String getString(int someInt, String someString) { + return "String"; + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondFieldLongNam2 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + boolean flag = + conditionFirst( + "Loooooooooooooooooong", + new SecondFieldLongNam2("Loooooooooooooooooog") + .getInteger(new FooFieldClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + + boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "looooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + + FooFieldClass anonymousClass = + new FooFieldClass() { + final boolean secondFlag = + conditionSecond( + 10000000000.0, + new SecondFieldLongNam2("Looooooooooooo" + "oooooooooooong") + .getString( + new FooFieldClass(), + new SecondFieldLongNam2("loooooooooong") + .getInteger(new FooFieldClass(), "looooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondFieldLongNam2("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooFieldClass(), false)) + || conditionFifth( + true, + new SecondFieldLongNam2( + getString( + 2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooFieldClass(), true)) + || conditionSixth( + false, new SecondFieldLongNam2(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + }; + } + + class SecondFieldLongNam2 { + + public SecondFieldLongNam2(String string) {} + + String getString(FooFieldClass instance, int integer) { + return "String"; + } + + int getInteger(FooFieldClass instance, String string) { + return -1; + } + + boolean getBoolean(FooFieldClass instance, boolean flag) { + return false; + } + + SecondFieldLongNam2 getInstance() { + return new SecondFieldLongNam2("VeryLoooooooooo" + "oongString"); + } + } + + class FooFieldClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectForAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectForAndParameter.java index 3862985816af..0ee89e58a0e7 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectForAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectForAndParameter.java @@ -1,113 +1,126 @@ -package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0 - -import java.util.ArrayList; //indent:0 exp:0 -import java.util.HashMap; //indent:0 exp:0 -import java.util.Iterator; //indent:0 exp:0 -import java.util.List; //indent:0 exp:0 -import java.util.Map; //indent:0 exp:0 - -class InputIndentationCorrectForAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - for (int i = 1; i < 10; i ++) {} //indent:4 exp:4 - - for (int i = new SecondForLongName("Loooooooooooooooooooo" //indent:4 exp:4 - + "oong").getInteger(new FooForClass(), //indent:8 exp:8 - getString(1000000000, "Loooooooooooooooong")); i < 10; i++) {} //indent:10 exp:>=8 - - for (Map.Entry entry : new SecondForLongName("Loo" //indent:4 exp:4 - + "ooooooooooooooooooooong").getMap(new //indent:8 exp:8 - FooForClass(), 10000000, //indent:8 exp:8 - getString(10000, "Loooooooooo" //indent:8 exp:8 - + "ooooong")).entrySet()) {} //indent:8 exp:8 - - for (Map.Entry entry : new SecondForLongName("Loo" //indent:4 exp:4 - + "ooooooooooooooooooooong").getMap(new //indent:8 exp:8 - FooForClass(), 10000000, //indent:12 exp:>=8 - getString(10000, "Loooooooooo" //indent:10 exp:>=8 - + "ooooong")).entrySet()) {} //indent:15 exp:>=8 - - for (String string : new SecondForLongName(getString(1024 //indent:4 exp:4 - , "Looooooooooooooooooong")). //indent:8 exp:8 - getList(new FooForClass(), 1000, getString(1024, //indent:8 exp:8 - "Loooooooooooooooooooooooooooooooo" //indent:8 exp:8 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:8 exp:8 - + "oooooooooong"))) {} //indent:8 exp:8 - - for (String string : new SecondForLongName(getString(1024 //indent:4 exp:4 - , "Looooooooooooooooooong")). //indent:8 exp:8 - getList(new FooForClass(), 1000, getString(1024, //indent:12 exp:>=8 - "Loooooooooooooooooooooooooooooooo" //indent:14 exp:>=8 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:10 exp:>=8 - + "oooooooooong"))) {} //indent:13 exp:>=8 - - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - - for (int i = 1; i < 10; i ++) {} //indent:6 exp:6 - - for (int i = new SecondForLongName("Loooooooooooooooooooo" //indent:6 exp:6 - + "oong").getInteger(new FooForClass(), //indent:10 exp:10 - getString(1000000000, "Loooooooooooooooong")); i < 10; i++) {} //indent:12 exp:>=10 - - for (Map.Entry entry : new SecondForLongName("Loo" //indent:6 exp:6 - + "ooooooooooooooooooooong").getMap(new //indent:10 exp:10 - FooForClass(), 10000000, //indent:10 exp:10 - getString(10000, "Loooooooooo" //indent:10 exp:10 - + "ooooong")).entrySet()) {} //indent:10 exp:10 - - for (Map.Entry entry : new SecondForLongName("Loo" //indent:6 exp:6 - + "ooooooooooooooooooooong").getMap(new //indent:12 exp:>=10 - FooForClass(), 10000000, //indent:13 exp:>=10 - getString(10000, "Loooooooooo" //indent:18 exp:>=10 - + "ooooong")).entrySet()) {} //indent:15 exp:>=10 - - for (String string : new SecondForLongName(getString(1024 //indent:6 exp:6 - , "Looooooooooooooooooong")). //indent:10 exp:10 - getList(new FooForClass(), 1000, getString(1024, //indent:10 exp:10 - "Loooooooooooooooooooooooooooooooo" //indent:10 exp:10 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:10 exp:10 - + "oooooooooong"))) {} //indent:10 exp:10 - - for (String string : new SecondForLongName(getString(1024 //indent:6 exp:6 - , "Looooooooooooooooooong")). //indent:15 exp:>=10 - getList(new FooForClass(), 1000, getString(1024, //indent:13 exp:>=10 - "Loooooooooooooooooooooooooooooooo" //indent:19 exp:>=10 - + "oooooooooooooooooooooooooooooooooooooooo" //indent:21 exp:>=10 - + "oooooooooong"))) {} //indent:10 exp:10 - } //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondForLongName //indent:0 exp:0 - implements Iterable{ //indent:8 exp:>=4 - - public SecondForLongName(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - int getInteger(FooForClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - Map getMap(FooForClass instance, int integer, String string) { //indent:2 exp:2 - return new HashMap(); //indent:4 exp:4 - } //indent:2 exp:2 - - List getList(FooForClass instance, long longLong, String string) { //indent:2 exp:2 - return new ArrayList(); //indent:4 exp:4 - } //indent:2 exp:2 - - public Iterator iterator() { //indent:2 exp:2 - return null; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooForClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +class InputIndentationCorrectForAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + for (int i = 1; i < 10; i++) {} + + for (int i = + new SecondForClassWithLongName1("Loooooooooooooooooooo" + "oong") + .getInteger(new FooForClass(), getString(1000000000, "Loooooooooooooooong")); + i < 10; + i++) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + } + + class InnerClassFoo { + + void fooMethodWithIf() { + + for (int i = 1; i < 10; i++) {} + + for (int i = + new SecondForClassWithLongName1("Loooooooooooooooooooo" + "oong") + .getInteger(new FooForClass(), getString(1000000000, "Loooooooooooooooong")); + i < 10; + i++) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (Map.Entry entry : + new SecondForClassWithLongName1("Loo" + "ooooooooooooooooooooong") + .getMap(new FooForClass(), 10000000, getString(10000, "Loooooooooo" + "ooooong")) + .entrySet()) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + + for (String string : + new SecondForClassWithLongName1(getString(1024, "Looooooooooooooooooong")) + .getList( + new FooForClass(), + 1000, + getString( + 1024, + "Loooooooooooooooooooooooooooooooo" + + "oooooooooooooooooooooooooooooooooooooooo" + + "oooooooooong"))) {} + } + } + + class SecondForClassWithLongName1 implements Iterable { + + public SecondForClassWithLongName1(String string) {} + + int getInteger(FooForClass instance, String string) { + return -1; + } + + Map getMap(FooForClass instance, int integer, String string) { + return new HashMap(); + } + + List getList(FooForClass instance, long longLong, String string) { + return new ArrayList(); + } + + public Iterator iterator() { + return null; + } + } + + class FooForClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectIfAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectIfAndParameter.java index 81a043666609..58f38a4a51e2 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectIfAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectIfAndParameter.java @@ -1,144 +1,180 @@ -package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0 - -class InputIndentationCorrectIfAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - if (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondClassLongNam6("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:8 exp:8 - new InnerClassFoo())) {} //indent:8 exp:8 - - if (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondClassLongNam6("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooIfClass(), //indent:8 exp:8 - new SecondClassLongNam6("loooooooooong"). //indent:8 exp:8 - getInteger(new FooIfClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondClassLongNam6("Looooooooooooooo" //indent:8 exp:8 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondClassLongNam6(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooIfClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondClassLongNam6(getString(100000, "Loooooong" //indent:8 exp:8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:8 exp:8 - conditionNoArg() || conditionNoArg()) {} //indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondClassLongNam6 instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - if (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondClassLongNam6("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())) {} //indent:14 exp:>=10 - - if (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondClassLongNam6("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooIfClass(), //indent:10 exp:10 - new SecondClassLongNam6("loooooooooong"). //indent:10 exp:10 - getInteger(new FooIfClass(), "loooooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondClassLongNam6("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondClassLongNam6(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooIfClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondClassLongNam6(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()) {} //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooIfClass anonymousClass = new FooIfClass() { //indent:4 exp:4 - - void fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - if (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondClassLongNam6("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooIfClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())) {} //indent:19 exp:>=12 - - if (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondClassLongNam6("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooIfClass(), //indent:12 exp:12 - new SecondClassLongNam6("loooooooooong"). //indent:12 exp:12 - getInteger(new FooIfClass(), "looooooooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondClassLongNam6("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooIfClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondClassLongNam6(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooIfClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondClassLongNam6(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName) {} //indent:21 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassLongNam6 { //indent:0 exp:0 - - public SecondClassLongNam6(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooIfClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooIfClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooIfClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondClassLongNam6 getInstance() { //indent:2 exp:2 - return new SecondClassLongNam6("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooIfClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +class InputIndentationCorrectIfAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) { + /* foo */ + } + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondClassLongNam3 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooIfClass anonymousClass = + new FooIfClass() { + + void fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "looooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName) { + /* foo */ + } + } + }; + + void fooMethodWithIf() { + if (conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam3("Loooooooooooooooooog") + .getInteger(new FooIfClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) { + /* foo */ + } + + if (conditionSecond( + 10000000000.0, + new SecondClassLongNam3("Looooooooooooo" + "oooooooooooong") + .getString( + new FooIfClass(), + new SecondClassLongNam3("loooooooooong") + .getInteger(new FooIfClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam3("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooIfClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam3( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooIfClass(), true)) + || conditionSixth( + false, new SecondClassLongNam3(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) { + /* foo */ + } + } + } + + class SecondClassLongNam3 { + + public SecondClassLongNam3(String string) {} + + String getString(FooIfClass instance, int integer) { + return "String"; + } + + int getInteger(FooIfClass instance, String string) { + return -1; + } + + boolean getBoolean(FooIfClass instance, boolean flag) { + return false; + } + + SecondClassLongNam3 getInstance() { + return new SecondClassLongNam3("VeryLoooooooooo" + "oongString"); + } + } + + class FooIfClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectNewChildren.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectNewChildren.java new file mode 100644 index 000000000000..b83ac1353ece --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectNewChildren.java @@ -0,0 +1,26 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputIndentationCorrectNewChildren { + + private final StringBuffer filter = + new StringBuffer( + new CharSequence() { + @Override + public char charAt(int index) { + return 'A'; + } + + public int length() { + return 1; + } + + public CharSequence subSequence(int start, int end) { + return this; + } + + public String toString() { + return "Foo"; + } + }); +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectReturnAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectReturnAndParameter.java index a17a70269dcb..6fa0484efeef 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectReturnAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectReturnAndParameter.java @@ -1,143 +1,166 @@ -package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0 - -class InputIndentationCorrectReturnAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean fooMethodWithIf() { //indent:2 exp:2 - - return conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondClassLongName("Looooooooooooo" //indent:8 exp:8 - + "oooooooooooong").getString(new FooReturnClass(), //indent:8 exp:8 - new SecondClassLongName("loooooooooong"). //indent:8 exp:8 - getInteger(new FooReturnClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondClassLongName("Looooooooooooooo" //indent:8 exp:8 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondClassLongName(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondClassLongName(getString(100000, "Loooooong" //indent:8 exp:8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:8 exp:8 - conditionNoArg() || conditionNoArg();//indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondClassLongName instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - boolean fooMethodWithIf() { //indent:4 exp:4 - return conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondClassLongName("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooReturnClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo()); //indent:14 exp:>=10 - } //indent:4 exp:4 - - boolean fooReturn() { //indent:4 exp:4 - return conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondClassLongName("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooReturnClass(), //indent:10 exp:10 - new SecondClassLongName("loooooooooong"). //indent:10 exp:10 - getInteger(new FooReturnClass(), "looooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondClassLongName("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondClassLongName(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondClassLongName(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg(); //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooReturnClass anonymousClass = new FooReturnClass() { //indent:4 exp:4 - - boolean fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - return conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondClassLongName("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooReturnClass(), //indent:12 exp:12 - new SecondClassLongName("loooooooooong"). //indent:12 exp:12 - getInteger(new FooReturnClass(), "looooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondClassLongName("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooReturnClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondClassLongName(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooReturnClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondClassLongName(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName; //indent:21 exp:>=12 - } //indent:6 exp:6 - - boolean fooReturn() { //indent:6 exp:6 - return conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondClassLongName("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooReturnClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo()); //indent:19 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondClassLongName { //indent:0 exp:0 - - public SecondClassLongName(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooReturnClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooReturnClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooReturnClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondClassLongName getInstance() { //indent:2 exp:2 - return new SecondClassLongName("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooReturnClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +class InputIndentationCorrectReturnAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + boolean fooMethodWithIf() { + + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondClassLongNam4 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooReturnClass anonymousClass = + new FooReturnClass() { + + boolean fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "looooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName; + } + + boolean fooReturn() { + return conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam4("Loooooooooooooooooog") + .getInteger(new FooReturnClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + } + }; + + boolean fooMethodWithIf() { + return conditionFirst( + "Loooooooooooooooooong", + new SecondClassLongNam4("Loooooooooooooooooog") + .getInteger(new FooReturnClass(), "Loooooooooooooooooog"), + new InnerClassFoo()); + } + + boolean fooReturn() { + return conditionSecond( + 10000000000.0, + new SecondClassLongNam4("Looooooooooooo" + "oooooooooooong") + .getString( + new FooReturnClass(), + new SecondClassLongNam4("loooooooooong") + .getInteger(new FooReturnClass(), "looooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondClassLongNam4("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooReturnClass(), false)) + || conditionFifth( + true, + new SecondClassLongNam4( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooReturnClass(), true)) + || conditionSixth( + false, new SecondClassLongNam4(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg(); + } + } + + class SecondClassLongNam4 { + + public SecondClassLongNam4(String string) {} + + String getString(FooReturnClass instance, int integer) { + return "String"; + } + + int getInteger(FooReturnClass instance, String string) { + return -1; + } + + boolean getBoolean(FooReturnClass instance, boolean flag) { + return false; + } + + SecondClassLongNam4 getInstance() { + return new SecondClassLongNam4("VeryLoooooooooo" + "oongString"); + } + } + + class FooReturnClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectWhileDoWhileAndParameter.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectWhileDoWhileAndParameter.java index 191dece07b80..85efa0f215e9 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectWhileDoWhileAndParameter.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputIndentationCorrectWhileDoWhileAndParameter.java @@ -1,221 +1,270 @@ -package com.google.checkstyle.test.chapter4formatting.rule4841indentation; //indent:0 exp:0 - -class InputIndentationCorrectWhileDoWhileAndParameter { //indent:0 exp:0 - - String getString(int someInt, String someString) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - void fooMethodWithIf() { //indent:2 exp:2 - - while (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondWhileLongName("Loooooooooooooooooog"). //indent:8 exp:8 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:11 exp:>=8 - new InnerClassFoo())) {} //indent:10 exp:>=8 - - do { //indent:4 exp:4 - - } while (conditionFirst("Loooooooooooooooooong", new //indent:4 exp:4 - SecondWhileLongName("Loooooooooooooooooog"). //indent:9 exp:>=8 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:15 exp:>=8 - new InnerClassFoo())); //indent:9 exp:>=8 - - while (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondWhileLongName("Looooooooooooo" //indent:9 exp:>=8 - + "oooooooooooong").getString(new FooWhileClass(), //indent:8 exp:8 - new SecondWhileLongName("loooooooooong"). //indent:11 exp:>=8 - getInteger(new FooWhileClass(), "loooooooooooooong")), "loooooooooooong") //indent:8 exp:8 - || conditionThird(2048) || conditionFourth(new //indent:14 exp:>=8 - SecondWhileLongName("Looooooooooooooo" //indent:14 exp:>=8 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondWhileLongName( //indent:12 exp:>=8 - getString(2048, "Looo" //indent:12 exp:>=8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondWhileLongName(getString(100000, "Loooooong" //indent:11 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:10 exp:>=8 - conditionNoArg() || conditionNoArg()) {} //indent:10 exp:10 - - do { //indent:4 exp:4 - - } while (conditionSecond(10000000000.0, new //indent:4 exp:4 - SecondWhileLongName("Looooooooooooo" //indent:10 exp:>=8 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:>=8 - new SecondWhileLongName("loooooooooong"). //indent:8 exp:8 - getInteger(new FooWhileClass(), "loooooooong")), "loooooooooooong") //indent:13 exp:>=8 - || conditionThird(2048) || conditionFourth(new //indent:8 exp:8 - SecondWhileLongName("Looooooooooooooo" //indent:11 exp:>=8 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:8 exp:8 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Looo" //indent:8 exp:8 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:8 exp:8 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:8 exp:8 - SecondWhileLongName(getString(100000, "Loooooong" //indent:11 exp:>=8 - + "Fooooooo><"))) || conditionNoArg() //indent:8 exp:8 - || conditionNoArg() || //indent:13 exp:>=8 - conditionNoArg() || conditionNoArg()); //indent:8 exp:8 - } //indent:2 exp:2 - - private boolean conditionFirst(String longString, int //indent:2 exp:2 - integer, InnerClassFoo someInstance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSecond(double longLongLongDoubleValue, //indent:2 exp:2 - String longLongLongString, String secondLongLongString) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionThird(long veryLongValue) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFourth(boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionFifth(boolean flag1, boolean flag2) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionSixth(boolean flag, //indent:2 exp:2 - SecondWhileLongName instance) { //indent:6 exp:6 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - private boolean conditionNoArg() { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - class InnerClassFoo { //indent:2 exp:2 - - void fooMethodWithIf() { //indent:4 exp:4 - while (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondWhileLongName("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())) {} //indent:14 exp:>=10 - - do { //indent:6 exp:6 - /* Do something*/ //indent:8 exp:8 - } while (conditionFirst("Loooooooooooooooooong", new //indent:6 exp:6 - SecondWhileLongName("Loooooooooooooooooog"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:14 exp:>=10 - new InnerClassFoo())); //indent:14 exp:>=10 - - while (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondWhileLongName("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:10 - new SecondWhileLongName("loooooooooong"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "loooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondWhileLongName("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondWhileLongName(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()) {} //indent:14 exp:>=10 - - do { //indent:6 exp:6 - /* Do smth*/ //indent:8 exp:8 - } while (conditionSecond(10000000000.0, new //indent:6 exp:6 - SecondWhileLongName("Looooooooooooo" //indent:10 exp:10 - + "oooooooooooong").getString(new FooWhileClass(), //indent:10 exp:10 - new SecondWhileLongName("loooooooooong"). //indent:10 exp:10 - getInteger(new FooWhileClass(), "loooooooooooong")), "loooooooooooong") //indent:10 exp:10 - || conditionThird(2048) || conditionFourth(new //indent:10 exp:10 - SecondWhileLongName("Looooooooooooooo" //indent:10 exp:10 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:12 exp:>=10 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Looo" //indent:12 exp:>=10 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:12 exp:>=10 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:12 exp:>=10 - SecondWhileLongName(getString(100000, "Loooooong" //indent:14 exp:>=10 - + "Fooooooo><"))) || conditionNoArg() //indent:14 exp:>=10 - || conditionNoArg() || //indent:14 exp:>=10 - conditionNoArg() || conditionNoArg()); //indent:14 exp:>=10 - } //indent:4 exp:4 - - FooWhileClass anonymousClass = new FooWhileClass() { //indent:4 exp:4 - - void fooMethodWithIf(String stringStringStringStringLooooongString, //indent:6 exp:6 - int intIntIntVeryLongNameForIntVariable, boolean //indent:10 exp:10 - fooooooooobooleanBooleanVeryLongName) { //indent:14 exp:>=10 - - while (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondWhileLongName("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())) {} //indent:19 exp:>=12 - - do { //indent:8 exp:8 - /* Do smth*/ //indent:10 exp:10 - } while (conditionFirst("Loooooooooooooooooong", new //indent:8 exp:8 - SecondWhileLongName("Loooooooooooooooooog"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "Loooooooooooooooooog"), //indent:16 exp:>=12 - new InnerClassFoo())); //indent:19 exp:>=12 - - while (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondWhileLongName("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooWhileClass(), //indent:12 exp:12 - new SecondWhileLongName("loooooooooong"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "loooooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondWhileLongName("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondWhileLongName(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName) {} //indent:21 exp:>=12 - - do { //indent:8 exp:8 - /* Do smth*/ //indent:10 exp:10 - } while (conditionSecond(10000000000.0, new //indent:8 exp:8 - SecondWhileLongName("Looooooooooooo" //indent:12 exp:12 - + "oooooooooooong").getString(new FooWhileClass(), //indent:12 exp:12 - new SecondWhileLongName("loooooooooong"). //indent:12 exp:12 - getInteger(new FooWhileClass(), "loooooooooong")), "loooooooooooong") //indent:12 exp:12 - || conditionThird(2048) || conditionFourth(new //indent:12 exp:12 - SecondWhileLongName("Looooooooooooooo" //indent:12 exp:12 - + "ooooooooooooong").getBoolean(new FooWhileClass(), false)) || //indent:14 exp:>=12 - conditionFifth(true, new SecondWhileLongName(getString(2048, "Lo" //indent:14 exp:>=12 - + "ooooooooooooooooooooooooooooooooooooooooooong")).getBoolean( //indent:14 exp:>=12 - new FooWhileClass(), true)) || conditionSixth(false, new //indent:14 exp:>=12 - SecondWhileLongName(getString(100000, "Loooooong" //indent:16 exp:>=12 - + "Fooooooo><"))) || conditionNoArg() //indent:16 exp:>=12 - || conditionNoArg() || //indent:16 exp:>=12 - conditionNoArg() || conditionNoArg() //indent:18 exp:>=12 - && fooooooooobooleanBooleanVeryLongName);//indent:21 exp:>=12 - } //indent:6 exp:6 - }; //indent:4 exp:4 - } //indent:2 exp:2 -} //indent:0 exp:0 - -class SecondWhileLongName { //indent:0 exp:0 - - public SecondWhileLongName(String string) { //indent:2 exp:2 - - } //indent:2 exp:2 - - String getString(FooWhileClass instance, int integer) { //indent:2 exp:2 - return "String"; //indent:4 exp:4 - } //indent:2 exp:2 - - int getInteger(FooWhileClass instance, String string) { //indent:2 exp:2 - return -1; //indent:4 exp:4 - } //indent:2 exp:2 - - boolean getBoolean(FooWhileClass instance, boolean flag) { //indent:2 exp:2 - return false; //indent:4 exp:4 - } //indent:2 exp:2 - - SecondWhileLongName getInstance() { //indent:2 exp:2 - return new SecondWhileLongName("VeryLoooooooooo" //indent:4 exp:4 - + "oongString"); //indent:8 exp:8 - } //indent:2 exp:2 -} //indent:0 exp:0 -class FooWhileClass {} //indent:0 exp:0 +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +class InputIndentationCorrectWhileDoWhileAndParameter { + + String getString(int someInt, String someString) { + return "String"; + } + + void fooMethodWithIf() { + + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do {} while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) {} + + do {} while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()); + } + + private boolean conditionFirst(String longString, int integer, InnerClassFoo someInstance) { + return false; + } + + private boolean conditionSecond( + double longLongLongDoubleValue, String longLongLongString, String secondLongLongString) { + return false; + } + + private boolean conditionThird(long veryLongValue) { + return false; + } + + private boolean conditionFourth(boolean flag) { + return false; + } + + private boolean conditionFifth(boolean flag1, boolean flag2) { + return false; + } + + private boolean conditionSixth(boolean flag, SecondWhileLongNam1 instance) { + return false; + } + + private boolean conditionNoArg() { + return false; + } + + class InnerClassFoo { + + FooWhileClass anonymousClass = + new FooWhileClass() { + + void fooMethodWithIf( + String stringStringStringStringLooooongString, + int intIntIntVeryLongNameForIntVariable, + boolean fooooooooobooleanBooleanVeryLongName) { + + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do { + /* Do smth*/ + + } while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName) {} + + do { + /* Do smth*/ + + } while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Lo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() && fooooooooobooleanBooleanVeryLongName); + } + }; + + void fooMethodWithIf() { + while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())) {} + + do { + /* Do something*/ + + } while (conditionFirst( + "Loooooooooooooooooong", + new SecondWhileLongNam1("Loooooooooooooooooog") + .getInteger(new FooWhileClass(), "Loooooooooooooooooog"), + new InnerClassFoo())); + + while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()) {} + + do { + /* Do smth*/ + + } while (conditionSecond( + 10000000000.0, + new SecondWhileLongNam1("Looooooooooooo" + "oooooooooooong") + .getString( + new FooWhileClass(), + new SecondWhileLongNam1("loooooooooong") + .getInteger(new FooWhileClass(), "loooooooooooong")), + "loooooooooooong") + || conditionThird(2048) + || conditionFourth( + new SecondWhileLongNam1("Looooooooooooooo" + "ooooooooooooong") + .getBoolean(new FooWhileClass(), false)) + || conditionFifth( + true, + new SecondWhileLongNam1( + getString(2048, "Looo" + "ooooooooooooooooooooooooooooooooooooooooooong")) + .getBoolean(new FooWhileClass(), true)) + || conditionSixth( + false, new SecondWhileLongNam1(getString(100000, "Loooooong" + "Fooooooo><"))) + || conditionNoArg() + || conditionNoArg() + || conditionNoArg() + || conditionNoArg()); + } + } + + class SecondWhileLongNam1 { + + public SecondWhileLongNam1(String string) {} + + String getString(FooWhileClass instance, int integer) { + return "String"; + } + + int getInteger(FooWhileClass instance, String string) { + return -1; + } + + boolean getBoolean(FooWhileClass instance, boolean flag) { + return false; + } + + SecondWhileLongNam1 getInstance() { + return new SecondWhileLongNam1("VeryLoooooooooo" + "oongString"); + } + } + + class FooWhileClass {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaAndChildOnTheSameLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaAndChildOnTheSameLine.java new file mode 100644 index 000000000000..787219ace5e9 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaAndChildOnTheSameLine.java @@ -0,0 +1,67 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.lang.reflect.Proxy; + +/** some javadoc. */ +public class InputLambdaAndChildOnTheSameLine { + + enum A { A1, A2, A3, A4, A5 } + + enum B { B1, B2, B3, B4, B5 } + + enum R { + R1, R2; + boolean isOk() { + return this == R2; + } + } + + boolean testMethod1(A a, B b, R r) { + return switch (a) { + case A1 -> switch (b) { + case B1, B2 -> true; + case B3 -> r != R.R1; + case B4 -> false; + case B5 -> throw new IllegalStateException("Unexpected: " + b); + }; + case A2, A3 -> + switch (b) { + case B1 -> r.isOk(); + case B2, B3 -> false; + case B4 -> true; + case B5 -> throw new RuntimeException("Test: " + b); + }; + case A4 -> false; + case A5 -> throw new IllegalArgumentException("Bad A: " + a); + }; + } + + void testMethod2() { + var service = (CharSequence) Proxy.newProxyInstance( + InputLambdaAndChildOnTheSameLine.class.getClassLoader(), + new Class[]{CharSequence.class}, + (proxy, method, methodArgs) -> switch (method.getName()) { + case "hashCode" -> 123456789; + case "equals" -> methodArgs[0] == proxy; + case "toString" -> "FakeInstanceServiceA"; + default -> throw new IllegalArgumentException(method.getName()); + } + ); + } + + void testMethod3() { + var service = (CharSequence) Proxy.newProxyInstance( + InputLambdaAndChildOnTheSameLine.class.getClassLoader(), + new Class[]{CharSequence.class}, + (proxy, method, methodArgs) -> + switch (method.getName()) { + case "hashCode" -> 123456789; + case "equals" -> methodArgs[0] == proxy; + case "toString" -> "FakeInstanceServiceA"; + default -> throw new IllegalArgumentException(method.getName()); + } + ); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaChild.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaChild.java new file mode 100644 index 000000000000..1bdb4b9c5651 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaChild.java @@ -0,0 +1,52 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + +/**some javadoc.*/ +public class InputLambdaChild { + String testMethod1(List operations) { + return operations.stream() + .map( + op -> + switch (op) { + case 1 -> "test"; + default -> "TEST"; + }) + .findFirst().orElse("defaultValue"); + } + + String testMethod2(List operations) { + return operations.stream() + .map( + op -> + switch (op) { + // violation above '.* expected level should be one of the following: 14, 16, 20.' + case 1 -> "test"; + default -> "TEST"; + }) + .findFirst().orElse("defaultValue"); + } + + void main(String[] args) { + group((Function) x -> switch (x) { default: yield x; }, + (Function) x -> switch (x) { default: yield x; }); + } + + List getThrowsTrees(Object input) { + return getBlockTags(input, + kind -> switch (kind) { case "EXCEPTION", "THROWS" -> true; default -> false; }, + String.class); + } + + void group(Function f1, Function f2) { + // Dummy method to test syntax/indentation + } + + List getBlockTags(Object input, Predicate filter, Class type) { + return List.of(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaChildCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaChildCorrect.java new file mode 100644 index 000000000000..fc0440246fb1 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLambdaChildCorrect.java @@ -0,0 +1,57 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + +/** some javadoc. */ +public class InputLambdaChildCorrect { + String testMethod1(List operations) { + return operations.stream() + .map( + op -> + switch (op) { + case 1 -> "test"; + default -> "TEST"; + }) + .findFirst() + .orElse("defaultValue"); + } + + void main(String[] args) { + group( + (Function) + x -> + switch (x) { + default: + yield x; + }, + (Function) + x -> + switch (x) { + default: + yield x; + }); + } + + List getThrowsTrees(Object input) { + return getBlockTags( + input, + kind -> + switch (kind) { + case "EXCEPTION", "THROWS" -> true; + default -> false; + }, + String.class); + } + + void group(Function f1, Function f2) { + // Dummy method to test syntax/indentation + } + + List getBlockTags(Object input, Predicate filter, Class type) { + return List.of(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLineBreakAfterLeftCurlyOfBlockInSwitch.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLineBreakAfterLeftCurlyOfBlockInSwitch.java new file mode 100644 index 000000000000..1f0fc4426454 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputLineBreakAfterLeftCurlyOfBlockInSwitch.java @@ -0,0 +1,35 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputLineBreakAfterLeftCurlyOfBlockInSwitch { + + void testMethod1(int month) { + int result = + switch (month) { + case 1, 6, 7 -> { + System.out.println("try"); + yield 1; + } + case 2, 9, 10, 11, 12 -> { yield 2; } // false-negative, ok until #17565 + case 3, 5, 4, 8 -> { yield month << 2; } // false-negative, ok until #17565 + default -> 0; + }; + } + + void testMethod2(int number) { + switch (number) { + case 0, 1 -> System.out.println("0"); + case 2 -> + handleTwoWithAnExtremelyLongMethodCallThatWouldNotFitOnTheSameLine(); + default -> { handleSurprisingNumber(number); } // false-negative, ok until #17565 + } + } + + private static int handleSurprisingNumber(int number) { + return number; + } + + private int handleTwoWithAnExtremelyLongMethodCallThatWouldNotFitOnTheSameLine() { + return 0; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputMultilineStatementsCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputMultilineStatementsCorrect.java new file mode 100644 index 000000000000..fe713215f527 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputMultilineStatementsCorrect.java @@ -0,0 +1,47 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some class. */ +public class InputMultilineStatementsCorrect { + + /** some test method. */ + public void test1() { + try { + System.out.println("try0"); + } catch (NullPointerException | IllegalArgumentException expected) { + } + } + + public void test2() { + try { + System.out.println("try"); + } catch ( + @SuppressWarnings("PMD.AvoidCatchingGenericException") + Exception e) { + java.util.logging.Logger.getAnonymousLogger().severe(e.toString()); + } + } + + private static String testCodeBlock() { + final String simplePropertyUpdateScript = ""; + return """ + def newInstance = params.instance; + def existingInstance = ctx._source; + """ + + simplePropertyUpdateScript; + } + + void testConditionals(boolean result) { + int collect = result ? 0 : 1; + } + + int testIfConditionMultiline(int newState, int tableName) { + int flag = 0; + if ((newState == 10) && tableName == 1 && flag > 0 + || (newState != 0 && flag < 0 && tableName == 0)) { + flag = 1; + } + return flag; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputNewKeywordChildren.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputNewKeywordChildren.java new file mode 100644 index 000000000000..0e6092b5df67 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputNewKeywordChildren.java @@ -0,0 +1,84 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Optional; + +/** some data. */ +public class InputNewKeywordChildren { + + static { + try { + Class.forName("org.postgresql.Driver"); + } catch (ClassNotFoundException e) { + throw new IllegalStateException( + "Please check if you have proper PostgreSQL JDBC Driver jar on the classpath", + e); + } + } + + static { + try { + Class.forName("org.postgresql.Driver"); + } catch (ClassNotFoundException e) { + throw new IllegalStateException( + "Please check if you have proper PostgreSQL JDBC Driver jar on the classpath", + e); + } + } + + /** some data. */ + public Object foo() { + return Optional.empty() + .orElseThrow( + () -> +// violation below '.* incorrect indentation level 0, expected .* 14, 16.' +new IllegalArgumentException( +"Something wrong 1, something wrong 2, something wrong 3")); + // violation above '.* incorrect indentation level 0, expected level should be one .* 18, 20' + } + + /** some data. */ + public Object foo1() { + return Optional.empty() + .orElseThrow( + () -> + new IllegalArgumentException( +"Something wrong 1, something wrong 2, something wrong 3")); + // violation above '.* incorrect indentation level 0, expected .* 18, 20.' + } + + /** some data. */ + public void foo2() throws IOException { + BufferedReader bf = + new BufferedReader( + new InputStreamReader(System.in) { + int anInt = 0; + }); + } + + /** some data. */ + public Object foo4(int data) { + return Optional.empty() + .orElseThrow( + () -> new IllegalArgumentException( + "something wrong 1, something wrong 2, something wrong 3")); + } + + /** some data. */ + public Object foo5(int data) { + return Optional.empty() + .orElseThrow( + () -> new IllegalArgumentException( + "something wrong 1, something wrong 2, something wrong 3")); + // violation above '.* incorrect indentation level 8, expected .* 16.' + } + + /** some data. */ + public void createExpressionIssue(Object invocation, String toBeRemovedExpression) { + throw new IllegalArgumentException("The expression " + toBeRemovedExpression + + ", which creates argument of the invocation " + invocation + " cannot be removed." + + " Override method `canRemoveExpression` to customize this behavior."); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputNewKeywordChildrenCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputNewKeywordChildrenCorrect.java new file mode 100644 index 000000000000..40c048eb5928 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputNewKeywordChildrenCorrect.java @@ -0,0 +1,28 @@ +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Optional; + +/** some data. */ +public class InputNewKeywordChildrenCorrect { + + /** some data. */ + public Object foo() { + return Optional.empty() + .orElseThrow( + () -> + new IllegalArgumentException( + "Something wrong 1, something wrong 2, something wrong 3")); + } + + /** some data. */ + public void foo2() throws IOException { + BufferedReader bf = + new BufferedReader( + new InputStreamReader(System.in) { + int anInt = 0; + }); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSingleSwitchStatementWithoutCurly.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSingleSwitchStatementWithoutCurly.java new file mode 100644 index 000000000000..7f0045bf3e72 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSingleSwitchStatementWithoutCurly.java @@ -0,0 +1,62 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/**some javadoc.*/ +public class InputSingleSwitchStatementWithoutCurly { + void testCorrectIndentation(int obj) { + switch (obj) { + case 0 + -> + System.out.println("Test"); + case 1 -> + System.out.println("TEST"); + case 2 -> { + System.out.println("Test"); + } + default -> System.out.println("test"); + } + } + + void testIncorrectIndentation(int obj) { + switch (obj) { + case 1 + -> // violation '.* incorrect indentation level 6, expected .* 10.' + System.out.println("Test"); + // violation above '.* incorrect indentation level 6, expected .* 14.' + case 2 -> // violation '.* incorrect indentation level 4, expected .* 6.' +System.out.println("Test"); // violation '.* incorrect indentation level 0, expected .* 10.' + default -> System.out.println("test"); + } + } + + void testMixedCases(int obj) { + switch (obj) { + case 1 -> System.out.println("TEST"); + case 2 + -> System.out.println("Test"); + case 3 -> + System.out.println("Test"); + // violation above '.* incorrect indentation level 20, expected .* 10.' + case 4 -> { + System.out.println("Test"); + System.out.println("Another statement"); + // violation above '.* incorrect indentation level 6, expected .* 8.' + } + default -> System.out.println("test"); + } + } + + private boolean testLineWrapping(int x, int y, int z) { + return switch (x) { + case 1 -> true; + case 2 -> x != y + && y != 5; + case 3 -> + y != 4 + && z != 2 + && y != z; + default -> false; + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSingleSwitchStatementWithoutCurlyCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSingleSwitchStatementWithoutCurlyCorrect.java new file mode 100644 index 000000000000..5d12092cb6d8 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSingleSwitchStatementWithoutCurlyCorrect.java @@ -0,0 +1,47 @@ +// Java21 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputSingleSwitchStatementWithoutCurlyCorrect { + void testCorrectIndentation(int obj) { + switch (obj) { + case 0 -> System.out.println("Test"); + case 1 -> System.out.println("TEST"); + case 2 -> { + System.out.println("Test"); + } + default -> System.out.println("test"); + } + } + + void testIncorrectIndentation(int obj) { + switch (obj) { + case 1 -> System.out.println("Test"); + case 2 -> System.out.println("Test"); + default -> System.out.println("test"); + } + } + + void testMixedCases(int obj) { + switch (obj) { + case 1 -> System.out.println("TEST"); + case 2 -> System.out.println("Test"); + case 3 -> System.out.println("Test"); + case 4 -> { + System.out.println("Test"); + System.out.println("Another statement"); + } + default -> System.out.println("test"); + } + } + + private boolean testLineWrapping(int x, int y, int z) { + return switch (x) { + case 1 -> true; + case 2 -> x != y && y != 5; + case 3 -> y != 4 && z != 2 && y != z; + default -> false; + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchOnStartOfTheLine.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchOnStartOfTheLine.java new file mode 100644 index 000000000000..6382c370053d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchOnStartOfTheLine.java @@ -0,0 +1,47 @@ +// Java17 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/**some javadoc.*/ +public class InputSwitchOnStartOfTheLine { + String testMethod1(int i) { + String s = + switch (i) { + case 1 -> "one"; + case 2 -> "two"; + default -> "zero"; + }; + return s; + } + + void testMethod2(int month) { + int result = + switch (month) { + case 1, 6, 7 -> 3; + case 2, 9, 10, 11, 12 -> 1; + case 3, 5, 4, 8 -> { + yield month * 4; + } + default -> 0; + }; + } + + void testMethod3Invalid(int num) { + int odd = + switch (num) { // violation '.* incorrect indentation level 6, expected .* 8.' + case 1, 3, 7 -> 1; // violation '.* incorrect indentation level 8, expected .* 10.' + case 2, 4, 6 -> 2; // violation '.* incorrect indentation level 8, expected .* 10.' + default -> 0; // violation '.* incorrect indentation level 8, expected .* 10.' + }; // violation '.* incorrect indentation level 6, expected .* 8.' + } + + String testMethod4Invalid(int i) { + String s = + switch (i) { // violation '.* incorrect indentation level 10, expected .* 8.' + case 1 -> "one"; // violation '.* incorrect indentation level 12, expected .* 10.' + case 2 -> "two"; // violation '.* incorrect indentation level 12, expected .* 10.' + default -> "zero"; // violation '.* incorrect indentation level 12, expected .* 10.' + }; + return s; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchOnStartOfTheLineCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchOnStartOfTheLineCorrect.java new file mode 100644 index 000000000000..816dc0741a9b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchOnStartOfTheLineCorrect.java @@ -0,0 +1,28 @@ +// Java17 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +/** some javadoc. */ +public class InputSwitchOnStartOfTheLineCorrect { + String testMethod1(int i) { + String s = + switch (i) { + case 1 -> "one"; + case 2 -> "two"; + default -> "zero"; + }; + return s; + } + + void testMethod2(int month) { + int result = + switch (month) { + case 1, 6, 7 -> 3; + case 2, 9, 10, 11, 12 -> 1; + case 3, 5, 4, 8 -> { + yield month * 4; + } + default -> 0; + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchWrappingIndentation.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchWrappingIndentation.java new file mode 100644 index 000000000000..a9a12533ef3c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchWrappingIndentation.java @@ -0,0 +1,54 @@ +// Java17 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.util.List; + +/**some javadoc.*/ +public class InputSwitchWrappingIndentation { + String testMethod1(int i) { + String name = ""; + name = + switch (i) { + case 1 -> "one"; + case 2 -> "two"; + default -> "zero"; + }; + return name; + } + + String testMethod2(int x, int y) { + return switch (x) { + case 1 -> + switch (y) { + case 2 -> "test"; + default -> "inner default"; + }; + default -> "outer default"; + }; + } + + String testMethod3(List operations) { + return operations.stream() + .map( + op -> + switch (op) { + case 1 -> "test"; + default -> "TEST"; + }) + .findFirst().orElse("defaultValue"); + } + + String testMethod4Invalid(int x, int y) { + return switch (x) { + case 1 -> + switch (y) { + // violation above '.* incorrect indentation level 8, expected .* 10.' + case 2 -> "test"; + // violation above '.* incorrect indentation level 10, expected .* 12.' + default -> "inner default"; + }; + default -> "outer default"; + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchWrappingIndentationCorrect.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchWrappingIndentationCorrect.java new file mode 100644 index 000000000000..1cc46709c486 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4841indentation/InputSwitchWrappingIndentationCorrect.java @@ -0,0 +1,53 @@ +// Java17 + +package com.google.checkstyle.test.chapter4formatting.rule4841indentation; + +import java.util.List; + +/** some javadoc. */ +public class InputSwitchWrappingIndentationCorrect { + String testMethod1(int i) { + String name = ""; + name = + switch (i) { + case 1 -> "one"; + case 2 -> "two"; + default -> "zero"; + }; + return name; + } + + String testMethod2(int x, int y) { + return switch (x) { + case 1 -> + switch (y) { + case 2 -> "test"; + default -> "inner default"; + }; + default -> "outer default"; + }; + } + + String testMethod3(List operations) { + return operations.stream() + .map( + op -> + switch (op) { + case 1 -> "test"; + default -> "TEST"; + }) + .findFirst() + .orElse("defaultValue"); + } + + String testMethod4(int x, int y) { + return switch (x) { + case 1 -> + switch (y) { + case 2 -> "test"; + default -> "inner default"; + }; + default -> "outer default"; + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/InputFallThrough.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/InputFallThrough.java index a09fab430d74..b6b9372d4ebd 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/InputFallThrough.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4842fallthrough/InputFallThrough.java @@ -1,453 +1,470 @@ package com.google.checkstyle.test.chapter4formatting.rule4842fallthrough; -public class InputFallThrough -{ - void method(int i, int j, boolean cond) { - while (true) { - switch (i) { - case 0: // no problem +/** Some javadoc. */ +public class InputFallThrough { + void method(int i, int j, boolean cond) { + while (true) { + switch (i) { + case 0: // no problem + case 1: + i++; + break; + case 2: + i++; + case 3: // violation 'Fall through from previous branch of the switch statement.' + i++; + break; + case 4: + return; + case 5: + throw new RuntimeException(""); + case 6: + continue; + case 7: + { + break; + } + case 8: + { + return; + } + case 9: + { + throw new RuntimeException(""); + } + case 10: + { + continue; + } + case 11: + { + i++; + } + case 12: // violation 'Fall through from previous branch of the switch statement.' + if (false) { + break; + } else { + break; + } + case 13: + if (true) { + return; + } + case 14: // violation 'Fall through from previous branch of the switch statement.' + if (true) { + return; + } else { + // do nothing + } + case 15: // violation 'Fall through from previous branch of the switch statement.' + do { + System.identityHashCode("something"); + return; + } while (true); + case 16: + for (int j1 = 0; j1 < 10; j1++) { + System.identityHashCode("something"); + return; + } + case 17: + while (true) { + throw new RuntimeException(""); + } + case 18: + while (cond) { + break; + } + case 19: // violation 'Fall through from previous branch of the switch statement.' + try { + i++; + break; + } catch (RuntimeException e) { + break; + } catch (Error e) { + return; + } + case 20: + try { + i++; + break; + } catch (RuntimeException e) { + // do nothing + } catch (Error e) { + return; + } + case 21: // violation 'Fall through from previous branch of the switch statement.' + try { + i++; + } catch (RuntimeException e) { + i--; + } finally { + break; + } + case 22: + try { + i++; + break; + } catch (RuntimeException e) { + i--; + break; + } finally { + i++; + } + case 23: + switch (j) { case 1: - i++; - break; + continue; case 2: - i++; - case 3: //warn - i++; - break; - case 4: - return; - case 5: - throw new RuntimeException(""); - case 6: - continue; - case 7: { - break; - } - case 8: { - return; - } - case 9: { - throw new RuntimeException(""); - } - case 10: { - continue; - } - case 11: { - i++; - } - case 12: //warn - if (false) - break; - else - break; - case 13: - if (true) { - return; - } - case 14: //warn - if (true) { - return; - } else { - //do nothing - } - case 15: //warn - do { - System.identityHashCode("something"); - return; - } while(true); - case 16: - for (int j1 = 0; j1 < 10; j1++) { - System.identityHashCode("something"); - return; - } - case 17: - while (true) - throw new RuntimeException(""); - case 18: - while(cond) { - break; - } - case 19: //warn - try { - i++; - break; - } catch (RuntimeException e) { - break; - } catch (Error e) { - return; - } - case 20: - try { - i++; - break; - } catch (RuntimeException e) { - } catch (Error e) { - return; - } - case 21: //warn - try { - i++; - } catch (RuntimeException e) { - i--; - } finally { - break; - } - case 22: - try { - i++; - break; - } catch (RuntimeException e) { - i--; - break; - } finally { - i++; - } - case 23: - switch (j) { - case 1: - continue; - case 2: - return; - default: - return; - } - case 24: - switch (j) { - case 1: - continue; - case 2: - break; - default: - return; - } - default: //warn - // this is the last label - i++; - } - } - } - - - - /* Like above, but all fall throughs with relief comment */ - void methodFallThru(int i, int j, boolean cond) { - while (true) { - switch (i) { - case -1: // FALLTHRU - - case 0: // no problem - case 1: - i++; - break; - case 2: - i++; - // fallthru - case 3: - i++; - break; - case 4: return; - case 5: - throw new RuntimeException(""); - case 6: + default: + return; + } + case 24: + switch (j) { + case 1: continue; - case 7: { + case 2: break; - } - case 8: { + default: return; } - case 9: { - throw new RuntimeException(""); + default: // violation 'Fall through from previous branch of the switch statement.' + // this is the last label + i++; + } + } + } + + /* Like above, but all fall throughs with relief comment */ + void methodFallThru(int i, int j, boolean cond) { + while (true) { + switch (i) { + case -1: // FALLTHRU + + case 0: // no problem + case 1: + i++; + break; + case 2: + i++; + // fallthru + case 3: + i++; + break; + case 4: + return; + case 5: + throw new RuntimeException(""); + case 6: + continue; + case 7: + { + break; } - case 10: { - continue; + case 8: + { + return; } - case 11: { - i++; + case 9: + { + throw new RuntimeException(""); } - // fallthru - case 12: - if (false) - break; - else - break; - case 13: - if (true) { - return; - } - case 14: //warn - if (true) { - return; - } else { - //do nothing - } - // fallthru - case 15: - do { - System.identityHashCode("something"); - return; - } while(true); - case 16: - for (int j1 = 0; j1 < 10; j1++) { - System.identityHashCode("something"); - return; - } - case 17: - while (cond) - throw new RuntimeException(""); - case 18: - while(cond) { - break; - } - // fallthru - case 19: - try { - i++; - break; - } catch (RuntimeException e) { - break; - } catch (Error e) { - return; - } - case 20: - try { - i++; - break; - } catch (RuntimeException e) { - } catch (Error e) { - return; - } - // fallthru - case 21: - try { - i++; - } catch (RuntimeException e) { - i--; - } finally { - break; - } - case 22: - try { - i++; - break; - } catch (RuntimeException e) { - i--; - break; - } finally { - i++; - } - /* fallthru */ - case 23: - switch (j) { - case 1: - continue; - case 2: - return; - default: - return; - } - case 24: - i++; - /* fallthru */ case 25: - i++; - break; + case 10: + { + continue; + } + case 11: + { + i++; + } + // fallthru + case 12: + if (false) { + break; + } else { + break; + } + case 13: + if (true) { + return; + } + case 14: // violation 'Fall through from previous branch of the switch statement.' + if (true) { + return; + } else { + // do nothing + } + // fallthru + case 15: + do { + System.identityHashCode("something"); + return; + } while (true); + case 16: + for (int j1 = 0; j1 < 10; j1++) { + System.identityHashCode("something"); + return; + } + case 17: + while (cond) { + throw new RuntimeException(""); + } + case 18: + while (cond) { + break; + } + // fallthru + case 19: + try { + i++; + break; + } catch (RuntimeException e) { + break; + } catch (Error e) { + return; + } + case 20: + try { + i++; + break; + } catch (RuntimeException e) { + return; + } catch (Error e) { + return; + } + // fallthru + case 21: + try { + i++; + } catch (RuntimeException e) { + i--; + } finally { + break; + } + case 22: + try { + i++; + break; + } catch (RuntimeException e) { + i--; + break; + } finally { + i++; + } + /* fallthru */ + case 23: + switch (j) { + case 1: + continue; + case 2: + return; + default: + return; + } + case 24: + i++; + /* fallthru */ case 25: + i++; + break; - case 26: - switch (j) { - case 1: - continue; - case 2: - break; - default: - return; - } - // fallthru - default: - // this is the last label - i++; + case 26: + switch (j) { + case 1: + continue; + case 2: + break; + default: + return; + } + // fallthru + default: + // this is the last label + i++; // fallthru - } } - } + } + } - /* Test relief comment. */ - void methodFallThruCC(int i, int j, boolean cond) { - while (true) { - switch (i){ - case 0: - i++; // fallthru + /* Test relief comment. */ + void methodFallThruCc(int i, int j, boolean cond) { + while (true) { + switch (i) { // violation 'switch without "default" clause.' + case 0: + i++; // fallthru - case 1: - i++; - // fallthru - case 2: { - i++; + case 1: + i++; + // fallthru + case 2: + { + i++; } + // fallthru + case 3: + i++; + /* fallthru */ case 4: + break; + case 5: + i++; // fallthru - case 3: - i++; - /* fallthru */case 4: - break; - case 5: - i++; - // fallthru - } } - } + } + } - /* Like above, but C-style comments. */ - void methodFallThruC(int i, int j, boolean cond) { - while (true) { - switch (i){ - case 0: - i++; /* fallthru */ + /* Like above, but C-style comments. */ + void methodFallThruC(int i, int j, boolean cond) { + while (true) { + switch (i) { // violation 'switch without "default" clause.' + case 0: + i++; /* fallthru */ - case 1: - i++; - /* fallthru */ - case 2: - i++; - /* fallthru */case 3: - break; - case 4: - i++; + case 1: + i++; + /* fallthru */ + case 2: + i++; + /* fallthru */ case 3: + break; + case 4: + i++; /* fallthru */ - } } - } + } + } - /* Like above, but C-style comments with no spaces. */ - void methodFallThruC2(int i, int j, boolean cond) { - while (true) { - switch (i){ - case 0: - i++; /*fallthru*/ + /* Like above, but C-style comments with no spaces. */ + void methodFallThruC2(int i, int j, boolean cond) { + while (true) { + switch (i) { // violation 'switch without "default" clause.' + case 0: + i++; /*fallthru*/ - case 1: - i++; - /*fallthru*/ - case 2: - i++; - /*fallthru*/case 3: - break; - case 4: - i++; + case 1: + i++; + /*fallthru*/ + case 2: + i++; + /*fallthru*/ case 3: + break; + case 4: + i++; /*fallthru*/ - } } - } + } + } - /* C-style comments with other default fallthru-comment. */ - void methodFallThruCOtherWords(int i, int j, boolean cond) { - while (true) { - switch (i){ - case 0: - i++; /* falls through */ + /* C-style comments with other default fallthru-comment. */ + void methodFallThruOtherWords(int i, int j, boolean cond) { + while (true) { + switch (i) { // violation 'switch without "default" clause.' + case 0: + i++; /* falls through */ - case 1: - i++; - /* falls through */ - case 2: - i++; - /* falls through */case 3: - break; - case 4: - i++; + case 1: + i++; + /* falls through */ + case 2: + i++; + /* falls through */ case 3: + break; + case 4: + i++; /* falls through */ - } } - } + } + } - /* C-style comments with custom fallthru-comment. */ - void methodFallThruCustomWords(int i, int j, boolean cond) { - while (true) { - switch (i){ - case 0: - i++; /* Continue with next case */ + /* C-style comments with custom fallthru-comment. */ + void methodFallThruCustomWords(int i, int j, boolean cond) { + while (true) { + switch (i) { // violation 'switch without "default" clause.' + case 0: + i++; /* Continue with next case */ - case 1: //warn - i++; - /* Continue with next case. */ - case 2: //warn - i++; - /* Continue with next case. */case 3: //warn - break; - case 4: - i++; + case 1: // violation 'Fall through from previous branch of the switch statement.' + i++; + /* Continue with next case. */ + case 2: // violation 'Fall through from previous branch of the switch statement.' + i++; + /* Continue with next case. */ case 3: + // violation above 'Fall through from previous branch of the switch statement.' + break; + case 4: + i++; /* Continue with next case */ - } } - } + } + } - void methodFallThruLastCaseGroup(int i, int j, boolean cond) { - while (true) { - switch (i){ - case 0: - i++; // fallthru - } - switch (i){ - case 0: - i++; - // fallthru - } - switch (i){ - case 0: - i++; - /* fallthru */ } - } + void methodFallThruLastCaseGroup(int i, int j, boolean cond) { + while (true) { + switch (i) { // violation 'switch without "default" clause.' + case 0: + i++; // fallthru + } + switch (i) { // violation 'switch without "default" clause.' + case 0: + i++; + // fallthru + } + switch (i) { // violation 'switch without "default" clause.' + case 0: + i++; + /* fallthru */ + } } + } - void method1472228(int i) { - switch(i) { - case 2: - // do nothing - break; - default: - } + void method1472228(int i) { + switch (i) { + case 2: + // do nothing + break; + default: } + } - /* Test relief comment. */ - void methodFallThruWithDash(int i, int j, boolean cond) { - while (true) { - switch (i){ - case 0: - i++; // fallthru - case 1: - i++; // fall thru - case 2: - i++; // fall-thru - case 3: - i++; // fallthrough - case 4: - i++; // fall through - case 5: - i++; // fall-through - case 6: - i++; // fallsthru - case 7: - i++; // falls thru - case 8: - i++; // falls-thru - case 9: - i++; // fallsthrough - case 10: - i++; // falls through - case 11: - i++; // falls-through - case 12: - i++; // fall--through - case 13: //warn - i++; // fall+through - case 14: //warn - i++; // falls_thru - case 15: //warn - i++; // falls=through - case 16: //warn - i++; // falls-throug - default: //warn - throw new RuntimeException(); - } + /* Test relief comment. */ + void methodFallThruWithDash(int i, int j, boolean cond) { + while (true) { + switch (i) { + case 0: + i++; // fallthru + case 1: + i++; // fall thru + case 2: + i++; // fall-thru + case 3: + i++; // fallthrough + case 4: + i++; // fall through + case 5: + i++; // fall-through + case 6: + i++; // fallsthru + case 7: + i++; // falls thru + case 8: + i++; // falls-thru + case 9: + i++; // fallsthrough + case 10: + i++; // falls through + case 11: + i++; // falls-through + case 12: + i++; // fall--through + case 13: // violation 'Fall through from previous branch of the switch statement.' + i++; // fall+through + case 14: // violation 'Fall through from previous branch of the switch statement.' + i++; // falls_thru + case 15: // violation 'Fall through from previous branch of the switch statement.' + i++; // falls=through + case 16: // violation 'Fall through from previous branch of the switch statement.' + i++; // falls-throug + default: // violation 'Fall through from previous branch of the switch statement.' + throw new RuntimeException(); } - } + } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4843defaultcasepresent/InputMissingSwitchDefault.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4843defaultcasepresent/InputMissingSwitchDefault.java deleted file mode 100644 index c459bdc82104..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4843defaultcasepresent/InputMissingSwitchDefault.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule4843defaultcasepresent; - -public class InputMissingSwitchDefault { - public void foo() { - int i = 1; - switch (i) { - case 1: i++; break; - case 2: i--; break; - default: return; - } - switch (i) { // warn - } - } -} - -class bad_test { - public void foo() { - int i = 1; - switch (i) { // warn - case 1: i++; break; - case 2: i--; break; - } - switch (i) { // warn - } - } - - class inner - { - public void foo1() { - int i = 1; - switch (i) { // warn - case 1: i++; break; - case 2: i--; break; - } - Foo foo = new Foo() { - public void foo() { - int i = 1; - switch (i) { // warn - case 1: i++; break; - case 2: i--; break; - } - switch (i) { // warn - } - } - }; - } - } -} - -interface Foo { - public void foo(); -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4843defaultlabelpresence/InputPresenceOfDefaultLabel.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4843defaultlabelpresence/InputPresenceOfDefaultLabel.java new file mode 100644 index 000000000000..c21bbbeb4a37 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4843defaultlabelpresence/InputPresenceOfDefaultLabel.java @@ -0,0 +1,74 @@ +package com.google.checkstyle.test.chapter4formatting.rule4843defaultlabelpresence; + +/** Some javadoc. */ +public class InputPresenceOfDefaultLabel { + /** Some javadoc. */ + public void foo() { + int i = 1; + switch (i) { + case 1: + i++; + break; + case 2: + i--; + break; + default: + return; + } + switch (i) { // violation 'switch without "default" clause.' + } + } + + class BadTest { + /** Some javadoc. */ + public void foo() { + int i = 1; + switch (i) { // violation 'switch without "default" clause.' + case 1: + i++; + break; + case 2: + i--; + break; + } + switch (i) { // violation 'switch without "default" clause.' + } + } + + class Inner { + /** Some javadoc. */ + public void foo1() { + int i = 1; + switch (i) { // violation 'switch without "default" clause.' + case 1: + i++; + break; + case 2: + i--; + break; + } + Foo foo = + new Foo() { + /** Some javadoc. */ + public void foo() { + int i = 1; + switch (i) { // violation 'switch without "default" clause.' + case 1: + i++; + break; + case 2: + i--; + break; + } + switch (i) { // violation 'switch without "default" clause.' + } + } + }; + } + } + } + + interface Foo { + public void foo(); + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputClassAnnotation2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputClassAnnotation2.java new file mode 100644 index 000000000000..7d2663690c47 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputClassAnnotation2.java @@ -0,0 +1,34 @@ +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; + +import javax.annotation.CheckReturnValue; + +/** somejavadoc data. */ +@Deprecated +@CheckReturnValue +public final class InputClassAnnotation2 { + void test1() {} + + /** somejavadoc data. */ + @Deprecated @CheckReturnValue + public class Inner { + // violation 2 lines above 'Annotation 'CheckReturnValue' should be alone on line' + void test2() {} + } +} + +// violation 2 lines below 'Top-level class InputClassAnnotation3 has to reside' +/** somejavadoc data. */ +@Deprecated @CheckReturnValue +final class InputClassAnnotation3 { + // violation 2 lines above 'Annotation 'CheckReturnValue' should be alone on line' + void test2() {} +} + +// violation 2 lines below 'Top-level class InputClassAnnotation5 has to reside' +/** some javadoc. */ +@Deprecated +// testing +@CheckReturnValue +final class InputClassAnnotation5 { + void test3() {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputClassAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputClassAnnotations.java new file mode 100644 index 000000000000..f80e36df42cb --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputClassAnnotations.java @@ -0,0 +1,46 @@ +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; + +/** + * Test class for checking the rule 4852. + */ +public class InputClassAnnotations { + /** + * Custom annotation 1. + */ + public @interface SomeAnnotation1 { } + // violation above 'Empty blocks should have no spaces. .* may only be represented as {}' + + /** + * Custom annotation 2. + */ + public @interface SomeAnnotation2 { } + // violation above 'Empty blocks should have no spaces. .* may only be represented as {}' + + /** + * Inner class 2. + */ + @SomeAnnotation1 + @SomeAnnotation2 + class Inner1 {} + + @SomeAnnotation1 + @SomeAnnotation2 + /** // violation 'Javadoc comment is placed in the wrong location.' + * Inner class 2. + */ + class Inner2 {} + + /** + * Inner class 3. + */ + @SomeAnnotation1 @SomeAnnotation2 + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + class Inner3 {} + + @SomeAnnotation1 @SomeAnnotation2 + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + /** // violation 'Javadoc comment is placed in the wrong location.' + * Inner class 4. + */ + class Inner4 {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputFormattedClassAnnotation2.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputFormattedClassAnnotation2.java new file mode 100644 index 000000000000..2ff35285db15 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputFormattedClassAnnotation2.java @@ -0,0 +1,34 @@ +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; + +import javax.annotation.CheckReturnValue; + +/** somejavadoc data. */ +@Deprecated +@CheckReturnValue +public final class InputFormattedClassAnnotation2 { + void test1() {} + + /** somejavadoc data. */ + @Deprecated + @CheckReturnValue + public class Inner { + void test2() {} + } +} + +// violation 2 lines below 'Top-level class InputClassAnnotation4 has to reside' +/** somejavadoc data. */ +@Deprecated +@CheckReturnValue +final class InputClassAnnotation4 { + void test2() {} +} + +// violation 2 lines below 'Top-level class InputClassAnnotation6 has to reside' +/** some javadoc. */ +@Deprecated +// testing +@CheckReturnValue +final class InputClassAnnotation6 { + void test3() {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputFormattedClassAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputFormattedClassAnnotations.java new file mode 100644 index 000000000000..392b1a51e6f4 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/InputFormattedClassAnnotations.java @@ -0,0 +1,20 @@ +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; + +/** Test class for checking the rule 4852. */ +public class InputFormattedClassAnnotations { + /** Custom annotation 1. */ + public @interface SomeAnnotation1 {} + + /** Custom annotation 2. */ + public @interface SomeAnnotation2 {} + + /** Inner class 2. */ + @SomeAnnotation1 + @SomeAnnotation2 + class Inner1 {} + + /** Inner class 3. */ + @SomeAnnotation1 + @SomeAnnotation2 + class Inner3 {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/Name.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/Name.java new file mode 100644 index 000000000000..2116651424e5 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/Name.java @@ -0,0 +1,12 @@ +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.PACKAGE, ElementType.TYPE}) +public @interface Name { + String value(); +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/ParentPackage.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/ParentPackage.java new file mode 100644 index 000000000000..941c4b9a8e88 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/ParentPackage.java @@ -0,0 +1,12 @@ +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.PACKAGE, ElementType.TYPE}) +public @interface ParentPackage { + String value(); +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/SizePackage.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/SizePackage.java new file mode 100644 index 000000000000..95afbe042e0a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/SizePackage.java @@ -0,0 +1,12 @@ +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.PACKAGE, ElementType.TYPE}) +public @interface SizePackage { + String value(); +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/package-info.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/package-info.java new file mode 100644 index 000000000000..af68ca2e75d0 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/package-info.java @@ -0,0 +1,4 @@ +/** This is a package. */ +@Deprecated +@SuppressWarnings("...") +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations; diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample1/package-info.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample1/package-info.java new file mode 100644 index 000000000000..e7e5581cb281 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample1/package-info.java @@ -0,0 +1,4 @@ +// violation 2 lines below 'Annotation 'SuppressWarnings' should be alone on line' +/** This is a package. */ +@Deprecated @SuppressWarnings("...") +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations.sample1; diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample2/package-info.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample2/package-info.java new file mode 100644 index 000000000000..f9546447aa4a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample2/package-info.java @@ -0,0 +1,5 @@ +/** This is a package. */ +@Deprecated +// testing +@SuppressWarnings("...") +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations.sample2; diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample3/package-info.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample3/package-info.java new file mode 100644 index 000000000000..28ba096a426a --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample3/package-info.java @@ -0,0 +1,10 @@ +/* + * Licensed to the Software Foundation under one + * or more contributor license agreements. +*/ + +@ParentPackage("person") // violation below 'Annotation 'Name' should be alone on line' +@Name("/") package com.google.checkstyle.test.chapter4formatting.rule4852classannotations.sample3; + +import com.google.checkstyle.test.chapter4formatting.rule4852classannotations.Name; +import com.google.checkstyle.test.chapter4formatting.rule4852classannotations.ParentPackage; diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample4/package-info.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample4/package-info.java new file mode 100644 index 000000000000..fdd0b6b84eaa --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample4/package-info.java @@ -0,0 +1,14 @@ +/* + * All rights reserved. + */ + +// 3 violations 4 lines below: +// 'Annotation 'ParentPackage' should be alone on line' +// 'Annotation 'Name' should be alone on line' +// 'Annotation 'SizePackage' should be alone on line' +@ParentPackage("val") @Name("1") @SizePackage("2") +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations.sample4; + +import com.google.checkstyle.test.chapter4formatting.rule4852classannotations.Name; +import com.google.checkstyle.test.chapter4formatting.rule4852classannotations.ParentPackage; +import com.google.checkstyle.test.chapter4formatting.rule4852classannotations.SizePackage; diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample5/package-info.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample5/package-info.java new file mode 100644 index 000000000000..156879c02927 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4852classannotations/sample5/package-info.java @@ -0,0 +1,12 @@ +/* + * All rights reserved. + */ + +@ParentPackage("val") +@Name("1") +@SizePackage("2") +package com.google.checkstyle.test.chapter4formatting.rule4852classannotations.sample5; + +import com.google.checkstyle.test.chapter4formatting.rule4852classannotations.Name; +import com.google.checkstyle.test.chapter4formatting.rule4852classannotations.ParentPackage; +import com.google.checkstyle.test.chapter4formatting.rule4852classannotations.SizePackage; diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/InputFormattedMethodsAndConstructorsAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/InputFormattedMethodsAndConstructorsAnnotations.java new file mode 100644 index 000000000000..eb1b8e483e9c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/InputFormattedMethodsAndConstructorsAnnotations.java @@ -0,0 +1,56 @@ +package com.google.checkstyle.test.chapter4formatting.rule4853methodsandconstructorsannotations; + +/** Some javadoc. */ +public class InputFormattedMethodsAndConstructorsAnnotations { + /** Some javadoc. */ + public @interface SomeAnnotation1 {} + + /** Some javadoc. */ + public @interface SomeAnnotation2 {} + + // ********testing methods.*********** + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 + void test1() {} + + /** testing. */ + @SomeAnnotation1 + void test2() {} + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 + void test3() {} + + @SomeAnnotation1 + @SomeAnnotation2 + void test6() {} + + @SuppressWarnings("blah") + void test7() {} + + // ********testing constructors.********* + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 + InputFormattedMethodsAndConstructorsAnnotations() {} + + /** testing. */ + @SomeAnnotation1 + InputFormattedMethodsAndConstructorsAnnotations(float f) {} + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 + InputFormattedMethodsAndConstructorsAnnotations(int x) {} + + @SomeAnnotation1 + @SomeAnnotation2 + InputFormattedMethodsAndConstructorsAnnotations(String a, String b) {} + + @SuppressWarnings("blah") + InputFormattedMethodsAndConstructorsAnnotations(int x, int y) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/InputMethodsAndConstructorsAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/InputMethodsAndConstructorsAnnotations.java new file mode 100644 index 000000000000..1c05870985f5 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4853methodsandconstructorsannotations/InputMethodsAndConstructorsAnnotations.java @@ -0,0 +1,73 @@ +package com.google.checkstyle.test.chapter4formatting.rule4853methodsandconstructorsannotations; + +/** Some javadoc. */ +public class InputMethodsAndConstructorsAnnotations { + /** Some javadoc. */ + public @interface SomeAnnotation1 {} + + /** Some javadoc. */ + public @interface SomeAnnotation2 {} + + // ********testing methods.*********** + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 + void test1() {} + + /** testing. */ + @SomeAnnotation1 void test2() {} + + /** testing. */ + @SomeAnnotation1 @SomeAnnotation2 + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + void test3() {} + + @SomeAnnotation1 + @SomeAnnotation2 + /** testing. */ // violation 'Javadoc comment is placed in the wrong location.' + void test4() {} + + @SomeAnnotation1 @SomeAnnotation2 + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + /** testing. */ // violation 'Javadoc comment is placed in the wrong location.' + void test5() {} + + @SomeAnnotation1 @SomeAnnotation2 void test6() {} + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + + @SuppressWarnings("blah") void test7() {} + // violation above 'Annotation 'SuppressWarnings' should be alone on line.' + + // ********testing constructors.********* + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 + InputMethodsAndConstructorsAnnotations() {} + + /** testing. */ + @SomeAnnotation1 InputMethodsAndConstructorsAnnotations(float f) {} + + /** testing. */ + @SomeAnnotation1 @SomeAnnotation2 + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + InputMethodsAndConstructorsAnnotations(int x) {} + + @SomeAnnotation1 + @SomeAnnotation2 + /** testing. */ // violation 'Javadoc comment is placed in the wrong location.' + InputMethodsAndConstructorsAnnotations(String str) {} + + @SomeAnnotation1 @SomeAnnotation2 + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + /** testing. */ // violation 'Javadoc comment is placed in the wrong location.' + InputMethodsAndConstructorsAnnotations(double d) {} + + // violation below 'Annotation 'SomeAnnotation2' should be alone on line.' + @SomeAnnotation1 @SomeAnnotation2 InputMethodsAndConstructorsAnnotations(String a, + String b) {} + + // violation below 'Annotation 'SuppressWarnings' should be alone on line.' + @SuppressWarnings("blah") InputMethodsAndConstructorsAnnotations(int x, int y) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/InputFieldAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/InputFieldAnnotations.java new file mode 100644 index 000000000000..bc7776a22e06 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/InputFieldAnnotations.java @@ -0,0 +1,60 @@ +package com.google.checkstyle.test.chapter4formatting.rule4854fieldannotations; + +import java.util.ArrayList; +import java.util.List; + +/** Some javadoc. */ +public class InputFieldAnnotations { + /** Some javadoc. */ + public @interface SomeAnnotation1 {} + + /** Some javadoc. */ + public @interface SomeAnnotation2 {} + + /** Some javadoc. */ + public @interface SomeAnnotation3 { + /** Some javadoc. */ + int x(); + } + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 + String name = "Zops"; + + /** testing. */ + @SomeAnnotation1 @SomeAnnotation2 + int age = 19; + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 String favLanguage = "Java"; + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation3(x = 90) String favPet = "Dog"; + + @SomeAnnotation1 @SomeAnnotation2 boolean test = false; + + @SuppressWarnings("bla") @SomeAnnotation3(x = 0) float pi = 3.14f; + + @SomeAnnotation1 @SomeAnnotation3(x = 14) + /** testing. */ // violation 'Javadoc comment is placed in the wrong location.' + List list = new ArrayList<>(); + + @SuppressWarnings("bla") + @SomeAnnotation1 + /** testing. */ // violation 'Javadoc comment is placed in the wrong location.' + InputFieldAnnotations obj = new InputFieldAnnotations(); + + /** testing. */ + @SomeAnnotation1 @SomeAnnotation2 + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + void test1() {} + + @SomeAnnotation1 @SomeAnnotation2 void test2() {} + // violation above 'Annotation 'SomeAnnotation2' should be alone on line.' + + @SomeAnnotation3(x = 78) void test3() {} + // violation above 'Annotation 'SomeAnnotation3' should be alone on line.' +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/InputFormattedFieldAnnotations.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/InputFormattedFieldAnnotations.java new file mode 100644 index 000000000000..a7d9211b7504 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4854fieldannotations/InputFormattedFieldAnnotations.java @@ -0,0 +1,60 @@ +package com.google.checkstyle.test.chapter4formatting.rule4854fieldannotations; + +import java.util.ArrayList; +import java.util.List; + +/** Some javadoc. */ +public class InputFormattedFieldAnnotations { + /** Some javadoc. */ + public @interface SomeAnnotation1 {} + + /** Some javadoc. */ + public @interface SomeAnnotation2 {} + + /** Some javadoc. */ + public @interface SomeAnnotation3 { + /** Some javadoc. */ + int x(); + } + + /** testing. */ + @SomeAnnotation1 @SomeAnnotation2 String name = "Zops"; + + /** testing. */ + @SomeAnnotation1 @SomeAnnotation2 int age = 19; + + /** testing. */ + @SomeAnnotation1 @SomeAnnotation2 String favLanguage = "Java"; + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation3(x = 90) + String favPet = "Dog"; + + @SomeAnnotation1 @SomeAnnotation2 boolean test = false; + + @SuppressWarnings("bla") + @SomeAnnotation3(x = 0) + float pi = 3.14f; + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation3(x = 14) + List list = new ArrayList<>(); + + /** testing. */ + @SuppressWarnings("bla") + InputFormattedFieldAnnotations obj = new InputFormattedFieldAnnotations(); + + /** testing. */ + @SomeAnnotation1 + @SomeAnnotation2 + void test1() {} + + @SomeAnnotation1 + @SomeAnnotation2 + void test2() {} + + @SomeAnnotation3(x = 78) + void test3() {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule485annotations/InputAnnotationLocation.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule485annotations/InputAnnotationLocation.java deleted file mode 100644 index b0c8fdfe711a..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule485annotations/InputAnnotationLocation.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule485annotations; - -@MyAnnotation2 @MyAnnotation1 //warn -class InputAnnotationLocation -{ - - @MyAnnotation2 @MyAnnotation1 - public int a; - - @MyAnnotation1 public int b; - - @MyAnnotation2 - @MyAnnotation1 - public int c; - - @MyAnnotation1 - public int d; - - @MyAnnotation2 - @MyAnnotation1 //warn - public InputAnnotationLocation() {} - - @MyAnnotationWithParam("foo") - @MyAnnotation2 void foo1() {} - - @MyAnnotation1 - @MyAnnotation2 //warn - void foo2() {} - - @MyAnnotation1 - @MyAnnotation2 //warn - @MyAnnotation3 //warn - @MyAnnotation4 //warn - class InnerClass - { - @MyAnnotation2 @MyAnnotation1 - public int a; - - @MyAnnotation1 public int b; - - @MyAnnotation2 - @MyAnnotation1 - public int c; - - @MyAnnotation1 - public int d; - - @MyAnnotation2 - @MyAnnotation1 public InnerClass() - { - // OOOO Auto-generated constructor stub - } - @MyAnnotation1 - @MyAnnotation2 //warn - void foo1() {} - - @MyAnnotation1 - @MyAnnotation2 //warn - void foo2() {} - } - - @MyAnnotation1 - @MyAnnotation2 - InnerClass anon = new InnerClass() - { - @MyAnnotation2 @MyAnnotation1 public int a; - - @MyAnnotation1 public int b; - - @MyAnnotation2 - @MyAnnotation1 - public int c; - - @MyAnnotation1 - public int d; - - @MyAnnotation1 - @MyAnnotation2 void foo1() {} //warn - - @MyAnnotation1 - @MyAnnotation2 //warn - void foo2() {} - - @MyAnnotation1 void foo42() {} - }; - -} - -@MyAnnotation1 - @MyAnnotation2 //warn -class Foo {} - -@MyAnnotationWithParam(value = "bar") class Bar {} //warn - -@interface MyAnnotation1 {} - -@interface MyAnnotation2 {} - -@interface MyAnnotation3 {} - -@interface MyAnnotation4 {} - -@interface MyAnnotationWithParam { - - String value();} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule485annotations/InputAnnotationLocationVariables.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule485annotations/InputAnnotationLocationVariables.java deleted file mode 100644 index ea2e759c522b..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule485annotations/InputAnnotationLocationVariables.java +++ /dev/null @@ -1,103 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule485annotations; - -@MyAnnotation2 @MyAnnotation1 // ok - in variables config -class InputAnnotationLocationVariables -{ - - @MyAnnotation2 @MyAnnotation1 - public int a; - - @MyAnnotation1 public int b; - - @MyAnnotation2 - @MyAnnotation1 - public int c; - - @MyAnnotation1 - public int d; - - @MyAnnotation2 - @MyAnnotation1 // ok - in variables config - public InputAnnotationLocationVariables() {} - - @MyAnnotationWithParam("foo") - @MyAnnotation2 void foo1() {} - - @MyAnnotation1 - @MyAnnotation2 // ok - in variables config - void foo2() {} - - @MyAnnotation1 - @MyAnnotation2 // ok - in variables config - @MyAnnotation3 // ok - in variables configwarn - @MyAnnotation4 // ok - in variables config - class InnerClass - { - @MyAnnotation2 @MyAnnotation1 - public int a; - - @MyAnnotation1 public int b; - - @MyAnnotation2 - @MyAnnotation1 - public int c; - - @MyAnnotation1 - public int d; - - @MyAnnotation2 - @MyAnnotation1 public InnerClass() - { - // OOOO Auto-generated constructor stub - } - @MyAnnotation1 - @MyAnnotation2 // ok - in variables config - void foo1() {} - - @MyAnnotation1 - @MyAnnotation2 // ok - in variables config - void foo2() {} - } - - @MyAnnotation1 - @MyAnnotation2 //warn - InnerClass anon = new InnerClass() - { - @MyAnnotation2 @MyAnnotation1 public int a; - - @MyAnnotation1 public int b; - - @MyAnnotation2 - @MyAnnotation1 - public int c; - - @MyAnnotation1 - public int d; - - @MyAnnotation1 - @MyAnnotation2 void foo1() {} // ok - in variables config - - @MyAnnotation1 - @MyAnnotation2 // ok - in variables config - void foo2() {} - - @MyAnnotation1 void foo42() {} - }; - -} - -@MyAnnotation1 - @MyAnnotation2 // ok - in variables config -class FooVariables {} - -@interface MyAnnotationVariables1 {} - -@interface MyAnnotationVariables2 {} - -@interface MyAnnotationVariables3 {} - -@interface MyAnnotationVariables4 {} - -@interface MyAnnotationWithParamVariables { - - String value();} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationCommentIsAtTheEndOfBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationCommentIsAtTheEndOfBlock.java index 0b078e551097..02b70096f9ae 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationCommentIsAtTheEndOfBlock.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationCommentIsAtTheEndOfBlock.java @@ -1,367 +1,428 @@ package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; - - - -/** - * Contains examples of using comments at the end of the block. - */ +/** Contains examples of using comments at the end of the block. */ public class InputCommentsIndentationCommentIsAtTheEndOfBlock { - public void foo1() { - foo2(); - // OOOO: missing functionality - } - - public void foo2() { - foo3(); - // warn - } - - public void foo3() { - foo2(); - // refreshDisplay(); - } - - public void foo4() { - foooooooooooooooooooooooooooooooooooooooooo(); - // ^-- some hint - } - - public void foooooooooooooooooooooooooooooooooooooooooo() { } - - /////////////////////////////// warn (a single line border to separate a group of methods) - - public void foo7() { - int a = 0; -// warn - } - - /////////////////////////////// (a single line border to separate a group of methods) - - public void foo8() {} - - public class TestClass { - public void test() { - int a = 0; - // warn - } - // warn - } - - public void foo9() { - this.foo1(); - // warn - } - - // public void foo10() { - // - // } - - public void foo11() { - String - .valueOf(new Integer(0)) - .trim() - .length(); - // comment - } - - public void foo12() { - String - .valueOf(new Integer(0)) - .trim() - .length(); - // warn - } - - public void foo13() { - String.valueOf(new Integer(0)) - .trim() - .length(); - // comment - } - - public void foo14() { - String.valueOf(new Integer(0)) - .trim() - .length(); - // warn - } - - public void foo15() { - String - .valueOf(new Integer(0)); - // comment - } - - public void foo16() { - String - .valueOf(new Integer(0)); - // warn - } - - public void foo17() { - String - .valueOf(new Integer(0)) + /** some javadoc. */ + public void foo1() { + foo2(); + // OOOO: missing functionality + } + + /** some javadoc. */ + public void foo2() { + // violation 2 lines below '.* indentation should be the same level as line 15.' + foo3(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo3() { + foo2(); + // refreshDisplay(); + } + + /** some javadoc. */ + public void foo4() { + foooooooooooooooooooooooooooooooooooooooooo(); + // ^-- some hint + } + + /** some javadoc. */ + public void foooooooooooooooooooooooooooooooooooooooooo() {} + + /////////////////////////////// odd indentation comment + // violation above '.* indentation should be the same level as line 38.' + + /** some javadoc. */ + public void foo7() { + // violation 2 lines below'.* indentation should be the same level as line 40.' + int a = 0; +// odd indentation comment + } + + /////////////////////////////// (a single-line border to separate a group of methods) + + /** some javadoc. */ + public void foo8() {} + + /** some javadoc. */ + public class TestClass { + /** some javadoc. */ + public void test() { + // violation 3 lines below '.* indentation should be the same level as line 55.' + // violation 4 lines below'.* indentation should be the same level as line 52.' + int a = 0; + // odd indentation comment + } + // odd indentation comment + } + + /** some javadoc. */ + public void foo9() { + // violation 2 lines below '.* indentation should be the same level as line 64.' + this.foo1(); + // odd indentation comment + } + + // public void foo10() { + // + // } + + /** some javadoc. */ + public void foo11() { + String.valueOf(new Integer(0)).trim().length(); + // comment + } + + /** some javadoc. */ + public void foo12() { + // violation 5 lines below '.* indentation should be the same level as line 81.' + String + .valueOf(new Integer(0)) + .trim() + .length(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo13() { + String.valueOf(new Integer(0)).trim().length(); + // comment + } + + /** some javadoc. */ + public void foo14() { + // violation 4 lines below '.* indentation should be the same level as line 97.' + String.valueOf(new Integer(0)) + .trim() + .length(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo15() { + String.valueOf(new Integer(0)); + // comment + } + + /** some javadoc. */ + public void foo16() { + // violation 3 lines below '.* indentation should be the same level as line 112.' + String + .valueOf(new Integer(0)); + // odd indentation comment + } + + /** some javadoc. */ + public void foo17() { + String.valueOf(new Integer(0)) .trim() // comment .length(); - } - - public void foo18() { - String - .valueOf(new Integer(0)) - .trim() - // warn - .length(); - } - - public void foo19() { - (new Thread(new Runnable() { - @Override - public void run() { - - } - })). - run(); - // comment - } - - public void foo20() { - (new Thread(new Runnable() { - @Override - public void run() { - - } - })). - run(); - // warn - } - - public void foo21() { - int[] array = new int[5]; - - java.util.List expected = new java.util.ArrayList<>(); - for (int i = 0; i < 5; i++) { - org.junit.Assert.assertEquals(expected.get(i), array[i]); - } - String s = String.format(java.util.Locale.ENGLISH, "The array element " - + "immediately following the end of the collection should be nulled", - array[1]); - // the above example was taken from hibernate-orm and was modified a bit - } - - public void foo22() { - int[] array = new int[5]; - - java.util.List expected = new java.util.ArrayList<>(); - for (int i = 0; i < 5; i++) { - org.junit.Assert.assertEquals(expected.get(i), array[i]); - } - String s = String.format(java.util.Locale.ENGLISH, "The array element " - + "immediately following the end of the collection should be nulled", - array[1]); - // warn - } - - public void foo23() { - new Object(); - // comment - } - - public void foo24() { - new Object(); - // warn - } - - public String foo25() { - return String.format(java.util.Locale.ENGLISH, "%d", - 1); - // comment - } - - public String foo26() { - return String.format(java.util.Locale.ENGLISH, "%d", - 1); - // warn - } - - public void foo27() { - // comment - // block - foo17(); - - // OOOO - } - - public String foo28() { - int a = 5; - return String.format(java.util.Locale.ENGLISH, "%d", - 1); - // comment - } - - public String foo29() { - int a = 5; - return String.format(java.util.Locale.ENGLISH, "%d", - 1); - // warn - } - - public void foo30() { - // comment - int a = 5; -// warn - } - - public void foo31() { - String s = new String ("A" - + "B" - + "C"); - // comment - } - - public void foo32() { - String s = new String ("A" - + "B" - + "C"); - // warn - } - - public void foo33() { - // comment - this.foo22(); -// warn - } - - public void foo34() throws Exception { - throw new Exception("", - new Exception() - ); - // comment - } - - public void foo35() throws Exception { - throw new Exception("", - new Exception() - ); - // warn - } - - public void foo36() throws Exception { - throw new Exception("", - new Exception() - ); -// warn - } - - public void foo37() throws Exception { - throw new Exception("", new Exception()); - // comment - } - - public void foo38() throws Exception { - throw new Exception("", new Exception()); - // warn - } - - public void foo39() throws Exception { - throw new Exception("", - new Exception()); - // warn - } - - public void foo40() throws Exception { - int a = 88; - throw new Exception("", new Exception()); - // warn - } - - public void foo41() throws Exception { - int a = 88; - throw new Exception("", new Exception()); - // comment - } - - public void foo42() { - int a = 5; - if (a == 5) { - int b; - // comment - } else if (a ==6) { - - } - } - - public void foo43() { - try { - int a; - // comment - } catch (Exception e) { + } + + /** some javadoc. */ + public void foo18() { + // violation 4 lines below '.* indentation should be the same level as line 132.' + String + .valueOf(new Integer(0)) + .trim() + // odd indentation comment + .length(); + } + + /** some javadoc. */ + public void foo19() { + (new Thread( + new Runnable() { + @Override + public void run() {} + })) + .run(); + // comment + } + + /** some javadoc. */ + public void foo20() { + // violation 8 lines below '.* indentation should be the same level as line 149.' + (new Thread(new Runnable() { + @Override + public void run() { } - } - - public void foo44() { - int ar = 5; - // comment - ar = 6; - // comment - } - - public void foo45() { - int ar = 5; - // comment - ar = 6; - // warn - } - - public void foo46() { + })) + .run(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo21() { + int[] array = new int[5]; + + java.util.List expected = new java.util.ArrayList<>(); + for (int i = 0; i < 5; i++) { + org.junit.Assert.assertEquals(expected.get(i), array[i]); + } + String s = + String.format( + java.util.Locale.ENGLISH, + "The array element " + + "immediately following the end of the collection should be nulled", + array[1]); + // the above example was taken from hibernate-orm and was modified a bit + } + + /** some javadoc. */ + public void foo22() { + int[] array = new int[5]; + + java.util.List expected = new java.util.ArrayList<>(); + for (int i = 0; i < 5; i++) { + org.junit.Assert.assertEquals(expected.get(i), array[i]); + } + // violation 4 lines below '.* indentation should be the same level as line 185.' + String s = String.format(java.util.Locale.ENGLISH, "The array element " + + "immediately following the end of the collection should be nulled", + array[1]); + // odd indentation comment + } + + /** some javadoc. */ + public void foo23() { + new Object(); + // comment + } + + /** some javadoc. */ + public void foo24() { + // violation 2 lines below '.* indentation should be the same level as line 200.' + new Object(); + // odd indentation comment + } + + /** some javadoc. */ + public String foo25() { + return String.format(java.util.Locale.ENGLISH, "%d", 1); + // comment + } + + /** some javadoc. */ + public String foo26() { + // violation 3 lines below '.* indentation should be the same level as line 213.' + return String.format(java.util.Locale.ENGLISH, "%d", + 1); + // odd indentation comment + } + + /** some javadoc. */ + public void foo27() { + // comment + // block + foo17(); + + // OOOO + } + + /** some javadoc. */ + public String foo28() { + int a = 5; + return String.format(java.util.Locale.ENGLISH, "%d", 1); + // comment + } + + /** some javadoc. */ + public String foo29() { + int a = 5; + // violation 3 lines below '.* indentation should be the same level as line 238.' + return String.format(java.util.Locale.ENGLISH, "%d", + 1); + // odd indentation comment + } + + /** some javadoc. */ + public void foo30() { + // comment + // violation 2 lines below '.* indentation should be the same level as line 247.' + int a = 5; +// odd indentation comment + } + + /** some javadoc. */ + public void foo31() { + String s = new String("A" + "B" + "C"); + // comment + } + + /** some javadoc. */ + public void foo32() { + // violation 4 lines below '.* indentation should be the same level as line 260.' + String s = new String("A" + + "B" + + "C"); + // odd indentation comment + } + + /** some javadoc. */ + public void foo33() { + // comment + // violation 2 lines below '.* indentation should be the same level as line 270.' + this.foo22(); +// odd indentation comment + } + + /** some javadoc. */ + public void foo34() throws Exception { + throw new Exception("", new Exception()); + // comment + } + + /** some javadoc. */ + public void foo35() throws Exception { + // violation 4 lines below '.* indentation should be the same level as line 283.' + throw new Exception("", + new Exception() + ); + // odd indentation comment + } + + /** some javadoc. */ + public void foo36() throws Exception { + // violation 4 lines below '.* indentation should be the same level as line 292.' + throw new Exception("", + new Exception() + ); +// odd indentation comment + } + + /** some javadoc. */ + public void foo37() throws Exception { + throw new Exception("", new Exception()); + // comment + } + + /** some javadoc. */ + public void foo38() throws Exception { + // violation 2 lines below '.* indentation should be the same level as line 307.' + throw new Exception("", new Exception()); + // odd indentation comment + } + + /** some javadoc. */ + public void foo39() throws Exception { + // violation 3 lines below'.* indentation should be the same level as line 314.' + throw new Exception("", + new Exception()); + // odd indentation comment + } + + /** some javadoc. */ + public void foo40() throws Exception { + int a = 88; + // violation 2 lines below '.* indentation should be the same level as line 323.' + throw new Exception("", new Exception()); + // odd indentation comment + } + + /** some javadoc. */ + public void foo41() throws Exception { + int a = 88; + throw new Exception("", new Exception()); + // comment + } + + /** some javadoc. */ + public void foo42() { + int a = 5; + if (a == 5) { + int b; + // comment + } else if (a == 6) { + /* foo */ + } + } + + /** some javadoc. */ + public void foo43() { + try { + int a; + // comment + } catch (Exception e) { + /* foo */ + } + } + + /** some javadoc. */ + public void foo44() { + int ar = 5; + // comment + ar = 6; + // comment + } + + /** some javadoc. */ + public void foo45() { + int ar = 5; + // comment + // violation 2 lines below '.* indentation should be the same level as line 368.' + ar = 6; + // odd indentation comment + } + + /** some javadoc. */ + public void foo46() { + // violation 3 lines below '.* indentation should be the same level as line 378.' // comment // block -// warn - } - - public void foo47() { - int a = 5; - // comment - // block - // comment - } - - public void foo48() { - int a = 5; +// odd indentation comment + } + + /** some javadoc. */ + public void foo47() { + int a = 5; + // comment + // block + // comment + } + + /** some javadoc. */ + public void foo48() { + // violation 4 lines below '.* indentation should be the same level as line 391.' + int a = 5; // comment // block -// warn - } - - public void foo49() { - // comment - // block - // ok - } - - public void foo50() { - return; - - // No NPE here! - } - - public String foo51() { - return String - .valueOf("11" - ); - // warn - } +// odd indentation comment + } + + /** some javadoc. */ + public void foo49() { + // comment + // block + // ok + } + + /** some javadoc. */ + public void foo50() { + return; + + // No NPE here! + } + + /** some javadoc. */ + public String foo51() { + // violation 4 lines below '.* indentation should be the same level as line 414.' + return String + .valueOf("11" + ); + // odd indentation comment + } - public String foo52() { - return String - .valueOf("11" - ); - // comment - } + /** some javadoc. */ + public String foo52() { + return String.valueOf("11"); + // comment + } - // We almost reached the end of the class here. + // We almost reached the end of the class here. } // The END of the class. diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInEmptyBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInEmptyBlock.java index 20d3e9a93d80..80e7c0d362a6 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInEmptyBlock.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInEmptyBlock.java @@ -1,86 +1,86 @@ package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; +/** some javadoc. */ public class InputCommentsIndentationInEmptyBlock { - private void foo1() { - int a = 5, b = 3, v = 6; - if (a == b - && v == b || ( a ==1 - /// // warn - /* // warn - * one fine day ... */ - && b == 1) ) { - // Cannot clearly detect user intention of explanation target. - } + private void foo1() { + int a = 5; + int b = 3; + int v = 6; + if (a == b && v == b + || (a == 1 + // violation 2 lines below '.* should be the same level as line 18.' + // violation 3 lines below '.* should be the same level as line 18.' + /// // odd indentation comment + // + /* // odd indentation comment + * one fine day ... */ + && b == 1)) { + // Cannot clearly detect user intention of explanation target. } + } - private void foo2() { - int a = 5, b = 3, v = 6; - if (a == b - && v == b || ( a ==1 - && b == 1) ) { - + private void foo2() { + int a = 5; + int b = 3; + int v = 6; + if (a == b && v == b || (a == 1 && b == 1)) { - // comment - } + // comment } + } - private void foo3() { - int a = 5, b = 3, v = 6; - if (a == b - && v == b || (a == 1 - && b == 1)) { -// warn - } + private void foo3() { + int a = 5; + int b = 3; + int v = 6; + if (a == b && v == b || (a == 1 && b == 1)) { +// odd indentation comment } + // violation 2 lines above '.* indentation should be the same level as line 39.' + } - // Comments here should be ok by Check - @SuppressWarnings("unused") // trailing - private static void foo4() { // trailing - if (true) // trailing comment - { - // some comment - } - if (true) { // trailing comment - - } - /** - * - */ + // Comments here should be ok by Check + @SuppressWarnings("unused") // trailing + private static void foo4() { // trailing + if (true) { // trailing comment + // some comment } - - // Comments here should be ok by Check - @SuppressWarnings("unused") // trailing - private static void foo5() { // trailing - if (true) // trailing comment - { -// warn - } - if (true) { // trailing comment - - } - /** - * - */ + if (true) { // trailing comment } + } - public void foo6() { - try { - - } catch (Exception e) { -// warn - } + // Comments here should be ok by Check + @SuppressWarnings("unused") // trailing + private static void foo5() { // trailing + if (true) { // trailing comment + // violation below '.* indentation should be the same level as line 59.' +// odd indentation comment } + if (true) { // trailing comment + } + } - public void foo7() { - try { - - } catch (Exception e) { - // OOOO: handle exception here - } + /** some javadoc. */ + public void foo6() { + try { + /* foo */ + } catch (Exception e) { +// odd indentation comment } + // violation 2 lines above '.* indentation should be the same level as line 70.' + } - private static class MyClass extends Object { - // no members + /** some javadoc. */ + public void foo7() { + try { + /* foo */ + } catch (Exception e) { + // OOOO: handle exception here } + } + + private static class MyClass extends Object { + // no members + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInSwitchBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInSwitchBlock.java index fca025b72532..9f113ca4e014 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInSwitchBlock.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationInSwitchBlock.java @@ -1,268 +1,331 @@ package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; +/** some javadoc. */ public class InputCommentsIndentationInSwitchBlock { - private static void fooSwitch() { - switch("") { - case "0": //some comment - case "1": - // my comment - foo1(); - break; - case "2": - // my comment - //comment - foo1(); - // comment - break; - case "3": - /* // warn */ - foo1(); - /* com */ - break; - case "5": - foo1(); - // warn - case "6": - int k = 7; - // fall through - case "7": - if (true) {} - // warn - case "8": - break; - case "9": - foo1(); - // fall through - case "10": { - if (true) {} - // fall through - } - case "11": { - // fall through - } - case "28": { - // fall through - } - case "12": { - // warn - int i; - } - case "13": { - // some comment in empty case block - } - case "14": { - // warn - } - case "15": { - foo1(); - // warn - } - case "16": { - int a; - } - // fall through - case "17": { - int a; - } - // warn - case "18": { System.lineSeparator(); - } // trailing comment - case "19": - // comment - case "20": - // comment - case "21": - default: - // comment - break; + private static void fooSwitch() { + switch ("") { + case "0": // some comment + case "1": + // my comment + foo1(); + break; + case "2": + // my comment + // comment + foo1(); + // comment + break; + case "3": + /* // odd indentation comment + * */ + // violation 2 lines above '.* indentation should be the same level as line 23.' + foo1(); + /* com */ + break; + case "5": + // violation 2 lines below '.* indentation should be the same level as line 30.' + foo1(); + // odd indentation comment + break; + case "6": + int k = 7; + // fall through + case "7": + // violation 2 lines below '.* indentation should be the same level as line 38.' + if (true) { /* foo */ } + // odd indentation comment + break; + case "8": + break; + case "9": + foo1(); + // fall through + case "10": + { + if (true) { /* foo */ } } - } - - private static void foo1() { - if (true) { - switch(1) { - case 0: - - case 1: - // warn - int b = 10; - default: - // comment - } - + // fall through + case "11": + { + } + // fall through + case "28": + { + } + // fall through + case "12": + { + // odd indentation comment + // violation above '.* indentation should be the same level as line 61.' + int i; + } + break; + case "13": + { + // some comment in empty case block } + break; + case "14": + { + // odd indentation comment + // violation above '.* indentation should be the same level as line 73.' + } + break; + case "15": + { + // violation 2 lines below '.* indentation should be the same level as line 78.' + foo1(); + // odd indentation comment + } + break; + case "16": + { + int a; + } + // fall through + case "17": + { + int a; + } + // violation below '.* indentation should be the same level as line 93.' + // odd indentation comment + break; + case "18": + { + System.lineSeparator(); + } // trailing comment + break; + case "19": + // comment + case "20": + // comment + case "21": + default: + // comment + break; } + } - public void fooDotInCaseBlock() { - int i = 0; - String s = ""; + private static void foo1() { + if (true) { + switch (1) { + case 0: - switch (i) { - case -2: - // what - i++; - // no break here - case 0: - // what - s.indexOf("ignore"); - // no break here - case -1: - // what - s.indexOf("no way"); - // warn - case 1: - case 2: - i--; - // no break here - case 3: { } - // fall through + case 1: + // violation below '.* indentation should be the same level as line 118.' + // odd indentation comment + int b = 10; + break; + default: + // comment + } + } + } + /** some javadoc. */ + public void fooDotInCaseBlock() { + int i = 0; + String s = ""; + switch (i) { + case -2: + // what + i++; + break; + case 0: + // what + s.indexOf("ignore"); + break; + case -1: + // what + // violation 2 lines below '.* indentation should be the same .* as line 145.' + s.indexOf("no way"); + // odd indentation comment + break; + case 1: + case 2: + i--; + break; + case 3: + { } - - String breaks = "" - // warn - + "" - // middle - + "" - // end - ; + // fall through + default: } - public void foo2() { - int a = 1; - switch (a) { - case 1: - default: - // warn - } + String breaks = + "" + // violation below '.* indentation should be the same level as line 161.' + // odd indentation comment + + "" + // middle + + "" + // end + ; + } + + /** some javadoc. */ + public void foo2() { + int a = 1; + switch (a) { + case 1: + default: + // odd indentation comment } + // violation 2 lines above'.* indentation should be the same level as line 175.' + } - public void foo3() { - int a = 1; - switch (a) { - case 1: - default: + /** some javadoc. */ + public void foo3() { + int a = 1; + switch (a) { + case 1: + default: - // comment - } + // comment } + } - public void foo4() { - int a = 1; - switch (a) { - case 1: - int b; - // warn - default: - } + /** some javadoc. */ + public void foo4() { + int a = 1; + switch (a) { + case 1: + // violation 2 lines below '.* indentation should be the same .* as line 198.' + int b; + // odd indentation comment + break; + default: } + } - public void foo5() { - int a = 1; - switch (a) { - case 1: - int b; - // comment - default: - } + /** some javadoc. */ + public void foo5() { + int a = 1; + switch (a) { + case 1: + int b; + // comment + break; + default: } + } - public void foo6() { - int a = 1; - switch (a) { - case 1: - int b; - // comment - default: - } + /** some javadoc. */ + public void foo6() { + int a = 1; + switch (a) { + case 1: + int b; + // comment + break; + default: } + } - public void foo7() { - int a = 2; - String s = ""; - switch (a) { - // comment - // comment - // comment - case 1: - case 2: - // comment - // comment - foo1(); - // comment - case 3: - // comment - // comment - // comment - case 4: - // warn - case 5: - s.toString().toString().toString(); - // warn - // warn - // warn - default: - } + /** some javadoc. */ + public void foo7() { + int a = 2; + String s = ""; + switch (a) { + // comment + // comment + // comment + case 1: + case 2: + // comment + // comment + foo1(); + // comment + break; + case 3: + // comment + // comment + // comment + // violation 2 lines below'.* indentation should be the same .* as line 247, 249.' + case 4: + // odd indentation comment + case 5: + // violation 4 lines below 'indentation should be the same level as line 257.' + // violation 4 lines below 'indentation should be the same level as line 257.' + // violation 4 lines below 'indentation should be the same level as line 257.' + s.toString().toString().toString(); + // odd indentation comment + // odd indentation comment + // odd indentation comment + break; + default: } + } - public void foo8() { - int a = 2; - String s = ""; - switch (a) { - // comment - // comment - // comment - case 1: - case 2: - // comment - // comment - foo1(); - // comment - case 3: - // comment - // comment - s.toString().toString().toString(); - // comment - case 4: - // warn - default: - } + /** some javadoc. */ + public void foo8() { + int a = 2; + String s = ""; + switch (a) { + // comment + // comment + // comment + case 1: + case 2: + // comment + // comment + foo1(); + // comment + break; + case 3: + // comment + // comment + s.toString().toString().toString(); + // comment + // violation 3 lines below '.* indentation should be the same level as line 284, 286.' + break; + case 4: + // odd indentation comment + default: } + } - public void foo9() { - int a = 5; - switch (a) { - case 1: - case 2: - // comment - } + /** some javadoc. */ + public void foo9() { + int a = 5; + switch (a) { + case 1: + case 2: + // comment + default: } + } - public void foo10() { - int a = 5; - switch (a) { - case 1: - default: - // comment - } + /** some javadoc. */ + public void foo10() { + int a = 5; + switch (a) { + case 1: + default: + // comment } + } - public void foo11() { - int a = 5; - switch (a) { - case 1: - case 2: - // comment - } + /** some javadoc. */ + public void foo11() { + int a = 5; + switch (a) { + case 1: + case 2: + // comment + default: } + } - public void foo12() { - int a = 5; - switch (a) { - // comment - case 1: - } + /** some javadoc. */ + public void foo12() { + int a = 5; + switch (a) { + // comment + case 1: + default: } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationSurroundingCode.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationSurroundingCode.java index 04503871e55a..d9d27250d97c 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationSurroundingCode.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputCommentsIndentationSurroundingCode.java @@ -1,127 +1,146 @@ // comment + package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; import java.util.Arrays; // some -public class InputCommentsIndentationSurroundingCode -{ - private void foo1() { - if (true) { - // here initialize some variables - int k = 0; // trailing comment - // warn - int b = 10; - // sss - } +/** some javadoc. */ +public class InputCommentsIndentationSurroundingCode { + private void foo1() { + if (true) { + // here initialize some variables + int k = 0; // trailing comment + // odd indentation comment + // violation above '.* indentation should be the same level as line 16.' + int b = 10; + // sss } + } - private void foo2() { - if (true) { - /* some */ - int k = 0; - /* // warn */ - int b = 10; - /* // warn - * */ - double d; /* trailing comment */ - /* // warn - * - */ - boolean bb; - /***/ - /* my comment*/ - /* - * - * - * some - */ - /* - * comment - */ - boolean x; - } + private void foo2() { + if (true) { + /* some */ + int k = 0; + /* // odd indentation comment + */ + // violation 2 lines above '.* indentation should be the same level as line 28.' + int b = 10; + /* // odd indentation comment + * */ + // violation 2 lines above '.* indentation should be the same level as line 32.' + double d; /* trailing comment */ + /* // odd indentation comment + * + */ + // violation 3 lines above '.* indentation should be the same level as line 37.' + boolean bb; + /* my comment*/ + /* + * + * + * some + */ + /* + * comment + */ + boolean x; } + } - private void foo3() { - int a = 5, b = 3, v = 6; - if (a == b - && v == b || ( a ==1 - /// // warn - /* // warn - * one fine day ... */ - && b == 1) ) { - } - } + private void foo3() { + int a = 5; + int b = 3; + int v = 6; + if (a == b && v == b + || (a == 1 + /// // odd indentation comment + /* // odd indentation comment + * one fine day ... */ + // violation 3 lines above '.* indentation should.* as line 62.' + // violation 3 lines above '.* indentation should.* as line 62.' + && b == 1)) { /* foo */ } + } - private static void com() { - /* here's my weird trailing comment */ boolean b = true; - } + private static void com() { + /* here's my weird trailing comment */ boolean b = true; + } - private static final String[][] mergeMatrix = { - // This example of trailing block comments was found in PMD sources. - /* TOP */{ "", }, - /* ALWAYS */{ "", "", }, - /* NEVER */{ "NEVER", "UNKNOWN", "NEVER", }, - /* UNKNOWN */{ "UNKNOWN", "UNKNOWN", "UNKNOWN", "UNKNOWN" }, }; - - private void foo4() { - if (!Arrays.equals(new String[]{""}, new String[]{""}) - /* wierd trailing comment */) { - } - } - /** - * some javadoc - */ - private static void l() { - } + private static final String[][] mergeMatrix = { + // This example of trailing block comments was found in PMD sources. + /* TOP */ { + "", + }, + /* ALWAYS */ { + "", "", + }, + /* NEVER */ { + "NEVER", "UNKNOWN", "NEVER", + }, + /* UNKNOWN */ {"UNKNOWN", "UNKNOWN", "UNKNOWN", "UNKNOWN"}, + }; - public void foid5() { - String s = ""; - s.toString().toString().toString(); - // comment - } + private void foo4() { + if (!Arrays.equals(new String[] {""}, new String[] {""})/* wierd comment */) { /* foo */ } + } - public void foo6() { - // comment - // ... - // block - // ... - // warn - String someStr = new String(); - } + /** some javadoc. */ + private static void testing() {} - public void foo7() { - // comment - // ... - // block - // warn - // comment - String someStr = new String(); - } + /** some javadoc. */ + public void foid5() { + String s = ""; + s.toString().toString().toString(); + // comment + } - public void foo8() { - String s = new String(); // comment - // ... - // block - // ... - // warn - String someStr = new String(); - } + /** some javadoc. */ + public void foo6() { + // comment + // ... + // block + // ... + // odd indentation comment + // violation above '.* indentation should be the same level as line 105.' + String someStr = new String(); + } - public String foo9(String s1, String s2, String s3) { - return ""; - } + /** some javadoc. */ + public void foo7() { + // comment + // ... + // block + // odd indentation comment + // comment + // violation 2 lines above'.* indentation should be the same level as line 116.' + String someStr = new String(); + } - public void foo10() - throws Exception { + /** some javadoc. */ + public void foo8() { + String s = new String(); // comment + // ... + // block + // ... + // odd indentation comment + // violation above '.* indentation should be the same level as line 127.' + String someStr = new String(); + } - final String pattern = "^foo$"; + /** some javadoc. */ + public String foo9(String s1, String s2, String s3) { + return ""; + } - final String[] expected = { - "7:13: " + foo9("", "", ""), - // comment - }; - } + /** some javadoc. */ + public void foo10() throws Exception { + + final String pattern = "^foo$"; + + final String[] expected = { + "7:13: " + foo9("", "", ""), + // comment + }; + } } // The Check should not throw NPE here! // The Check should not throw NPE here! diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationCommentIsAtTheEndOfBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationCommentIsAtTheEndOfBlock.java new file mode 100644 index 000000000000..e8a06ee02fb2 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationCommentIsAtTheEndOfBlock.java @@ -0,0 +1,410 @@ +package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; + +/** Contains examples of using comments at the end of the block. */ +public class InputFormattedCommentsIndentationCommentIsAtTheEndOfBlock { + + /** some javadoc. */ + public void foo1() { + foo2(); + // OOOO: missing functionality + } + + /** some javadoc. */ + public void foo2() { + + foo3(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo3() { + foo2(); + // refreshDisplay(); + } + + /** some javadoc. */ + public void foo4() { + foooooooooooooooooooooooooooooooooooooooooo(); + // ^-- some hint + } + + /** some javadoc. */ + public void foooooooooooooooooooooooooooooooooooooooooo() {} + + /////////////////////////////// odd indentation comment + + /** some javadoc. */ + public void foo7() { + + int a = 0; + // odd indentation comment + } + + /////////////////////////////// (a single-line border to separate a group of methods) + + /** some javadoc. */ + public void foo8() {} + + /** some javadoc. */ + public class TestClass { + /** some javadoc. */ + public void test() { + + int a = 0; + // odd indentation comment + } + // odd indentation comment + } + + /** some javadoc. */ + public void foo9() { + + this.foo1(); + // odd indentation comment + } + + // public void foo10() { + // + // } + + /** some javadoc. */ + public void foo11() { + String.valueOf(new Integer(0)).trim().length(); + // comment + } + + /** some javadoc. */ + public void foo12() { + + String.valueOf(new Integer(0)).trim().length(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo13() { + String.valueOf(new Integer(0)).trim().length(); + // comment + } + + /** some javadoc. */ + public void foo14() { + + String.valueOf(new Integer(0)).trim().length(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo15() { + String.valueOf(new Integer(0)); + // comment + } + + /** some javadoc. */ + public void foo16() { + + String.valueOf(new Integer(0)); + // odd indentation comment + } + + /** some javadoc. */ + public void foo17() { + String.valueOf(new Integer(0)) + .trim() + // comment + .length(); + } + + /** some javadoc. */ + public void foo18() { + + String.valueOf(new Integer(0)) + .trim() + // odd indentation comment + .length(); + } + + /** some javadoc. */ + public void foo19() { + (new Thread( + new Runnable() { + @Override + public void run() {} + })) + .run(); + // comment + } + + /** some javadoc. */ + public void foo20() { + + (new Thread( + new Runnable() { + @Override + public void run() {} + })) + .run(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo21() { + int[] array = new int[5]; + + java.util.List expected = new java.util.ArrayList<>(); + for (int i = 0; i < 5; i++) { + org.junit.Assert.assertEquals(expected.get(i), array[i]); + } + String s = + String.format( + java.util.Locale.ENGLISH, + "The array element " + + "immediately following the end of the collection should be nulled", + array[1]); + // the above example was taken from hibernate-orm and was modified a bit + } + + /** some javadoc. */ + public void foo22() { + int[] array = new int[5]; + + java.util.List expected = new java.util.ArrayList<>(); + for (int i = 0; i < 5; i++) { + org.junit.Assert.assertEquals(expected.get(i), array[i]); + } + + String s = + String.format( + java.util.Locale.ENGLISH, + "The array element " + + "immediately following the end of the collection should be nulled", + array[1]); + // odd indentation comment + } + + /** some javadoc. */ + public void foo23() { + new Object(); + // comment + } + + /** some javadoc. */ + public void foo24() { + + new Object(); + // odd indentation comment + } + + /** some javadoc. */ + public String foo25() { + return String.format(java.util.Locale.ENGLISH, "%d", 1); + // comment + } + + /** some javadoc. */ + public String foo26() { + + return String.format(java.util.Locale.ENGLISH, "%d", 1); + // odd indentation comment + } + + /** some javadoc. */ + public void foo27() { + // comment + // block + foo17(); + + // OOOO + } + + /** some javadoc. */ + public String foo28() { + int a = 5; + return String.format(java.util.Locale.ENGLISH, "%d", 1); + // comment + } + + /** some javadoc. */ + public String foo29() { + int a = 5; + + return String.format(java.util.Locale.ENGLISH, "%d", 1); + // odd indentation comment + } + + /** some javadoc. */ + public void foo30() { + // comment + + int a = 5; + // odd indentation comment + } + + /** some javadoc. */ + public void foo31() { + String s = new String("A" + "B" + "C"); + // comment + } + + /** some javadoc. */ + public void foo32() { + + String s = new String("A" + "B" + "C"); + // odd indentation comment + } + + /** some javadoc. */ + public void foo33() { + // comment + + this.foo22(); + // odd indentation comment + } + + /** some javadoc. */ + public void foo34() throws Exception { + throw new Exception("", new Exception()); + // comment + } + + /** some javadoc. */ + public void foo35() throws Exception { + + throw new Exception("", new Exception()); + // odd indentation comment + } + + /** some javadoc. */ + public void foo36() throws Exception { + + throw new Exception("", new Exception()); + // odd indentation comment + } + + /** some javadoc. */ + public void foo37() throws Exception { + throw new Exception("", new Exception()); + // comment + } + + /** some javadoc. */ + public void foo38() throws Exception { + + throw new Exception("", new Exception()); + // odd indentation comment + } + + /** some javadoc. */ + public void foo39() throws Exception { + + throw new Exception("", new Exception()); + // odd indentation comment + } + + /** some javadoc. */ + public void foo40() throws Exception { + int a = 88; + + throw new Exception("", new Exception()); + // odd indentation comment + } + + /** some javadoc. */ + public void foo41() throws Exception { + int a = 88; + throw new Exception("", new Exception()); + // comment + } + + /** some javadoc. */ + public void foo42() { + int a = 5; + if (a == 5) { + int b; + // comment + } else if (a == 6) { + /* foo */ + } + } + + /** some javadoc. */ + public void foo43() { + try { + int a; + // comment + } catch (Exception e) { + /* foo */ + } + } + + /** some javadoc. */ + public void foo44() { + int ar = 5; + // comment + ar = 6; + // comment + } + + /** some javadoc. */ + public void foo45() { + int ar = 5; + // comment + + ar = 6; + // odd indentation comment + } + + /** some javadoc. */ + public void foo46() { + + // comment + // block + // odd indentation comment + } + + /** some javadoc. */ + public void foo47() { + int a = 5; + // comment + // block + // comment + } + + /** some javadoc. */ + public void foo48() { + + int a = 5; + // comment + // block + // odd indentation comment + } + + /** some javadoc. */ + public void foo49() { + // comment + // block + // ok + } + + /** some javadoc. */ + public void foo50() { + return; + + // No NPE here! + } + + /** some javadoc. */ + public String foo51() { + + return String.valueOf("11"); + // odd indentation comment + } + + /** some javadoc. */ + public String foo52() { + return String.valueOf("11"); + // comment + } + + // We almost reached the end of the class here. +} +// The END of the class. diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationInEmptyBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationInEmptyBlock.java new file mode 100644 index 000000000000..b1d5b90946d8 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationInEmptyBlock.java @@ -0,0 +1,83 @@ +package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; + +/** some javadoc. */ +public class InputFormattedCommentsIndentationInEmptyBlock { + + private void foo1() { + int a = 5; + int b = 3; + int v = 6; + if (a == b && v == b + || (a == 1 + + /// // odd indentation comment + // + /* // odd indentation comment + * one fine day ... */ + && b == 1)) { + // Cannot clearly detect user intention of explanation target. + } + } + + private void foo2() { + int a = 5; + int b = 3; + int v = 6; + if (a == b && v == b || (a == 1 && b == 1)) { + + // comment + } + } + + private void foo3() { + int a = 5; + int b = 3; + int v = 6; + if (a == b && v == b || (a == 1 && b == 1)) { + // odd indentation comment + } + } + + // Comments here should be ok by Check + @SuppressWarnings("unused") // trailing + private static void foo4() { // trailing + if (true) { // trailing comment + // some comment + } + if (true) { // trailing comment + } + } + + // Comments here should be ok by Check + @SuppressWarnings("unused") // trailing + private static void foo5() { // trailing + if (true) { // trailing comment + + // odd indentation comment + } + if (true) { // trailing comment + } + } + + /** some javadoc. */ + public void foo6() { + try { + /* foo */ + } catch (Exception e) { + // odd indentation comment + } + } + + /** some javadoc. */ + public void foo7() { + try { + /* foo */ + } catch (Exception e) { + // OOOO: handle exception here + } + } + + private static class MyClass extends Object { + // no members + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationInSwitchBlock.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationInSwitchBlock.java new file mode 100644 index 000000000000..37af38421a52 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationInSwitchBlock.java @@ -0,0 +1,327 @@ +package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; + +/** some javadoc. */ +public class InputFormattedCommentsIndentationInSwitchBlock { + + private static void fooSwitch() { + switch ("") { + case "0": // some comment + case "1": + // my comment + foo1(); + break; + case "2": + // my comment + // comment + foo1(); + // comment + break; + case "3": + /* // odd indentation comment + * */ + + foo1(); + /* com */ + break; + case "5": + foo1(); + // odd indentation comment + break; + case "6": + int k = 7; + // fall through + case "7": + if (true) { + /* foo */ + } + // odd indentation comment + break; + case "8": + break; + case "9": + foo1(); + // fall through + case "10": + { + if (true) { + /* foo */ + } + } + // fall through + case "11": + { + } + // fall through + case "28": + { + } + // fall through + case "12": + { + // odd indentation comment + + int i; + } + break; + case "13": + { + // some comment in empty case block + } + break; + case "14": + { + // odd indentation comment + + } + break; + case "15": + { + foo1(); + // odd indentation comment + } + break; + case "16": + { + int a; + } + // fall through + case "17": + { + int a; + } + + // odd indentation comment + break; + case "18": + { + System.lineSeparator(); + } // trailing comment + break; + case "19": + // comment + case "20": + // comment + case "21": + default: + // comment + break; + } + } + + private static void foo1() { + if (true) { + switch (1) { + case 0: + + case 1: + + // odd indentation comment + int b = 10; + break; + default: + // comment + } + } + } + + /** some javadoc. */ + public void fooDotInCaseBlock() { + int i = 0; + String s = ""; + + switch (i) { + case -2: + // what + i++; + break; + case 0: + // what + s.indexOf("ignore"); + break; + case -1: + // what + + s.indexOf("no way"); + // odd indentation comment + break; + case 1: + case 2: + i--; + break; + case 3: + { + } + // fall through + default: + } + + String breaks = + "" + + // odd indentation comment + + "" + // middle + + "" + // end + ; + } + + /** some javadoc. */ + public void foo2() { + int a = 1; + switch (a) { + case 1: + default: + // odd indentation comment + } + } + + /** some javadoc. */ + public void foo3() { + int a = 1; + switch (a) { + case 1: + default: + + // comment + } + } + + /** some javadoc. */ + public void foo4() { + int a = 1; + switch (a) { + case 1: + int b; + // odd indentation comment + break; + default: + } + } + + /** some javadoc. */ + public void foo5() { + int a = 1; + switch (a) { + case 1: + int b; + // comment + break; + default: + } + } + + /** some javadoc. */ + public void foo6() { + int a = 1; + switch (a) { + case 1: + int b; + // comment + break; + default: + } + } + + /** some javadoc. */ + public void foo7() { + int a = 2; + String s = ""; + switch (a) { + // comment + // comment + // comment + case 1: + case 2: + // comment + // comment + foo1(); + // comment + break; + case 3: + // comment + // comment + // comment + + case 4: + // odd indentation comment + case 5: + s.toString().toString().toString(); + // odd indentation comment + // odd indentation comment + // odd indentation comment + break; + default: + } + } + + /** some javadoc. */ + public void foo8() { + int a = 2; + String s = ""; + switch (a) { + // comment + // comment + // comment + case 1: + case 2: + // comment + // comment + foo1(); + // comment + break; + case 3: + // comment + // comment + s.toString().toString().toString(); + // comment + + break; + case 4: + // odd indentation comment + default: + } + } + + /** some javadoc. */ + public void foo9() { + int a = 5; + switch (a) { + case 1: + case 2: + // comment + default: + } + } + + /** some javadoc. */ + public void foo10() { + int a = 5; + switch (a) { + case 1: + default: + // comment + } + } + + /** some javadoc. */ + public void foo11() { + int a = 5; + switch (a) { + case 1: + case 2: + // comment + default: + } + } + + /** some javadoc. */ + public void foo12() { + int a = 5; + switch (a) { + // comment + case 1: + default: + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationSurroundingCode.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationSurroundingCode.java new file mode 100644 index 000000000000..904430ae377c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4861blockcommentstyle/InputFormattedCommentsIndentationSurroundingCode.java @@ -0,0 +1,150 @@ +// comment + +package com.google.checkstyle.test.chapter4formatting.rule4861blockcommentstyle; + +import java.util.Arrays; + +// some + +/** some javadoc. */ +public class InputFormattedCommentsIndentationSurroundingCode { + private void foo1() { + if (true) { + // here initialize some variables + int k = 0; // trailing comment + // odd indentation comment + + int b = 10; + // sss + } + } + + private void foo2() { + if (true) { + /* some */ + int k = 0; + /* // odd indentation comment + */ + + int b = 10; + /* // odd indentation comment + * */ + + double d; /* trailing comment */ + /* // odd indentation comment + * + */ + + boolean bb; + /* my comment*/ + /* + * + * + * some + */ + /* + * comment + */ + boolean x; + } + } + + private void foo3() { + int a = 5; + int b = 3; + int v = 6; + if (a == b && v == b + || (a == 1 + /// // odd indentation comment + /* // odd indentation comment + * one fine day ... */ + + && b == 1)) { + /* foo */ + } + } + + private static void com() { + /* here's my weird trailing comment */ boolean b = true; + } + + private static final String[][] mergeMatrix = { + // This example of trailing block comments was found in PMD sources. + /* TOP */ { + "", + }, + /* ALWAYS */ { + "", "", + }, + /* NEVER */ { + "NEVER", "UNKNOWN", "NEVER", + }, + /* UNKNOWN */ {"UNKNOWN", "UNKNOWN", "UNKNOWN", "UNKNOWN"}, + }; + + private void foo4() { + if (!Arrays.equals(new String[] {""}, new String[] {""}) /* wierd comment */) { + /* foo */ + } + } + + /** some javadoc. */ + private static void testing() {} + + /** some javadoc. */ + public void foid5() { + String s = ""; + s.toString().toString().toString(); + // comment + } + + /** some javadoc. */ + public void foo6() { + // comment + // ... + // block + // ... + // odd indentation comment + + String someStr = new String(); + } + + /** some javadoc. */ + public void foo7() { + // comment + // ... + // block + // odd indentation comment + // comment + + String someStr = new String(); + } + + /** some javadoc. */ + public void foo8() { + String s = new String(); // comment + // ... + // block + // ... + // odd indentation comment + + String someStr = new String(); + } + + /** some javadoc. */ + public String foo9(String s1, String s2, String s3) { + return ""; + } + + /** some javadoc. */ + public void foo10() throws Exception { + + final String pattern = "^foo$"; + + final String[] expected = { + "7:13: " + foo9("", "", ""), + // comment + }; + } +} // The Check should not throw NPE here! +// The Check should not throw NPE here! diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4862todocomments/InputTodoCommentAllVariants.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4862todocomments/InputTodoCommentAllVariants.java new file mode 100644 index 000000000000..419600c3f16d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule4862todocomments/InputTodoCommentAllVariants.java @@ -0,0 +1,181 @@ +package com.google.checkstyle.test.chapter4formatting.rule4862todocomments; + +/** some javadoc. */ +public class InputTodoCommentAllVariants { + + void myFunc1(int i) { + // todo: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc2(int i) { + // TodO: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc3(int i) { + // toDo: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc4(int i) { + // toDO: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc5(int i) { + // TOdo: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc6(int i) { + // tOdO: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc7(int i) { + // tODO: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc8(int i) { + // tODO: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc9(int i) { + // Todo: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc10(int i) { + // TodO: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc11(int i) { + // ToDo: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc12(int i) { + // TODo: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc13(int i) { + // TOdO: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc14(int i) { + // TODo: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc15(int i) { + // tODo: implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc16(int i) { + // TODO: implementing + } + + void myFunc17(int i) { + // todo:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc18(int i) { + // TodO:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc19(int i) { + // toDo:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc20(int i) { + // toDO:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc21(int i) { + // TOdo:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc22(int i) { + // tOdO:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc23(int i) { + // tODO:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc24(int i) { + // tODO:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc25(int i) { + // Todo:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc26(int i) { + // TodO:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc27(int i) { + // ToDo:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc28(int i) { + // TODo:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc29(int i) { + // TOdO:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc30(int i) { + // TODo:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc31(int i) { + // tODo:implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc32(int i) { + // TODO:implementing + } + + void myFunc33(int i) { + // tODo implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc34(int i) { + // TODO implementing + // violation above ''TODO:' must be written in all caps and followed by a colon' + } + + void myFunc35(int i) { + // TODO: correct TODO comment + } + + void myFunc36(int i) { + // TODO:correct TODO comment + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrder.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrder.java new file mode 100644 index 000000000000..a754daf220b1 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrder.java @@ -0,0 +1,302 @@ +package com.google.checkstyle.test.chapter4formatting.rule487modifiers; + +abstract strictfp class InputFormattedModifierOrder { + private transient String dontSaveMe; + + public volatile int whatImReading; + + public volatile boolean ssModifierOrderVar = false; + + /** + * Illegal order of modifiers for methods. Make sure that the first and last modifier from the JLS + * sequence is used. + */ + private strictfp void doStuff() {} + + /** Single annotation without other modifiers. */ + @MyAnnotationFormatted + void someMethod() {} + + /** Illegal order of annotation - must come first. */ + private @MyAnnotationFormatted void someMethod2() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + /** Annotation in middle of other modifiers otherwise in correct order. */ + private @MyAnnotationFormatted strictfp void someMethod3() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + /** Correct order. */ + @MyAnnotationFormatted + private strictfp void someMethod4() {} + + /** Annotation in middle of other modifiers otherwise in correct order. */ + @MyAnnotationFormatted + public static @MyAnnotationFormatted2 strictfp void someMethod5() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + public static final synchronized strictfp void fooMethod() {} + + protected final strictfp @MyAnnotationFormatted static synchronized void fooMethod1() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + synchronized @MyAnnotationFormatted private static final strictfp void fooMethod2() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + protected static final synchronized strictfp void fooMethod3() {} + + @MyAnnotationFormatted + private static final synchronized strictfp void fooMethod4() {} + + final synchronized strictfp @MyAnnotationFormatted public static void fooMethod5() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + private static final synchronized strictfp void fooMethod6() {} + + protected static final synchronized strictfp @MyAnnotationFormatted void fooMethod7() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + protected abstract void fooMet(); + + abstract @MyAnnotationFormatted public void fooMet1(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + /** holder for redundant 'public' modifier check. */ + public static interface InputRedundantPublicModifier { + public void abc1(); + + void abc2(); + + abstract void abc3(); + + public float PI_PUBLIC = (float) 3.14; + + final float PI_FINAL = (float) 3.14; + + /** all OK. */ + float PI_OK = (float) 3.14; + } + + private final void method() {} +} + +// violation below 'Top-level class RedundantFinalClass2 has to reside in its own source file.' +final class RedundantFinalClass2 { + public final void finalMethod() {} + + public void method() {} + + protected @MyAnnotationFormatted static synchronized native void fooMethod(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + protected static @MyAnnotationFormatted synchronized native void fooMethod1(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + protected synchronized native void fooMethod2(); + + protected static synchronized native @MyAnnotationFormatted void fooMethod3(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + native @MyAnnotationFormatted protected static synchronized void fooMethod4(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + public static @MyAnnotationFormatted synchronized native void fooMethod5(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + static synchronized native @MyAnnotationFormatted public void fooMethod6(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + private static synchronized native @MyAnnotationFormatted void fooMethod7(); + // violation above '.* annotation modifier does not precede non-annotation modifiers.' +} + +// violation 2 lines below 'Top-level class .* has to reside in its own source file.' +/** Holder for redundant modifiers of inner implementation. */ +interface InnerImplementation2 { + InnerImplementation2 inner = + new InnerImplementation2() { + /** compiler requires 'public' modifier. */ + public void method() {} + }; + + void method(); +} + +// violation below 'Top-level class WithInner2 has to reside in its own source file.' +class WithInner2 { + /** + * Inner class. + * + * @author max + */ + class Inner { + private transient String dontSaveMe; + + public volatile int whatImReading; + + @MyAnnotationFormatted + protected synchronized native void fooMethod(); + + protected @MyAnnotationFormatted synchronized native void fooMethod1(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + protected synchronized @MyAnnotationFormatted native void fooMethod2(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + protected synchronized native @MyAnnotationFormatted void fooMethod3(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + native @MyAnnotationFormatted protected synchronized void fooMethod4(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + public @MyAnnotationFormatted synchronized native void fooMethod5(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + synchronized native @MyAnnotationFormatted public void fooMethod6(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + private synchronized native @MyAnnotationFormatted void fooMethod7(); + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + /** Anonymous class. */ + InnerImplementation2 foo = + new InnerImplementation2() { + + public void method() { + // OOOO Auto-generated method stub + + } + + private transient String dontSaveMe; + + public volatile int whatImReading; + + protected @MyAnnotationFormatted synchronized native void fooMethod(); + + // violation 2 lines above '.* annotation .* does not precede non-annotation modifiers.' + + protected @MyAnnotationFormatted synchronized native void fooMethod1(); + + // violation 2 lines above '.* annotation .* does not precede non-annotation modifiers.' + + protected synchronized @MyAnnotationFormatted native void fooMethod2(); + + // violation 2 lines above '.* annotation .* does not precede non-annotation modifiers.' + + protected synchronized native @MyAnnotationFormatted void fooMethod3(); + + // violation 2 lines above '.* annotation .* does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + protected synchronized native void fooMethod4(); + + public @MyAnnotationFormatted synchronized native void fooMethod5(); + + // violation 2 lines above '.* annotation .* does not precede non-annotation modifiers.' + + synchronized native @MyAnnotationFormatted public void fooMethod6(); + + // violation 2 lines above '.* annotation .* does not precede non-annotation modifiers.' + + private synchronized native @MyAnnotationFormatted void fooMethod7(); + // violation above '.* annotation modifier does not precede non-annotation modifiers.' + }; + } + + /** + * Inner abstract class. + * + * @author max + */ + abstract class AbsInner { + private transient String dontSaveMe; + + public volatile int whatImReading; + + @MyAnnotationFormatted + public final synchronized strictfp void fooMethod() {} + + protected final strictfp @MyAnnotationFormatted synchronized void fooMethod1() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + synchronized @MyAnnotationFormatted private final strictfp void fooMethod2() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + protected final synchronized strictfp void fooMethod3() {} + + @MyAnnotationFormatted + private final synchronized strictfp void fooMethod4() {} + + final synchronized strictfp @MyAnnotationFormatted public void fooMethod5() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + private final synchronized strictfp void fooMethod6() {} + + protected final synchronized strictfp @MyAnnotationFormatted void fooMethod7() {} + + // violation 2 lines above '.* annotation modifier does not precede non-annotation modifiers.' + + @MyAnnotationFormatted + protected abstract void fooMet(); + + abstract @MyAnnotationFormatted public void fooMet1(); + // violation above '.* annotation modifier does not precede non-annotation modifiers.' + } +} + +// violation 2 lines below 'Top-level class Annotation2 has to reside in its own source file.' +/** Holder for redundant modifiers of annotation fields/variables. */ +@interface Annotation2 { + public String s1 = ""; + final String s2 = ""; + static String s3 = ""; + String s4 = ""; + + public String blah(); + + abstract String blah2(); +} + +// violation below 'Top-level class MyAnnotationFormatted has to reside in its own source file.' +@interface MyAnnotationFormatted {} + +// violation below 'Top-level class MyAnnotationFormatted2 has to reside in its own source file.' +@interface MyAnnotationFormatted2 {} + +// violation 2 lines below 'Top-level class .* has to reside in its own source file.' +/** Illegal order of modifiers for interface methods. */ +interface InputModifierOrderInterface2 { + default strictfp void abc1() {} + + default strictfp void abc2() {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrderNonSealed.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrderNonSealed.java new file mode 100644 index 000000000000..59d3e0b54ed9 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrderNonSealed.java @@ -0,0 +1,39 @@ +package com.google.checkstyle.test.chapter4formatting.rule487modifiers; + +/** some javadoc. */ +public sealed class InputFormattedModifierOrderNonSealed + permits InputFormattedModifierOrderNonSealed.CircleOne, + InputFormattedModifierOrderNonSealed.RectangleOne, + InputFormattedModifierOrderNonSealed.SquareOne { + + final class CircleOne extends InputFormattedModifierOrderNonSealed implements SquircleOne {} + + sealed class RectangleOne extends InputFormattedModifierOrderNonSealed + permits TransparentRectangleOne, FilledRectangleOne {} + + final class TransparentRectangleOne extends RectangleOne {} + + sealed class SquareOne extends InputFormattedModifierOrderNonSealed implements SquircleOne { + + private sealed class OtherSquare extends SquareOne permits OtherSquare2 {} + + private final class OtherSquare2 extends OtherSquare {} + + static non-sealed class StaticClass implements SquircleOne {} + } + + final class FilledRectangleOne extends RectangleOne {} + + sealed interface SquircleOne permits CircleOne, SquareOne, Ellipse, SquareOne.StaticClass {} + + sealed interface Rhombus permits Parallelogram, Parallelogram.Trapezoid {} + + record Parallelogram(int x, int y, double z) implements Rhombus { + + public record Trapezoid(int x, int y, double z) implements Rhombus {} + } + + non-sealed interface Ellipse extends SquircleOne {} + + class Oval implements Ellipse {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrderSealed.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrderSealed.java new file mode 100644 index 000000000000..22da568f9acb --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputFormattedModifierOrderSealed.java @@ -0,0 +1,23 @@ +package com.google.checkstyle.test.chapter4formatting.rule487modifiers; + +/** some javadoc. */ +public sealed class InputFormattedModifierOrderSealed + permits InputFormattedModifierOrderSealed.Four1, + InputFormattedModifierOrderSealed.Three1, + InputFormattedModifierOrderSealed.Two1 { + final class Two1 extends InputFormattedModifierOrderSealed implements Five1 {} + + sealed class Four1 extends InputFormattedModifierOrderSealed {} + + sealed class Three1 extends InputFormattedModifierOrderSealed implements Five1 { + + private sealed class OtherSquare3 extends Three1 {} + + private final class OtherSquare4 extends OtherSquare3 {} + } + + /** some javadoc. */ + public final class FilledFour1 extends Four1 {} + + abstract sealed interface Five1 permits Two1, Three1 {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrder.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrder.java index 9bfd1e037fd0..545996033d18 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrder.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrder.java @@ -1,246 +1,275 @@ package com.google.checkstyle.test.chapter4formatting.rule487modifiers; -strictfp abstract class InputModifierOrder //warn -{ - transient private String dontSaveMe; //warn +// violation below ''abstract' modifier out of order with the JLS suggestions.' +strictfp abstract class InputModifierOrder { + transient private String dontSaveMe; + // violation above ''private' modifier out of order with the JLS suggestions.' - volatile public int whatImReading; //warn + volatile public int whatImReading; + // violation above ''public' modifier out of order with the JLS suggestions.' - public volatile boolean sModifierOrderVar = false; // ok + public volatile boolean ssModifierOrderVar = false; - /** - * Illegal order of modifiers for methods. Make sure that the - * first and last modifier from the JLS sequence is used. - */ - strictfp private void doStuff() //warn - { - } + /** + * Illegal order of modifiers for methods. Make sure that the first and last modifier from the JLS + * sequence is used. + */ + strictfp private void doStuff() {} + // violation above ''private' modifier out of order with the JLS suggestions.' - /** Single annotation without other modifiers */ - @MyAnnotation2 void someMethod() - { - } + /** Single annotation without other modifiers. */ + @MyAnnotation2 void someMethod() {} - /** Illegal order of annotation - must come first */ - private @MyAnnotation2 void someMethod2() //warn - { - } + /** Illegal order of annotation - must come first. */ + private @MyAnnotation2 void someMethod2() {} + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - /** Annotation in middle of other modifiers otherwise in correct order */ - private @MyAnnotation2 strictfp void someMethod3() //warn - { - } + /** Annotation in middle of other modifiers otherwise in correct order. */ + private @MyAnnotation2 strictfp void someMethod3() {} + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - /** Correct order */ - @MyAnnotation2 private strictfp void someMethod4() - { - } + /** Correct order. */ + @MyAnnotation2 private strictfp void someMethod4() {} - /** Annotation in middle of other modifiers otherwise in correct order */ - @MyAnnotation2 public static @MyAnnotation4 strictfp void someMethod5() //warn - { - } + /** Annotation in middle of other modifiers otherwise in correct order. */ + @MyAnnotation2 public static @MyAnnotation4 strictfp void someMethod5() {} + // violation above ''@MyAnnotation4' .* does not precede non-annotation modifiers.' - @MyAnnotation2 public static final synchronized strictfp void fooMethod() {}; //ok + @MyAnnotation2 public static final synchronized strictfp void fooMethod() {} - strictfp protected final @MyAnnotation2 static synchronized void fooMethod1() {}; //warn + // violation below ''protected' modifier out of order with the JLS suggestions.' + strictfp protected final @MyAnnotation2 static synchronized void fooMethod1() {} - synchronized @MyAnnotation2 strictfp private final static void fooMethod2() {}; //warn + // violation below ''@MyAnnotation2' .* does not precede non-annotation modifiers.' + synchronized @MyAnnotation2 strictfp private final static void fooMethod2() {} - @MyAnnotation2 static synchronized final strictfp protected void fooMethod3() {}; //warn + // violation below ''final' modifier out of order with the JLS suggestions.' + @MyAnnotation2 static synchronized final strictfp protected void fooMethod3() {} - @MyAnnotation2 strictfp static final synchronized private void fooMethod4() {}; //warn + // violation below ''static' modifier out of order with the JLS suggestions.' + @MyAnnotation2 strictfp static final synchronized private void fooMethod4() {} - synchronized final strictfp @MyAnnotation2 static public void fooMethod5() {}; //warn + // violation below ''final' modifier out of order with the JLS suggestions.' + synchronized final strictfp @MyAnnotation2 static public void fooMethod5() {} - @MyAnnotation2 static synchronized strictfp private final void fooMethod6() {}; //warn + // violation below ''private' modifier out of order with the JLS suggestions.' + @MyAnnotation2 static synchronized strictfp private final void fooMethod6() {} - final strictfp synchronized static protected @MyAnnotation2 void fooMethod7() {}; //warn + // violation below ''synchronized' modifier out of order with the JLS suggestions.' + final strictfp synchronized static protected @MyAnnotation2 void fooMethod7() {} - @MyAnnotation2 abstract protected void fooMet(); //warn + // violation below ''protected' modifier out of order with the JLS suggestions.' + @MyAnnotation2 abstract protected void fooMet(); - abstract @MyAnnotation2 public void fooMet1(); //warn + // violation below ''@MyAnnotation2' .* does not precede non-annotation modifiers.' + abstract @MyAnnotation2 public void fooMet1(); - /** holder for redundant 'public' modifier check. */ - public static interface InputRedundantPublicModifier - { - public void a(); + /** holder for redundant 'public' modifier check. */ + public static interface InputRedundantPublicModifier { + public void abc1(); - void b(); + void abc2(); - abstract void c(); + abstract void abc3(); - public float PI_PUBLIC = (float) 3.14; + public float PI_PUBLIC = (float) 3.14; - final float PI_FINAL = (float) 3.14; + final float PI_FINAL = (float) 3.14; - /** all OK */ - float PI_OK = (float) 3.14; - } - final private void method() // warn - { - } -} + /** all OK. */ + float PI_OK = (float) 3.14; + } -final class RedundantFinalClass -{ - public final void finalMethod() - { - } + // violation below ''private' modifier out of order with the JLS suggestions.' + final private void method() {} +} +// violation below 'Top-level class RedundantFinalClass has to reside in its own source file.' +final class RedundantFinalClass { + public final void finalMethod() {} - public void method() - { - } + public void method() {} - protected @MyAnnotation2 static synchronized native void fooMethod(); // warn + protected @MyAnnotation2 static synchronized native void fooMethod(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - static protected @MyAnnotation2 synchronized native void fooMethod1(); // warn + static protected @MyAnnotation2 synchronized native void fooMethod1(); + // violation above ''protected' modifier out of order with the JLS suggestions.' - @MyAnnotation2 protected synchronized native void fooMethod2(); // ok + @MyAnnotation2 protected synchronized native void fooMethod2(); - native synchronized protected static @MyAnnotation2 void fooMethod3(); // warn + native synchronized protected static @MyAnnotation2 void fooMethod3(); + // violation above ''synchronized' modifier out of order with the JLS suggestions.' - native @MyAnnotation2 protected static synchronized void fooMethod4(); // warn + native @MyAnnotation2 protected static synchronized void fooMethod4(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - public static @MyAnnotation2 synchronized native void fooMethod5(); // warn + public static @MyAnnotation2 synchronized native void fooMethod5(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - synchronized static native @MyAnnotation2 public void fooMethod6(); // warn + synchronized static native @MyAnnotation2 public void fooMethod6(); + // violation above ''static' modifier out of order with the JLS suggestions.' - static synchronized private native @MyAnnotation2 void fooMethod7(); // warn + static synchronized private native @MyAnnotation2 void fooMethod7(); + // violation above ''private' modifier out of order with the JLS suggestions.' } -/** Holder for redundant modifiers of inner implementation */ -interface InnerImplementation -{ - InnerImplementation inner = - new InnerImplementation() - { - /** compiler requires 'public' modifier */ - public void method() - { - } - }; - - void method(); -} +// violation 2 lines below 'Top-level class .* has to reside in its own source file.' +/** Holder for redundant modifiers of inner implementation. */ +interface InnerImplementation { + InnerImplementation inner = + new InnerImplementation() { + /** compiler requires 'public' modifier. */ + public void method() {} + }; -class WithInner -{ - /** - * Inner class - * @author max - * - */ - class Inner - { - transient private String dontSaveMe; //warn + void method(); +} - volatile public int whatImReading; //warn +// violation below 'Top-level class WithInner has to reside in its own source file.' +class WithInner { + /** + * Inner class. + * + * @author max + */ + class Inner { + transient private String dontSaveMe; + // violation above ''private' modifier out of order with the JLS suggestions.' - @MyAnnotation2 protected synchronized native void fooMethod(); // ok + volatile public int whatImReading; + // violation above ''public' modifier out of order with the JLS suggestions.' - protected @MyAnnotation2 synchronized native void fooMethod1(); // warn + @MyAnnotation2 protected synchronized native void fooMethod(); - synchronized protected @MyAnnotation2 native void fooMethod2(); // warn + protected @MyAnnotation2 synchronized native void fooMethod1(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - native synchronized protected @MyAnnotation2 void fooMethod3(); // warn + synchronized protected @MyAnnotation2 native void fooMethod2(); + // violation above ''protected' modifier out of order with the JLS suggestions.' - native @MyAnnotation2 protected synchronized void fooMethod4(); // warn + native synchronized protected @MyAnnotation2 void fooMethod3(); + // violation above ''synchronized' modifier out of order with the JLS suggestions.' - public @MyAnnotation2 synchronized native void fooMethod5(); // warn + native @MyAnnotation2 protected synchronized void fooMethod4(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - synchronized native @MyAnnotation2 public void fooMethod6(); // warn + public @MyAnnotation2 synchronized native void fooMethod5(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - synchronized private native @MyAnnotation2 void fooMethod7(); // warn + synchronized native @MyAnnotation2 public void fooMethod6(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - /** - * Anonymous class - */ - InnerImplementation foo = new InnerImplementation() { + synchronized private native @MyAnnotation2 void fooMethod7(); + // violation above ''private' modifier out of order with the JLS suggestions.' + /** Anonymous class. */ + InnerImplementation foo = + new InnerImplementation() { - public void method() { + public void method() { // OOOO Auto-generated method stub - } + } - transient private String dontSaveMe; //warn + transient private String dontSaveMe; + // violation above ''private' modifier out of order with the JLS suggestions.' - volatile public int whatImReading; //warn + volatile public int whatImReading; + // violation above ''public' modifier out of order with the JLS suggestions.' - protected @MyAnnotation2 synchronized native void fooMethod(); // warn + protected @MyAnnotation2 synchronized native void fooMethod(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - protected @MyAnnotation2 synchronized native void fooMethod1(); // warn + protected @MyAnnotation2 synchronized native void fooMethod1(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - synchronized protected @MyAnnotation2 native void fooMethod2(); // warn + synchronized protected @MyAnnotation2 native void fooMethod2(); + // violation above ''protected' modifier out of order with the JLS suggestions.' - native synchronized protected @MyAnnotation2 void fooMethod3(); // warn + native synchronized protected @MyAnnotation2 void fooMethod3(); + // violation above ''synchronized' modifier out of order with the JLS suggestions.' - @MyAnnotation2 protected synchronized native void fooMethod4(); // ok + @MyAnnotation2 protected synchronized native void fooMethod4(); - public @MyAnnotation2 synchronized native void fooMethod5(); // warn + public @MyAnnotation2 synchronized native void fooMethod5(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - synchronized native @MyAnnotation2 public void fooMethod6(); // warn + synchronized native @MyAnnotation2 public void fooMethod6(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' - synchronized private native @MyAnnotation2 void fooMethod7(); // warn - }; - } + synchronized private native @MyAnnotation2 void fooMethod7(); + // violation above ''private' modifier out of order with the JLS suggestions.' + }; + } - /** - * Inner abstract class - * @author max - * - */ - abstract class AbsInner - { - transient private String dontSaveMe; //warn + /** + * Inner abstract class. + * + * @author max + */ + abstract class AbsInner { + transient private String dontSaveMe; + // violation above ''private' modifier out of order with the JLS suggestions.' - volatile public int whatImReading; //warn + volatile public int whatImReading; + // violation above ''public' modifier out of order with the JLS suggestions.' - @MyAnnotation2 public final synchronized strictfp void fooMethod() {}; //ok + @MyAnnotation2 public final synchronized strictfp void fooMethod() {} - strictfp protected final @MyAnnotation2 synchronized void fooMethod1() {}; //warn + // violation below ''protected' modifier out of order with the JLS suggestions.' + strictfp protected final @MyAnnotation2 synchronized void fooMethod1() {} - synchronized @MyAnnotation2 strictfp private final void fooMethod2() {}; //warn + // violation below ''@MyAnnotation2' .* does not precede non-annotation modifiers.' + synchronized @MyAnnotation2 strictfp private final void fooMethod2() {} - @MyAnnotation2 synchronized final strictfp protected void fooMethod3() {}; //warn + // violation below ''final' modifier out of order with the JLS suggestions.' + @MyAnnotation2 synchronized final strictfp protected void fooMethod3() {} - @MyAnnotation2 strictfp final synchronized private void fooMethod4() {}; //warn + // violation below ''final' modifier out of order with the JLS suggestions.' + @MyAnnotation2 strictfp final synchronized private void fooMethod4() {} - synchronized final strictfp @MyAnnotation2 public void fooMethod5() {}; //warn + // violation below ''final' modifier out of order with the JLS suggestions.' + synchronized final strictfp @MyAnnotation2 public void fooMethod5() {} - @MyAnnotation2 synchronized strictfp private final void fooMethod6() {}; //warn + // violation below ''private' modifier out of order with the JLS suggestions.' + @MyAnnotation2 synchronized strictfp private final void fooMethod6() {} - final strictfp synchronized protected @MyAnnotation2 void fooMethod7() {}; //warn + // violation below ''synchronized' modifier out of order with the JLS suggestions.' + final strictfp synchronized protected @MyAnnotation2 void fooMethod7() {} - @MyAnnotation2 abstract protected void fooMet(); //warn + @MyAnnotation2 abstract protected void fooMet(); + // violation above ''protected' modifier out of order with the JLS suggestions.' - abstract @MyAnnotation2 public void fooMet1(); //warn - } + abstract @MyAnnotation2 public void fooMet1(); + // violation above ''@MyAnnotation2' .* does not precede non-annotation modifiers.' + } } -/** Holder for redundant modifiers of annotation fields/variables */ -@interface Annotation -{ - public String s1 = ""; - final String s2 = ""; - static String s3 = ""; - String s4 = ""; - public String blah(); - abstract String blah2(); -} +// violation 2 lines below 'Top-level class Annotation has to reside in its own source file.' +/** Holder for redundant modifiers of annotation fields/variables. */ +@interface Annotation { + public String s1 = ""; + final String s2 = ""; + static String s3 = ""; + String s4 = ""; -@interface MyAnnotation2 { -} + public String blah(); -@interface MyAnnotation4 { + abstract String blah2(); } -/** Illegal order of modifiers for interface methods */ -interface InputModifierOrderInterface -{ - default strictfp void a() { } //ok +// violation below 'Top-level class MyAnnotation2 has to reside in its own source file.' +@interface MyAnnotation2 {} + +// violation below 'Top-level class MyAnnotation4 has to reside in its own source file.' +@interface MyAnnotation4 {} + +// violation 2 lines below 'Top-level class .* has to reside in its own source file.' +/** Illegal order of modifiers for interface methods. */ +interface InputModifierOrderInterface { + default strictfp void abc1() {} - strictfp default void b() { } //warn + strictfp default void abc2() {} + // violation above ''default' modifier out of order with the JLS suggestions.' } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrderNonSealed.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrderNonSealed.java new file mode 100644 index 000000000000..d1afaeacbd7b --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrderNonSealed.java @@ -0,0 +1,46 @@ +package com.google.checkstyle.test.chapter4formatting.rule487modifiers; + +// violation 2 lines below ''public' modifier out of order with the JLS suggestions.' +/** some javadoc. */ +sealed public class InputModifierOrderNonSealed + permits InputModifierOrderNonSealed.CircleOne1, InputModifierOrderNonSealed.RectangleOne1, + InputModifierOrderNonSealed.SquareOne1 { + + final class CircleOne1 extends InputModifierOrderNonSealed + implements SquircleOne1 { + } + + sealed class RectangleOne1 extends InputModifierOrderNonSealed + permits TransparentRectangleOne1, FilledRectangleOne1 { + } + + final class TransparentRectangleOne1 extends RectangleOne1 { + } + + sealed class SquareOne1 extends InputModifierOrderNonSealed implements SquircleOne1 { + + sealed private class OtherSquare extends SquareOne1 permits OtherSquare2 { + } // violation above ''private' modifier out of order with the JLS suggestions.' + + private final class OtherSquare2 extends OtherSquare {} + + static non-sealed class StaticClass1 implements SquircleOne1 {} + } + + final class FilledRectangleOne1 extends RectangleOne1 {} + + sealed interface SquircleOne1 permits CircleOne1, SquareOne1, Ellipse1, SquareOne1.StaticClass1 { + } + + sealed interface Rhombus1 permits Parallelogram1, + Parallelogram1.Trapezoid1 {} + + record Parallelogram1(int x, int y, double z) implements Rhombus1 { + + public record Trapezoid1(int x, int y, double z) implements Rhombus1 {} + } + + non-sealed interface Ellipse1 extends SquircleOne1 {} + + class Oval1 implements Ellipse1 {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrderSealed.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrderSealed.java new file mode 100644 index 000000000000..0092c8cb3eb0 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule487modifiers/InputModifierOrderSealed.java @@ -0,0 +1,28 @@ +package com.google.checkstyle.test.chapter4formatting.rule487modifiers; + +// violation 2 lines below ''public' modifier out of order with the JLS suggestions' +/** some javadoc. */ +sealed public class InputModifierOrderSealed permits + InputModifierOrderSealed.Four, + InputModifierOrderSealed.Three, + InputModifierOrderSealed.Two { + + /** some javadoc. */ + public final class Two extends InputModifierOrderSealed implements Five {} + + sealed class Four extends InputModifierOrderSealed {} + + sealed class Three extends InputModifierOrderSealed implements Five { + + // violation below ''private' modifier out of order with the JLS suggestions' + sealed private class OtherSquare extends Three {} + + private final class OtherSquare2 extends OtherSquare {} + } + + /** some javadoc. */ + public final class FilledFour extends Four {} + + // violation below ''abstract' modifier out of order with the JLS suggestions' + sealed abstract interface Five permits Three, Two {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/InputNumericLiterals.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/InputNumericLiterals.java new file mode 100644 index 000000000000..f58df6192e0c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/InputNumericLiterals.java @@ -0,0 +1,103 @@ +package com.google.checkstyle.test.chapter4formatting.rule488numericliterals; + +class InputNumericLiterals { + /** test. * */ + private final long ignore = 666l + 666L; // violation 'Should use uppercase 'L'.' + + private String notWarn = "666l"; // ok + + private long foo() { + processUpperEll(66l); // violation 'Should use uppercase 'L'.' + processUpperEll(66L); // ok + processUpperEll("s", 66l); // violation 'Should use uppercase 'L'.' + processUpperEll("s", 66L); // ok + + return 666l + 666L; // violation 'Should use uppercase 'L'.' + } + + private void processUpperEll(long xyz) { + long bad = + (4 + 5 * 7 ^ 66l / 7 + 890) // violation 'Should use uppercase 'L'.' + & (88l + 78 * 4); // violation 'Should use uppercase 'L'.' + long good = (4 + 5 * 7 ^ 66L / 7 + 890) & (88L + 78 * 4); // ok + long[] array = { + 66l, // violation 'Should use uppercase 'L'.' + 66L, // ok + }; + } + + private void processUpperEll(String s, long l) {} + + class Inner { + /** test. * */ + private static final long IGNORE = 666l + 666L; // violation 'Should use uppercase 'L'.' + + private static final String notWarn = "666l"; // ok + + private long foo() { + processUpperEll(66l); // violation 'Should use uppercase 'L'.' + processUpperEll(66L); // ok + processUpperEll("s", 66l); // violation 'Should use uppercase 'L'.' + processUpperEll("s", 66L); // ok + + return 666l + 666L; // violation 'Should use uppercase 'L'.' + } + + private void processUpperEll(long xyz) { + long bad = + (4 + 5 * 7 ^ 66l / 7 + 890) // violation 'Should use uppercase 'L'.' + & (88l + 78 * 4); // violation 'Should use uppercase 'L'.' + long good = (4 + 5 * 7 ^ 66L / 7 + 890) & (88L + 78 * 4); // ok + } + + private void processUpperEll(String s, long l) { + long[] array = { + 66l, // violation 'Should use uppercase 'L'.' + 66L, // ok + }; + } + + void fooMethod() { + Foo foo = + new Foo() { + /** test. * */ + private final long ignore = 666l + 666L; // violation 'Should use uppercase 'L'.' + + private String notWarn = "666l"; // ok + + private long foo() { + processUpperEll(66l); // violation 'Should use uppercase 'L'.' + processUpperEll(66L); // ok + processUpperEll("s", 66l); // violation 'Should use uppercase 'L'.' + processUpperEll("s", 66L); // ok + + return 666l + 666L; // violation 'Should use uppercase 'L'.' + } + + private void processUpperEll(long x) { + long bad = + (4 + 5 * 7 ^ 66l / 7 + 890) // violation 'Should use uppercase 'L'.' + & (88l + 78 * 4); // violation 'Should use uppercase 'L'.' + long good = (4 + 5 * 7 ^ 66L / 7 + 890) & (88L + 78 * 4); // ok + long[] array = { + 66l, // violation 'Should use uppercase 'L'.' + 66L, // ok + }; + } + + private void processUpperEll(String s, long x) {} + }; + } + } + + class Foo {} + + interface Long { + public static final long IGNORE = 666l + 666L; // violation 'Should use uppercase 'L'.' + public static final String notWarn = "666l"; // ok + long bad = + (4 + 5 * 7 ^ 66l / 7 + 890) // violation 'Should use uppercase 'L'.' + & (88l + 78 * 4); // violation 'Should use uppercase 'L'.' + long good = (4 + 5 * 7 ^ 66L / 7 + 890) & (88L + 78 * 4); // ok + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/InputUpperEll.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/InputUpperEll.java deleted file mode 100644 index 3da221b85be7..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule488numericliterals/InputUpperEll.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.google.checkstyle.test.chapter4formatting.rule488numericliterals; - -class InputUpperEll -{ - /** test **/ - private final long IGNORE = 666l + 666L; //warn - - private String notWarn = "666l"; //ok - - private long foo() - { - processUpperEll(66l); //warn - processUpperEll(66L); //ok - processUpperEll("s", 66l); //warn - processUpperEll("s", 66L); //ok - - return 666l + 666L; //warn - } - - private void processUpperEll(long aLong) { - long bad = (4+5*7^66l/7+890) //warn - & (88l + 78 * 4); //warn - long good = (4+5*7^66L/7+890) & (88L + 78 * 4); //ok - long[] array = { - 66l, //warn - 66L, //ok - }; - } - - private void processUpperEll(String s, long l) {} - - class Inner { - /** test **/ - private static final long IGNORE = 666l + 666L; //warn - - private static final String notWarn = "666l"; //ok - - private long foo() - { - processUpperEll(66l); //warn - processUpperEll(66L); //ok - processUpperEll("s", 66l); //warn - processUpperEll("s", 66L); //ok - - return 666l + 666L; //warn - } - - private void processUpperEll(long aLong) - { - long bad = (4+5*7^66l/7+890) //warn - & (88l + 78 * 4); //warn - long good = (4+5*7^66L/7+890) & (88L + 78 * 4); //ok - } - private void processUpperEll(String s, long l) { - long[] array = { - 66l, //warn - 66L, //ok - }; - } - - void fooMethod() - { - Foo foo = new Foo() { - /** test **/ - private final long IGNORE = 666l + 666L; //warn - - private String notWarn = "666l"; //ok - - private long foo() - { - processUpperEll(66l); //warn - processUpperEll(66L); //ok - processUpperEll("s", 66l); //warn - processUpperEll("s", 66L); //ok - - return 666l + 666L; //warn - } - - private void processUpperEll(long aLong) { - long bad = (4+5*7^66l/7+890) //warn - & (88l + 78 * 4); //warn - long good = (4+5*7^66L/7+890) & (88L + 78 * 4); //ok - long[] array = { - 66l, //warn - 66L, //ok - }; - } - - private void processUpperEll (String s, long aLong) {} - }; - } - } - - class Foo {} - - interface Long { - public static final long IGNORE = 666l + 666L; //warn - public static final String notWarn = "666l"; //ok - long bad = (4+5*7^66l/7+890) //warn - & (88l + 78 * 4); //warn - long good = (4+5*7^66L/7+890) & (88L + 78 * 4); //ok - } -} - - - diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputFormattedTextBlocksGeneralForm.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputFormattedTextBlocksGeneralForm.java new file mode 100644 index 000000000000..82e23fff1f84 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputFormattedTextBlocksGeneralForm.java @@ -0,0 +1,74 @@ +package com.google.checkstyle.test.chapter4formatting.rule489textblocks; + +/** somejavadoc. */ +public class InputFormattedTextBlocksGeneralForm { + + /** some javadoc. */ + public static void textFun() { + + final String simpleScript = + """ + s + """; + + final String simpleScript1 = + """ + this is simple test; + """; + + getData( + """ + Hello, + This is a multi-line message. + """); + } + + /** somejavadoc. */ + public void textFun2() { + + final String simpleScript2 = + """ + this is sample text + """; + + getData( + """ + Hello, + This is a multi-line message. + """); + } + + /** somejavadoc. */ + public String textFun3() { + + String s = + """ + Hello there + """ + + getName(); + + getData( + """ + hello there1 + """, + 0); + + return s + + """ + very good + """ + .charAt(0) + + getName(); + } + + /** somejavadoc. */ + public String getName() { + return "name"; + } + + /** somejavadoc. */ + public static void getData(String data) {} + + /** somejavadoc. */ + public static void getData(String data, int length) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputFormattedTextBlocksIndentation.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputFormattedTextBlocksIndentation.java new file mode 100644 index 000000000000..2edf01a9f664 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputFormattedTextBlocksIndentation.java @@ -0,0 +1,48 @@ +package com.google.checkstyle.test.chapter4formatting.rule489textblocks; + +/** somejavadoc. */ +public class InputFormattedTextBlocksIndentation { + + /** somejavadoc. */ + public void textIndentation1() { + String e1 = + """ + content of the block. e1 + """; + + String e2 = + """ + content of the block of e3 + """; + + String e3 = + """ + content of the block. e1 + """; + + getData( + """ + Indentation of Text-block + """, + 5); + } + + /** somejavadoc. */ + public void textFuncIndenation2() { + // violation 2 lines below '.* incorrect indentation level 0, expected .* 8.' + String e2 = +""" +content of the block e2 +"""; + // violation above '.* incorrect indentation level 0, expected .* 8.' + + getData( + """ + Indentation of Text-block + """, + 5); + } + + /** somejavadoc. */ + public static void getData(String data, int length) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputTextBlocksGeneralForm.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputTextBlocksGeneralForm.java new file mode 100644 index 000000000000..bb818c779931 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputTextBlocksGeneralForm.java @@ -0,0 +1,92 @@ +package com.google.checkstyle.test.chapter4formatting.rule489textblocks; + +/** somejavadoc. */ +public class InputTextBlocksGeneralForm { + + /** some javadoc. */ + public static String textFun() { + + // opening quotes should be on new line below, ok until #17223 + final String simpleScript = """ + s + """; + // not vertically aligned with opening quotes above, ok until #17223 + + final String simpleScript1 = + """ + this is simple test; + """; + + // opening quotes should be on new line below, ok until #17223 + getData(""" + Hello, + This is a multi-line message. + """); + // not vertically aligned with opening quotes above, ok until #17223 + + // opening quotes should be on new line below, ok until #17223 + return """ + this is sample text + """; + // not vertically aligned with opening quotes above, ok until #17223 + } + + /** somejavadoc. */ + public String textFun2() { + + final String simpleScript2 = + """ + this is sample text"""; + // Two violations above, ok until #17223 + // 'closing quotes should be on new line' + // 'not vertically aligned with opening quotes' + + getData( + """ + Hello, + This is a multi-line message.""" + ); + // Two violations 2 lines above, ok until #17223 + // 'closing quotes should be on new line' + // 'not vertically aligned with opening quotes' + + return + """ + THE MULTI-LINE MESSAGE"""; + // Two violations above, ok until #17223 + // 'closing quotes should be on new line' + // 'not vertically aligned with opening quotes' + } + + /** somejavadoc. */ + public String textFun3() { + + String s = + """ + Hello there + """ + getName(); + + getData( + """ + hello there1 + """, 0); + + return s + + + """ + very good + """.charAt(0) + getName(); + } + + /** somejavadoc. */ + public String getName() { + return "name"; + } + + /** somejavadoc. */ + public static void getData(String data) {} + + /** somejavadoc. */ + public static void getData(String data, int length) {} + +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputTextBlocksIndentation.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputTextBlocksIndentation.java new file mode 100644 index 000000000000..6c6346b46d88 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule489textblocks/InputTextBlocksIndentation.java @@ -0,0 +1,54 @@ +package com.google.checkstyle.test.chapter4formatting.rule489textblocks; + +/** somejavadoc. */ +public class InputTextBlocksIndentation { + + /** somejavadoc. */ + public void textIndentation1() { + String e1 = + """ + content of the block. e1 + """; + + String e2 = + """ + content of the block of e3 + """; // 'not vertically aligned with opening quotes', ok until #17223 + + // 'wrong indentation of 10, expected 8' below, ok until #17223 + String e3 = + """ + content of the block. e1 + """; + // not vertically aligned with opening quotes above, ok until #17223 + + // 'wrong indentation of 12, expected 8' 2 lines below, ok until #17223 + getData( + """ + Indentation of Text-block + """, + 5 + ); + } + + /** somejavadoc. */ + public void textFuncIndenation2() { + // violation 2 lines below '.* incorrect indentation level 0, expected .* 8.' + String e2 = +""" +content of the block e2 +"""; + // violation above '.* incorrect indentation level 0, expected .* 8.' + + // violation 2 lines below '.* incorrect indentation level 4, expected .* 6.' + getData( + """ + Indentation of Text-block + """, // violation '.* incorrect indentation level 4, expected .* 6.' + 5 + ); + } + + /** somejavadoc. */ + public static void getData(String data, int length) {} +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule51identifiernames/InputCatchParameterName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule51identifiernames/InputCatchParameterName.java index 42133bf8f99c..baec888b4aec 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule51identifiernames/InputCatchParameterName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule51identifiernames/InputCatchParameterName.java @@ -1,65 +1,115 @@ package com.google.checkstyle.test.chapter5naming.rule51identifiernames; +/** some javadoc. */ public class InputCatchParameterName { - { - try { - } catch (Exception e) { // ok - } - try { - } catch (Exception ex) { // ok - } - try { - } catch (Error | Exception err) { // ok - } - try { - } catch (Exception exception) { // ok - } - try { - } catch (Exception exception1) { // ok - } - try { - } catch (Exception noWorries) { // ok - } - try { - } catch (Throwable t) { // ok - } - try { - throw new InterruptedException("interruptedException"); - } catch (InterruptedException ie) { // ok - } - try { - } catch (Exception ok) { // ok - // appropriate to take no action here - } - try { - } catch (Exception e1) { // ok - try { - } catch (Exception e2) { // ok - } - } - try { - } catch (Throwable t1) { // ok - try { - } catch (Throwable t2) { // ok - } - } - try { - } catch (Exception iException) { // warn - } - try { - } catch (Exception ex_1) { // warn - } - try { - } catch (Exception eX) { // warn - } - try { - } catch (Exception eXX) { // warn - } - try { - } catch (Exception x_y_z) { // warn - } - try { - } catch (Exception Ex) { // warn - } + { + try { + /* foo */ + } catch (Exception e) { + /* foo */ } + try { + /* foo */ + } catch (Exception ex) { + /* foo */ + } + try { + /* foo */ + } catch (Error | Exception err) { + /* foo */ + } + try { + /* foo */ + } catch (Exception exception) { + /* foo */ + } + try { + /* foo */ + } catch (Exception exception1) { + /* foo */ + } + try { + /* foo */ + } catch (Exception noWorries) { + /* foo */ + } + try { + /* foo */ + } catch (Throwable t) { + /* foo */ + } + try { + throw new InterruptedException("interruptedException"); + } catch (InterruptedException ie) { + /* foo */ + } + try { + /* foo */ + } catch (Exception ok) { + // appropriate to take no action here + } + try { + /* foo */ + } catch (Exception e1) { + try { + /* foo */ + } catch (Exception e2) { + /* foo */ + } + } + try { + /* foo */ + } catch (Throwable t1) { + try { + /* foo */ + } catch (Throwable t2) { + /* foo */ + } + } + try { + /* foo */ + } catch (Exception iException) { + // violation above 'Catch parameter name 'iException' must match pattern' + } + try { + /* foo */ + } catch (Exception ex_1) { // violation 'Catch parameter name 'ex_1' must match pattern' + } + try { + /* foo */ + } catch (Exception eX) { // violation 'Catch parameter name 'eX' must match pattern' + } + try { + /* foo */ + } catch (Exception eXX) { + // 2 violations above: + // 'Abbreviation in name 'eXX' must contain no more than '1' consecutive capital letters.' + // 'Catch parameter name 'eXX' must match pattern' + /* foo */ + } + try { + /* foo */ + } catch (Exception x_y_z) { // violation 'Catch parameter name 'x_y_z' must match pattern' + } + try { + /* foo */ + } catch (Exception Ex) { // violation 'Catch parameter name 'Ex' must match pattern' + } + try { + /* foo */ + } catch (Exception name_) { // violation 'Catch parameter name 'name_' must match pattern' + } + try { + /* foo */ + } catch (Exception mName) { // violation 'Catch parameter name 'mName' must match pattern' + } + try { + /* foo */ + } catch (Exception s_name) { // violation 'Catch parameter name 's_name' must match pattern' + } + try { + /* foo */ + } catch (Exception kName) { // violation 'Catch parameter name 'kName' must match pattern' + } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521$packagenames/InputPackageBadName3.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521$packagenames/InputPackageBadName3.java index b2c8cb39107a..1d2ac52d025f 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521$packagenames/InputPackageBadName3.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521$packagenames/InputPackageBadName3.java @@ -1,2 +1,5 @@ -package com.google.checkstyle.test.chapter5naming.rule521$packagenames; //warn +package com.google.checkstyle.test.chapter5naming.rule521$packagenames; + +// violation 2 lines above 'Package name .* must match pattern .*' + final class InputPackageBadName3 {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521_packagenames/InputBadPackageName2.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521_packagenames/InputBadPackageName2.java index e204f6b311f2..e0f260f21ffe 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521_packagenames/InputBadPackageName2.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521_packagenames/InputBadPackageName2.java @@ -1,2 +1,5 @@ -package com.google.checkstyle.test.chapter5naming.rule521_packagenames; //warn +package com.google.checkstyle.test.chapter5naming.rule521_packagenames; + +// violation 2 lines above 'Package name .* must match pattern .*' + final class InputBadPackageName2 {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521packageNamesCamelCase/InputPackageNameBad.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521packageNamesCamelCase/InputPackageNameBad.java index 37dcbfbaeae6..ea36a96d8138 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521packageNamesCamelCase/InputPackageNameBad.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521packageNamesCamelCase/InputPackageNameBad.java @@ -1,2 +1,5 @@ -package com.google.checkstyle.test.chapter5naming.rule521packageNamesCamelCase; //warn +package com.google.checkstyle.test.chapter5naming.rule521packageNamesCamelCase; + +// violation 2 lines above 'Package name .* must match pattern .*' + final class InputPackageNameBad {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521packagenames/InputPackageNameGood.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521packagenames/InputPackageNameGood.java index 96b59c24e630..fe63cd0fd364 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521packagenames/InputPackageNameGood.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule521packagenames/InputPackageNameGood.java @@ -1,2 +1,3 @@ -package com.google.checkstyle.test.chapter5naming.rule521packagenames; //ok +package com.google.checkstyle.test.chapter5naming.rule521packagenames; + final class InputPackageNameGood {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputClassNames.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputClassNames.java new file mode 100644 index 000000000000..2aa764d517bb --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputClassNames.java @@ -0,0 +1,87 @@ +package com.google.checkstyle.test.chapter5naming.rule522classnames; + +class inputHeaderClass { + // 2 violations above: + // 'The name of the outer type and the file do not match.' + // 'Type name 'inputHeaderClass' must match pattern' + + // violation below 'Type name 'InputHeader___Interface' .* .*' + public interface InputHeader___Interface {} + + // violation below 'Type name 'inputHeaderEnum' must match pattern' + public enum inputHeaderEnum { + one, + two + } + + class NoValid$Name {} + // violation above 'Type name 'NoValid\$Name' must match pattern' + + class $NoValidName {} + // violation above 'Type name '\$NoValidName' must match pattern' + + class NoValidName$ {} + // violation above 'Type name 'NoValidName\$' must match pattern' + + class ValidName {} + + class _ValidName {} // violation 'Type name '_ValidName' must match pattern' + + class Valid_Name {} // violation 'Type name 'Valid_Name' must match pattern' + + class ValidName_ {} // violation 'Type name 'ValidName_' must match pattern' + + interface Foo {} + + interface _Foo {} // violation 'Type name '_Foo' must match pattern' + + interface Fo_o {} // violation 'Type name 'Fo_o' must match pattern' + + interface Foo_ {} // violation 'Type name 'Foo_' must match pattern' + + interface $Foo {} // violation 'Type name '\$Foo' must match pattern' + + interface Fo$o {} // violation 'Type name 'Fo\$o' must match pattern' + + interface Foo$ {} // violation 'Type name 'Foo\$' must match pattern' + + enum FooEnum {} + + enum _FooEnum {} // violation 'Type name '_FooEnum' must match pattern' + + enum Foo_Enum {} // violation 'Type name 'Foo_Enum' must match pattern' + + enum FooEnum_ {} // violation 'Type name 'FooEnum_' must match pattern' + + enum $FooEnum {} // violation 'Type name '\$FooEnum' must match pattern' + + enum Foo$Enum {} // violation 'Type name 'Foo\$Enum' must match pattern' + + enum FooEnum$ {} // violation 'Type name 'FooEnum\$' must match pattern' + + class aaa {} // violation 'Type name 'aaa' must match pattern' + + interface bbb {} // violation 'Type name 'bbb' must match pattern' + + enum ccc {} // violation 'Type name 'ccc' must match pattern' + + @interface Annotation {} + + @interface _Annotation {} + // violation above 'Type name '_Annotation' must match pattern' + + @interface Annot_ation {} + // violation above 'Type name 'Annot_ation' must match pattern' + + @interface Annotation_ {} + // violation above 'Type name 'Annotation_' must match pattern' + + @interface $Annotation {} + // violation above 'Type name '\$Annotation' must match pattern' + + @interface Annot$ation {} + // violation above 'Type name 'Annot\$ation' must match pattern' + + @interface Annotation$ {} + // violation above 'Type name 'Annotation\$' must match pattern' +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputClassNamesWithUnderscore.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputClassNamesWithUnderscore.java new file mode 100644 index 000000000000..0cc141e92273 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputClassNamesWithUnderscore.java @@ -0,0 +1,16 @@ +package com.google.checkstyle.test.chapter5naming.rule522classnames; + +class InputClassNamesWithUnderscore { + + class ConvertToKotlinVersion_ {} // violation, _ at the end, 'must match' + + class ConvertToKotlinVersion_1_9_24 {} // violation, _ between digit and letter, 'must match' + + class ConvertToKotlinVersion1_9_24 {} + + class ConvertToKotlinVersion1_9_24_ {} // violation, _ at the end, 'must match' + + class ConvertToKotlinVersion10_0 {} + + class ConvertToKotlinVersion__ {} // violation, two _s at the end, 'must match' +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputFormattedClassNames.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputFormattedClassNames.java new file mode 100644 index 000000000000..f112323fd96c --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522classnames/InputFormattedClassNames.java @@ -0,0 +1,95 @@ +package com.google.checkstyle.test.chapter5naming.rule522classnames; + +class inputHeaderClass2 { + // 2 violations above: + // 'The name of the outer type and the file do not match.' + // 'Type name 'inputHeaderClass2' must match pattern' + + // violation below 'Type name 'InputHeader___Interface' .* .*' + public interface InputHeader___Interface {} + + // violation below 'Type name 'inputHeaderEnum' must match pattern' + public enum inputHeaderEnum { + one, + two + } + + class NoValid$Name {} + + // violation 2 lines above 'Type name 'NoValid\$Name' must match pattern' + + class $NoValidName {} + + // violation 2 lines above 'Type name '\$NoValidName' must match pattern' + + class NoValidName$ {} + + // violation 2 lines above 'Type name 'NoValidName\$' must match pattern' + + class ValidName {} + + class _ValidName {} // violation 'Type name '_ValidName' must match pattern' + + class Valid_Name {} // violation 'Type name 'Valid_Name' must match pattern' + + class ValidName_ {} // violation 'Type name 'ValidName_' must match pattern' + + interface Foo {} + + interface _Foo {} // violation 'Type name '_Foo' must match pattern' + + interface Fo_o {} // violation 'Type name 'Fo_o' must match pattern' + + interface Foo_ {} // violation 'Type name 'Foo_' must match pattern' + + interface $Foo {} // violation 'Type name '\$Foo' must match pattern' + + interface Fo$o {} // violation 'Type name 'Fo\$o' must match pattern' + + interface Foo$ {} // violation 'Type name 'Foo\$' must match pattern' + + enum FooEnum {} + + enum _FooEnum {} // violation 'Type name '_FooEnum' must match pattern' + + enum Foo_Enum {} // violation 'Type name 'Foo_Enum' must match pattern' + + enum FooEnum_ {} // violation 'Type name 'FooEnum_' must match pattern' + + enum $FooEnum {} // violation 'Type name '\$FooEnum' must match pattern' + + enum Foo$Enum {} // violation 'Type name 'Foo\$Enum' must match pattern' + + enum FooEnum$ {} // violation 'Type name 'FooEnum\$' must match pattern' + + class aaa {} // violation 'Type name 'aaa' must match pattern' + + interface bbb {} // violation 'Type name 'bbb' must match pattern' + + enum ccc {} // violation 'Type name 'ccc' must match pattern' + + @interface Annotation {} + + @interface _Annotation {} + + // violation 2 lines above 'Type name '_Annotation' must match pattern' + + @interface Annot_ation {} + + // violation 2 lines above 'Type name 'Annot_ation' must match pattern' + + @interface Annotation_ {} + + // violation 2 lines above 'Type name 'Annotation_' must match pattern' + + @interface $Annotation {} + + // violation 2 lines above 'Type name '\$Annotation' must match pattern' + + @interface Annot$ation {} + + // violation 2 lines above 'Type name 'Annot\$ation' must match pattern' + + @interface Annotation$ {} + // violation above 'Type name 'Annotation\$' must match pattern' +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522typenames/InputTypeName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522typenames/InputTypeName.java deleted file mode 100644 index e14d08268d11..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule522typenames/InputTypeName.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.google.checkstyle.test.chapter5naming.rule522typenames; - -class inputHeaderClass { //warn - - public interface InputHeader___Interface {}; //warn - - public enum inputHeaderEnum { one, two }; //warn - - class NoValid$Name {} //warn - - class $NoValidName {} //warn - - class NoValidName$ {} //warn - -} - -class ValidName {} //ok - -class _ValidName {} //warn - -class Valid_Name {} //warn - -class ValidName_ {} //warn - -interface Foo {} // ok - -interface _Foo {} // warn - -interface Fo_o {} // warn - -interface Foo_ {} // warn - -interface $Foo {} // warn - -interface Fo$o {} // warn - -interface Foo$ {} // warn - -enum FooEnum {} //ok - -enum _FooEnum {} //warn - -enum Foo_Enum {} //warn - -enum FooEnum_ {} //warn - -enum $FooEnum {} //warn - -enum Foo$Enum {} //warn - -enum FooEnum$ {} //warn - -class aaa {} //warn - -interface bbb {} //warn - -enum ccc {} //warn - -@interface Annotation {} //ok - -@interface _Annotation {} //warn - -@interface Annot_ation {} //warn - -@interface Annotation_ {} //warn - -@interface $Annotation {} //warn - -@interface Annot$ation {} //warn - -@interface Annotation$ {} //warn diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule523methodnames/InputMethodName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule523methodnames/InputMethodName.java index 818323e1c17b..b1d2f24a1ffa 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule523methodnames/InputMethodName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule523methodnames/InputMethodName.java @@ -1,51 +1,335 @@ package com.google.checkstyle.test.chapter5naming.rule523methodnames; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + /** - * Test input for MethodNameCheck specifically - * whether the method name equals the class name. + * Test input for MethodNameCheck specifically whether the method name equals the class name. * * @author Travis Schneeberger */ public class InputMethodName { + void foo() {} + + void Foo() {} // violation 'Method name 'Foo' must match pattern' + + void fOo() {} // violation 'Method name 'fOo' must match pattern' + + void f0o() {} + + void f$o() {} // violation 'Method name 'f\$o' must match pattern' + + void f_oo() {} // violation 'Method name 'f_oo' must match pattern' + + void f() {} // violation 'Method name 'f' must match pattern' + + void fO() {} // violation 'Method name 'fO' must match pattern' + + @Test + void testing_foo() { + class LocalFoo { + void foo() {} + + // violation below 'Method name 'testing_foo' must match pattern' + void testing_foo() {} + } + + new Object() { + void foo() {} + + // violation below 'Method name 'testing_foo' must match pattern' + void testing_foo() {} + }; + } + + void testing_foo(@FooTest String str) { + // violation above 'Method name 'testing_foo' must match pattern' + class LocalFoo { + void foo() {} + + // violation below 'Method name 'testing_foo' must match pattern' + void testing_foo() {} + } + + new Object() { + void foo() {} + + // violation below 'Method name 'testing_foo' must match pattern' + void testing_foo() {} + }; + } + + @Test + void testing_Foo() {} // violation 'Method name 'testing_Foo' must match pattern' + + @Test + void testing_fOo() {} // violation 'Method name 'testing_fOo' must match pattern' + + @Test + void testingFoo() {} + + @Test + void testingFoo_foo() {} + + @Test + void testing_0123() {} // false-negative, _ between digit and letter + + @Test + void testing_0123_() {} // violation 'Method name 'testing_0123_' must match pattern' + + @Test + void testing__0123() {} // violation 'Method name 'testing__0123' must match pattern' + + @Test + void testing__0123_() {} // violation 'Method name 'testing__0123_' must match pattern' + + @Test + void testing__0123__() {} // violation 'Method name 'testing__0123__' must match pattern' + + @Test + void Testing_Foo() {} // violation 'Method name 'Testing_Foo' must match pattern' + + @Test + void t_esting() {} // violation 'Method name 't_esting' must match pattern' + + @Test + void _testing() {} // violation 'Method name '_testing' must match pattern' + + void Testing_Foo2() {} // violation 'Method name 'Testing_Foo2' must match pattern' + + @Test + void TestingFooBad() {} // violation 'Method name 'TestingFooBad' must match pattern' + + @Test + void testing_foo_() {} // violation 'Method name 'testing_foo_' must match pattern' + + @Test + void testing_Foo_() {} // violation 'Method name 'testing_Foo_' must match pattern' + + @Test + void testing__foo() {} // violation 'Method name 'testing__foo' must match pattern' + + @Test + void testing__Foo() {} // violation 'Method name 'testing__Foo' must match pattern' + + @Test + void testing__foo_() {} // violation 'Method name 'testing__foo_' must match pattern' + + @Test + void testing__Foo_() {} // violation 'Method name 'testing__Foo_' must match pattern' + + @Test + public void testing_123Foo() {} // violation 'Method name 'testing_123Foo' must match pattern' + + // violation 2 lines below 'testing_123FOO' must contain no more than '1' consecutive capital' + @Test + public void testing_123FOO() {} // violation 'Method name 'testing_123FOO' must match pattern' + + // violation 2 lines below 'TESTING_123Foo' must contain no more than '1' consecutive capital' + @Test + public void TESTING_123Foo() {} // violation 'Method name 'TESTING_123Foo' must match pattern' + + @Test + public void testing_Foo123() {} // violation 'Method name 'testing_Foo123' must match pattern' + + // violation 2 lines below 'testing_FOO123' must contain no more than '1' consecutive capital' + @Test + public void testing_FOO123() {} // violation 'Method name 'testing_FOO123' must match pattern' + + @Test + public void testing_Foo_123() {} // violation 'Method name 'testing_Foo_123' must match pattern' + + @Test + public void testing_123_Foo() {} // violation 'Method name 'testing_123_Foo' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testing_foo1(String str) { + class LocalFoo { + void foo() {} + + // violation below 'Method name 'testing_foo' must match pattern' + void testing_foo() {} + } + + new Object() { + void foo() {} + + // violation below 'Method name 'testing_foo' must match pattern' + void testing_foo() {} + }; + } + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testing_Foo1(String str) {} // violation 'Method name 'testing_Foo1' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testing_fOo1(String str) {} // violation 'Method name 'testing_fOo1' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testingFoo1(String str) {} + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testingFoo_foo1(String str) {} + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testing_01231(String str) {} // false-negative, _ between digit and letter + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void Testing_Foo1(String str) {} // violation 'Method name 'Testing_Foo1' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void t_esting1(String str) {} // violation 'Method name 't_esting1' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void _testing1(String str) {} // violation 'Method name '_testing1' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testing_124Foo() {} // violation 'Method name 'testing_124Foo' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + // violation below ''testing_124FOO' must contain no more than '1'' + void testing_124FOO() {} // violation 'Method name 'testing_124FOO' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + // violation below 'TESTING_124Foo' must contain no more than '1' consecutive capital letters' + void TESTING_124Foo() {} // violation 'Method name 'TESTING_124Foo' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testing_Foo124() {} // violation 'Method name 'testing_Foo124' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + // violation below 'testing_FOO124' must contain no more than '1' consecutive capital letters' + void testing_FOO124() {} // violation 'Method name 'testing_FOO124' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testing_Foo_124() {} // violation 'Method name 'testing_Foo_124' must match pattern' + + @ParameterizedTest + @ValueSource(strings = {"racecar", "radar", "level", "madam", "noon"}) + void testing_124_Foo() {} // violation 'Method name 'testing_124_Foo' must match pattern' + + @RepeatedTest(2) + void testing_foo4() {} + + @RepeatedTest(2) + void testing_Foo2() {} // violation 'Method name 'testing_Foo2' must match pattern' + + @RepeatedTest(2) + void testing_fOo2() {} // violation 'Method name 'testing_fOo2' must match pattern' + + @RepeatedTest(2) + void testingFoo2() {} + + @RepeatedTest(2) + void testingFoo_foo2() {} + + @RepeatedTest(2) + void testing_01232() {} // false-negative, _ between digit and letter + + @RepeatedTest(2) + void Testing_Foo3() {} // violation 'Method name 'Testing_Foo3' must match pattern' + + @RepeatedTest(2) + void t_esting2() {} // violation 'Method name 't_esting2' must match pattern' + + @RepeatedTest(2) + void _testing2() {} // violation 'Method name '_testing2' must match pattern' + + @RepeatedTest(2) + void TestingFooBad2() {} // violation 'Method name 'TestingFooBad2' must match pattern' + + @BeforeAll + static void _testingFoooo() {} // violation 'Method name '_testingFoooo' must match pattern' + + @org.junit.jupiter.api.Test + void testing_fq() {} + + class InnerFoo { void foo() {} - void Foo() {} //warn - void fOo() {} //warn + + void Foo() {} // violation 'Method name 'Foo' must match pattern' + + void fOo() {} // violation 'Method name 'fOo' must match pattern' + void f0o() {} - void f$o() {} //warn - void f_oo() {} //warn - void f() {} //warn - void fO() {} //warn - class InnerFoo { - void foo() {} - void Foo() {} //warn - void fOo() {} //warn - void f0o() {} - void f$o() {} //warn - void f_oo() {} //warn - void f() {} //warn - void fO() {} //warn - } + void f$o() {} // violation 'Method name 'f\$o' must match pattern' + + void f_oo() {} // violation 'Method name 'f_oo' must match pattern' + + void f() {} // violation 'Method name 'f' must match pattern' + + void fO() {} // violation 'Method name 'fO' must match pattern' + + void testing_foo() {} // violation 'Method name 'testing_foo' must match pattern' + + void testing_Foo() {} // violation 'Method name 'testing_Foo' must match pattern' + + void testing_fOo() {} // violation 'Method name 'testing_fOo' must match pattern' - InnerFoo anon = new InnerFoo() { + void testingFoo() {} + + void testingFoo_foo() {} // violation 'Method name 'testingFoo_foo' must match pattern' + + void testing_0123() {} // false-negative, _ between digit and letter + + void TestingFooBad() {} // violation 'Method name 'TestingFooBad' must match pattern' + } + + InnerFoo anon = + new InnerFoo() { void foo() {} - void Foo() {} //warn - void fOo() {} //warn + + void Foo() {} // violation 'Method name 'Foo' must match pattern' + + void fOo() {} // violation 'Method name 'fOo' must match pattern' + void f0o() {} - void f$o() {} //warn - void f_oo() {} //warn - void f() {} //warn - void fO() {} //warn - }; -} -interface FooIn { + void f$o() {} // violation 'Method name 'f\$o' must match pattern' + + void f_oo() {} // violation 'Method name 'f_oo' must match pattern' + + void f() {} // violation 'Method name 'f' must match pattern' + + void fO() {} // violation 'Method name 'fO' must match pattern' + }; + + interface FooIn { void foo(); - void Foo(); //warn - void fOo(); //warn + + void Foo(); // violation 'Method name 'Foo' must match pattern' + + void fOo(); // violation 'Method name 'fOo' must match pattern' + void f0o(); - void f$o(); //warn - void f_oo(); //warn - void f(); //warn - void fO(); //warn + + void f$o(); // violation 'Method name 'f\$o' must match pattern' + + void f_oo(); // violation 'Method name 'f_oo' must match pattern' + + void f(); // violation 'Method name 'f' must match pattern' + + void fO(); // violation 'Method name 'fO' must match pattern' + } + + @interface FooTest {} } diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule523methodnames/InputMethodName2.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule523methodnames/InputMethodName2.java new file mode 100644 index 000000000000..175107cd6ed6 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule523methodnames/InputMethodName2.java @@ -0,0 +1,37 @@ +package com.google.checkstyle.test.chapter5naming.rule523methodnames; + +import org.junit.jupiter.api.Test; + +/** some data. */ +public class InputMethodName2 { + + @Test + public void transferMoney_deductsFromSource() {} + + @Test // violation below 'Method name 'transferMoney_DeductsFromSource' must match pattern' + public void transferMoney_DeductsFromSource() {} + + @Test + public void solve6x6_returnsTrue() {} + + @Test // violation below 'Method name 'solve6x6_ReturnsTrue' must match pattern' + public void solve6x6_ReturnsTrue() {} + + @Test + public void solve6x6_noSolution_returnsFalse() {} + + @Test // violation below ''solve6x6_NoSolution_ReturnsFalse' must match pattern' + public void solve6x6_NoSolution_ReturnsFalse() {} + + @Test + public void openMenu_deletePreviousView() {} + + @Test // violation below 'Method name 'openMenu_DeletePreviousView' must match pattern' + public void openMenu_DeletePreviousView() {} + + @Test + public void test_general_logic() {} + + @Test + public void test_General_Logic() {} // violation ''test_General_Logic' must match pattern' +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputMemberNameBasic.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputMemberNameBasic.java deleted file mode 100644 index 1a41e9a373cc..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputMemberNameBasic.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.google.checkstyle.test.chapter5naming.rule525nonconstantfieldnames; - -public class InputMemberNameBasic -{ - public int mPublic; //warn - protected int mProtected; //warn - int mPackage; //warn - private int mPrivate; //warn - - public int _public; //warn - protected int prot_ected; //warn - int package_; //warn - private int priva$te; //warn - - public int ppublic; //ok - protected int pprotected; //ok - int ppackage; //ok - private int pprivate; //ok - - int ABC = 0; //warn - final int C_D_E = 0; //warn - - public int $mPublic; //warn - protected int mPro$tected; //warn - int mPackage$; //warn -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputMemberNameSimple.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputMemberNameSimple.java deleted file mode 100644 index e377ef0132c5..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputMemberNameSimple.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.google.checkstyle.test.chapter5naming.rule525nonconstantfieldnames; -import java.io.*; - -final class InputMemberNameSimple -{ - - public static final int badConstant = 2; - - public static final int MAX_ROWS = 2; - - - private int bad$Static = 2; //warn - - private static int sum_Created = 0; - - - private int bad_Member = 2; //warn - - private int m = 0; //warn - - protected int m_M = 0; //warn - - - private int[] m$nts = new int[] {1,2, 3, //warn - 4}; - - - public static int sTest1; - - protected static int sTest3; - - static int sTest2; - - - int mTest1; //warn - - public int mTest2; //warn - - public int $mTest2; //warn - - public int mTes$t2; //warn - - public int mTest2$; //warn - - /** test local variables. This Check doesn't verify local variables, only members.*/ - private void localVariables() - { - int a; - int aA; - int a1_a; - int A_A; - int aa2_a; - int _a; - int _aa; - int aa_; - int aaa$aaa; - int $aaaaaa; - int aaaaaa$; - - int aa; - int aaAa1a; - int aaAaaAa2a1; - } - - interface Foo { - public void greet(); - - } - - class InnerClass - { - public static final int badConstant = 2; - - public static final int MAX_ROWS = 2; - - - private int bad$Static = 2; //warn - - private int sum_Created = 0; //warn - - - private int bad_Member = 2; //warn - - private int m = 0; //warn - - protected int m_M = 0; //warn - - - private int[] m$nts = new int[] {1,2, 3, //warn - 4}; - - - int mTest1; //warn - - public int mTest2; //warn - - public int $mTest2; //warn - - public int mTes$t2; //warn - - public int mTest2$; //warn - - void fooMethod() - { - Foo foo = new Foo() { - - int bad$Static = 2; //warn - - int sum_Created = 0; //warn - - - int bad_Member = 2; //warn - - int m = 0; //warn - - int m_M = 0; //warn - - - int[] m$nts = new int[] {1,2, 3, //warn - 4}; - - - int mTest1; //warn - - int mTest2; //warn - - int $mTest2; //warn - - int mTes$t2; //warn - - int mTest2$; //warn - - public void greet() {} - }; - } - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputNonConstantNamesBasic.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputNonConstantNamesBasic.java new file mode 100644 index 000000000000..fb848841bafe --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputNonConstantNamesBasic.java @@ -0,0 +1,29 @@ +package com.google.checkstyle.test.chapter5naming.rule525nonconstantfieldnames; + +/** some javadoc. */ +public class InputNonConstantNamesBasic { + public int mPublic; // violation 'Member name 'mPublic' must match pattern' + protected int mProtected; // violation 'Member name 'mProtected' must match pattern' + int mPackage; // violation 'Member name 'mPackage' must match pattern' + private int mPrivate; // violation 'Member name 'mPrivate' must match pattern' + + public int _public; // violation 'Member name '_public' must match pattern' + protected int prot_ected; // violation 'Member name 'prot_ected' must match pattern' + int package_; // violation 'Member name 'package_' must match pattern' + private int priva$te; // violation 'Member name 'priva\$te' must match pattern' + + public int ppublic; + protected int pprotected; + int ppackage; + private int pprivate; + + int ABC = 0; + // 2 violations above: + // 'Abbreviation in name 'ABC' must contain no more than '1' consecutive capital letters.' + // 'Member name 'ABC' must match pattern' + final int C_D_E = 0; // violation 'Member name 'C_D_E' must match pattern' + + public int $mPublic; // violation 'Member name '\$mPublic' must match pattern' + protected int mPro$tected; // violation 'Member name 'mPro\$tected' must match pattern' + int mPackage$; // violation 'Member name 'mPackage\$' must match pattern' +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputNonConstantNamesSimple.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputNonConstantNamesSimple.java new file mode 100644 index 000000000000..419059700dca --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule525nonconstantfieldnames/InputNonConstantNamesSimple.java @@ -0,0 +1,109 @@ +package com.google.checkstyle.test.chapter5naming.rule525nonconstantfieldnames; + +final class InputNonConstantNamesSimple { + + public static final int badConstant = 2; + + public static final int MAX_ROWS = 2; + + private int bad$Static = 2; // violation 'Member name 'bad\$Static' must match pattern' + + private static int sum_Created = 0; + + private int bad_Member = 2; // violation 'Member name 'bad_Member' must match pattern' + + private int m = 0; // violation 'Member name 'm' must match pattern' + + protected int m_M = 0; // violation 'Member name 'm_M' must match pattern' + + private int[] m$nts = // violation 'Member name 'm\$nts' must match pattern' + new int[] {1, 2, 3, 4}; + + public static int sTest1; + + protected static int sTest3; + + static int sTest2; + + int mTest1; // violation 'Member name 'mTest1' must match pattern' + + public int mTest2; // violation 'Member name 'mTest2' must match pattern' + + public int $mTest2; // violation 'Member name '\$mTest2' must match pattern' + + public int mTes$t2; // violation 'Member name 'mTes\$t2' must match pattern' + + private void localVariables() { + int a; + int aa; + int aaAa1a; + int aaAaaAa2a1; + } + + interface Foo { + public void greet(); + } + + class InnerClass { + public static final int badConstant = 2; + + public static final int MAX_ROWS = 2; + + private int bad$Static = 2; // violation 'Member name 'bad\$Static' must match pattern' + + private int sum_Created = 0; + // violation above 'Member name 'sum_Created' must match pattern' + + private int bad_Member = 2; // violation 'Member name 'bad_Member' must match pattern' + + private int m = 0; // violation 'Member name 'm' must match pattern' + + protected int m_M = 0; // violation 'Member name 'm_M' must match pattern' + + private int[] m$nts = new int[] {1, 2, 3, 4}; + // violation above 'Member name 'm\$nts' must match pattern' + + int mTest1; // violation 'Member name 'mTest1' must match pattern' + + public int mTest2; // violation 'Member name 'mTest2' must match pattern' + + public int $mTest2; // violation 'Member name '\$mTest2' must match pattern' + + public int mTes$t2; // violation 'Member name 'mTes\$t2' must match pattern' + + public int mTest2$; // violation 'Member name 'mTest2\$' must match pattern' + + void fooMethod() { + Foo foo = + new Foo() { + + int bad$Static = 2; // violation 'Member name 'bad\$Static' must match pattern' + + int sum_Created = 0; + // violation above 'Member name 'sum_Created' must match pattern' + + int bad_Member = 2; + // violation above 'Member name 'bad_Member' must match pattern' + + int m = 0; // violation 'Member name 'm' must match pattern' + + int m_M = 0; // violation 'Member name 'm_M' must match pattern' + + int[] m$nts = new int[] {1, 2, 3, 4}; + // violation above 'Member name 'm\$nts' must match pattern' + + int mTest1; // violation 'Member name 'mTest1' must match pattern' + + int mTest2; // violation 'Member name 'mTest2' must match pattern' + + int $mTest2; // violation 'Member name '\$mTest2' must match pattern' + + int mTes$t2; // violation 'Member name 'mTes\$t2' must match pattern' + + int mTest2$; // violation 'Member name 'mTest2\$' must match pattern' + + public void greet() {} + }; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputCatchParameterName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputCatchParameterName.java new file mode 100644 index 000000000000..d926df9da850 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputCatchParameterName.java @@ -0,0 +1,98 @@ +package com.google.checkstyle.test.chapter5naming.rule526parameternames; + +/** some javadoc. */ +public class InputCatchParameterName { + { + try { + /* foo */ + } catch (Exception e) { + /* foo */ + } + try { + /* foo */ + } catch (Exception ex) { + /* foo */ + } + try { + /* foo */ + } catch (Error | Exception err) { + /* foo */ + } + try { + /* foo */ + } catch (Exception exception) { + /* foo */ + } + try { + /* foo */ + } catch (Exception exception1) { + /* foo */ + } + try { + /* foo */ + } catch (Exception noWorries) { + /* foo */ + } + try { + /* foo */ + } catch (Throwable t) { + /* foo */ + } + try { + throw new InterruptedException("interruptedException"); + } catch (InterruptedException ie) { + /* foo */ + } + try { + /* foo */ + } catch (Exception ok) { + // appropriate to take no action here + } + try { + /* foo */ + } catch (Exception e1) { + try { + /* foo */ + } catch (Exception e2) { + /* foo */ + } + } + try { + /* foo */ + } catch (Throwable t1) { + try { + /* foo */ + } catch (Throwable t2) { + /* foo */ + } + } + try { + /* foo */ + } catch (Exception iException) { + // violation above 'Catch parameter name 'iException' must match pattern' + } + try { + /* foo */ + } catch (Exception ex_1) { // violation 'Catch parameter name 'ex_1' must match pattern' + } + try { + /* foo */ + } catch (Exception eX) { // violation 'Catch parameter name 'eX' must match pattern' + } + try { + /* foo */ + } catch (Exception eXX) { + // 2 violations above: + // 'Abbreviation in name 'eXX' must contain no more than '1' consecutive capital letters.' + // 'Catch parameter name 'eXX' must match pattern' + } + try { + /* foo */ + } catch (Exception x_y_z) { // violation 'Catch parameter name 'x_y_z' must match pattern' + } + try { + /* foo */ + } catch (Exception Ex) { // violation 'Catch parameter name 'Ex' must match pattern' + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputFormattedRecordComponentNameTwo.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputFormattedRecordComponentNameTwo.java new file mode 100644 index 000000000000..3169a637a200 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputFormattedRecordComponentNameTwo.java @@ -0,0 +1,13 @@ +// Java17 + +package com.google.checkstyle.test.chapter5naming.rule526parameternames; + +/** some javadoc. Config: format = "^[a-z]([a-z0-9][a-zA-Z0-9]*)?$" */ +public record InputFormattedRecordComponentNameTwo(int _componentName, String componentName2) {} + +// violation 2 lines above 'Record component name '_componentName' must match pattern' + +record InputRecordComponentName(int Capital) {} +// 2 violations above: +// 'Top-level class InputRecordComponentName has to reside in its own source file.' +// 'Record component name 'Capital' must match pattern' diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputLambdaParameterName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputLambdaParameterName.java index f440cbba237d..c4b7cb22ab8d 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputLambdaParameterName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputLambdaParameterName.java @@ -3,26 +3,29 @@ import java.util.function.BiFunction; import java.util.function.Function; +/** some javadoc. */ public class InputLambdaParameterName { - Function badNamedParameterWithoutParenthesis = - S -> S.trim().toLowerCase(); // warn + Function badNamedParameterWithoutParenthesis = + S -> S.trim().toLowerCase(); // violation 'Lambda parameter name 'S' must match pattern' - Function badNamedParameterWithParenthesis = - (sT) -> sT.trim().toLowerCase(); // warn + Function badNamedParameterWithParenthesis = (sT) -> sT.trim().toLowerCase(); + // violation above 'Lambda parameter name 'sT' must match pattern' - BiFunction twoBadNamedParameters = (sT1, sT2) -> sT1 + sT2; // warn + BiFunction twoBadNamedParameters = (sT1, sT2) -> sT1 + sT2; + // 2 violations above: + // 'Lambda parameter name 'sT1' must match pattern' + // 'Lambda parameter name 'sT2' must match pattern' - BiFunction badNamedParameterInBiFunction = - (first, _s) -> first + _s; // warn + BiFunction badNamedParameterInBiFunction = + (first, _s) -> first + _s; // violation 'Lambda parameter name '_s' must match pattern' - Function goodNamedParameterWithoutParenthesis = - notTrimmedString -> notTrimmedString.trim().length(); + Function goodNamedParameterWithoutParenthesis = + notTrimmedString -> notTrimmedString.trim().length(); - Function goodNamedParameterWithParenthesis = - (notTrimmedString) -> notTrimmedString.trim().length(); - - BiFunction goodNamedParameters = - (first, second) -> (first + second).length(); + Function goodNamedParameterWithParenthesis = + (notTrimmedString) -> notTrimmedString.trim().length(); + BiFunction goodNamedParameters = + (first, second) -> (first + second).length(); } diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputParameterName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputParameterName.java index 6a9329f3a8ff..c00ee404dba0 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputParameterName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputParameterName.java @@ -1,75 +1,61 @@ package com.google.checkstyle.test.chapter5naming.rule526parameternames; -import java.io.*; - -class InputParameterName -{ - - /** Some more Javadoc. */ - public void doSomething(int aaa, int abn, String aaA, - boolean bB) //warn - { - for (Object O : new java.util.ArrayList()) - { - - } - } -} - - -/** Test enum for member naming check */ -enum MyEnum1 -{ - /** ABC constant */ +class InputParameterName { + + /** Some more Javadoc. */ + public void doSomething( + int aaa, + int abn, + String aaA, + boolean bB) { // violation 'Parameter name 'bB' must match pattern' + for (Object obj : new java.util.ArrayList()) {} + } + + /** Test enum for member naming check. */ + enum MyEnum1 { + /** ABC constant. */ ABC, - /** XYZ constant */ + /** XYZ constant. */ XYZ; - /** Should be mSomeMember */ + /** Should be mSomeMember. */ private int someMember; - public void doEnum(int aaaL, - long llll_llll, //warn - boolean bB) {} //warn -} + public void doEnum( + int aaaL, + long llll_llll, // violation 'Parameter name 'llll_llll' must match pattern' + boolean bB) {} // violation 'Parameter name 'bB' must match pattern' + } -/** Test public vs private method parameter naming check. */ -class InputParameterNameSimplePub -{ - /** Valid: public and more than one char Long */ - public void a(int par, int parA) {} + /** Test public vs private method parameter naming check. */ + class InputParameterNameSimplePub { + public void testing0(int par, int parA) {} - /** Invalid: public and one char long */ - public void b(int p) {} + public void testing1(int p) {} - /** Valid: private and one char long. */ - private void c(int p) {} - - /** Holder for inner anonymous classes */ - private void d(int param) { - new Object() { - /** Invalid: public and one char long. */ - public void e(int p) { } - }; + /** Holder for inner anonymous classes. */ + private void testing2(int param) { + new Object() { + public void testing3(int p) {} + }; } - /** Invalid: public constructor and one char long */ - public InputParameterNameSimplePub(int p) { } + /** Invalid: public constructor and one char long. */ + public InputParameterNameSimplePub(int p) {} - /** Valid: private constructor and one char long */ - private InputParameterNameSimplePub(float p) { } + /** Valid: private constructor and one char long. */ + private InputParameterNameSimplePub(float p) {} void toManyArgs( - int $arg1, //warn - int ar$g2, //warn - int arg3$, //warn - int a_rg4, //warn - int _arg5, //warn - int arg6_, //warn - int aArg7, //warn - int aArg8, //warn - int aar_g) //warn - - {} + int $arg1, // violation 'Parameter name .* must match pattern' + int ar$g2, // violation 'Parameter name .* must match pattern' + int arg3$, // violation 'Parameter name .* must match pattern' + int a_rg4, // violation 'Parameter name 'a_rg4' must match pattern' + int _arg5, // violation 'Parameter name '_arg5' must match pattern' + int arg6_, // violation 'Parameter name 'arg6_' must match pattern' + int aArg7, // violation 'Parameter name 'aArg7' must match pattern' + int aArg8, // violation 'Parameter name 'aArg8' must match pattern' + int aar_g) {} // violation 'Parameter name 'aar_g' must match pattern' + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputRecordComponentNameTwo.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputRecordComponentNameTwo.java new file mode 100644 index 000000000000..7b4139c3c4bb --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule526parameternames/InputRecordComponentNameTwo.java @@ -0,0 +1,17 @@ +// Java17 + +package com.google.checkstyle.test.chapter5naming.rule526parameternames; + +/** + * some javadoc. + * Config: + * format = "^[a-z]([a-z0-9][a-zA-Z0-9]*)?$" + * + */ +public record InputRecordComponentNameTwo(int _componentName, String componentName2) {} +// violation above 'Record component name '_componentName' must match pattern' + +record InputRecordComponentNameVariant(int Capital) {} +// 2 violations above: +// 'Top-level class InputRecordComponentNameVariant has to reside in its own source file.' +// 'Record component name 'Capital' must match pattern' diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputFormattedPatternVariableNameEnhancedInstanceofTestDefault.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputFormattedPatternVariableNameEnhancedInstanceofTestDefault.java new file mode 100644 index 000000000000..b959e4a21472 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputFormattedPatternVariableNameEnhancedInstanceofTestDefault.java @@ -0,0 +1,97 @@ +// Java17 + +package com.google.checkstyle.test.chapter5naming.rule527localvariablenames; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** some javadoc. */ +public class InputFormattedPatternVariableNameEnhancedInstanceofTestDefault { + private Object obj; + + static boolean doStuff(Object obj) { + return obj instanceof Integer OTHER && OTHER > 0; + // 2 violations above: + // 'Abbreviation in name 'OTHER' must contain no more than '1' consecutive capital letters.' + // 'Pattern variable name 'OTHER' must match pattern' + } + + static { + Object o = ""; + if (o instanceof String s) { + System.out.println(s.toLowerCase(Locale.forLanguageTag(s))); + boolean stringCheck = "test".equals(s); + } + + if (o instanceof Integer Count) { + // violation above 'Pattern variable name 'Count' must match pattern' + int value = Count.byteValue(); + if (Count.equals(value)) { + value = 25; + } + } + } + + interface VoidPredicate { + public boolean get(); + } + + /** some javadoc. */ + public void testing(Object o1, Object o2) { + Object b; + Object c; + if (!(o1 instanceof String aA) + // violation above 'Pattern variable name 'aA' must match pattern' + && (o2 instanceof String a1_a)) { + // violation above 'Pattern variable name 'a1_a' must match pattern' + } + + if (o1 instanceof String A_A + // violation above 'Pattern variable name 'A_A' must match pattern' + || !(o2 instanceof String aa2_a)) { + // violation above 'Pattern variable name 'aa2_a' must match pattern' + } + b = ((VoidPredicate) () -> o1 instanceof String s).get(); + + List arrayList = new ArrayList(); + if (arrayList instanceof ArrayList ai) { + System.out.println("Blah"); + } + + boolean result = + (o1 instanceof String a) ? (o1 instanceof String x) : (!(o1 instanceof String y)); + + // violation below 'Pattern variable name '_a' must match pattern' + if (!(o1 instanceof Integer _a) ? false : _a > 0) { + System.out.println("done"); + } + + { + while (!(o1 instanceof String _aa)) { + // violation above 'Pattern variable name '_aa' must match pattern' + L3: + break L3; + } + while (o1 instanceof String aa_) { + // violation above 'Pattern variable name 'aa_' must match pattern' + aa_.length(); + } + } + + int x = o1 instanceof String aaa$aaa ? aaa$aaa.length() : 2; + // violation above 'Pattern variable name .* must match pattern' + x = !(o1 instanceof String $aaaaaa) ? 2 : $aaaaaa.length(); + // violation above 'Pattern variable name .* must match pattern' + for (; o1 instanceof String aaaaaa$; aaaaaa$.length()) { + // violation above 'Pattern variable name .* must match pattern' + System.out.println(aaaaaa$); + } + + do { + L4: + break L4; + } while (!(o1 instanceof String _A_aa_B)); + // violation above 'Pattern variable name '_A_aa_B' must match pattern' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputLocalVariableNameOneCharVarName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputLocalVariableNameOneCharVarName.java index 495ced314039..0aac9a84cf57 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputLocalVariableNameOneCharVarName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputLocalVariableNameOneCharVarName.java @@ -1,65 +1,66 @@ package com.google.checkstyle.test.chapter5naming.rule527localvariablenames; -import java.io.*; import java.util.HashMap; import java.util.Map; -class InputLocalVariableNameOneCharVarName -{ - public void fooMethod() - { - for(int i = 1; i <10; i++) { //ok - //some code - } +class InputLocalVariableNameOneCharVarName { + /** some javadoc. */ + public void fooMethod() { + for (int i = 1; i < 10; i++) { + // some code + } - int i = 0; // ok + for (int index = 1; index < 10; index++) { + // some code + } - for(int index = 1; index < 10; index++) { //ok - //some code - } + for (int I_ndex = 1; I_ndex < 10; I_ndex++) { + // violation above 'Local variable name 'I_ndex' must match pattern' + // some code + } - for(int I_ndex = 1; I_ndex < 10; I_ndex++) { //warn - //some code - } + int index = 1; - int index = 1; + for (; index < 10; index++) { + // some code + } - for(; index < 10; index++) { //ok - //some code - } + int i = 0; - for(; i < 12; i++) { //ok - //some code - } + for (; i < 12; i++) { + // some code + } - Map map = new HashMap(); + Map map = new HashMap(); - for (Map.Entry e : map.entrySet()) { //ok - //some code - } + for (Map.Entry e : map.entrySet()) { + // some code + } - for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) { //ok - // something - } + int[] b = {1}; + int[][] c = {{1}, {2}}; + for (int a = 0; a < 10; a++) { + // something + } - for(int i_ndex = 1; i_ndex < 10; i_ndex++) { //warn - //some code - } + for (int i_ndex = 1; i_ndex < 10; i_ndex++) { + // violation above 'Local variable name 'i_ndex' must match pattern' + } - for(int ii_i1 = 1; ii_i1 < 10; ii_i1++) { //warn - //some code - } + for (int ii_i1 = 1; ii_i1 < 10; ii_i1++) { + // violation above 'Local variable name 'ii_i1' must match pattern' + } - for(int $index = 1; $index < 10; $index++) { //warn - //some code - } + for (int $index = 1; $index < 10; $index++) { + // violation above 'Local variable name .* must match pattern' + } - for(int in$dex = 1; in$dex < 10; in$dex++) { //warn - //some code - } + for (int in$dex = 1; in$dex < 10; in$dex++) { + // violation above 'Local variable name .* must match pattern' + } - for(int index$ = 1; index$ < 10; index$++) { //warn - //some code - } + for (int index$ = 1; index$ < 10; index$++) { + // violation above 'Local variable name .* must match pattern' } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputLocalVariableNameSimple.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputLocalVariableNameSimple.java index fb1440cdb583..a4cc7681b10b 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputLocalVariableNameSimple.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputLocalVariableNameSimple.java @@ -1,43 +1,40 @@ package com.google.checkstyle.test.chapter5naming.rule527localvariablenames; -final class InputLocalVariableNameSimple -{ - public static final int badConstant = 2; - - public static final int MAX_ROWS = 2; - - private static int badStatic = 2; - - private static int sNumCreated = 0; - - private int badMember = 2; - - private int mNumCreated1 = 0; - - protected int mNumCreated2 = 0; - - private int[] mInts = new int[] {1,2, 3, - 4}; - - /** test local variables */ - private void localVariables() - { - //bad examples - int a; - int aA; //warn - int a1_a; //warn - int A_A; //warn - int aa2_a; //warn - int _a; //warn - int _aa; //warn - int aa_; //warn - int aaa$aaa; //warn - int $aaaaaa; //warn - int aaaaaa$; //warn - - //good examples - int aa; - int aaAa1a; - int aaAaaAa2a1; - } +final class InputLocalVariableNameSimple { + public static final int badConstant = 2; + + public static final int MAX_ROWS = 2; + + private static int badStatic = 2; + + private static int sNumCreated = 0; + + private int badMember = 2; + + private int numCreated1 = 0; + + protected int numCreated2 = 0; + + private int[] ints = new int[] {1, 2, 3, 4}; + + /** test local variables. */ + private void localVariables() { + // bad examples + int a; + int aA; // violation 'Local variable name 'aA' must match pattern' + int a1_a; // violation 'Local variable name 'a1_a' must match pattern' + int A_A; // violation 'Local variable name 'A_A' must match pattern' + int aa2_a; // violation 'Local variable name 'aa2_a' must match pattern' + int _a; // violation 'Local variable name '_a' must match pattern' + int _aa; // violation 'Local variable name '_aa' must match pattern' + int aa_; // violation 'Local variable name 'aa_' must match pattern' + int aaa$aaa; // violation 'Local variable name .* must match pattern' + int $aaaaaa; // violation 'Local variable name .* must match pattern' + int aaaaaa$; // violation 'Local variable name .* must match pattern' + + // good examples + int aa; + int aaAa1a; + int aaAaaAa2a1; + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputPatternVariableNameEnhancedInstanceofTestDefault.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputPatternVariableNameEnhancedInstanceofTestDefault.java new file mode 100644 index 000000000000..4f6578bb9d55 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule527localvariablenames/InputPatternVariableNameEnhancedInstanceofTestDefault.java @@ -0,0 +1,100 @@ +// Java17 + +package com.google.checkstyle.test.chapter5naming.rule527localvariablenames; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** some javadoc. */ +public class InputPatternVariableNameEnhancedInstanceofTestDefault { + private Object obj; + + static boolean doStuff(Object obj) { + return obj instanceof Integer OTHER && OTHER > 0; + // 2 violations above: + // 'Abbreviation in name 'OTHER' must contain no more than '1' consecutive capital letters.' + // 'Pattern variable name 'OTHER' must match pattern' + } + + static { + Object o = ""; + if (o instanceof String s) { + System.out.println(s.toLowerCase(Locale.forLanguageTag(s))); + boolean stringCheck = "test".equals(s); + } + + if (o instanceof Integer Count) { + // violation above 'Pattern variable name 'Count' must match pattern' + int value = Count.byteValue(); + if (Count.equals(value)) { + value = 25; + } + } + } + + interface VoidPredicate { + public boolean get(); + } + + /** some javadoc. */ + public void testing(Object o1, Object o2) { + Object b; + Object c; + if (!(o1 instanceof String aA) + // violation above 'Pattern variable name 'aA' must match pattern' + && (o2 instanceof String a1_a)) { + // violation above 'Pattern variable name 'a1_a' must match pattern' + } + + if (o1 instanceof String A_A + // violation above 'Pattern variable name 'A_A' must match pattern' + || !(o2 instanceof String aa2_a)) { + // violation above 'Pattern variable name 'aa2_a' must match pattern' + } + b = ((VoidPredicate) () -> o1 instanceof String s).get(); + + List arrayList = new ArrayList(); + if (arrayList instanceof ArrayList ai) { + System.out.println("Blah"); + } + + boolean result = + (o1 instanceof String a) ? (o1 instanceof String x) : (!(o1 instanceof String y)); + + // violation below 'Pattern variable name '_a' must match pattern' + if (!(o1 instanceof Integer _a) + ? + false + : _a > 0) { + System.out.println("done"); + } + + { + while (!(o1 instanceof String _aa)) { + // violation above 'Pattern variable name '_aa' must match pattern' + L3: + break L3; + } + while (o1 instanceof String aa_) { + // violation above 'Pattern variable name 'aa_' must match pattern' + aa_.length(); + } + } + + int x = o1 instanceof String aaa$aaa ? aaa$aaa.length() : 2; + // violation above 'Pattern variable name .* must match pattern' + x = !(o1 instanceof String $aaaaaa) ? 2 : $aaaaaa.length(); + // violation above 'Pattern variable name .* must match pattern' + for (; o1 instanceof String aaaaaa$; aaaaaa$.length()) { + // violation above 'Pattern variable name .* must match pattern' + System.out.println(aaaaaa$); + } + + do { + L4: + break L4; + } while (!(o1 instanceof String _A_aa_B)); + // violation above 'Pattern variable name '_A_aa_B' must match pattern' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputClassTypeParameterName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputClassTypeParameterName.java index 923ef2500131..fb4ba949dbcf 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputClassTypeParameterName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputClassTypeParameterName.java @@ -2,45 +2,44 @@ import java.io.Serializable; -class InputClassTypeParameterName //warn -{ - public void foo() { } +class InputClassTypeParameterName { // violation 'Class type name 't' must match pattern' + public void foo() {} - void foo(int i) { - } + void foo(int i) {} } -class Other { //warn +// violation below 'Top-level class Other has to reside in its own source file.' +class Other { + // violation above 'Class type name 'foo' must match pattern' - foo getOne() { + foo getOne() { return null; - } + } - Tfo$o2T getTwo(Tfo$o2T a) { + T getTwo(T a) { return null; - } + } - foo getShadow() { + foo getShadow() { return null; - } + } - static class Junk <$foo> { //warn - <_abc extends $foo> void getMoreFoo() { - } - } + static class Junk<$foo> { // violation 'Class type name '\$foo' must match pattern' + void getMoreFoo() {} + } } -class MoreOther { +// violation below 'Top-level class MoreOther has to reside in its own source file.' +class MoreOther { - void getMore() { - new Other() { - void getMoreFoo() { - } + void getMore() { + new Other() { + void getMoreFoo() {} }; - Other o = new Other() { - void getMoreFoo() { - } + Other o = + new Other() { + void getMoreFoo() {} }; - } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputInterfaceTypeParameterName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputInterfaceTypeParameterName.java index 07969354b28c..28e01ecbb5b6 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputInterfaceTypeParameterName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputInterfaceTypeParameterName.java @@ -2,85 +2,97 @@ import java.io.Serializable; -public class InputInterfaceTypeParameterName -{ - public void foo() { } +/** some javadoc. */ +public class InputInterfaceTypeParameterName { + /** some javadoc. */ + public void foo() {} - void foo(int i) { - } + void foo(int i) {} } -class OtherClass { +// violation below 'Top-level class OtherClass has to reside in its own source file.' +class OtherClass { - foo getOne() { - return null;//comment - } + T getOne() { + return null; // comment + } - /*comment*/Tfo$o2T getTwo(Tfo$o2T a) { - return null; - } + /*comment*/ X getTwo(X a) { + return null; + } - foo getShadow() { - return null; - } + E getShadow() { + return null; + } - static class Junk { - <_fo extends foo> void getMoreFoo() { - } - } + static class Junk { + void getMoreFoo() {} + } } -class MoreOtherClass { +// violation below 'Top-level class MoreOtherClass has to reside in its own source file.' +class MoreOtherClass { - void getMore() { - new Other() { - void getMoreFoo() { - } - }; + void getMore() { + new Other() { + void getMoreFoo() {} + }; -// Other o = new Other() { -// void getMoreFoo() { -// } -// }; - } + // Other o = new Other() { + // void getMoreFoo() { + // } + // }; + } } -interface Boo { // warn - Input boo(); +// violation below 'Top-level class Boo has to reside in its own source file.' +interface Boo { // violation 'Interface type name 'Input' must match pattern' + Input boo(); } +// violation below 'Top-level class FooInterface has to reside in its own source file.' interface FooInterface { - T foo(); + T foo(); } +// violation below 'Top-level class FooInterface2 has to reside in its own source file.' interface FooInterface2 { - Input foo(); + Input foo(); } +// violation below 'Top-level class FooInterface3 has to reside in its own source file.' interface FooInterface3 { - Input foo(); + Input foo(); } +// violation below 'Top-level class FooInterface4 has to reside in its own source file.' interface FooInterface4 { - Input foo(); + Input foo(); } +// violation below 'Top-level class FooInterface5 has to reside in its own source file.' interface FooInterface5 { - Input foo(); + Input foo(); } +// violation below 'Top-level class FooInterface6 has to reside in its own source file.' interface FooInterface6 { - Input foo(); + Input foo(); } -interface FooInterface7 { // warn - Input foo(); +interface FooInterface7 { + // 2 violations above: + // 'Top-level class FooInterface7 has to reside in its own source file.' + // 'Interface type name 'Request' must match pattern' + Input foo(); } -interface FooInterface8 { // warn - Input foo(); +interface FooInterface8 { + // 2 violations above: + // 'Top-level class FooInterface8 has to reside in its own source file.' + // 'Interface type name 'TRequest' must match pattern' + Input foo(); } -class Input { - -} +// violation below 'Top-level class Input has to reside in its own source file.' +class Input {} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputMethodTypeParameterName.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputMethodTypeParameterName.java index a665db6e9a2e..12a3a8105476 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputMethodTypeParameterName.java +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputMethodTypeParameterName.java @@ -2,45 +2,50 @@ import java.io.Serializable; -class InputMethodTypeParameterName -{ - public void foo() { } +class InputMethodTypeParameterName { + public void foo() {} - void foo(int i) { //warn - } + void foo(int i) { // violation 'Method type name 'e_e' must match pattern' + } } -class Other2 { +// violation below 'Top-level class Other2 has to reside in its own source file.' +class Other2 { - foo getOne() { + T getOne() { return null; - } + } - Tfo$o2T getTwo(Tfo$o2T a) { //warn + Tfo$o2T getTwo(Tfo$o2T a) { + // violation above 'Method type name 'Tfo\$o2T' must match pattern' return null; - } + } - foo getShadow() { //warn + T getShadow() { + // violation above 'Method type name 'foo_' must match pattern' return null; - } + } - static class Junk <$foo> { - <_abc extends $foo> void getMoreFoo() { //warn - } + static class Junk { + <_abc extends E> void getMoreFoo() { + // violation above 'Method type name '_abc' must match pattern' } + } } -class MoreOther3 { +// violation below 'Top-level class MoreOther3 has to reside in its own source file.' +class MoreOther3 { - void getMore() { - new Other2() { - void getMoreFoo() { //warn - } + void getMore() { + new Other2() { + void getMoreFoo() { // violation 'Method type name 'T\$' must match pattern' + } }; - Other2 o = new Other2() { - void getMoreFoo() { //warn - } + Other2 o = + new Other2() { + void getMoreFoo() { // violation 'Method type name 'EE' must match pattern' + } }; - } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputRecordTypeParameterNameOne.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputRecordTypeParameterNameOne.java new file mode 100644 index 000000000000..132fdf15a2e8 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule528typevariablenames/InputRecordTypeParameterNameOne.java @@ -0,0 +1,52 @@ +// Java17 + +package com.google.checkstyle.test.chapter5naming.rule528typevariablenames; + +import java.io.Serializable; +import java.util.LinkedHashMap; + +/** some javadoc. Config: pattern = "(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)" */ +public record InputRecordTypeParameterNameOne(Integer x, String str) { + // violation above 'Record type name 't' must match pattern' + /** some javadoc. */ + public void foo() {} + + void foo(int i) {} + + // violation below 'Record type name 'foo' must match pattern' + record Other(LinkedHashMap linkedHashMap) { + + foo getOne() { + return null; // comment + } + + /*comment*/ T getTwo(T a) { + return null; + } + + E getShadow() { + return null; + } + + static record Junk() { // violation 'Record type name 'foo' must match pattern' + void getMoreFoo() {} + } + } + + record MoreOther(char c, String string) { + + interface Boo { + I boo(); + } + + interface FooInterface { + T foo(); + } + + interface FooInterface2 { + I foo(); + } + + record I(int x, int y) {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputAbbreviationAsWordInTypeNameCheck.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputAbbreviationAsWordInTypeNameCheck.java deleted file mode 100644 index 194edde9233e..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputAbbreviationAsWordInTypeNameCheck.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.google.checkstyle.test.chapter5naming.rule53camelcase; - -class InputAbbreviationAsWordInTypeNameCheck { - - int newCustomerId; - - String innerStopwatch; - - boolean supportsIpv6OnIos; - - void XmlHttpRequest() {} - - void YouTubeImporter() {} - - void YoutubeImporter() {} - - class InnerGood { - - int newCustomerId; - - String innerStopwatch; - - boolean supportsIpv6OnIos; - - void XmlHttpRequest() {} - - void YouTubeImporter() {} - - void YoutubeImporter() {} - } - - InputAbbreviationAsWordInTypeNameCheck anonymousGood - = new InputAbbreviationAsWordInTypeNameCheck() { - - int newCustomerId; - - String innerStopwatch; - - boolean supportsIpv6OnIos; - - void XmlHttpRequest() {} - - void YouTubeImporter() {} - - void YoutubeImporter() {} - }; -} - -class AbbreviationsIncorrect { - - int newCustomerID; - - boolean supportsIPv6OnIOS; //warn - - void XMLHTTPRequest() {} //warn - - class InnerBad { - - int newCustomerID; - - boolean supportsIPv6OnIOS; //warn - - void XMLHTTPRequest() {} //warn - } - - InputAbbreviationAsWordInTypeNameCheck anonymousBad - = new InputAbbreviationAsWordInTypeNameCheck() { - - int newCustomerID; - - boolean supportsIPv6OnIOS; //warn - - void XMLHTTPRequest() {} //warn - }; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputCamelCaseDefined.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputCamelCaseDefined.java new file mode 100644 index 000000000000..0d87bd88603f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputCamelCaseDefined.java @@ -0,0 +1,99 @@ +package com.google.checkstyle.test.chapter5naming.rule53camelcase; + +class InputCamelCaseDefined { + + int newCustomerId; + + String innerStopwatch; + + boolean supportsIpv6OnIos; + + void XmlHttpRequest() {} + // violation above 'Method name 'XmlHttpRequest' must match pattern' + + void YouTubeImporter() {} + // violation above 'Method name 'YouTubeImporter' must match pattern' + + void YoutubeImporter() {} + // violation above 'Method name 'YoutubeImporter' must match pattern' + + class InnerGood { + + int newCustomerId; + + String innerStopwatch; + + boolean supportsIpv6OnIos; + + void XmlHttpRequest() {} + // violation above 'Method name 'XmlHttpRequest' must match pattern' + + void YouTubeImporter() {} + // violation above 'Method name 'YouTubeImporter' must match pattern' + + void YoutubeImporter() {} + // violation above 'Method name 'YoutubeImporter' must match pattern' + } + + InputCamelCaseDefined anonymousGood = + new InputCamelCaseDefined() { + + int newCustomerId; + + String innerStopwatch; + + boolean supportsIpv6OnIos; + + void XmlHttpRequest() {} + // violation above 'Method name 'XmlHttpRequest' must match pattern' + + void YouTubeImporter() {} + // violation above 'Method name 'YouTubeImporter' must match pattern' + + void YoutubeImporter() {} + // violation above 'Method name 'YoutubeImporter' must match pattern' + }; + + class AbbreviationsIncorrect { + + int newCustomerID; + // violation above 'newCustomerID.* more than '1' .* capital letters.' + + boolean supportsIPv6OnIOS; + // violation above 'supportsIPv6OnIOS.* more than '1' .* capital letters.' + + void XMLHTTPRequest() {} + // 2 violations above: + // 'XMLHTTPRequest.* more than '1' .* capital letters.' + // 'Method name 'XMLHTTPRequest' must match pattern' + + class InnerBad { + + int newCustomerID; + // violation above 'newCustomerID.* more than '1' .* capital letters.' + + boolean supportsIPv6OnIOS; + // violation above 'supportsIPv6OnIOS.* more than '1' .* capital letters.' + + void XMLHTTPRequest() {} + // 2 violations above: + // 'XMLHTTPRequest.* more than '1' .* capital letters.' + // 'Method name 'XMLHTTPRequest' must match pattern' + } + + InputCamelCaseDefined anonymousBad = + new InputCamelCaseDefined() { + + int newCustomerID; + // violation above 'newCustomerID.* more than '1' .* capital letters.' + + boolean supportsIPv6OnIOS; + // violation above 'supportsIPv6OnIOS.* more than '1' .* capital letters.' + + void XMLHTTPRequest() {} + // 2 violations above: + // 'XMLHTTPRequest.* more than '1' .* capital letters.' + // 'Method name 'XMLHTTPRequest' must match pattern' + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputFormattedCamelCaseDefined.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputFormattedCamelCaseDefined.java new file mode 100644 index 000000000000..29904344db20 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputFormattedCamelCaseDefined.java @@ -0,0 +1,110 @@ +package com.google.checkstyle.test.chapter5naming.rule53camelcase; + +class InputFormattedCamelCaseDefined { + + int newCustomerId; + + String innerStopwatch; + + boolean supportsIpv6OnIos; + + void XmlHttpRequest() {} + + // violation 2 lines above 'Method name 'XmlHttpRequest' must match pattern' + + void YouTubeImporter() {} + + // violation 2 lines above 'Method name 'YouTubeImporter' must match pattern' + + void YoutubeImporter() {} + + // violation 2 lines above 'Method name 'YoutubeImporter' must match pattern' + + class InnerGood { + + int newCustomerId; + + String innerStopwatch; + + boolean supportsIpv6OnIos; + + void XmlHttpRequest() {} + + // violation 2 lines above 'Method name 'XmlHttpRequest' must match pattern' + + void YouTubeImporter() {} + + // violation 2 lines above 'Method name 'YouTubeImporter' must match pattern' + + void YoutubeImporter() {} + // violation above 'Method name 'YoutubeImporter' must match pattern' + } + + InputFormattedCamelCaseDefined anonymousGood = + new InputFormattedCamelCaseDefined() { + + int newCustomerId; + + String innerStopwatch; + + boolean supportsIpv6OnIos; + + void XmlHttpRequest() {} + + // violation 2 lines above 'Method name 'XmlHttpRequest' must match pattern' + + void YouTubeImporter() {} + + // violation 2 lines above 'Method name 'YouTubeImporter' must match pattern' + + void YoutubeImporter() {} + // violation above 'Method name 'YoutubeImporter' must match pattern' + }; + + class AbbreviationsIncorrect { + + int newCustomerID; + // violation above 'newCustomerID.* more than '1' .* capital letters.' + + boolean supportsIPv6OnIOS; + + // violation 2 lines above 'supportsIPv6OnIOS.* more than '1' .* capital letters.' + + void XMLHTTPRequest() {} + + // 2 violations 2 lines above: + // 'XMLHTTPRequest.* more than '1' .* capital letters.' + // 'Method name 'XMLHTTPRequest' must match pattern' + + class InnerBad { + + int newCustomerID; + // violation above 'newCustomerID.* more than '1' .* capital letters.' + + boolean supportsIPv6OnIOS; + + // violation 2 lines above 'supportsIPv6OnIOS.* more than '1' .* capital letters.' + + void XMLHTTPRequest() {} + // 2 violations above: + // 'XMLHTTPRequest.* more than '1' .* capital letters.' + // 'Method name 'XMLHTTPRequest' must match pattern' + } + + InputFormattedCamelCaseDefined anonymousBad = + new InputFormattedCamelCaseDefined() { + + int newCustomerID; + // violation above 'newCustomerID.* more than '1' .* capital letters.' + + boolean supportsIPv6OnIOS; + + // violation 2 lines above 'supportsIPv6OnIOS.* more than '1' .* capital letters.' + + void XMLHTTPRequest() {} + // 2 violations above: + // 'XMLHTTPRequest.* more than '1' .* capital letters.' + // 'Method name 'XMLHTTPRequest' must match pattern' + }; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputUnderscoreUsedInNames.java b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputUnderscoreUsedInNames.java new file mode 100644 index 000000000000..e13b7fec4b62 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter5naming/rule53camelcase/InputUnderscoreUsedInNames.java @@ -0,0 +1,168 @@ +package com.google.checkstyle.test.chapter5naming.rule53camelcase; + +import org.junit.jupiter.api.Test; + +/** some javadoc. */ +public class InputUnderscoreUsedInNames { + + private String guava33_4_6; + + private String guava3346; + + private String jdk8_0_392; + + private String jdk80392; + + private String kotlin1_9_24; + + private String kotlin1924; + + private String gradle8_5_1; + + private String gradle851; + + class InnerBad { + int guava_33_4_7; // false-negative, _ between digit and letter + int guava33_4_7; + + int guava33_4_8_; // violation, _ at the end, 'must match pattern' + int guava33_4_8; + + int jdk_8_90; // false-negative, _ between digit and letter + int jdk8_90; + + int jdk8_91_; // violation, _ at the end, 'must match pattern' + int jdk8_91; + + int kotlin_1_9_24; // false-negative, _ between digit and letter + int kotlin1_9_24; + + // violation below, _ not allowed between lowercase character sequences, 'pattern' + int kotlin_version1_9_24; + + int kotlinVersion1_9_24; + + int kotlin1_9_25_; // violation, _ at the end, 'must match pattern' + int kotlin1_9_25; + } + + static class MultipartVersioningNamesBad { + + void guava_34_4_6() {} // false-negative, _ between digit and letter + + void guava34_4_6() {} + + void kotlin_2_9_94() {} // false-negative, _ between digit and letter + + void kotlin2_9_94() {} + + void gradle_9_5_1() {} // false-negative, _ between digit and letter + + void gradle9_5_1() {} + + void jdk_9_0_392() {} // false-negative, _ between digit and letter + + void jdk9_0_392() {} + + // violation below, _ not allowed between lowercase character sequences, 'pattern' + void kotlin_lang1_9_2() {} + + void kotlinLang1_9_2() {} + + void convertToKotlinVersion1_9_24() {} + + // violation below, _ not allowed between lowercase character sequences, 'pattern' + void jdk_method8_90() {} + + void jdk_Method8_90() {} // violation, uppercase letter after _, 'must match pattern' + + void jdkMethod8_90() {} + + // violation below, _ not allowed between lowercase character sequences, 'pattern' + void guava_version33_4_2() {} + + void guava_Version33_4_2() {} // violation, uppercase letter after _, 'match pattern' + + void guavaVersion33_4_2() {} + + void kotlin1_9_24_() {} // violation, _ at the end, 'must match pattern' + + void kotlin1_9_24() {} + + void guava_33_4_5_() {} // violation, _ at the end, 'must match pattern' + + void guava33_4_5() {} + } + + class UnderscoresInNonTestMethods { + + // violation below, normal method must not use _, 'must match pattern' + void testSetCount_zeroToZero_addSupported() {} + + void testSetCountZeroToZeroAddSupported() {} + + // violation below, normal method must not use _, 'must match pattern' + void testPutNullValue_supported() {} + + void testPutNullValueSupported() {} + + // violation below, normal method must not use _, 'must match pattern' + void testAddAll_nonEmptyList() {} + + void testAddAllNonEmptyList() {} + + // violation below, normal method must not use _, 'must match pattern' + void testEntrySet_hashCode_size1() {} + + void testEntrySetHashCodeSize1() {} + + void testCount_3() {} // false-negative, normal method must not use _ + + void testCount3() {} + } + + class UnderscoreInTestMethodNames { + + @Test + void testSetCount_zeroToZero_addSupported() {} + + @Test + void testsetcount_zerotozero_addsupported() {} + + @Test // violation below, uppercase letter after _, 'must match pattern' + void testSetCount_ZeroToZero_AddSupported() {} + + @Test + void testPutNullValue_supported() {} + + @Test + void testputnullvalue_supported() {} + + @Test // violation below, uppercase letter after _, 'must match pattern' + void testPutNullValue_Supported() {} + + @Test + void testAddAll_nonEmptyList() {} + + @Test + void testaddall_nonemptylist() {} + + @Test + void testAddAll_NonEmptyList() {} // violation, uppercase letter after _, 'pattern' + + @Test + void testEntrySet_hashCode_size1() {} + + @Test + void testentryset_hashcode_size1() {} + + @Test + void testEntrySet_HashCode_Size1() {} // violation, uppercase letter after _, 'pattern' + + @Test + void testCount_3() {} + + @Test + void testCount_number3() {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule61overridealwaysused/InputOverrideAlwaysUsedForRecord.java b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule61overridealwaysused/InputOverrideAlwaysUsedForRecord.java new file mode 100644 index 000000000000..c91fc8d5f0e4 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule61overridealwaysused/InputOverrideAlwaysUsedForRecord.java @@ -0,0 +1,20 @@ +package com.google.checkstyle.test.chapter6programpractice.rule61overridealwaysused; + +import java.util.Locale; + +/** some javadoc. */ +public record InputOverrideAlwaysUsedForRecord(String name, int age) { + + /** some javadoc. */ + public String name() { // false-negative, ok until #17561 + return name.toUpperCase(Locale.ROOT); + } +} + +// violation below 'Top-level class Container has to reside in its own source file' +record Container(String fileName, int port) { + + public int port() { // false-negative, ok until #17561 + return port; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/InputEmptyBlockCatch.java b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/InputEmptyBlockCatch.java deleted file mode 100644 index 3575f33ec5b3..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/InputEmptyBlockCatch.java +++ /dev/null @@ -1,91 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// Test case file for checkstyle. -// Created: 2001 -//////////////////////////////////////////////////////////////////////////////// -package com.google.checkstyle.test.chapter6programpractice.rule62donotignoreexceptions; - -import java.io.*; -import java.awt.Dimension; -import java.awt.Color; - -class InputEmptyBlockCatch { - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} - finally {} //warn - } - - class Inner { - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} - finally {} //warn - } - } - - Inner anon = new Inner(){ - boolean flag; - void doSm() {} - void foo() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) { /* ignore */ } //ok - finally {/* ignore */} //ok - } - - void foo2() { - try { - if (!flag) { - doSm(); - } - } catch (Exception e) {} - finally {} //warn - } - }; - - void bar1() { - try { - if(!flag) { - doSm(); - } - } catch (Exception expected) {} - } - - void bar2() { - try { - if(!flag) { - doSm(); - } - } catch (Exception expected) {} - } -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/InputEmptyFinallyBlock.java b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/InputEmptyFinallyBlock.java new file mode 100644 index 000000000000..e8d1ab294e7d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule62donotignoreexceptions/InputEmptyFinallyBlock.java @@ -0,0 +1,114 @@ +/////////////////////////////////////////////////////////////////////////////////////////////// +// Test case file for checkstyle. +// Created: 2001 +/////////////////////////////////////////////////////////////////////////////////////////////// + +package com.google.checkstyle.test.chapter6programpractice.rule62donotignoreexceptions; + +class InputEmptyFinallyBlock { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + } + } + + class Inner { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + } + } + } + + Inner anon = + new Inner() { + boolean flag; + + void doSm() {} + + void foo() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + /* ignore */ + } + } + + void foo2() { + try { + if (!flag) { + doSm(); + } + } catch (Exception e) { + /* ignore */ + } finally { + } + } + }; + + void bar1() { + try { + if (!flag) { + doSm(); + } + } catch (Exception expected) { + // ignore + } + } + + void bar2() { + try { + if (!flag) { + doSm(); + } + } catch (Exception expected) { + // ignore + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/InputNoFinalizeExtend.java b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/InputNoFinalizeExtend.java index 685a0087383e..ea00b49a6ce3 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/InputNoFinalizeExtend.java +++ b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/InputNoFinalizeExtend.java @@ -2,136 +2,146 @@ class InputNoFinalizeExtend { - public static void doStuff() { - // This method do some stuff - } + public static void doStuff() { + // This method do some stuff + } - protected void finalize() throws Throwable { //warn - try { - doStuff(); - } finally { - super.finalize(); - } + protected void finalize() throws Throwable { // violation 'Avoid using finalizer method.' + try { + doStuff(); + } finally { + super.finalize(); } + } } // negates effect of superclass finalizer +// violation below 'Top-level class EmptyFinalizer has to reside in its own source file.' class EmptyFinalizer { - protected void finalize() throws Throwable { //warn - // empty finalize () - } + protected void finalize() throws Throwable { // violation 'Avoid using finalizer method.' + // empty finalize () + } } // fails to call superclass finalize method +// violation below 'Top-level class WithoutTryCatchFinalizer has to reside in its own source file.' class WithoutTryCatchFinalizer { - public static void doStuff() { - // This method do some stuff - } + public static void doStuff() { + // This method do some stuff + } - protected void finalize() throws Throwable { //warn - doStuff(); - } + protected void finalize() throws Throwable { // violation 'Avoid using finalizer method.' + doStuff(); + } } // public finalizer -class PublicFinalizer { +// violation below 'Top-level class InputPublicFinalizer has to reside in its own source file.' +class InputPublicFinalizer { - public static void doStuff() { - // This method do some stuff - } + public static void doStuff() { + // This method do some stuff + } - public void finalize() throws Throwable { //warn - try { - doStuff(); - } finally { - super.finalize(); - } + public void finalize() throws Throwable { // violation 'Avoid using finalizer method.' + try { + doStuff(); + } finally { + super.finalize(); } + } } // unless (or worse) finalizer -class SuperFinalizer { +// violation below 'Top-level class InputSuperFinalizer has to reside in its own source file.' +class InputSuperFinalizer { - protected void finalize() throws Throwable { //warn - super.finalize(); - } + protected void finalize() throws Throwable { // violation 'Avoid using finalizer method.' + super.finalize(); + } } // public finalizer -class StaticFinalizer { - - public static void doStuff() { - // This method do some stuff - } +// violation below 'Top-level class InputStaticFinalizer has to reside in its own source file.' +class InputStaticFinalizer { - protected void finalize() { //warn - try { - doStuff(); - } finally { + public static void doStuff() { + // This method do some stuff + } - } + protected void finalize() { // violation 'Avoid using finalizer method.' + try { + doStuff(); + } finally { + // do nothing } + } - class InnerFinalizer { - - protected void finalize() { //warn - try { - doStuff(); - } finally { + class InnerFinalizer { - } - } + protected void finalize() { // violation 'Avoid using finalizer method.' + try { + doStuff(); + } finally { + // do nothing + } } + } } +// violation below 'Top-level class WithoutFinalize has to reside in its own source file.' class WithoutFinalize { - public void doStuff() { - // This method do some stuff - } + public void doStuff() { + // This method do some stuff + } - public void finalizeMe() { - // This method do some stuff - } + public void finalizeMe() { + // This method do some stuff + } - public void doFinalize() { - // This method do some stuff - } + public void doFinalize() { + // This method do some stuff + } } +// violation below 'Top-level class WithoutMethods has to reside in its own source file.' class WithoutMethods {} +// violation below 'Top-level class WithAnonymousClass has to reside in its own source file.' class WithAnonymousClass { - public static void doStuff() { - // This method do some stuff - } - - public void foo() { + public static void doStuff() { + // This method do some stuff + } - Ball b = new Ball() { + public void foo() { - public void hit() { - System.identityHashCode("You hit it!"); - } + Ball b = + new Ball() { - protected void finalize() { //warn - try { - doStuff(); - } finally { + public void hit() { + System.identityHashCode("You hit it!"); + } - } + protected void finalize() { // violation 'Avoid using finalizer method.' + try { + doStuff(); + } finally { + // do nothing } + } }; - b.hit(); - } + b.hit(); + } - interface Ball { - void hit(); - } + interface Ball { + void hit(); + } } +// violation below 'Top-level class WithFinalizer has to reside in its own source file.' interface WithFinalizer { - void finalize(); //warn + void finalize(); // violation 'Avoid using finalizer method.' } diff --git a/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/InputNoFinalizer.java b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/InputNoFinalizer.java index 21b0ada0083a..f0f2f9328eb0 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/InputNoFinalizer.java +++ b/src/it/resources/com/google/checkstyle/test/chapter6programpractice/rule64finalizers/InputNoFinalizer.java @@ -1,27 +1,25 @@ package com.google.checkstyle.test.chapter6programpractice.rule64finalizers; -public class InputNoFinalizer -{ - public void finalize() //warn - { - // It's not enough to check if the METHOD_DEF branch contains a PARAMETER_DEF, as that would - // treat this method as having a parameter. - Runnable runnable = new Runnable() { +/** Some javadoc. */ +public class InputNoFinalizer { - public void run() { - reallyFinalize("hi"); - } + /** Some javadoc. */ + public void finalize() { // violation 'Avoid using finalizer method.' + // It's not enough to check if the METHOD_DEF branch contains a PARAMETER_DEF, as that would + // treat this method as having a parameter. + Runnable runnable = + new Runnable() { - // generates a PARAMETER_DEF AST inside the METHOD_DEF of finalize() - private void reallyFinalize(String s) - { - } + public void run() { + reallyFinalize("hi"); + } + + // generates a PARAMETER_DEF AST inside the METHOD_DEF of finalize() + private void reallyFinalize(String s) {} }; - runnable.run(); - } + runnable.run(); + } - // should not be reported by NoFinalizer check - public void finalize(String x) - { - } + /** should not be reported by NoFinalizer check. */ + public void finalize(String x) {} } diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputCorrectJavadocLeadingAsteriskAlignment.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputCorrectJavadocLeadingAsteriskAlignment.java new file mode 100644 index 000000000000..b7a6d746e0f3 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputCorrectJavadocLeadingAsteriskAlignment.java @@ -0,0 +1,98 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** + * This file contains violations, still it is named "Correct" + * because it doesn't contain any violations regarding + * Javadoc's Leading Asterisk Alignments. + * Other violations are kept to ensure that we cover all the edge cases. + */ +public class InputCorrectJavadocLeadingAsteriskAlignment { + + /** javadoc for instance variable. */ + private int int1; + + /** */ // violation "Summary javadoc is missing." + private int int2; + + /***/ // violation "Summary javadoc is missing." + private String str; + + /** */ // violation "Summary javadoc is missing." + private String str1; + + /** + No leading asterisk present. False negative until #17778, Subproblem 2. + */ + public InputCorrectJavadocLeadingAsteriskAlignment() {} + + // violation 2 lines below "Summary javadoc is missing." + // violation 2 lines below "Javadoc tag '@param' should be preceded with an empty line." + /*** + * @param a testing.... + */ + public InputCorrectJavadocLeadingAsteriskAlignment(int a) {} + + /************************************************* + *** @param str testing..... + **********************************/ + // False negative for above javadoc, until #17778, Subproblem 1 & 3. + public InputCorrectJavadocLeadingAsteriskAlignment(String str) {} + + /** * */ // violation "Summary javadoc is missing." + private String str2; + + /****/ // violation "Summary javadoc is missing." + private String str3; + + /** + * This method does nothing. + */ + private void foo() {} + + /** Opening tag should be alone on line. // False negative until #17778, Subproblem 1. + * This method does nothing. + */ + private void foo2() {} + + /** + * Javadoc for foo3. + Closing tag should be alone on line. */ // False negative until #17778, Subproblem 3. + private void foo3() { + // foo2 code goes here + } + + /** + * Javadoc for enum. + * */ // False negative until #17778, Subproblem 3. + private enum CorrectJavadocEnum { + // violation 2 lines below "Summary javadoc is missing." + // False negative until #17778, Subproblem 2. + /** + + */ + ONE, + + // False negative until #17778, Subproblem 2. + /** + Not allowed. No leading asterisk present. + */ + TWO, + + // False negative until #17778, Subproblem 1 & 2. + /** Not allowed. Opening javadoc tag should be alone on line. + + */ + THREE, + + // False negative until #17778, Subproblem 3. + /** + * Not allowed. Closing javadoc tag should be alone on line. */ + FOUR, + + // violation below "Summary javadoc is missing." + /** + + */ + FIVE + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedCorrectJavadocLeadingAsteriskAlignment.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedCorrectJavadocLeadingAsteriskAlignment.java new file mode 100644 index 000000000000..3868f93a4d1e --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedCorrectJavadocLeadingAsteriskAlignment.java @@ -0,0 +1,88 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** + * This file contains violations, still it is named "Correct" because it doesn't contain any + * violations regarding Javadoc's Leading Asterisk Alignments. Other violations are kept to ensure + * that we cover all the edge cases. + */ +public class InputFormattedCorrectJavadocLeadingAsteriskAlignment { + + /** javadoc for instance variable. */ + private int int1; + + /** */ + // violation above "Summary javadoc is missing." + private int int2; + + /***/ + // violation above "Summary javadoc is missing." + private String str; + + /** */ + // violation above "Summary javadoc is missing." + private String str1; + + /** No leading asterisk present. False negative until #17778, Subproblem 2. */ + public InputFormattedCorrectJavadocLeadingAsteriskAlignment() {} + + // violation 2 lines below "Summary javadoc is missing." + // violation 2 lines below "Javadoc tag '@param' should be preceded with an empty line." + /*** + * @param a testing.... + */ + public InputFormattedCorrectJavadocLeadingAsteriskAlignment(int a) {} + + /************************************************* + *** @param str testing..... + **********************************/ + // False negative for above javadoc, until #17778, Subproblem 1 & 3. + public InputFormattedCorrectJavadocLeadingAsteriskAlignment(String str) {} + + /** * */ + // violation above "Summary javadoc is missing." + private String str2; + + /****/ + // violation above "Summary javadoc is missing." + private String str3; + + /** This method does nothing. */ + private void foo() {} + + /** + * Opening tag should be alone on line. // False negative until #17778, Subproblem 1. This method + * does nothing. + */ + private void foo2() {} + + /** Javadoc for foo3. Closing tag should be alone on line. */ + // False negative until #17778, Subproblem 3. + private void foo3() { + // foo2 code goes here + } + + /** Javadoc for enum. */ + // False negative until #17778, Subproblem 3. + private enum CorrectJavadocEnum { + // violation 2 lines below "Summary javadoc is missing." + // False negative until #17778, Subproblem 2. + /** */ + ONE, + + // False negative until #17778, Subproblem 2. + /** Not allowed. No leading asterisk present. */ + TWO, + + // False negative until #17778, Subproblem 1 & 2. + /** Not allowed. Opening javadoc tag should be alone on line. */ + THREE, + + // False negative until #17778, Subproblem 3. + /** Not allowed. Closing javadoc tag should be alone on line. */ + FOUR, + + // violation below "Summary javadoc is missing." + /** */ + FIVE + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedIncorrectJavadocLeadingAsteriskAlignment.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedIncorrectJavadocLeadingAsteriskAlignment.java new file mode 100644 index 000000000000..572b684f13dd --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedIncorrectJavadocLeadingAsteriskAlignment.java @@ -0,0 +1,54 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** Extra violations are kept in this file to cover edge cases. */ +public class InputFormattedIncorrectJavadocLeadingAsteriskAlignment { + /** Javadoc for instance variable. */ + private int age; + + /** Misaligned leading asterisk. */ + private String name; + + /** Javadoc for foo. */ + public void foo() {} + + // violation below "Summary javadoc is missing." + /** */ + public void foo2() {} + + /** Misaligned leading asterisk. */ + public void foo3() {} + + /** Misaligned leading asterisk. */ + public void foo4() {} + + /** Default Constructor. */ + public InputFormattedIncorrectJavadocLeadingAsteriskAlignment() {} + + /** Parameterized Constructor. */ + public InputFormattedIncorrectJavadocLeadingAsteriskAlignment(String a) {} + + /** Misaligned leading asterisk. Inner Class. */ + private static class Inner { + // No leading asterisk present. False-negative until #17778, Subproblem 2 + // violation below "Summary javadoc is missing." + /** */ + private Object obj; + + // violation below "Summary javadoc is missing." + /** + * @param testing Testing...... + */ + void foo(String testing) {} + } + + private enum IncorrectJavadocEnum { + + // violation below "Summary javadoc is missing." + /** */ + ONE, + + // Closing tag should be alone on line. False negative until #17778, subproblem 3 + /** Wrong Alignment. */ + TWO + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnCanonicalConstructorsWithAnnotation.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnCanonicalConstructorsWithAnnotation.java new file mode 100644 index 000000000000..f9576691d977 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnCanonicalConstructorsWithAnnotation.java @@ -0,0 +1,86 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** some javadoc. */ +public class InputFormattedJavadocPositionOnCanonicalConstructorsWithAnnotation { + @interface SizeType { + int max(); + } + + /** + * Maps the ports. + * + * @param from the from param + */ + @SizeType(max = 3) + record Mapping(String from) { + + /** + * The constructor for Mapping. + * + * @param from The source + */ + @SizeType(max = 3) + Mapping(String from) { + this.from = from; + } + } + + /** + * Maps the ports. + * + * @param to the param + */ + @SizeType(max = 3) + public record Mapping2(String to) { + + /** + * The constructor for Mapping. + * + * @param to The source + */ + @SizeType(max = 3) + public Mapping2(String to) { + this.to = to; + } + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + record BindCtor(String from, String to) { + + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + BindCtor(String from, String to) { + this.from = from; + this.to = to; + } + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + public record BindCtor2(String from, String to) { + + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + public BindCtor2(String from, String to) { + this.from = from; + this.to = to; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnCompactConstructorsWithAnnotation.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnCompactConstructorsWithAnnotation.java new file mode 100644 index 000000000000..f3c8f264b391 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnCompactConstructorsWithAnnotation.java @@ -0,0 +1,58 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** Some description. */ +public class InputFormattedJavadocPositionOnCompactConstructorsWithAnnotation { + + @interface SizeType { + int max(); + } + + /** + * Something something. + * + * @param containerPath a path on the container + */ + @SizeType(max = 2) + record BindMount(String containerPath) { + + /** + * Creates a mount. + * + * @param containerPath a path on the container + */ + @SizeType(max = 1) + BindMount {} + } + + /** + * Something something. + * + * @param goPath a path on the container + */ + public record BindMount2(String goPath) { + + /** + * Creates a mount. + * + * @param goPath a path on the container + */ + public BindMount2 {} + } + + /** + * Something something. + * + * @param fileSystem a path on the container + */ + @SizeType(max = 4) + public record MyRecord(String fileSystem) { + + /** + * Creates a mount. + * + * @param fileSystem a path on the container + */ + @SizeType(max = 2) + public MyRecord {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnConstructorInRecord.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnConstructorInRecord.java new file mode 100644 index 000000000000..feb4d9064156 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedJavadocPositionOnConstructorInRecord.java @@ -0,0 +1,78 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** Some description. */ +public class InputFormattedJavadocPositionOnConstructorInRecord { + + /** + * The configuration of a bind mount. + * + * @param containerPath a path on the container + * @param options mounting options + */ + record BindMount(String containerPath, String... options) { + + /** + * Creates a mount. + * + * @param containerPath a path on the container + * @param options mounting options + * @throws NullPointerException if any of the arguments are null + */ + BindMount {} + } + + /** + * The configuration. + * + * @param text the text + */ + public record MyRecord(String text) { + + // violation 3 lines below 'Javadoc comment is placed in the wrong location.' + /** invalid comment. */ + public MyRecord {} + /** invalid comment. */ + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + record Mapping(String from, String to) { + + // violation below 'Javadoc comment is placed in the wrong location.' + /** some javadoc. */ + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + Mapping(String from, String to) { + this.from = from; + this.to = to; + } + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + public record Mapping2(String from, String to) { + + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + public Mapping2(String from, String to) { + this.from = from; + this.to = to; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedRecordClassJavadocPosition.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedRecordClassJavadocPosition.java new file mode 100644 index 000000000000..4d8ae1c1934f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedRecordClassJavadocPosition.java @@ -0,0 +1,71 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** + * The configuration of a bind mount. + * + * @param containerPath a path on the container + * @param options mounting options + */ +public record InputFormattedRecordClassJavadocPosition(String containerPath, String... option) { + + /** + * Creates a mount. + * + * @param containerPath a path on the container + * @param options mounting options + * @throws NullPointerException if any of the arguments are null + */ + public InputFormattedRecordClassJavadocPosition {} + + /** + * The configuration of a bind mount. + * + * @param containerPath a path on the container + */ + record BindMount2(String containerPath) { + + /** + * Creates a mount. + * + * @param containerPath a path on the container + */ + BindMount2 {} + } + + /** + * Maps the ports. + * + * @param from the from param + */ + record Mapping(String from) { + + /** + * The constructor for Mapping. + * + * @param from The source + */ + Mapping(String from) { + this.from = from; + } + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + public record Mapping2(String from, String to) { + + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + public Mapping2(String from, String to) { + this.from = from; + this.to = to; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedSingleLineJavadocAndInvalidJavadocPosition.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedSingleLineJavadocAndInvalidJavadocPosition.java new file mode 100644 index 000000000000..287c2a0340a0 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputFormattedSingleLineJavadocAndInvalidJavadocPosition.java @@ -0,0 +1,222 @@ +package // violation 'package statement should not be line-wrapped.' + // violation below 'Javadoc comment is placed in the wrong location.' + /** invalid javadoc. */ + com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +// violation below 'Javadoc comment is placed in the wrong location.' +/** invalid javadoc. */ +import javax.swing.JFrame; + +/** some javadoc. */ +public class InputFormattedSingleLineJavadocAndInvalidJavadocPosition { + + /** As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)}. */ + void foo1() {} + + /** As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)}. */ + void foo2() {} + + // violation below 'Summary javadoc is missing.' + /** + * @throws CheckstyleException if a problem occurs + */ + void foo3() {} + + /** + * summary. + * + * @throws CheckstyleException if a problem occurs + */ + void foo4() {} + + /** An especially short bit of Javadoc. */ + void foo5() {} + + /** An especially short bit of Javadoc. */ + void foo6() {} + + // violation below 'Summary javadoc is missing.' + /** + * @inheritDoc + */ + void foo7() {} + + /** {@inheritDoc} */ + void foo8() {} + + // violation below 'Summary javadoc is missing.' + /** + * @customTag + */ + void bar() {} + + /** + * summary. + * + *

    Some header

    + * + * {@inheritDoc} {@code bar1} text + */ + void bar2() {} + + // violation below 'Summary javadoc is missing.' + /** + * @customTag href="https://github.com/checkstyle/checkstyle/"text + */ + void bar3() {} + + /** Single line Javadoc that references {@link String}. */ + void bar4() {} + + // violation below 'Summary javadoc is missing.' + /** + * @return in single line javadoc + */ + int bar5() { + return 0; + } + + /** + * summary. + * + * @return in multi line javadoc + */ + int bar6() { + return 0; + } +} + +// violation below 'Javadoc comment is placed in the wrong location.' +/** invalid javadoc. */ +/** valid javadoc. */ +class ExtraInputInvalidJavadocPosition { + // violation above '.* ExtraInputInvalidJavadocPosition has to reside in its own source file.' + // violation below 'Javadoc comment is placed in the wrong location.' + /** invalid javadoc. */ +} + +/** valid javadoc. */ +/* ignore */ +class ExtraInputInvalidJavadocPosition2 { + // violation above '.* ExtraInputInvalidJavadocPosition2 has to reside in its own source file.' + // violation below 'Javadoc comment is placed in the wrong location.' + /** invalid javadoc. */ + static { + /* ignore */ + } + + // violation below 'Javadoc comment is placed in the wrong location.' + /** invalid javadoc. */ + /** valid javadoc. */ + int field1; + + /** valid javadoc. */ + int[] field2; + + /** valid javadoc. */ + public int[] field3; + + /** valid javadoc. */ + @Deprecated int field4; + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + int + /** invalid javadoc. */ + field20; + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + int field21 + /** invalid javadoc. */ + ; + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + @Deprecated + /** invalid javadoc. */ + JFrame frame = new JFrame(); + + void method1() {} + + /** valid javadoc. */ + void method2() {} + + /** valid javadoc. */ + T method3() { + return null; + } + + /** valid javadoc. */ + String[] method4() { + return null; + } + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void + /** invalid javadoc. */ + method20() {} + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method21 + /** invalid javadoc. */ + () {} + + // 2 violations 2 lines above: + // ''method def lparen' has incorrect indentation level 6, expected .* 2.' + // ''(' should be on the previous line.' + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method22( + /** invalid javadoc. */ + ) {} + + // violation 2 lines above ''method def rparen' has incorrect indentation level 6, expected .* 2.' + + // 2 violations 4 lines below: + // '.* indentation should be the same level as line 178.' + // 'Javadoc comment is placed in the wrong location.' + void method23() + /** invalid javadoc. */ + {} + + // violation 2 lines above ''method def lcurly' has incorrect indentation level 6, expected .* 4.' + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method24() { + /** invalid javadoc. */ + } + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method25() { + /** invalid javadoc. */ + int variable; + } +} + +// violation 2 lines below '.* has to reside in its own source file.' +// violation 2 lines below 'Javadoc comment is placed in the wrong location.' +@Deprecated +/** invalid javadoc. */ +class ExtraInputInvalidJavadocPosition3 {} + +// violation 2 lines below '.* has to reside in its own source file.' +/** valid javadoc. */ +@Deprecated +class ExtraInputInvalidJavadocPosition4 {} + +// violation 2 lines below '.* has to reside in its own source file.' +// violation 2 lines below 'Javadoc comment is placed in the wrong location.' +class +/** invalid javadoc. */ +ExtraInputInvalidJavadocPosition5 {} + +// violation 2 lines above '.* has incorrect indentation .* 0, expected .* 4.' + +// violation 2 lines below '.* has to reside in its own source file.' +// violation 2 lines below 'Javadoc comment is placed in the wrong location.' +class ExtraInputInvalidJavadocPosition6 +/** invalid javadoc. */ +{} +/** invalid javadoc. */ +// 2 violations 2 lines above: +// ''class def lcurly' has incorrect indentation level 0, expected level should be 2.' +// ''}' at column 2 should be alone on a line.' +// violation 4 lines above 'Javadoc comment is placed in the wrong location.' diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputIncorrectJavadocLeadingAsteriskAlignment.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputIncorrectJavadocLeadingAsteriskAlignment.java new file mode 100644 index 000000000000..cd0e312a6735 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputIncorrectJavadocLeadingAsteriskAlignment.java @@ -0,0 +1,95 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** +* Extra violations are kept in this file to cover edge cases. + */ +// violation 2 lines above 'Leading asterisk has .* indentation .* 1, expected is 2.' +public class InputIncorrectJavadocLeadingAsteriskAlignment { + /** + * Javadoc for instance variable. + */ + // violation 2 lines above 'Leading asterisk has .* indentation .* 5, expected is 4.' + private int age; + + /** + * Misaligned leading asterisk. + */ + // violation 2 lines above 'Leading asterisk has .* indentation .* 3, expected is 4.' + private String name; + + /** + * Javadoc for foo. + */ + // violation above 'Leading asterisk has .* indentation .* 5, expected is 4.' + public void foo() {} + + // violation below "Summary javadoc is missing." + /** + */ + // violation above 'Leading asterisk has .* indentation .* 3, expected is 4.' + public void foo2() {} + + // violation 2 lines below 'Leading asterisk has .* indentation .* 7, expected is 4.' + /** + * Misaligned leading asterisk. + */ + public void foo3() {} + + // violation 2 lines below 'Leading asterisk has .* indentation .* 1, expected is 4.' + /** +* Misaligned leading asterisk. + */ + public void foo4() {} + + /** + * Default Constructor. + */ + // violation above 'Leading asterisk has .* indentation .* 7, expected is 4.' + public InputIncorrectJavadocLeadingAsteriskAlignment() {} + + /** + * Parameterized Constructor. +*/ + // violation above 'Leading asterisk has .* indentation .* 1, expected is 4.' + public InputIncorrectJavadocLeadingAsteriskAlignment(String a) {} + + // violation 2 lines below 'Leading asterisk has .* indentation .* 7, expected is 4.' + /** + * Misaligned leading asterisk. + * Inner Class. */ + // violation above 'Leading asterisk has .* indentation .* 5, expected is 4.' + private static class Inner { + // No leading asterisk present. False-negative until #17778, Subproblem 2 + // violation below "Summary javadoc is missing." + /** + + */ + // violation above 'Leading asterisk has .* indentation .* 9, expected is 6.' + private Object obj; + + // violation below "Summary javadoc is missing." + /** + * @param testing + * Testing...... + * + */ + // violation 3 lines above 'Leading asterisk has .* indentation .* 8, expected is 6.' + void foo(String testing) {} + } + + private enum IncorrectJavadocEnum { + + // violation below "Summary javadoc is missing." + /** + */ + // violation above 'Leading asterisk has .* indentation .* 4, expected is 6.' + ONE, + + + // Closing tag should be alone on line. False negative until #17778, subproblem 3 + /** + * Wrong Alignment. */ + // violation above 'Leading asterisk has .* indentation .* 7, expected is 6' + TWO + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputInvalidJavadocPosition.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputInvalidJavadocPosition.java deleted file mode 100644 index 0418ae8cc476..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputInvalidJavadocPosition.java +++ /dev/null @@ -1,54 +0,0 @@ -package /** warn */ com.google.checkstyle.test.chapter7javadoc.rule711generalform; - -/** warn */ -import java.lang.String; - -/** warn */ -/** valid */ -class InputInvalidJavadocPosition { - /** warn */ -} -/** valid */ -/* ignore */ -class InputInvalidJavadocPosition2 { - /** warn */ - static { /* ignore */ } - - /** warn */ - /** valid */ - int field1; - /** valid */ - int[] field2; - /** valid */ - public int[] field3; - /** valid */ - @Deprecated int field4; - - int /** warn */ field20; - int field21 /** warn */; - @Deprecated /** warn */ int field22; - - void method1() {} - /** valid */ - void method2() {} - /** valid */ - T method3() { return null; } - /** valid */ - String[] method4() { return null; } - - void /** warn */ method20() {} - void method21 /** warn */ () {} - void method22(/** warn */) {} - void method23() /** warn */ {} - void method24() { /** warn */ } - void method25() { /** warn */ int variable; } -} -@Deprecated -/** warn */ -class InputInvalidJavadocPosition3 {} -/** valid */ -@Deprecated -class InputInvalidJavadocPosition4 {} -class /** warn */ InputInvalidJavadocPosition5 {} -class InputInvalidJavadocPosition6 /** warn */ {} -/** warn */ diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnCanonicalConstructorsWithAnnotation.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnCanonicalConstructorsWithAnnotation.java new file mode 100644 index 000000000000..9315f805c999 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnCanonicalConstructorsWithAnnotation.java @@ -0,0 +1,89 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** some javadoc. */ +public class InputJavadocPositionOnCanonicalConstructorsWithAnnotation { + + @interface SizeType { + int max(); + } + + /** + * Maps the ports. + * + * @param from the from param + */ + @SizeType(max = 3) + record Mapping(String from) { + + /** + * The constructor for Mapping. + * + * @param from The source + */ + @SizeType(max = 3) + Mapping(String from) { + this.from = from; + } + } + + /** + * Maps the ports. + * + * @param to the param + */ + @SizeType(max = 3) + public record Mapping2(String to) { + + /** + * The constructor for Mapping. + * + * @param to The source + */ + @SizeType(max = 3) + public Mapping2(String to) { + this.to = to; + } + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + record BindCtor(String from, String to) { + + // violation below 'Javadoc comment is placed in the wrong location.' + /** some javadoc. */ + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + BindCtor(String from, String to) { + this.from = from; + this.to = to; + } + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + public record BindCtor2(String from, String to) { + + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + public BindCtor2(String from, String to) { + this.from = from; + this.to = to; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnCompactConstructorsWithAnnotation.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnCompactConstructorsWithAnnotation.java new file mode 100644 index 000000000000..a30d6c6e798d --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnCompactConstructorsWithAnnotation.java @@ -0,0 +1,60 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** Some description. */ +public class InputJavadocPositionOnCompactConstructorsWithAnnotation { + + @interface SizeType { + int max(); + } + + /** + * Something something. + * + * @param containerPath a path on the container + */ + @SizeType(max = 2) + record BindMount(String containerPath) { + + /** + * Creates a mount. + * + * @param containerPath a path on the container + */ + @SizeType(max = 1) + BindMount {} + } + + /** + * Something something. + * + * @param goPath a path on the container + */ + public record BindMount2(String goPath) { + + /** + * Creates a mount. + * + * @param goPath a path on the container + */ + public BindMount2 {} + } + + /** + * Something something. + * + * @param fileSystem a path on the container + */ + @SizeType(max = 4) + public record MyRecord(String fileSystem) { + + /** + * Creates a mount. + * + * @param fileSystem a path on the container + */ + @SizeType(max = 2) + public MyRecord {} + /** invalid javadoc.*/ + // violation above 'Javadoc comment is placed in the wrong location.' + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnConstructorInRecord.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnConstructorInRecord.java new file mode 100644 index 000000000000..e6090502d079 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputJavadocPositionOnConstructorInRecord.java @@ -0,0 +1,81 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** + * Some description. + */ +public class InputJavadocPositionOnConstructorInRecord { + + /** + * The configuration of a bind mount. + * + * @param containerPath a path on the container + * @param options mounting options + */ + record BindMount(String containerPath, String... options) { + + /** + * Creates a mount. + * + * @param containerPath a path on the container + * @param options mounting options + * @throws NullPointerException if any of the arguments are null + */ + BindMount { + } + } + + /** + * The configuration. + * + * @param text the text + */ + public record MyRecord(String text) { + + // violation 3 lines below 'Javadoc comment is placed in the wrong location.' + /** invalid comment. */ + public MyRecord {} + /** invalid comment. */ + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + record Mapping(String from, String to) { + + // violation below 'Javadoc comment is placed in the wrong location.' + /** some javadoc. */ + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + Mapping(String from, String to) { + this.from = from; + this.to = to; + } + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + public record Mapping2(String from, String to) { + + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + public Mapping2(String from, String to) { + this.from = from; + this.to = to; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputRecordClassJavadocPosition.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputRecordClassJavadocPosition.java new file mode 100644 index 000000000000..3a3f2d67f378 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputRecordClassJavadocPosition.java @@ -0,0 +1,71 @@ +package com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +/** + * The configuration of a bind mount. + * + * @param containerPath a path on the container + * @param options mounting options + */ +public record InputRecordClassJavadocPosition(String containerPath, String... option) { + + /** + * Creates a mount. + * + * @param containerPath a path on the container + * @param options mounting options + * @throws NullPointerException if any of the arguments are null + */ + public InputRecordClassJavadocPosition {} + + /** + * The configuration of a bind mount. + * + * @param containerPath a path on the container + */ + record BindMount2(String containerPath) { + + /** + * Creates a mount. + * + * @param containerPath a path on the container + */ + BindMount2 {} + } + + /** + * Maps the ports. + * + * @param from the from param + */ + record Mapping(String from) { + + /** + * The constructor for Mapping. + * + * @param from The source + */ + Mapping(String from) { + this.from = from; + } + } + + /** + * Maps the ports. + * + * @param from the from param + * @param to the to param + */ + public record Mapping2(String from, String to) { + + /** + * The constructor for Mapping. + * + * @param from The source + * @param to The destination + */ + public Mapping2(String from, String to) { + this.from = from; + this.to = to; + } + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputSingleLineJavadocAndInvalidJavadocPosition.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputSingleLineJavadocAndInvalidJavadocPosition.java new file mode 100644 index 000000000000..f2fa44312405 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputSingleLineJavadocAndInvalidJavadocPosition.java @@ -0,0 +1,214 @@ +package // violation 'package statement should not be line-wrapped.' + // violation below 'Javadoc comment is placed in the wrong location.' + /** invalid javadoc. */ + com.google.checkstyle.test.chapter7javadoc.rule711generalform; + +// violation below 'Javadoc comment is placed in the wrong location.' +/** invalid javadoc. */ +import javax.swing.JFrame; + +/** some javadoc. */ +public class InputSingleLineJavadocAndInvalidJavadocPosition { + + /** As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)}. */ + void foo1() {} + + /** As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)}. */ + void foo2() {} + + /** @throws CheckstyleException if a problem occurs */ + // 3 violations above: + // 'Javadoc tag '@throws' should be preceded with an empty line.' + // 'Single-line Javadoc comment should be multi-line.' + // 'Summary javadoc is missing.' + void foo3() {} + + /** + * summary. + * + * @throws CheckstyleException if a problem occurs + */ + void foo4() {} + + /** An especially short bit of Javadoc. */ + void foo5() {} + + /** An especially short bit of Javadoc. */ + void foo6() {} + + // 3 violations 4 lines below: + // 'Javadoc tag '@inheritDoc' should be preceded with an empty line.' + // 'Single-line Javadoc comment should be multi-line.' + // 'Summary javadoc is missing.' + /** @inheritDoc */ + void foo7() {} + + /** {@inheritDoc} */ + void foo8() {} + + // 3 violations 4 lines below: + // 'Javadoc tag '@customTag' should be preceded with an empty line.' + // 'Single-line Javadoc comment should be multi-line.' + // 'Summary javadoc is missing.' + /** @customTag */ + void bar() {} + + /** + * summary. + * + *

    Some header

    + * + * {@inheritDoc} {@code bar1} text + */ + void bar2() {} + + // 3 violations 4 lines below: + // 'Javadoc tag '@customTag' should be preceded with an empty line.' + // 'Single-line Javadoc comment should be multi-line.' + // 'Summary javadoc is missing.' + /** @customTag href="https://github.com/checkstyle/checkstyle/"text */ + void bar3() {} + + /** Single line Javadoc that references {@link String}. */ + void bar4() {} + + // 3 violations 4 lines below: + // 'Javadoc tag '@return' should be preceded with an empty line.' + // 'Single-line Javadoc comment should be multi-line.' + // 'Summary javadoc is missing.' + /** @return in single line javadoc */ + int bar5() { + return 0; + } + + /** + * summary. + * + * @return in multi line javadoc + */ + int bar6() { + return 0; + } +} + +// violation below 'Javadoc comment is placed in the wrong location.' +/** invalid javadoc. */ +/** valid javadoc. */ +class InputInvalidJavadocPosition { + // violation above '.* InputInvalidJavadocPosition has to reside in its own source file.' + // violation below 'Javadoc comment is placed in the wrong location.' + /** invalid javadoc. */ +} + +/** valid javadoc. */ +/* ignore */ +class InputInvalidJavadocPosition2 { + // violation above '.* InputInvalidJavadocPosition2 has to reside in its own source file.' + // violation below 'Javadoc comment is placed in the wrong location.' + /** invalid javadoc. */ + static { + /* ignore */ + } + + // violation below 'Javadoc comment is placed in the wrong location.' + /** invalid javadoc. */ + /** valid javadoc. */ + int field1; + + /** valid javadoc. */ + int[] field2; + + /** valid javadoc. */ + public int[] field3; + + /** valid javadoc. */ + @Deprecated int field4; + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + int + /** invalid javadoc. */ + field20; + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + int field21 + /** invalid javadoc. */ + ; + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + @Deprecated + /** invalid javadoc. */ + JFrame frame = new JFrame(); + + void method1() {} + + /** valid javadoc. */ + void method2() {} + + /** valid javadoc. */ + T method3() { + return null; + } + + /** valid javadoc. */ + String[] method4() { + return null; + } + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void + /** invalid javadoc. */ + method20() {} + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method21 + /** invalid javadoc. */ + () {} // violation ''(' should be on the previous line.' + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method22( + /** invalid javadoc. */ + ) {} + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method23() + /** invalid javadoc. */ + {} + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method24() { + /** invalid javadoc. */ + } + + // violation 2 lines below 'Javadoc comment is placed in the wrong location.' + void method25() { + /** invalid javadoc. */ + int variable; + } +} + +// violation 2 lines below '.* InputInvalidJavadocPosition3 has to reside in its own source file.' +// violation 2 lines below 'Javadoc comment is placed in the wrong location.' +@Deprecated +/** invalid javadoc. */ +class InputInvalidJavadocPosition3 {} + +// violation 2 lines below '.* InputInvalidJavadocPosition4 has to reside in its own source file.' +/** valid javadoc. */ +@Deprecated +class InputInvalidJavadocPosition4 {} + +// violation 2 lines below '.* InputInvalidJavadocPosition5 has to reside in its own source file.' +// violation 2 lines below 'Javadoc comment is placed in the wrong location.' +class +/** invalid javadoc. */ +InputInvalidJavadocPosition5 {} +// violation above ''InputInvalidJavadocPosition5' has incorrect indentation .* 0, expected .* 4.' + +// violation 2 lines below '.* InputInvalidJavadocPosition6 has to reside in its own source file.' +// violation 2 lines below 'Javadoc comment is placed in the wrong location.' +class InputInvalidJavadocPosition6 + /** invalid javadoc. */ + {} +/** invalid javadoc. */ +// violation 2 lines above''}' at column 4 should be alone on a line.' +// violation 2 lines above 'Javadoc comment is placed in the wrong location.' diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputSingleLineJavadocCheck.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputSingleLineJavadocCheck.java deleted file mode 100644 index f72f785b1aae..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule711generalform/InputSingleLineJavadocCheck.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.google.checkstyle.test.chapter7javadoc.rule711generalform; - -class InputSingleLineJavadocCheck{ - - /** As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)} */ //warn - void foo1() {} - - /** - * As of JDK 1.1, replaced by {@link #setBounds(int,int,int,int)} - */ - void foo2() {} - - /** @throws CheckstyleException if a problem occurs */ //warn - void foo3() {} - - /** - * @throws CheckstyleException if a problem occurs - */ - void foo4() {} - - /** An especially short bit of Javadoc. */ - void foo5() {} - - /** - * An especially short bit of Javadoc. - */ - void foo6() {} - - /** @inheritDoc */ //warn - void foo7() {} - - /** {@inheritDoc} */ //warn - void foo8() {} - - /** @customTag */ //warn - void bar() {} - - /**

    Some header

    {@inheritDoc} {@code bar1} text*/ //warn - void bar2() {} - - /** @customTag href="https://github.com/checkstyle/checkstyle/" text*/ //warn - void bar3() {} -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectJavadocParagraph.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectJavadocParagraph.java new file mode 100644 index 000000000000..23887533fa34 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectJavadocParagraph.java @@ -0,0 +1,130 @@ +package com.google.checkstyle.test.chapter7javadoc.rule712paragraphs; + +/** + * Some Javadoc. + * + *

    Some Javadoc. + */ +class InputCorrectJavadocParagraph { + + /** + * Some Javadoc. + * + *

    {@code function} will never be invoked with a null value. + * + * @since 8.0 + */ + public static final byte NUL = 0; + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    +   * class Foo {
    +   *
    +   *   void foo() {}
    +   * }
    +   * 
    + * + * @see Documentation about GWT emulated source + */ + boolean emulated() { + return false; + } + + /** + * Some Javadoc. + * + *

    Some Javadoc. + */ + class InnerInputCorrectJavaDocParagraphCheck { + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    Some Javadoc. + * + * @since 8.0 + */ + public static final byte NUL = 0; + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + * @see Documentation about GWT emulated source + */ + boolean emulated() { + return false; + } + } + + InnerInputCorrectJavaDocParagraphCheck anon = + new InnerInputCorrectJavaDocParagraphCheck() { + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    Some Javadoc. + * + * @since 8.0 + */ + public static final byte NUL = 0; + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    Some Javadoc. + * + * @see Documentation about GWT emulated source + */ + boolean emulated() { + return false; + } + }; + + /** + * Some summary. + * + *

    testing + * + *

    testing + */ + class InnerPrecedingPtag { + /** + * Some summary. + * + *

    testing + */ + public void foo() {} + + /** + * Some summary. + * + * + * + *

    + * + *
    + */ + public void fooo() {} + + /** + * Some summary. + * + *

    testing... + * + *

    testing...
    + */ + public void foooo() {} + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectJavadocParagraphCheck.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectJavadocParagraphCheck.java deleted file mode 100644 index 708138c0703b..000000000000 --- a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectJavadocParagraphCheck.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.google.checkstyle.test.chapter7javadoc.rule712paragraphs; - -/** - * Some Javadoc. - * - *

    Some Javadoc. - * - */ -class InputCorrectJavadocParagraphCheck { - - /** - * Some Javadoc. - * - *

    {@code function} will never be invoked with a null value. - * - * @since 8.0 - */ - public static final byte NUL = 0; - - /** - * Some Javadoc. - * - *

    Some Javadoc. - * - *

    -     * class Foo {
    -     *
    -     *   void foo() {}
    -     * }
    -     * 
    - * - * @see - * Documentation about GWT emulated source - */ - boolean emulated() {return false;} - - /** - * Some Javadoc. - * - *

    Some Javadoc. - * - */ - class InnerInputCorrectJavaDocParagraphCheck { - - /** - * Some Javadoc. - * - *

    Some Javadoc. - * - *

    Some Javadoc. - * - * @since 8.0 - */ - public static final byte NUL = 0; - - /** - * Some Javadoc. - * - *

    Some Javadoc. - * - * @see - * Documentation about GWT emulated source - */ - boolean emulated() {return false;} - } - - InnerInputCorrectJavaDocParagraphCheck anon = new InnerInputCorrectJavaDocParagraphCheck() { - - /** - * Some Javadoc. - * - *

    Some Javadoc. - * - *

    Some Javadoc. - * - * @since 8.0 - */ - public static final byte NUL = 0; - - /** - * Some Javadoc. - * - *

    Some Javadoc. - * - *

    Some Javadoc. - * - * @see - * Documentation about GWT emulated source - */ - boolean emulated() {return false;} - }; -} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectRequireEmptyLineBeforeBlockTagGroup.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectRequireEmptyLineBeforeBlockTagGroup.java new file mode 100644 index 000000000000..080da0f38eda --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputCorrectRequireEmptyLineBeforeBlockTagGroup.java @@ -0,0 +1,38 @@ +package com.google.checkstyle.test.chapter7javadoc.rule712paragraphs; + +/** + * Some Javadoc. + * + * @since 8.36 + */ +class InputCorrectRequireEmptyLineBeforeBlockTagGroup { + + /** This javadoc does not have a tag. There should be no violations. */ + public static final byte NO_TAG = 0; + + /** + * This Javadoc has one tag, with an empty line. There should be no violations. + * + * @since 8.36 + */ + public static final byte ONE_TAG = 0; + + /** + * This Javadoc has multiple tags, with an empty line before them. There should be no violations. + * + * @param input this is the first tag + * @return this is the second tag + */ + public static boolean test(boolean input) { + return false; + } + + /** + * summary. + * + * @return this only has a tag. + */ + public static boolean test() { + return false; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedCorrectJavadocParagraph.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedCorrectJavadocParagraph.java new file mode 100644 index 000000000000..81bc89fdf4d8 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedCorrectJavadocParagraph.java @@ -0,0 +1,94 @@ +package com.google.checkstyle.test.chapter7javadoc.rule712paragraphs; + +/** + * Some Javadoc. + * + *

    Some Javadoc. + */ +class InputFormattedCorrectJavadocParagraph { + + /** + * Some Javadoc. + * + *

    {@code function} will never be invoked with a null value. + * + * @since 8.0 + */ + public static final byte NUL = 0; + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    +   * class Foo {
    +   *
    +   *   void foo() {}
    +   * }
    +   * 
    + * + * @see Documentation about GWT emulated source + */ + boolean emulated() { + return false; + } + + /** + * Some Javadoc. + * + *

    Some Javadoc. + */ + class InnerInputCorrectJavaDocParagraphCheck { + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    Some Javadoc. + * + * @since 8.0 + */ + public static final byte NUL = 0; + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + * @see Documentation about GWT emulated source + */ + boolean emulated() { + return false; + } + } + + InnerInputCorrectJavaDocParagraphCheck anon = + new InnerInputCorrectJavaDocParagraphCheck() { + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    Some Javadoc. + * + * @since 8.0 + */ + public static final byte NUL = 0; + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    Some Javadoc. + * + * @see Documentation about GWT emulated source + */ + boolean emulated() { + return false; + } + }; +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedCorrectRequireEmptyLineBeforeBlockTagGroup.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedCorrectRequireEmptyLineBeforeBlockTagGroup.java new file mode 100644 index 000000000000..3eeeccbb25b7 --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedCorrectRequireEmptyLineBeforeBlockTagGroup.java @@ -0,0 +1,38 @@ +package com.google.checkstyle.test.chapter7javadoc.rule712paragraphs; + +/** + * Some Javadoc. + * + * @since 8.36 + */ +class InputFormattedCorrectRequireEmptyLineBeforeBlockTagGroup { + + /** This javadoc does not have a tag. There should be no violations. */ + public static final byte NO_TAG = 0; + + /** + * This Javadoc has one tag, with an empty line. There should be no violations. + * + * @since 8.36 + */ + public static final byte ONE_TAG = 0; + + /** + * This Javadoc has multiple tags, with an empty line before them. There should be no violations. + * + * @param input this is the first tag + * @return this is the second tag + */ + public static boolean test(boolean input) { + return false; + } + + /** + * summary. + * + * @return this only has a tag. + */ + public static boolean test() { + return false; + } +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedIncorrectJavadocParagraph.java b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedIncorrectJavadocParagraph.java new file mode 100644 index 000000000000..363297e8109f --- /dev/null +++ b/src/it/resources/com/google/checkstyle/test/chapter7javadoc/rule712paragraphs/InputFormattedIncorrectJavadocParagraph.java @@ -0,0 +1,167 @@ +package com.google.checkstyle.test.chapter7javadoc.rule712paragraphs; + +/** + * Some Javadoc. + * + *

    Some Javadoc. + * + *

    + */ +// violation 2 lines above '

    tag should be placed immediately before the first word' +class InputFormattedIncorrectJavadocParagraph { + + // violation 4 lines below '

    tag should be placed immediately before the first word' + /** + * Some Javadoc. + * + *

    + * + *

    Some Javadoc. + * + * @since 8.0 + */ + public static final byte NUL = 0; + + /** + * Some. + * + *

    Javadoc. + * + *

    Some Javadoc. + * + * @see Documentation about GWT emulated source + */ + boolean emulated() { + return false; + } + + // violation 6 lines below '

    tag should be placed immediately before the first word' + // violation 7 lines below '

    tag should be placed immediately before the first word' + // violation 8 lines below '

    tag should be placed immediately before the first word' + /** + * Some Javadoc. + * + *

    + * + *

    + * + *

    + * + *

    Some Javadoc. + * + *

    + */ + // violation 2 lines above '

    tag should be placed immediately before the first word' + class InnerInputCorrectJavaDocParagraphCheck { + + // violation 4 lines below '

    tag should be placed immediately before the first word' + /** + * Some Javadoc. + * + *

    + * + * @since 8.0 + */ + public static final byte NUL = 0; + + // violation 5 lines below '

    tag should be placed immediately before the first word' + // violation 8 lines below '

    tag should be placed immediately before the first word' + /** + * Some Javadoc. + * + *

    + * + *

    Some Javadoc. + * + *

    + * + * @see Documentation about GWT emulated source + */ + boolean emulated() { + return false; + } + } + + InnerInputCorrectJavaDocParagraphCheck anon = + new InnerInputCorrectJavaDocParagraphCheck() { + + /** + * Some Javadoc. + * + *

    Some Javadoc. + * + * @since 8.0 + */ + public static final byte NUL = 0; + + // violation 4 lines below '

    tag should be placed immediately before the first word' + /** + * Some Javadoc. + * + *

    + * + *

    Some Javadoc. + * + * @see Documentation about + *

    GWT emulated source + */ + boolean emulated() { + return false; + } + }; + + // 2 violations 6 lines below: + // '

    tag should be placed immediately before the first word' + // '

    tag should not precede HTML block-tag '

    '' + /** + * Some summary. + * + *

    + * + *

    Testing...

    + */ + class InnerPrecedingPtag { + + // 2 violations 6 lines below: + // '

    tag should be placed immediately before the first word' + // '

    tag should not precede HTML block-tag '