Giter Site home page Giter Site logo

checkstyle / checkstyle Goto Github PK

View Code? Open in Web Editor NEW
8.1K 8.1K 3.6K 145.17 MB

Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. By default it supports the Google Java Style Guide and Sun Code Conventions, but is highly configurable. It can be invoked with an ANT task and a command line program.

Home Page: https://checkstyle.org

License: GNU Lesser General Public License v2.1

Shell 0.62% Java 98.23% CSS 0.06% JavaScript 0.07% Batchfile 0.01% Perl 0.01% HTML 0.55% Ruby 0.01% ANTLR 0.23% Groovy 0.22% Python 0.01%
code-quality command-line-tool java static-analysis static-code-analysis

checkstyle's Introduction

Checkstyle is a tool for checking Java source code for adherence to a Code Standard or set of validation rules (best practices).

Contributors chat:

The latest release version can be found at GitHub releases or at Maven repo.

Each-commit builds of maven artifacts can be found at Maven Snapshot repository.

Documentation is available in HTML format, see https://checkstyle.org/checks.html.

Build instructions and Contribution

Build instructions

Setup IDE for development

Explanation on how to create your own module

Verification of code quality

Sending Pull Request

Report Issue

Continuous integration and Quality reports

See our CIs statuses.

Quality reports: https://checkstyle.org/project-reports.html

JavaScript, CSS and Java source file analysis on Codacy:

Feedback/Support

Please send any feedback to https://groups.google.com/forum/?hl=en#!forum/checkstyle

Questions and Answers from community:

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:

Licensing

This software is licensed under the terms in the file named "LICENSE" in this directory.

