Fix PMD dogfood issues in pmd-core

This commit is contained in:
Andreas Dangel
2014-11-15 23:57:03 +01:00
parent 6b0ddaeb51
commit f7f89f2921
68 changed files with 449 additions and 266 deletions

View File

@ -26,13 +26,6 @@ public abstract class AbstractPropertySource implements PropertySource {
/** The values for each property. */
protected Map<PropertyDescriptor<?>, Object> propertyValuesByDescriptor = new HashMap<PropertyDescriptor<?>, Object>();
/**
* Creates a new empty property source.
*/
public AbstractPropertySource() {
super();
}
/**
* Creates a copied list of the property descriptors and returns it.
*

View File

@ -80,7 +80,9 @@ public class PMD {
try {
dataSources.add(new ReaderDataSource(dbmsMetadata.getSourceCode(sourceObject), falseFilePath));
} catch (SQLException ex) {
LOG.log(Level.WARNING, "Cannot get SourceCode for " + falseFilePath + " - skipping ...", ex);
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING, "Cannot get SourceCode for " + falseFilePath + " - skipping ...", ex);
}
}
}
} catch (URISyntaxException e) {
@ -115,8 +117,9 @@ public class PMD {
// TODO Handle Rules having different parser options.
LanguageVersionHandler languageVersionHandler = languageVersion.getLanguageVersionHandler();
ParserOptions options = languageVersionHandler.getDefaultParserOptions();
if (configuration != null)
if (configuration != null) {
options.setSuppressMarker(configuration.getSuppressMarker());
}
return languageVersionHandler.getParser(options);
}
@ -155,8 +158,10 @@ public class PMD {
ruleSets.removeDysfunctionalRules(brokenRules);
for (Rule rule : brokenRules) {
LOG.log(Level.WARNING,
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING,
"Removed misconfigured rule: " + rule.getName() + " cause: " + rule.dysfunctionReason());
}
}
return brokenRules;
@ -210,8 +215,9 @@ public class PMD {
// Load the RuleSets
RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration);
RuleSets ruleSets = RulesetsFactoryUtils.getRuleSetsWithBenchmark(configuration.getRuleSets(), ruleSetFactory);
if (ruleSets == null)
if (ruleSets == null) {
return;
}
Set<Language> languages = getApplicableLanguages(configuration, ruleSets);
List<DataSource> files = getApplicableFiles(configuration, languages);
@ -388,12 +394,15 @@ public class PMD {
for (Rule rule : ruleSets.getAllRules()) {
Language language = rule.getLanguage();
if (languages.contains(language))
if (languages.contains(language)) {
continue;
}
LanguageVersion version = discoverer.getDefaultLanguageVersion(language);
if (RuleSet.applies(rule, version)) {
languages.add(language);
LOG.fine("Using " + language.getShortName() + " version: " + version.getShortName());
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Using " + language.getShortName() + " version: " + version.getShortName());
}
}
}
return languages;

View File

@ -364,8 +364,9 @@ public class PMDConfiguration extends AbstractConfiguration {
public Renderer createRenderer(boolean withReportWriter) {
Renderer renderer = RendererFactory.createRenderer(reportFormat, reportProperties);
renderer.setShowSuppressedViolations(showSuppressedViolations);
if (withReportWriter)
if (withReportWriter) {
renderer.setWriter(IOUtil.createWriter(reportFile));
}
return renderer;
}

View File

@ -322,8 +322,9 @@ public class Report implements Iterable<RuleViolation> {
* @param error the error to add
*/
public void addConfigError(RuleConfigurationError error) {
if (configErrors == null)
if (configErrors == null) {
configErrors = new ArrayList<RuleConfigurationError>();
}
configErrors.add(error);
}
@ -333,8 +334,9 @@ public class Report implements Iterable<RuleViolation> {
* @param error the error to add
*/
public void addError(ProcessingError error) {
if (errors == null)
if (errors == null) {
errors = new ArrayList<ProcessingError>();
}
errors.add(error);
}

View File

@ -309,13 +309,15 @@ public class RuleSet {
Benchmarker.mark(Benchmark.Rule, rule.getName(), end - start, 1);
start = end;
}
} catch (ThreadDeath td) {
throw td;
} catch (Throwable t) {
if (ctx.isIgnoreExceptions()) {
LOG.log(Level.WARNING, "Exception applying rule " + rule.getName()
if (t instanceof ThreadDeath) {
throw (ThreadDeath)t;
} else if (ctx.isIgnoreExceptions()) {
if (LOG.isLoggable(Level.WARNING)) {
LOG.log(Level.WARNING, "Exception applying rule " + rule.getName()
+ " on file " + ctx.getSourceCodeFilename() + ", continuing with next rule",
t);
}
} else {
throw new RuntimeException(t);
}
@ -415,8 +417,9 @@ public class RuleSet {
* @param aPattern the pattern
*/
public void addExcludePattern(String aPattern) {
if (excludePatterns.contains(aPattern))
if (excludePatterns.contains(aPattern)) {
return;
}
excludePatterns.add(aPattern);
patternsChanged();
@ -429,8 +432,9 @@ public class RuleSet {
*/
public void addExcludePatterns(Collection<String> someExcludePatterns) {
int added = CollectionUtil.addWithoutDuplicates(someExcludePatterns, excludePatterns);
if (added > 0)
if (added > 0) {
patternsChanged();
}
}
/**
@ -439,8 +443,9 @@ public class RuleSet {
* @param theExcludePatterns the new patterns
*/
public void setExcludePatterns(Collection<String> theExcludePatterns) {
if (excludePatterns.equals(theExcludePatterns))
if (excludePatterns.equals(theExcludePatterns)) {
return;
}
excludePatterns.clear();
CollectionUtil.addWithoutDuplicates(theExcludePatterns, excludePatterns);
@ -457,9 +462,9 @@ public class RuleSet {
* @param aPattern the pattern
*/
public void addIncludePattern(String aPattern) {
if (includePatterns.contains(aPattern))
if (includePatterns.contains(aPattern)) {
return;
}
includePatterns.add(aPattern);
patternsChanged();
@ -471,10 +476,10 @@ public class RuleSet {
* @param someIncludePatterns the patterns
*/
public void addIncludePatterns(Collection<String> someIncludePatterns) {
int added = CollectionUtil.addWithoutDuplicates(someIncludePatterns, includePatterns);
if (added > 0)
if (added > 0) {
patternsChanged();
}
}
/**
@ -483,9 +488,9 @@ public class RuleSet {
* @param theIncludePatterns the new patterns
*/
public void setIncludePatterns(Collection<String> theIncludePatterns) {
if (includePatterns.equals(theIncludePatterns))
if (includePatterns.equals(theIncludePatterns)) {
return;
}
includePatterns.clear();
CollectionUtil.addWithoutDuplicates(theIncludePatterns, includePatterns);
@ -521,7 +526,6 @@ public class RuleSet {
* @param collector the removed rules will be added to this collection
*/
public void removeDysfunctionalRules(Collection<Rule> collector) {
Iterator<Rule> iter = rules.iterator();
while (iter.hasNext()) {

View File

@ -13,6 +13,7 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
@ -341,8 +342,9 @@ public class RuleSetFactory {
}
String attribute = ruleElement.getAttribute("class");
if ( attribute == null || "".equals(attribute))
if ( attribute == null || "".equals(attribute)) {
throw new IllegalArgumentException("The 'class' field of rule can't be null, nor empty.");
}
Rule rule = (Rule) classLoader.loadClass(attribute).newInstance();
rule.setName(ruleElement.getAttribute("name"));
@ -474,17 +476,23 @@ public class RuleSetFactory {
if (warnDeprecated && referencedRule.isDeprecated()) {
if (referencedRule instanceof RuleReference) {
RuleReference ruleReference = (RuleReference) referencedRule;
LOG.warning("Use Rule name " + ruleReference.getRuleSetReference().getRuleSetFileName() + "/"
if (LOG.isLoggable(Level.WARNING)) {
LOG.warning("Use Rule name " + ruleReference.getRuleSetReference().getRuleSetFileName() + "/"
+ ruleReference.getName() + " instead of the deprecated Rule name " + otherRuleSetReferenceId
+ ". Future versions of PMD will remove support for this deprecated Rule name usage.");
}
} else if (referencedRule instanceof MockRule) {
LOG.warning("Discontinue using Rule name " + otherRuleSetReferenceId
if (LOG.isLoggable(Level.WARNING)) {
LOG.warning("Discontinue using Rule name " + otherRuleSetReferenceId
+ " as it has been removed from PMD and no longer functions."
+ " Future versions of PMD will remove support for this Rule.");
}
} else {
LOG.warning("Discontinue using Rule name " + otherRuleSetReferenceId
if (LOG.isLoggable(Level.WARNING)) {
LOG.warning("Discontinue using Rule name " + otherRuleSetReferenceId
+ " as it is scheduled for removal from PMD."
+ " Future versions of PMD will remove support for this Rule.");
}
}
}

View File

@ -101,15 +101,15 @@ public class Formatter {
}
private static String unknownRendererMessage(String userSpecifiedType) {
StringBuilder sb = new StringBuilder(100);
sb.append("Formatter type must be one of: '");
String[] typeCodes = validRendererCodes();
sb.append(typeCodes[0]);
StringBuilder sb = new StringBuilder(100);
sb.append("Formatter type must be one of: '")
.append(typeCodes[0]);
for (int i = 1; i < typeCodes.length; i++) {
sb.append("', '").append(typeCodes[i]);
}
sb.append("', or a class name; you specified: ");
sb.append(userSpecifiedType);
sb.append("', or a class name; you specified: ")
.append(userSpecifiedType);
return sb.toString();
}

View File

@ -185,7 +185,7 @@ public class Benchmarker {
}
}
private static final Map<String, BenchmarkResult> BenchmarksByName = new HashMap<String, BenchmarkResult>();
private static final Map<String, BenchmarkResult> BENCHMARKS_BY_NAME = new HashMap<String, BenchmarkResult>();
/**
* @param type Benchmark
@ -212,16 +212,16 @@ public class Benchmarker {
} else if (typeName == null) {
typeName = name;
}
BenchmarkResult benchmarkResult = BenchmarksByName.get(typeName);
BenchmarkResult benchmarkResult = BENCHMARKS_BY_NAME.get(typeName);
if (benchmarkResult == null) {
benchmarkResult = new BenchmarkResult(type, typeName);
BenchmarksByName.put(typeName, benchmarkResult);
BENCHMARKS_BY_NAME.put(typeName, benchmarkResult);
}
benchmarkResult.update(time, count);
}
public static void reset() {
BenchmarksByName.clear();
BENCHMARKS_BY_NAME.clear();
}
/**
@ -229,6 +229,6 @@ public class Benchmarker {
* @return Map<String,BenchmarkResult>
*/
public static Map<String, BenchmarkResult> values() {
return BenchmarksByName;
return BENCHMARKS_BY_NAME;
}
}

View File

@ -25,10 +25,6 @@ public class TextReport implements BenchmarkReport {
private static final int NAME_COLUMN_WIDTH = 50;
private static final int VALUE_COLUMN_WIDTH = 8;
public TextReport() {
}
/**
*
* @param stressResults Set<Result>

View File

@ -56,8 +56,9 @@ public class PMDCommandLineInterface {
String allCommandsDescription = null;
if ( jcommander != null && jcommander.getCommands() != null ) {
for ( String command : jcommander.getCommands().keySet() )
for ( String command : jcommander.getCommands().keySet() ) {
allCommandsDescription += jcommander.getCommandDescription(command) + PMD.EOL;
}
}
// TODO: Externalize that to a file available within the classpath ? - with a poor's man templating ?
@ -150,7 +151,9 @@ public class PMDCommandLineInterface {
buf.append(" ").append(property.name()).append(" - ");
buf.append(property.description());
Object deflt = property.defaultValue();
if (deflt != null) buf.append(" default: ").append(deflt);
if (deflt != null) {
buf.append(" default: ").append(deflt);
}
buf.append(PMD.EOL);
}
@ -164,10 +167,11 @@ public class PMDCommandLineInterface {
}
public static void setStatusCodeOrExit(int status) {
if ( isExitAfterRunSet() )
if ( isExitAfterRunSet() ) {
System.exit(status);
else
} else {
setStatusCode(status);
}
}
private static boolean isExitAfterRunSet() {

View File

@ -78,14 +78,15 @@ public class PMDParameters {
// this has to be a public static class, so that JCommander can use it!
public static class PropertyConverter implements IStringConverter<Properties> {
private static final char separator = '=';
private static final char SEPARATOR = '=';
public Properties convert(String value) {
Properties properties = new Properties();
int indexOfSeparator = value.indexOf(separator);
if (indexOfSeparator < 0)
int indexOfSeparator = value.indexOf(SEPARATOR);
if (indexOfSeparator < 0) {
throw new ParameterException(
"Property name must be separated with an = sign from it value: name=value.");
}
String propertyName = value.substring(0, indexOfSeparator);
String propertyValue = value.substring(indexOfSeparator + 1);
properties.put(propertyName, propertyValue);
@ -98,9 +99,10 @@ public class PMDParameters {
public int validate(String value) throws ParameterException {
int minPriorityValue = Integer.parseInt(value);
if (minPriorityValue < 0 || minPriorityValue > 5)
if (minPriorityValue < 0 || minPriorityValue > 5) {
throw new ParameterException("Priority values can only be integer value, between 0 and 5," + value
+ " is not valid");
}
return minPriorityValue;
}

View File

@ -61,7 +61,9 @@ public class XPathCLI {
for (Iterator<RuleViolation> i = ctx.getReport().iterator(); i.hasNext();) {
RuleViolation rv = i.next();
StringBuilder sb = new StringBuilder("Match at line " + rv.getBeginLine() + " column " + rv.getBeginColumn());
StringBuilder sb = new StringBuilder(60)
.append("Match at line ").append(rv.getBeginLine())
.append(" column ").append(rv.getBeginColumn());
if (StringUtil.isNotEmpty(rv.getPackageName())) {
sb.append("; package name '" + rv.getPackageName() + "'");
}

View File

@ -22,13 +22,14 @@ public class CPDCommandLineInterface {
public static final String NO_EXIT_AFTER_RUN = "net.sourceforge.pmd.cli.noExit";
public static final String STATUS_CODE_PROPERTY = "net.sourceforge.pmd.cli.status";
private static final String progName = "cpd";
private static final String PROGRAM_NAME = "cpd";
public static void setStatusCodeOrExit(int status) {
if (isExitAfterRunSet())
if (isExitAfterRunSet()) {
System.exit(status);
else
} else {
setStatusCode(status);
}
}
private static boolean isExitAfterRunSet() {
@ -46,7 +47,7 @@ public class CPDCommandLineInterface {
public static void main(String[] args) {
CPDConfiguration arguments = new CPDConfiguration();
JCommander jcommander = new JCommander(arguments);
jcommander.setProgramName(progName);
jcommander.setProgramName(PROGRAM_NAME);
try {
jcommander.parse(args);
@ -91,10 +92,11 @@ public class CPDCommandLineInterface {
private static void addSourcesFilesToCPD(List<String> files, CPD cpd, boolean recursive) {
try {
for (String file : files)
if (recursive)
if (recursive) {
cpd.addRecursively(file);
else
} else {
cpd.addAllInDirectory(file);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}

View File

@ -122,12 +122,15 @@ public class CPDConfiguration extends AbstractConfiguration {
if (!getEncoding().equals(System.getProperty("file.encoding")))
System.setProperty("file.encoding", getEncoding());
}
if ( this.getLanguage() == null )
if ( this.getLanguage() == null ) {
this.setLanguage(CPDConfiguration.getLanguageFromString(DEFAULT_LANGUAGE));
if (this.getRendererName() == null )
}
if (this.getRendererName() == null ) {
this.setRendererName(DEFAULT_RENDERER);
if ( this.getRenderer() == null )
}
if ( this.getRenderer() == null ) {
this.setRenderer(getRendererFromString(getRendererName()));
}
}
public static Renderer getRendererFromString(String name /* , String encoding */) {
@ -211,14 +214,16 @@ public class CPDConfiguration extends AbstractConfiguration {
}
public Tokenizer tokenizer() {
if ( language == null )
if ( language == null ) {
throw new IllegalStateException("Language is null.");
}
return language.getTokenizer();
}
public FilenameFilter filenameFilter() {
if (language == null)
if (language == null) {
throw new IllegalStateException("Language is null.");
}
final FilenameFilter languageFilter = language.getFileFilter();
final Set<String> exclusions = new HashSet<String>();

View File

@ -23,21 +23,21 @@ public class CSVRenderer implements Renderer {
}
public String render(Iterator<Match> matches) {
StringBuilder rpt = new StringBuilder(1000);
rpt.append("lines").append(separator);
rpt.append("tokens").append(separator);
rpt.append("occurrences");
rpt.append(PMD.EOL);
StringBuilder rpt = new StringBuilder(1000)
.append("lines").append(separator)
.append("tokens").append(separator)
.append("occurrences")
.append(PMD.EOL);
while (matches.hasNext()) {
Match match = matches.next();
rpt.append(match.getLineCount()).append(separator);
rpt.append(match.getTokenCount()).append(separator);
rpt.append(match.getMarkCount()).append(separator);
rpt.append(match.getLineCount()).append(separator)
.append(match.getTokenCount()).append(separator)
.append(match.getMarkCount()).append(separator);
for (Iterator<TokenEntry> marks = match.iterator(); marks.hasNext();) {
TokenEntry mark = marks.next();
rpt.append(mark.getBeginLine()).append(separator);
rpt.append(mark.getTokenSrcID());
rpt.append(mark.getBeginLine()).append(separator)
.append(mark.getTokenSrcID());
if (marks.hasNext()) {
rpt.append(separator);
}

View File

@ -8,7 +8,7 @@ import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
public class LanguageFactory {
public final class LanguageFactory {
public static final String EXTENSION = "extension";
public static final String BY_EXTENSION = "by_extension";

View File

@ -19,13 +19,13 @@ public class TokenEntry implements Comparable<TokenEntry> {
private int identifier;
private int hashCode;
private static ThreadLocal<Map<String, Integer>> TOKENS = new ThreadLocal<Map<String, Integer>>(){
private static final ThreadLocal<Map<String, Integer>> TOKENS = new ThreadLocal<Map<String, Integer>>(){
@Override
protected Map<String, Integer> initialValue() {
return new HashMap<String, Integer>();
}
};
private static ThreadLocal<AtomicInteger> tokenCount = new ThreadLocal<AtomicInteger>(){
private static final ThreadLocal<AtomicInteger> TOKEN_COUNT = new ThreadLocal<AtomicInteger>(){
@Override
protected AtomicInteger initialValue() {
return new AtomicInteger(0);
@ -46,18 +46,18 @@ public class TokenEntry implements Comparable<TokenEntry> {
this.identifier = i.intValue();
this.tokenSrcID = tokenSrcID;
this.beginLine = beginLine;
this.index = tokenCount.get().getAndIncrement();
this.index = TOKEN_COUNT.get().getAndIncrement();
}
public static TokenEntry getEOF() {
tokenCount.get().getAndIncrement();
TOKEN_COUNT.get().getAndIncrement();
return EOF;
}
public static void clearImages() {
TOKENS.get().clear();
TOKENS.remove();
tokenCount.remove();
TOKEN_COUNT.remove();
}
/**
* Helper class to preserve and restore the current state
@ -68,12 +68,12 @@ public class TokenEntry implements Comparable<TokenEntry> {
private Map<String, Integer> tokens;
private List<TokenEntry> entries;
public State(List<TokenEntry> entries) {
this.tokenCount = TokenEntry.tokenCount.get().intValue();
this.tokenCount = TokenEntry.TOKEN_COUNT.get().intValue();
this.tokens = new HashMap<String, Integer>(TokenEntry.TOKENS.get());
this.entries = new ArrayList<TokenEntry>(entries);
}
public List<TokenEntry> restore() {
TokenEntry.tokenCount.get().set(tokenCount);
TokenEntry.TOKEN_COUNT.get().set(tokenCount);
TOKENS.get().clear();
TOKENS.get().putAll(tokens);
return entries;

View File

@ -27,7 +27,7 @@ import java.util.List;
*/
public interface Language {
static final String LANGUAGE_MODULES_CLASS_NAMES_PROPERTY = "languageModulesClassNames";
String LANGUAGE_MODULES_CLASS_NAMES_PROPERTY = "languageModulesClassNames";
/**
* Get the full name of this Language. This is generally the name of this

View File

@ -13,7 +13,7 @@ import java.util.ServiceLoader;
/**
* Created by christoferdutz on 20.09.14.
*/
public class LanguageRegistry {
public final class LanguageRegistry {
private static LanguageRegistry instance;
@ -58,8 +58,8 @@ public class LanguageRegistry {
public static LanguageVersion findLanguageVersionByTerseName(String terseName) {
String version = null;
if(terseName.contains(" ")) {
version = terseName.substring(terseName.lastIndexOf(" ") + 1);
terseName = terseName.substring(0, terseName.lastIndexOf(" "));
version = terseName.substring(terseName.lastIndexOf(' ') + 1);
terseName = terseName.substring(0, terseName.lastIndexOf(' '));
}
Language language = findLanguageByTerseName(terseName);
if(language != null) {

View File

@ -351,7 +351,9 @@ public abstract class AbstractNode implements Node {
*/
public final boolean hasDecendantOfAnyType(Class<?>... types) {
for (Class<?> type : types) {
if (hasDescendantOfType(type)) return true;
if (hasDescendantOfType(type)) {
return true;
}
}
return false;
}

View File

@ -5,9 +5,7 @@ package net.sourceforge.pmd.lang.dfa;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import net.sourceforge.pmd.lang.ast.Node;

View File

@ -8,5 +8,5 @@ import java.util.List;
import net.sourceforge.pmd.Rule;
public interface DFAGraphRule extends Rule {
public List<DFAGraphMethod> getMethods();
List<DFAGraphMethod> getMethods();
}

View File

@ -45,15 +45,19 @@ public class Linker {
);
}
if (sc.getFirstIndex() < 0 || sc.getLastIndex() < 0) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe("Sequence Checker problem: getFirstIndex()=="
+ sc.getFirstIndex() + ", getLastIndex()==" + sc.getLastIndex()
);
}
throw new SequenceException("computePaths(): return index < 0");
}
StackObject firstStackObject = braceStack.get(sc.getFirstIndex());
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Checking first braceStack element of type=="+ NodeType.stringFromType(firstStackObject.getType()) );
}
switch (firstStackObject.getType()) {
case NodeType.IF_EXPR:
LOGGER.finest("IF_EXPR");
@ -93,12 +97,18 @@ public class Linker {
default:
}
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("Removing braces from Last to first: " + sc.getLastIndex() + " to " + sc.getFirstIndex());
}
for (int y = sc.getLastIndex(); y >= sc.getFirstIndex(); y--) {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("Removing brace : " + y );
}
braceStack.remove(y);
}
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Completed Sequence checking loop" + braceStack );
}
}
if (LOGGER.isLoggable(Level.FINER))
{
@ -324,20 +334,24 @@ public class Linker {
DataFlowNode sEnd = this.braceStack.get(lastIndex).getDataFlowNode();
DataFlowNode end = sEnd.getChildren().get(0);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(
"Stack(sStart)=>" + sStart
+",Stack(sEnd)=>" + sEnd
+",end=>" + end
);
}
for (int i = 0; i < diff - 2; i++) {
StackObject so = this.braceStack.get(firstIndex + 2 + i);
DataFlowNode node = so.getDataFlowNode();
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine( "so(" + (firstIndex + 2 + i) + ")=>" + so
+" has dfn=>" + node
+" with first child =>" + node.getChildren().get(0)
);
}
sStart.addPathToChild(node.getChildren().get(0));
if (so.getType() == NodeType.SWITCH_LAST_DEFAULT_STATEMENT) {

View File

@ -45,42 +45,42 @@ public class NodeType {
public static final int THROW_STATEMENT = 70;
//Poor Man's Enum until we convert the class to real enum
private static final Map<Integer, String> typeMap = new HashMap<Integer, String>();
private static final Map<Integer, String> TYPE_MAP = new HashMap<Integer, String>();
static {
typeMap.put(NodeType.IF_EXPR, "IF_EXPR");
typeMap.put(NodeType.IF_LAST_STATEMENT, "IF_LAST_STATEMENT");
typeMap.put(NodeType.IF_LAST_STATEMENT_WITHOUT_ELSE, "IF_LAST_STATEMENT_WITHOUT_ELSE");
typeMap.put(NodeType.ELSE_LAST_STATEMENT, "ELSE_LAST_STATEMENT");
typeMap.put(NodeType.WHILE_LAST_STATEMENT, "WHILE_LAST_STATEMENT");
typeMap.put(NodeType.WHILE_EXPR, "WHILE_EXPR");
typeMap.put(NodeType.SWITCH_START, "SWITCH_START");
typeMap.put(NodeType.CASE_LAST_STATEMENT, "CASE_LAST_STATEMENT");
typeMap.put(NodeType.SWITCH_LAST_DEFAULT_STATEMENT, "SWITCH_LAST_DEFAULT_STATEMENT");
typeMap.put(NodeType.SWITCH_END, "SWITCH_END");
typeMap.put(NodeType.FOR_INIT, "FOR_INIT");
typeMap.put(NodeType.FOR_EXPR, "FOR_EXPR");
typeMap.put(NodeType.FOR_UPDATE, "FOR_UPDATE");
typeMap.put(NodeType.FOR_BEFORE_FIRST_STATEMENT, "FOR_BEFORE_FIRST_STATEMENT");
typeMap.put(NodeType.FOR_END, "FOR_END");
typeMap.put(NodeType.DO_BEFORE_FIRST_STATEMENT, "DO_BEFORE_FIRST_STATEMENT");
typeMap.put(NodeType.DO_EXPR, "DO_EXPR");
typeMap.put(NodeType.RETURN_STATEMENT, "RETURN_STATEMENT");
typeMap.put(NodeType.BREAK_STATEMENT, "BREAK_STATEMENT");
typeMap.put(NodeType.CONTINUE_STATEMENT, "CONTINUE_STATEMENT");
typeMap.put(NodeType.LABEL_STATEMENT, "LABEL_STATEMENT");
typeMap.put(NodeType.LABEL_LAST_STATEMENT, "LABEL_END");
typeMap.put(NodeType.THROW_STATEMENT, "THROW_STATEMENT");
TYPE_MAP.put(NodeType.IF_EXPR, "IF_EXPR");
TYPE_MAP.put(NodeType.IF_LAST_STATEMENT, "IF_LAST_STATEMENT");
TYPE_MAP.put(NodeType.IF_LAST_STATEMENT_WITHOUT_ELSE, "IF_LAST_STATEMENT_WITHOUT_ELSE");
TYPE_MAP.put(NodeType.ELSE_LAST_STATEMENT, "ELSE_LAST_STATEMENT");
TYPE_MAP.put(NodeType.WHILE_LAST_STATEMENT, "WHILE_LAST_STATEMENT");
TYPE_MAP.put(NodeType.WHILE_EXPR, "WHILE_EXPR");
TYPE_MAP.put(NodeType.SWITCH_START, "SWITCH_START");
TYPE_MAP.put(NodeType.CASE_LAST_STATEMENT, "CASE_LAST_STATEMENT");
TYPE_MAP.put(NodeType.SWITCH_LAST_DEFAULT_STATEMENT, "SWITCH_LAST_DEFAULT_STATEMENT");
TYPE_MAP.put(NodeType.SWITCH_END, "SWITCH_END");
TYPE_MAP.put(NodeType.FOR_INIT, "FOR_INIT");
TYPE_MAP.put(NodeType.FOR_EXPR, "FOR_EXPR");
TYPE_MAP.put(NodeType.FOR_UPDATE, "FOR_UPDATE");
TYPE_MAP.put(NodeType.FOR_BEFORE_FIRST_STATEMENT, "FOR_BEFORE_FIRST_STATEMENT");
TYPE_MAP.put(NodeType.FOR_END, "FOR_END");
TYPE_MAP.put(NodeType.DO_BEFORE_FIRST_STATEMENT, "DO_BEFORE_FIRST_STATEMENT");
TYPE_MAP.put(NodeType.DO_EXPR, "DO_EXPR");
TYPE_MAP.put(NodeType.RETURN_STATEMENT, "RETURN_STATEMENT");
TYPE_MAP.put(NodeType.BREAK_STATEMENT, "BREAK_STATEMENT");
TYPE_MAP.put(NodeType.CONTINUE_STATEMENT, "CONTINUE_STATEMENT");
TYPE_MAP.put(NodeType.LABEL_STATEMENT, "LABEL_STATEMENT");
TYPE_MAP.put(NodeType.LABEL_LAST_STATEMENT, "LABEL_END");
TYPE_MAP.put(NodeType.THROW_STATEMENT, "THROW_STATEMENT");
}
public static Map<Integer, String> getTypeMap() {
return typeMap;
return TYPE_MAP;
}
public static String stringFromType(int intype) {
if(-1 == intype) { return "<ROOT>" ; }
if (!typeMap.containsKey(intype) ) {
if (!TYPE_MAP.containsKey(intype) ) {
throw new RuntimeException("Couldn't find NodeType type id " + intype);
}
return typeMap.get(intype);
return TYPE_MAP.get(intype);
}
}

View File

@ -5,6 +5,7 @@ package net.sourceforge.pmd.lang.dfa;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -188,15 +189,16 @@ public class SequenceChecker {
int maximumIterations = this.bracesList.size() * this.bracesList.size() ;
for (int i = 0, l = 0; i < this.bracesList.size(); l++, i++) {
StackObject so = bracesList.get(i);
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("Processing bracesList(l,i)=("+l+","+i+") of Type "
+ NodeType.stringFromType(so.getType()) + " with State (aktStatus) = "
+ aktStatus
);
//LOGGER.finest("StackObject of Type="+so.getType());
LOGGER.finest("DataFlowNode @ line "+ so.getDataFlowNode().getLine() + " and index="
+ so.getDataFlowNode().getIndex()
);
}
//Attempt to get to this StackObject's NodeType from the current State
aktStatus = this.aktStatus.step(so.getType());
@ -212,7 +214,9 @@ public class SequenceChecker {
//Cope with incorrect bracesList contents
else if (l > maximumIterations )
{
LOGGER.severe("aktStatus is NULL: maximum Iterations exceeded, abort "+i);
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.severe("aktStatus is NULL: maximum Iterations exceeded, abort "+i);
}
LOGGER.exiting(this.getClass().getCanonicalName(),"run", false);
return false;
}
@ -220,13 +224,17 @@ public class SequenceChecker {
this.aktStatus = root;
this.firstIndex = i;
i--;
LOGGER.finest("aktStatus is NULL: Restarting search continue i==" +i + ", firstIndex=" + this.firstIndex );
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("aktStatus is NULL: Restarting search continue i==" +i + ", firstIndex=" + this.firstIndex );
}
continue;
}
} else { // This NodeType _is_ a valid transition from the previous State
if (aktStatus.isLastStep() && !aktStatus.hasMoreSteps()) { //Terminal State
this.lastIndex = i;
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("aktStatus is NOT NULL: lastStep reached and no moreSteps - firstIndex=" + firstIndex + ", lastIndex=" + lastIndex);
}
LOGGER.exiting(this.getClass().getCanonicalName(),"run", false);
return false;
} else if (aktStatus.isLastStep() && aktStatus.hasMoreSteps()) {
@ -236,7 +244,9 @@ public class SequenceChecker {
}
}
}
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finer("Completed search: firstIndex=" + firstIndex + ", lastIndex=" + lastIndex);
}
LOGGER.exiting(this.getClass().getCanonicalName(),"run", this.firstIndex == this.lastIndex);
return this.firstIndex == this.lastIndex;
}

View File

@ -5,6 +5,7 @@ package net.sourceforge.pmd.lang.dfa;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Stack;
@ -69,16 +70,20 @@ public class Structure {
|| type == NodeType.CONTINUE_STATEMENT || type == NodeType.THROW_STATEMENT) {
// ugly solution - stores the type information in two ways
continueBreakReturnStack.push(obj);
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("continueBreakReturnStack: line " + node.getNode().getBeginLine()
+ ", column " + node.getNode().getBeginColumn()
+" - " + node.toString()
);
}
} else {
braceStack.push(obj);
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("braceStack: line " + node.getNode().getBeginLine()
+ ", column " + node.getNode().getBeginColumn()
+" - " + node.toString()
);
}
}
node.setType(type);
}
@ -96,9 +101,9 @@ public class Structure {
* @return formatted dump of the DFA Structure's
*/
public String dump() {
StringBuilder stringDump = new StringBuilder() ;
stringDump.append ("Data Flow Analysis Structure:\n");
stringDump.append (" Edge Nodes (ContinueBraceReturn) :");
StringBuilder stringDump = new StringBuilder(120)
.append ("Data Flow Analysis Structure:\n")
.append (" Edge Nodes (ContinueBraceReturn) :");
for (StackObject stackObject : continueBreakReturnStack )
{
stringDump.append("\nCBR => ").append(stackObject.toString());

View File

@ -26,9 +26,9 @@ import org.apache.commons.io.IOUtils;
public class ReportHTMLPrintVisitor extends ReportVisitor {
@SuppressWarnings("PMD.AvoidStringBufferField")
private StringBuilder packageBuf = new StringBuilder();
private StringBuilder packageBuf = new StringBuilder(30);
@SuppressWarnings("PMD.AvoidStringBufferField")
private StringBuilder classBuf = new StringBuilder();
private StringBuilder classBuf = new StringBuilder(60);
private int length;
private String baseDir;

View File

@ -17,11 +17,15 @@ public class ImportWrapper {
}
public boolean equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if (other == null) {
return false;
}
if (other == this) {
return true;
}
if (other instanceof ImportWrapper) {
ImportWrapper i = (ImportWrapper) other;
if(name == null && i.getName() == null){
if (name == null && i.getName() == null) {
return i.getFullName().equals(fullname);
}
return i.getName().equals(name);

View File

@ -71,7 +71,9 @@ public class ParametricRuleViolation<T extends Node> implements RuleViolation {
protected String expandVariables(String message) {
if (message.indexOf("${") < 0) return message;
if (message.indexOf("${") < 0) {
return message;
}
StringBuilder buf = new StringBuilder(message);
int startIndex = -1;

View File

@ -301,7 +301,9 @@ public class RuleReference extends AbstractDelegateRule {
// not sure if we should go all the way through to the real thing?
getRule().useDefaultValueFor(desc);
if (propertyValues == null) return;
if (propertyValues == null) {
return;
}
propertyValues.remove(desc);

Some files were not shown because too many files have changed in this diff Show More