The software uses the ANTLR package (https://www.antlr.org/). Its license terms are in the file named "RIGHTS.antlr" in this directory.

This product includes software developed by The Apache Software Foundation (https://www.apache.org/).

The software uses the Logging and Beanutils packages from the Apache Commons project (https://commons.apache.org/). The license terms of these packages are in the file named "LICENSE.apache20" in this directory.

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.

The software uses the Picocli Library (https://github.com/remkop/picocli/). Its license terms are in the file named "LICENSE.apache20" in this directory.

checkstyle's People

Contributors

alexkravin avatar baratali avatar dependabot-preview[bot] avatar dependabot[bot] avatar gaurabdg avatar github-actions[bot] avatar kevin222004 avatar kietzmann avatar lkuehne avatar manish-k-07 avatar maxvetrenko avatar mezk avatar mkordas avatar nimfadora avatar nrmancuso avatar oburn avatar os97673 avatar pbludov avatar rahulkhinchi03 avatar rdiachenko avatar rnveach avatar romani avatar sabaka avatar shashwatj07 avatar stoyank7 avatar strkkk avatar subkrish avatar vladlis avatar voidfist avatar vyom-yadav avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

checkstyle's Issues

TreeWalker exception on using class for primitives

Created: 2009-07-22
Creator: costamojan
SF issue: 583

Code:

    public boolean isPrimitive2(Class<?> type) {
        return ((boolean.class == type) || (byte.class == type)
                || (char.class == type) || (short.class == type)
                || (int.class == type) || (long.class == type)
                || (float.class == type) || (double.class == type));
    }

Error: TreeWalker: Got an exception - expecting EOF, found '}'

code 2 from SF issue 373:

    public static void main(String[] args)
    {
        Class c = null;

        if (true && (boolean.class.equals(c) ||
boolean.class.equals(c)))
        {
            ;
        }
    }

Allow public fields for immutable classes

Affects: VisibilityModifierCheck

Rationale: Forcing all fields of class to have private modified by default is good in most cases, but it some cases it drawbacks in too much boilerplate get/set code. One of such cases are immutable classes.

Requested:

  • Allow immutable fields to be public.
  • Field is considered to be immutable if it have final modifier and either a primitive type or instance of class known to be immutable (such as String, ImmutableCollection from Guava and etc).
  • Also it is would be nice to check, that class itself is also final.
  • Classes known to be immutable should be listed by their fully qualified name

Example of immutable class that becomes much more concise with public fields

public final class ReportItem {

    public final ImmutableSet<String> includes;
    public final ImmutableSet<String> excludes;
    public final String notes;
    public final BigDecimal value;

    public ReportItem(Collection<String> includes, Collection<String> excludes, BigDecimal value, String notes) {
        this.includes = ImmutableSet.copyOf(includes);
        this.excludes = ImmutableSet.copyOf(excludes);
        this.value = value;
        this.notes = notes;
    }

StackOverflow in com.puppycrawl.tools.checkstyle.checks.regexp.MultilineDetector.findMatch

MultilineDetector.findMatch is a recursive function which will return only if it was not able to find a match. Otherwise it will call itself again which will cause StackOverflow.
There is some check for exceeded number of matches but that check only logs such situation but does not stops the recursion. Probably that check should also break recursion in some way.
Below is Eclipse's stack trace which encountered this problem.
java.lang.StackOverflowError
at java.util.AbstractCollection.toArray(AbstractCollection.java:175)
at com.google.common.collect.ImmutableMap.copyOf(ImmutableMap.java:236)
at com.puppycrawl.tools.checkstyle.DefaultConfiguration.getMessages(DefaultConfiguration.java:144)
at com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter.getCustomMessages(AbstractViolationReporter.java:132)
at com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck.log(AbstractFileSetCheck.java:147)
at com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck.log(AbstractFileSetCheck.java:140)
at com.puppycrawl.tools.checkstyle.checks.regexp.MultilineDetector.findMatch(MultilineDetector.java:83)
at com.puppycrawl.tools.checkstyle.checks.regexp.MultilineDetector.findMatch(MultilineDetector.java:88)
at com.puppycrawl.tools.checkstyle.checks.regexp.MultilineDetector.findMatch(MultilineDetector.java:88)
at com.puppycrawl.tools.checkstyle.checks.regexp.MultilineDetector.findMatch(MultilineDetector.java:88)

Wrong error reporting if class name ends with “Error”

Created: 2008-06-05
Creator: Subhash Chandran
SF issue: 515

http://checkstyle.sourceforge.net/config_design.html#MutableException

I am getting an unexpected checkstyle error in case of class names ending with the word “Error”. The error is “The field must be declared as final”. This error is reported for variables which could not be declared as final. Please see the below class.

package src;

public class SyncError
{
   //Mutable Exception: The field 'message' must be declared final.
   private String message;

}

If I am changing the class name such that it ends with any other string other than “Erorr” then this error is not reported by checkstyle.

Reason: checkstyle does not know anything about Types and their hierarchy. It deduce types by RegExp string to match Class name. Default regexp is "^._Exception$|^._Error$"

this Check will never be correct for that validation. All we could is improve a bit by checking that Class do extends of same name notation class ("an exception type must be a subclass of Throwable") and extend default value with "^.*Throwable$".

checkstyle attempts to analyze nonJava file: src/test/resources/test.html

Checkstyle is trying to analyze some nonJava files in my Maven project.

Trace

$ checkstyle -c checkstyle.xml -r src/
...
/Users/user/Desktop/src/jsoupcrawler/src/test/resources/test.html:4329: Line has trailing spaces.
Audit done.

I tried explicitly constraining the extensions searched, but checkstyle is ignoring this configuration.

$ cat checkstyle.xml
...
    <module name="TreeWalker">
      <property name="fileExtensions" value="java,ejb,jpf" />
...

I suspect that -r is somehow ignoring both the Checkstyle default file name patterns, as well as the XML configuration fileExtension patterns.

System

$ specs brew:checkstyle java os
Specs:

specs 0.4
https://github.com/mcandre/specs#readme

brew list checkstyle
/usr/local/Cellar/checkstyle/5.6/bin/checkstyle
/usr/local/Cellar/checkstyle/5.6/INSTALL_RECEIPT.json
/usr/local/Cellar/checkstyle/5.6/libexec/checkstyle-5.6-all.jar
/usr/local/Cellar/checkstyle/5.6/libexec/sun_checks.xml
/usr/local/Cellar/checkstyle/5.6/LICENSE
/usr/local/Cellar/checkstyle/5.6/README

mvn --version
Apache Maven 3.0.4 (r1232337; 2012-01-17 03:44:56-0500)
Maven home: /usr/share/maven
Java version: 1.6.0_51, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x", version: "10.8.4", arch: "x86_64", family: "mac"

echo $CLASSPATH


echo $JAVA_HOME
/Library/Java/Home

java -version
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-457-11M4509)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-457, mixed mode)

system_profiler SPSoftwareDataType | grep 'System Version'
      System Version: OS X 10.8.4 (12E55)

Unable to use the fileExtensions property

Change default sun_checks.xml to have fileExtensions
http://checkstyle.sourceforge.net/config.html#TreeWalker

<module name="Checker">
    <module name="TreeWalker">
        <property name="fileExtensions" value="java"/>

Prepare folder with pdf file - /home/user/Books.
Execute:

java -cp file:///home/user/java/git-others/checkstyle/target/checkstyle-5.7-SNAPSHOT-all.jar com.puppycrawl.tools.checkstyle.Main -c file:///home/user/java/git-others/checkstyle/sun_checks.xml -r /home/user/Books

Output:
....
/home/user/Books/book-of-vaadin-pocket.pdf:157179: Line has trailing spaces.
...

Created: 2012-12-13
Creator: Flavien Huynh
SF ticket: 691
Reported that it possible to get OutofMemoryError if files are big.

WhitespaceAround, false positive for right curly brace in Annotation

Created: 2013-02-27
Creator: Florian Reiser

http://checkstyle.sourceforge.net/config_whitespace.html#WhitespaceAround
When having the WhitespaceAround test configured in the default configuration, it reports an error for the right curly brace in the following snippet, even though the formatting of the annotation is completely fine. The error message is "There is no whitespace before '}'".
Code:

@Local({Interface1.class, Interface2.class})
public class Implementation implements Interface1, Interface2 {

In my opinion there should be no error in this case, as it is in an annotation (javax.ejb.Local specifically)

More examples:

    @Target({TYPE, FIELD, METHOD, LOCAL_VARIABLE}) //warning
    @SuppressWarnings({"unused", "all"}) //warning
    @SuppressWarnings({ "unused", "all" }) // ok and Eclipse do format like this
    @SuppressWarnings( { "unused", "all" } ) //ok with Check but ugly

It might be "religious" question how to format Annotation declarations, Sun/Oracle and others do that in bit different way, But I think it is reasonable to reconcile that in Checkstyle by option "skipAnnotationBraces" or smth similar

case from Created: 2009-10-07 Creator: Mark Hobson :

@MyAnnotation(myArrayElement = {"a", "b", "c"})

With: "'}' is not preceded with whitespace."

Whereas the same formatting used with array initialisation passes:

String myArrayElement = new String[] {"a", "b", "c"};

JavadocMethod: Javadoc Not Detected Above Multiline Comments

Check: http://checkstyle.sourceforge.net/config_javadoc.html#JavadocMethod

When programming in Java with JML annotations (http://www.jmlspecs.org/), the typical convention is to place the JML annotations - which are, for the purposes of any non-JML-aware tools, specially formatted Java comments - directly above the method they are annotating.

A Javadoc comment also needs to be placed above the method it is documenting. Most Javadoc processing tools (including "javadoc" itself with the standard doclet) have no problem ignoring non-Javadoc comments that occur between the Javadoc comment for a method and the method declaration. However, Checkstyle will fail to detect the Javadoc comment for a method if there is a multi-line (but not a single-line) comment between the Javadoc comment and the method declaration. For example, Checkstyle correctly detects the Javadoc in this case:

/**
 * A Javadoc comment.
 */
//@ A JML Annotation
public void foo() {}

but not in this case:

/**
 * A Javadoc comment.
 */
/*@ A JML Annotation */
public void foo() {} 

It would be very helpful for Checkstyle to be able to detect such Javadoc comments.

Examples of JML JavaDoc: https://sourceforge.net/apps/trac/jmlspecs/browser/TeachingMaterials/trunk/CAV2007Tutorial/examples/Actor.java?rev=2675 (https://sourceforge.net/apps/trac/jmlspecs/wiki/TeachingMaterials)

False positive with GenericWhitespace - Array

Created: 2010-08-04
Creator: markt_asf
SF issue: 617

http://checkstyle.sourceforge.net/config_whitespace.html#GenericWhitespace
The following line incorrectly triggers an error with the GenericWhitespace module

private HashMap<String, Class<?>[]> classCache;

Found when using checkstyle with Apache Tomcat. Specifically:
http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/core/ApplicationContextFacade.java

Second case, warning "Generic Whitespace: '>' is followed by whitespace.":

ListResult<String> result = new ListResult<String>(Collections.<String> emptyList());

Support Double Line Wrap Indentation

I would like to see support (and/or assist in the development of) double-indentation on line-wrapped statements.

Motivation

The Java code style guidelines for open source Android (and Chromium) require double-indentation on line-wraps.

We use 4 space indents for blocks. We never use tabs. When in doubt, be consistent with code around you.

We use 8 space indents for line wraps, including function calls and assignments. For example, this is correct:

Instrument i =
        someLongExpression(that, wouldNotFit, on, one, line);

and this is not correct:

Instrument i =
    someLongExpression(that, wouldNotFit, on, one, line);

http://source.android.com/source/code-style.html#use-spaces-for-indentation

ImportOrder should ignore grouping order in static group as option

Created: 2013-08-16
Creator: David Harkness

http://checkstyle.sourceforge.net/config_imports.html#ImportOrder

When you specify package groupings inside ImportOrder, that same ordering is applied to the single group of static imports. Eclipse's Organize Imports feature, however, sorts all static imports alphabetically within a single group--ignoring the package grouping order. There's no way to synchronize the behavior between the two tools.

For example, using "org,java" produces this in Eclipse:

import static java.Math.abs;
import static org.foo.Bar.*;

import org.foo.Foo;

import java.util.Set;

For maximum flexibility, add an option to control whether or not the static imports (when grouped using "top" and "bottom" option) are sorted normally or according to the package groupings.

PS:
Or perhaps it wants the two static imports above to be separated into groups as well. I cannot tell from the error message. So please make message more exact.

Web site: highlight that Sourceforge will be only Binaries hosting and web site hosting

Add Github icon above sourceforge in left panel. Change text to clearly state that SourceForge will have only binaries hosting.
Reason: https://github.com/blog/1302-goodbye-uploads
http://sourceforge.net/blog/github-projects-downloads-are-welcome/

Oliver want to have information about download count. But I doubt that this information in useful and actual as checkstyle is in Ubuntu repos (http://packages.ubuntu.com/lucid/checkstyle , https://launchpad.net/ubuntu/+source/checkstyle), Maven(http://mvnrepository.com/artifact/checkstyle/checkstyle), we already were asked to put them Mac and Windows unofficial repos.

Web site hosting is not questionable as it is already known and well indexed by all search engines.

Abstract Interface Should not be Allowed in RedundantModifier

Created: 2011-11-18
Creator: bkh
SF issue: 663

When declaring a method 'public abstract interface', the abstract shouldn't be allowed as it is redundant.

Code:

package test;

public abstract interface TestBug { // here we do not have warning
    abstract void foo(); // here we have warning
}

Problem with ClassResolving for RedundantThrowsCheck

Created: 2010-05-21
Creator: Arek Sokołowski
SF issue: 608

Code:

package a.b.c;

public class MyException { }

Code:

package test;

import a.b.c.MyClass;
import a.b.c.MyException;

/**
 * Doc.
 */
public class Asset {
  public final MyClass m() throws MyException {
    MyClass d = new MyClass("aaa");
    return myClass;
  }
}

Launch:
15:18 ~/Temp $ java -cp file:///home/rivanov/java/git-others/checkstyle/target/checkstyle-5.7-SNAPSHOT-all.jar com.puppycrawl.tools.checkstyle.Main -c file:///home/rivanov/java/git-others/checkstyle/sun_checks.xml MyException.java Asset.java
Starting audit...
/home/rivanov/Temp/MyException.java:0: File does not end with a newline.
/home/rivanov/Temp/MyException.java:0: Missing package-info.java file.
/home/rivanov/Temp/MyException.java:3: Missing a Javadoc comment.
/home/rivanov/Temp/MyException.java:3:27: '{' is not followed by whitespace.
/home/rivanov/Temp/MyException.java:3:27: '}' is not preceded with whitespace.
/home/rivanov/Temp/Asset.java:10:3: Missing a Javadoc comment.
/home/rivanov/Temp/Asset.java:10:35: Unable to get class information for MyException.

Unexpected: "Unable to get class information for MyException." from RedundantThrowsCheck (AbstractTypeAwareCheck, ClassResolver).

Nuance: this works fine in EclipseCS 5.6 - looks like problem/feature of ClassLoader.

StrictDuplicateCode trips up on file headers

Created: 2012-12-18
Creator: Yegor Bugayenko
Ref: #sf693
Created: 2009-04-20
Creator: Toby Byron
ref: #sf555

I cannot use the StrictDuplicateCode check because it reports excessive essentially false duplicates.

Specifically, each of my source code files starts with the same file header (a comment that contains a copyright notice and boilerplate relating to the GPL3 license that my code is released under).

Yes, literally speaking, StrictDuplicateCode is correctly finding duplicates here however standard file headers are clearly not what people want to have reported to them.

So, what StrictDuplicateCode needs is to automatically suppress any duplicate comments at the start of files from its reports.

Would be nice to have a property "header" for StrictDuplicateCodeCheck:

IllegalType does not check package/imports of type

SF issue: 530
Creator: Jem Mawson

http://checkstyle.sourceforge.net/config_coding.html#IllegalType

IllegalType will fail on a type with the same classname as an illegal type, without checking the package of that classname.

For example, the fj library at functionaljava.org has fj.data.HashMap. This does not implement java.util.Map and so cannot be declared as a Map.

Checkstyle will consider "HashMap map;" to be an illegal type, because it does not differentiate between fj.data.HashMap and java.util.HashMap.

Exclude some java.util classes from Class Fan out

The purpose of the ClassFanOutComplexityCheck is to ensure that classes don't get too complex and stay easy to maintain. Some classes are excluded from computation by default (like java.lang.*) because every java dev know about them and they don't increase the maintenance.

I'd like to propose to add the Java Collections too (Map, HashMap, List, ArrayList, etc) too since they're part of the language and every java dev know about them too (similar to the String class for example).

These classes are causing unnecessary class fan out violations on code.

Could you please consider excluding them?

See https://sourceforge.net/p/checkstyle/feature-requests/607/

The idea is to exclude the following which should be considered as part of the language now by all developers and thus shouldn't be counted as part of the class fan out:

        mIgnoredClassNames.add("Class");

        // java.util.*
        mIgnoredClassNames.add("Map");
        mIgnoredClassNames.add("List");
        mIgnoredClassNames.add("HashMap");
        mIgnoredClassNames.add("ArrayList");
        mIgnoredClassNames.add("Locale");

Documentation how to patch checkstyle is missing

Created: 2012-10-31
Creator: Markus Liebelt
SF ticker: 686

I would like to send a patch to one of the open checkstyle bugs, but could not find any documentation how to do that. Where is the documentation how to setup an IDE (preferred Eclipse) to develop a patch?

http://checkstyle.sourceforge.net/contributing.html

I tried the following:

Downloaded the binary and source release and tried to setup an Eclipse project with them. I had numerous problems, especially with the class path and the dynamically generated classes.
I do not understand how a build of checkstyle should then be done to test the code.
When I go to the code section, I find there a reference to git ?.

Please provide at least a recipe how to setup a pure Java development environment by providing the essential steps like:

Ensure that Git, Java JDK 1.5/6/7 is installed.
Checkout the current source code from that URL: https://github.com/checkstyle/checkstyle/
Develop the changes
Provide a pull request by ....

Turn on -r recursive by default

It would be helpful if the recursive option -r were on by default, so that commands like:

  • checkstyle -c config.xml .
  • checkstyle -c config.xml src/

Etc., worked out of the box, like JSHint does.

ConstantName module should not raise error on non-constants

I find that often, I have static final fields that are not constants. The best example is a logger (e.g. SLF4J):

private static final Logger log = LoggerFactory.getLogger(MyClass.class);

One could do something like this for a special case:

    <module name="ConstantName">
        <!-- Allow "log" -->
        <property name="format" value="^([A-Z][A-Z0-9]*(_[A-Z0-9]+)*|log)$"/>
    </module>

But this is obviously not very general. Perhaps it could be checked if the constant candidate has a . (dot) after it somewhere in the file?

See also the discussion here: http://stackoverflow.com/questions/1417190/should-a-static-final-logger-be-declared-in-upper-case

Add support for the Java 8 syntax

The upcoming Java 8 has a new language syntax that Checkstyle needs to support. The developer preview is quite stable and language syntax changes are not expected.

Besides that, the new language features might be an opportunity for new checks.

From RomanIvanov: please do "1 question" survey about Java8 support, without registration - https://www.surveymonkey.com/s/MNFHYSJ

SuppressionCommentFilter does not suppress StrictDuplicateCode Warnings

Created: 2012-10-31
Creator: Christoph Böhme
SF issue: 687

The SuppressionCommentFilter does not suppress warnings generated by the StrictDuplicateCode module.

My checkstyle configuration is:

<module name="Checker">
  <module name="TreeWalker">
        <module name="FileContentsHolder"/>
        <module name="AvoidInlineConditionals"/>
  </module>
  <module name="StrictDuplicateCode">
    <property name="min" value="5"/>
  </module>
  <module name="SuppressionCommentFilter"/>
</module>

The AvoidInlineConditionals is only included to verify that suppression is configured correctly.

In the java file checkstyle is disabled using comments:

public class StrictDuplicateCodeTest {

        // CHECKSTYLE:OFF

        public static void main(String[] args) {
                int i = 1;
                i += i == 1 ? 2 : 3;
                /* Some random comments
                 * in order to
                 * produce some
                 * duplicate
                 * code.
                 */
                duplicatedCode(i);
        }

        public static int duplicatedCode(int j) {
                int i = 1;
                i += i == 1 ? 2 : 3;
                /* Some random comments
                 * in order to
                 * produce some
                 * duplicate
                 * code.
                 */
                i += j;
                return i;
        }

        // CHECKSTYLE:ON
}

In my understanding checkstyle should not produce any warnings when checking this file. However, when running checkstyle on the file I get the following output:

java -jar checkstyle-5.6/checkstyle-5.6-all.jar -c checkstyle.xml StrictDuplicateCodeTest.java
Starting audit...
StrictDuplicateCodeTest.java:6: 8 gleiche Zeilen in StrictDuplicateCodeTest.java, beginnend bei Zeile 18
Audit done.

If I remove the two CHECKSTYLE comments from the file then the output also includes two AvoidInlineConditional warnings:

java -jar checkstyle-5.6/checkstyle-5.6-all.jar -c checkstyle.xml StrictDuplicateCodeTest.java
Starting audit...
D:\\StrictDuplicateCodeTest.java:5:29: Der Bedingungsoperator sollte vermieden werden.
D:\\StrictDuplicateCodeTest.java:17:29: Der Bedingungsoperator sollte vermieden werden.
StrictDuplicateCodeTest.java:4: 8 gleiche Zeilen in StrictDuplicateCodeTest.java, beginnend bei Zeile 16
Audit done.

NPathComplexity ignores multi-part boolean expressions

Created: 2008-11-19
Creator: Christian Oetterli
SF issue: 534

The rationale of NPath says that it takes into account also multi-part boolean expressions (http://checkstyle.sourceforge.net/config_metrics.html#NPathComplexity
). This is not the case.
At least PMD reports another NPath value for the method "aMethod2()" below.

public class NPathTest {
// Both = 4
void aMethod1() {
if (true) {
}
if (true) {
}
}
// Checkstyle = 4
// PMD = 6
void aMethod2() {
if (true || true) { // multi-part bool
}
if (true) {
}
}
}

For me PMD is right as we have 6 possible ways.

We have article for NPathComplexity algorithm.

AnnotationsUseStyle yields warning on "({})" of Array types

Created: 2012-07-31
Creator: Bjoern Kimminich
SF issue: 678 (https://sourceforge.net/p/checkstyle/bugs/678/)

There should be an exceptional handling of the meta-annotation @target({}) in the AnnotationsUseStyle check. Currently it is reported as "Annotations cannot have closing parenthesis" when using the closingParens:never option. As this is a meta-exception it should be excluded from the validation.

http://checkstyle.sourceforge.net/config_annotation.html#AnnotationUseStyle

http://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Target.html

Problem with treatment of Arrays, as Checkstyle does not have ability to know type of classes the declared in other files, we could rely only on user to privide us list of Annotations that have Array as values. Default value should be "Target" , option name is closingParensIgnoreList, that contains list of Annotation names separated by coma.

We still come to problem full name usage in code "@java.lang.annotation.Target({})", we can ask user to provide full name, additional analys of imports will be required, to distinguish Target from java.lang and from users Annotaton.

Additionally we need to put on web side description from JavaDoc, do the same for Eclipse CS plugin. We need to add description with code example what does closingParens mean, as took we awile to understand a reason of option.

package test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(value=RetentionPolicy.RUNTIME)
//@SomeAnnotation({ElementType.FIELD, ElementType.METHOD})
@SomeAnnotation({})
//@Target({ElementType.FIELD, ElementType.METHOD})
@Target({})
public @interface MyAnn {

}
package test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface SomeAnnotation  {
    String[] value();
}

Example of error if annotation is "@target()" or "@target":

sh-4.3# javac HelloWorld.java                                                                                                                                    
HelloWorld.java:10: error: annotation @Target is missing a default value for the element 'value'                                                                 
@Target()                                                                                                                                                
^                                                                                                                                                               
1 error  

Remove useless check for java.lang in AbstractClassCouplingCheck

I see in the code of AbstractClassCouplingCheck that java.lang are meant to be excluded:

private boolean isSignificant(String aClassName)
{
    return (aClassName.length() > 0)
            && !mIgnoredClassNames.contains(aClassName)
            && !aClassName.startsWith("java.lang.");
}

However in practice they are not excluded since the class names that are checked do NOT have their full package name computed.
For example "java.lang.Class" gets counted since only "Class" is passed to isSignificant().

This is a a big issue...

Here's the file on which I've traced the issue: https://raw.github.com/xwiki/xwiki-commons/a10d6f9ef079c08ef3fd01dd6c1e2ff2a9cc6120/xwiki-commons-core/xwiki-commons-component/xwiki-commons-component-api/src/main/java/org/xwiki/component/util/ReflectionUtils.java

See https://sourceforge.net/p/checkstyle/bugs/684/

Exception "expecting EOF"

Created: 2011-08-24
Creator: Bjoern Kimminich
SF issue: 652

For the following code the Eclipse Checkstyle Plug-in 5.6 reports a strange error in line 6, the same from command line execution on :
"Folgende Ausnahme ist aufgetreten - expecting EOF, found 'getterMethod'"

public static Method findGetterMethod(Class<?> beanClass, String propertyName, Class<?> propertyType) {
    String getterName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
    Method getterMethod = findMethod(beanClass, getterName, new Class[] {}, propertyType);
    if (getterMethod == null && (boolean.class.equals(propertyType) || Boolean.class.equals(propertyType))) {
        getterName = "is" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
        getterMethod = findMethod(beanClass, getterName, new Class[] {}, propertyType);
    }
    return getterMethod;
}

my test:

22:33 ~/Temp/4 $ java -cp file:///home/rivanov/java/git-others/checkstyle/target/checkstyle-5.7-SNAPSHOT-all.jar com.puppycrawl.tools.checkstyle.Main -c file:///home/rivanov/java/git-others/checkstyle/sun_checks.xml /home/rivanov/workspace-test/test/src/test/CheckStyleErrorTest.java
/home/rivanov/workspace-test/test/src/test/CheckStyleErrorTest.java:13:15: expecting RPAREN, found '.'
/home/rivanov/workspace-test/test/src/test/CheckStyleErrorTest.java:13:21: expecting IDENT, found '.'
/home/rivanov/workspace-test/test/src/test/CheckStyleErrorTest.java:14:21: expecting IDENT, found '.'
Starting audit...
/home/rivanov/workspace-test/test/src/test/CheckStyleErrorTest.java:0: File does not end with a newline.
/home/rivanov/workspace-test/test/src/test/CheckStyleErrorTest.java:7:1: File contains tab characters (this is the first instance).
/home/rivanov/workspace-test/test/src/test/CheckStyleErrorTest.java:13: Line has trailing spaces.
/home/rivanov/workspace-test/test/src/test/CheckStyleErrorTest.java:16:4: Got an exception - expecting EOF, found 'Class'
Audit done.

My File:

package test;

import java.lang.reflect.Method;

public class CheckStyleErrorTest {

    public static void main(String[] args) {
        Class[] classes = new Class[] {};
    }

    public static Method findGetterMethod(Class<?> beanClass,
            String propertyName, Class<?> propertyType, Method getterMethod) {
        if ((boolean.class.equals(propertyType) 
                || Boolean.class.equals(propertyType))) {
            propertyName = "";
            Class[] classes = new Class[] {}; //// Exception is here!!!
        }
        return getterMethod;
    }

    private static Method findMethod(Class<?> beanClass, String getterName,
            Class[] classes, Class<?> propertyType) {
        // TODO Auto-generated method stub
        return null;
    }
}

wrong lineNumber in DetailAST for class with annotation

Code:
Created: 2009-07-14
Creator: superbonbon
SF issue: 581

package src;

@SomeTestAnnotations({ @SomeTestAnnotation(key = "foo"),
        @SomeTestAnnotation(key = "bar") })
/* {@inheritDoc} */
public class MyGenericClassBad {
}

Picture of DetailAST:
screenshotast

detected: lineNumber=3.
expected: lineNumber for class have to be real - 6,

Support JavaDoc and comments in ANTLR grammar

Right now we support JavaDoc as manual parsing and RegExp validation - that is not reliable.
We need to update our ANTLR grammar to support comments (singleline and multiline) and JavaDoc.

FYI:
https://groups.google.com/forum/?hl=en#!topic/checkstyle-devel/vwaV8dc4pYw

Java6 grammar (might be reasonable to combine efforts on grammar creation):
http://www.antlr3.org/grammar/list.html (https://github.com/antlr/grammars-v4)

Do a google , looks like we are not alone, and smth happen outside :).

RequireThisCheck doesn't check methods

I have a class:

public final class This {
    private final int number = 1;

    public int check() {
        int sum = number;
        sum += other();
        return sum;
    }

    private int other() {
        return 0;
    }
}

and in checks I have enabled <module name="RequireThis"/>
Checkstyle correctly prints that number should be called with this. but it doesn't say anything about method call other().

SuppressionsLoader should use thread context class loader

As I can see SuppressionsLoader has been rewritten in 5.7 to properly handle URLs including jar file URLs but there still is a problem loading files from the classpath.

To properly load a suppressions file from classpath, Thread.currentThread().getContextClassLoader() needs to be used instead of SuppressionsLoader.class.getClassLoader() (see line 162).

Without this change checkstyle was unable to load the suppressions file from class path (via SuppressionFilter in xml config) when being executed by maven.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.