repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessiveParameterListTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveParameterListTest extends PmdRuleTst {
// no additional unit tests
}
| 284 | 22.75 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/NPathComplexityTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class NPathComplexityTest extends PmdRuleTst {
// no additional unit tests
}
| 277 | 22.166667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/TooManyMethodsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class TooManyMethodsTest extends PmdRuleTst {
// no additional unit tests
}
| 276 | 22.083333 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/CyclomaticComplexityTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class CyclomaticComplexityTest extends PmdRuleTst {
// no additional unit tests
}
| 282 | 22.583333 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessivePackageBodyLengthTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessivePackageBodyLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 288 | 23.083333 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessivePackageSpecificationLengthTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessivePackageSpecificationLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 297 | 23.833333 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/NcssObjectCountTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class NcssObjectCountTest extends PmdRuleTst {
// no additional unit tests
}
| 277 | 22.166667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/NcssMethodCountTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class NcssMethodCountTest extends PmdRuleTst {
// no additional unit tests
}
| 277 | 22.166667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessiveTypeLengthTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveTypeLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 281 | 22.5 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessiveObjectLengthTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveObjectLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 283 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessiveMethodLengthTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ExcessiveMethodLengthTest extends PmdRuleTst {
// no additional unit tests
}
| 283 | 22.666667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/rule/design/TooManyFieldsTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class TooManyFieldsTest extends PmdRuleTst {
// no additional unit tests
}
| 275 | 22 | 79 | java |
pmd | pmd-master/pmd-plsql/src/test/java/net/sourceforge/pmd/cpd/PLSQLTokenizerTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
class PLSQLTokenizerTest extends CpdTextComparisonTest {
PLSQLTokenizerTest() {
super(".sql");
}
@Override
protected String getResourcePrefix() {
return "../lang/plsql/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new PLSQLTokenizer();
}
@Test
void testSimple() {
doTest("sample-plsql");
}
@Test
void testSpecialComments() {
doTest("specialComments");
}
@Test
void testTabWidth() {
doTest("tabWidth");
}
}
| 825 | 17.355556 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/PLSQLHandler.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql;
import net.sourceforge.pmd.lang.AbstractPmdLanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLParser;
/**
* Implementation of LanguageVersionHandler for the PLSQL AST. It uses anonymous
* classes as adapters of the visitors to the VisitorStarter interface.
*
* @author sturton - PLDoc - pldoc.sourceforge.net
*/
public class PLSQLHandler extends AbstractPmdLanguageVersionHandler {
@Override
public Parser getParser() {
return new PLSQLParser();
}
}
| 672 | 25.92 | 80 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/PLSQLLanguageModule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.List;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
/**
* Created by christoferdutz on 20.09.14.
*/
public class PLSQLLanguageModule extends SimpleLanguageModuleBase {
public static final String NAME = "PLSQL";
public static final String TERSE_NAME = "plsql";
@InternalApi
public static final List<String> EXTENSIONS = listOf(
"sql",
"trg", // Triggers
"prc", "fnc", // Standalone Procedures and Functions
"pld", // Oracle*Forms
"pls", "plh", "plb", // Packages
"pck", "pks", "pkh", "pkb", // Packages
"typ", "tyb", // Object Types
"tps", "tpb" // Object Types
);
public PLSQLLanguageModule() {
super(
LanguageMetadata.withId(TERSE_NAME)
.name(NAME)
.extensions(EXTENSIONS)
.addVersion("11g")
.addVersion("12c_Release_1", "12.1")
.addVersion("12c_Release_2", "12.2")
.addVersion("18c")
.addVersion("19c")
.addDefaultVersion("21c"),
new PLSQLHandler()
);
}
}
| 1,531 | 30.916667 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTPackageSpecification.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public class ASTPackageSpecification extends AbstractPLSQLNode implements OracleObject {
ASTPackageSpecification(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Gets the name of the Oracle Object.
*
* @return a String representing the name of the Oracle Object
*/
@Override
public String getObjectName() {
return this.getImage();
}
}
| 671 | 23 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTFormalParameter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTFormalParameter extends AbstractPLSQLNode {
private boolean in;
private boolean out;
private boolean nocopy;
ASTFormalParameter(int id) {
super(id);
}
public boolean isIn() {
return this.in;
}
void setIn(boolean in) {
this.in = in;
}
public boolean isOut() {
return this.out;
}
void setOut(boolean out) {
this.out = out;
}
public boolean isNoCopy() {
return this.nocopy;
}
void setNoCopy(boolean nocopy) {
this.nocopy = nocopy;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public ASTDatatype getTypeNode() {
for (int i = 0; i < getNumChildren(); i++) {
if (getChild(i) instanceof ASTDatatype) {
return (ASTDatatype) getChild(i);
}
}
throw new IllegalStateException("ASTType not found");
}
}
| 1,169 | 20.272727 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTTriggerTimingPointSection.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTTriggerTimingPointSection extends AbstractPLSQLNode implements ExecutableCode {
ASTTriggerTimingPointSection(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* return executable's name.
*
* @return
*/
@Override
public String getMethodName() {
return getImage();
}
public String getName() {
return getMethodName();
}
}
| 691 | 20.625 | 101 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTDatatype.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTDatatype extends AbstractPLSQLNode {
ASTDatatype(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public String getTypeImage() {
return getImage();
}
}
| 476 | 20.681818 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTInnerCrossJoinClause.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTInnerCrossJoinClause extends AbstractPLSQLNode {
private boolean cross;
private boolean natural;
ASTInnerCrossJoinClause(int id) {
super(id);
}
public boolean isCross() {
return cross;
}
public boolean isNatural() {
return natural;
}
void setCross(boolean cross) {
this.cross = cross;
}
void setNatural(boolean natural) {
this.natural = natural;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 759 | 20.111111 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTComparisonCondition.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTComparisonCondition extends AbstractPLSQLNode {
private String operator;
ASTComparisonCondition(int id) {
super(id);
}
void setOperator(String operator) {
this.operator = operator;
}
public String getOperator() {
return this.operator;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 610 | 21.62963 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTName.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
public final class ASTName extends AbstractPLSQLNode {
private NameDeclaration nd;
ASTName(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
void setNameDeclaration(NameDeclaration nd) {
this.nd = nd;
}
public NameDeclaration getNameDeclaration() {
return this.nd;
}
}
| 653 | 21.551724 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTInput.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.lang.ast.AstInfo;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.RootNode;
public final class ASTInput extends AbstractPLSQLNode implements RootNode {
private AstInfo<ASTInput> astInfo;
ASTInput(int id) {
super(id);
}
@Override
public AstInfo<ASTInput> getAstInfo() {
return astInfo;
}
ASTInput addTaskInfo(ParserTask task) {
this.astInfo = new AstInfo<>(task, this);
return this;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
private int excludedRangesCount = 0;
private int excludedLinesCount = 0;
/**
* Let the user know that a range of lines were excluded from parsing.
*
* @param first First line of the excluded line range (1-based).
* @param last Last line of the excluded line range (1-based).
*/
void addExcludedLineRange(int first, int last) {
excludedLinesCount += last - first + 1;
excludedRangesCount += 1;
}
public int getExcludedLinesCount() {
return excludedLinesCount;
}
public int getExcludedRangesCount() {
return excludedRangesCount;
}
}
| 1,447 | 24.403509 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/AbstractSelectStatement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.annotation.InternalApi;
@InternalApi
abstract class AbstractSelectStatement extends AbstractPLSQLNode {
private boolean distinct;
private boolean unique;
private boolean all;
AbstractSelectStatement(int i) {
super(i);
}
protected void setDistinct(boolean distinct) {
this.distinct = true;
}
public boolean isDistinct() {
return distinct;
}
protected void setUnique(boolean unique) {
this.unique = unique;
}
public boolean isUnique() {
return unique;
}
protected void setAll(boolean all) {
this.all = all;
}
public boolean isAll() {
return all;
}
}
| 842 | 17.733333 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTSelectIntoStatement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTSelectIntoStatement extends AbstractSelectStatement {
ASTSelectIntoStatement(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 435 | 23.222222 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTMethodDeclarator.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTMethodDeclarator extends AbstractPLSQLNode {
ASTMethodDeclarator(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public int getParameterCount() {
return this.getChild(0).getNumChildren();
}
}
| 517 | 22.545455 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTTriggerUnit.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTTriggerUnit extends AbstractPLSQLNode implements ExecutableCode, OracleObject {
ASTTriggerUnit(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Gets the name of the trigger.
*
* @return a String representing the name of the trigger
*/
@Override
public String getMethodName() {
return getImage();
}
public String getName() {
return getMethodName();
}
/**
* Gets the name of the Oracle Object.
*
* @return a String representing the name of the Oracle Object
*/
@Override
public String getObjectName() {
return getImage();
}
}
| 944 | 21.5 | 101 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTExtractExpression.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import java.util.List;
public final class ASTExtractExpression extends AbstractPLSQLNode {
private boolean xml;
ASTExtractExpression(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
void setXml() {
xml = true;
}
public boolean isXml() {
return xml;
}
public String getXPath() {
if (xml) {
return getFirstChildOfType(ASTStringLiteral.class).getString();
}
return "";
}
public String getNamespace() {
if (xml) {
List<ASTStringLiteral> literals = findChildrenOfType(ASTStringLiteral.class);
if (literals.size() == 2) {
return literals.get(1).getString();
}
}
return "";
}
}
| 1,026 | 20.851064 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ExecutableCode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
/**
* Methods required to be considered as an executable piece of code.
*/
public interface ExecutableCode extends PLSQLNode {
/**
* Gets the name of the executable: named thus to match
* {@link ASTMethodDeclaration}.
*
* @return a String representing the name of the method
*/
String getMethodName();
}
| 473 | 22.7 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/PlsqlVisitorBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.lang.ast.AstVisitorBase;
/**
* Base implementation of {@link PlsqlVisitor}.
*/
public abstract class PlsqlVisitorBase<P, R> extends AstVisitorBase<P, R> implements PlsqlVisitor<P, R> {
}
| 351 | 22.466667 | 105 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTOuterJoinType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTOuterJoinType extends AbstractPLSQLNode {
private Type type;
ASTOuterJoinType(int id) {
super(id);
}
void setType(Type type) {
this.type = type;
}
public Type getType() {
return type;
}
@Override
public String getImage() {
return String.valueOf(type);
}
public boolean isLeft() {
return type == Type.LEFT;
}
public boolean isRight() {
return type == Type.RIGHT;
}
public boolean isFull() {
return type == Type.FULL;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public enum Type { FULL, LEFT, RIGHT }
}
| 907 | 18.73913 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTVariableOrConstantDeclaratorId.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import java.util.List;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
public final class ASTVariableOrConstantDeclaratorId extends AbstractPLSQLNode {
private int arrayDepth;
private NameDeclaration nameDeclaration;
ASTVariableOrConstantDeclaratorId(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public NameDeclaration getNameDeclaration() {
return nameDeclaration;
}
void setNameDeclaration(NameDeclaration decl) {
nameDeclaration = decl;
}
public List<NameOccurrence> getUsages() {
return getScope().getDeclarations().get(nameDeclaration);
}
void bumpArrayDepth() {
arrayDepth++;
}
public int getArrayDepth() {
return arrayDepth;
}
public boolean isArray() {
return arrayDepth > 0;
}
public Node getTypeNameNode() {
if (getParent() instanceof ASTFormalParameter) {
return findTypeNameNode(getParent());
} else if (getParent().getParent() instanceof ASTVariableOrConstantDeclaration
|| getParent().getParent() instanceof ASTFieldDeclaration) {
return findTypeNameNode(getParent().getParent());
}
throw new RuntimeException(
"Don't know how to get the type for anything other than ASTLocalVariableDeclaration/ASTFormalParameter/ASTFieldDeclaration");
}
public ASTDatatype getTypeNode() {
if (getParent() instanceof ASTFormalParameter) {
return ((ASTFormalParameter) getParent()).getTypeNode();
} else {
Node n = getParent().getParent();
if (n instanceof ASTVariableOrConstantDeclaration || n instanceof ASTFieldDeclaration) {
return n.getFirstChildOfType(ASTDatatype.class);
}
}
throw new RuntimeException(
"Don't know how to get the type for anything other than ASTLocalVariableDeclaration/ASTFormalParameter/ASTFieldDeclaration");
}
private Node findTypeNameNode(Node node) {
ASTDatatype typeNode = (ASTDatatype) node.getChild(0);
return typeNode.getChild(0);
}
}
| 2,526 | 30.5875 | 141 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/AbstractPLSQLNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.javacc.AbstractJjtreeNode;
import net.sourceforge.pmd.lang.symboltable.Scope;
abstract class AbstractPLSQLNode extends AbstractJjtreeNode<AbstractPLSQLNode, PLSQLNode> implements PLSQLNode {
protected Object value;
protected PLSQLParser parser;
protected Scope scope;
AbstractPLSQLNode(int i) {
super(i);
}
@Override // override to make protected member accessible to parser
protected void setImage(String image) {
super.setImage(image);
}
protected void jjtSetValue(Object value) {
this.value = value;
}
public Object jjtGetValue() {
return value;
}
protected abstract <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data);
@Override
@SuppressWarnings("unchecked")
public final <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {
if (visitor instanceof PlsqlVisitor) {
return acceptPlsqlVisitor((PlsqlVisitor<? super P, ? extends R>) visitor, data);
}
return visitor.cannotVisit(this, data);
}
@Override
public String getXPathNodeName() {
return PLSQLParserImplTreeConstants.jjtNodeName[id];
}
@Override
public Scope getScope() {
if (scope == null) {
return getParent().getScope();
}
return scope;
}
void setScope(Scope scope) {
this.scope = scope;
}
}
| 1,661 | 25.380952 | 112 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/InternalApiBridge.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.Scope;
/**
* Acts as a bridge between outer parts (e.g. symbol table) and the restricted
* access internal API of this package.
*
* <p>Note: This is internal API.
*/
@InternalApi
public final class InternalApiBridge {
private InternalApiBridge() {
}
public static void setScope(PLSQLNode node, Scope decl) {
((AbstractPLSQLNode) node).setScope(decl);
}
public static void setNameDeclaration(ASTName node, NameDeclaration decl) {
node.setNameDeclaration(decl);
}
public static void setNameDeclaration(ASTVariableOrConstantDeclaratorId node, NameDeclaration decl) {
node.setNameDeclaration(decl);
}
}
| 965 | 25.108108 | 105 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/PLSQLParserVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
import net.sourceforge.pmd.lang.ast.Node;
@Deprecated
@DeprecatedUntil700
public interface PLSQLParserVisitor extends PlsqlVisitor<Object, Object> {
@Override
default Object visitNode(Node node, Object param) {
node.children().forEach(it -> it.acceptVisitor(this, param));
return param;
}
}
| 512 | 24.65 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTOutOfLineConstraint.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTOutOfLineConstraint extends AbstractPLSQLNode {
private ConstraintType type;
ASTOutOfLineConstraint(int id) {
super(id);
}
void setType(ConstraintType type) {
this.type = type;
}
public ConstraintType getType() {
return type;
}
public boolean isUnique() {
return type == ConstraintType.UNIQUE;
}
public boolean isPrimaryKey() {
return type == ConstraintType.PRIMARY;
}
public boolean isForeignKey() {
return type == ConstraintType.FOREIGN;
}
public boolean isCheck() {
return type == ConstraintType.CHECK;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 949 | 21.093023 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/PLSQLNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeNode;
import net.sourceforge.pmd.lang.symboltable.Scope;
import net.sourceforge.pmd.lang.symboltable.ScopedNode;
public interface PLSQLNode extends ScopedNode, JjtreeNode<PLSQLNode> {
/**
* Accept the visitor.
*
* @deprecated Use {@link #acceptVisitor(AstVisitor, Object)}
*/
@Deprecated
@DeprecatedUntil700
default Object jjtAccept(PLSQLParserVisitor visitor, Object data) {
return acceptVisitor(visitor, data);
}
@Override
Scope getScope();
/**
* Return node image converted to the normal Oracle form.
*
* <p>
* Normally this is uppercase, unless the names is quoted ("name").
* </p>
*/
default String getCanonicalImage() {
return PLSQLParserImpl.canonicalName(this.getImage());
}
/**
* Convert arbitrary String to normal Oracle format, under assumption that
* the passed image is an Oracle name.
*
* <p>
* This a helper method for PLSQL classes dependent on SimpleNode, that
* would otherwise have to import PLSQParser.
* </p>
*
* @param image
* @return
*/
static String getCanonicalImage(String image) {
return PLSQLParserImpl.canonicalName(image);
}
}
| 1,537 | 25.982456 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTQueryBlock.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTQueryBlock extends AbstractSelectStatement {
ASTQueryBlock(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 417 | 22.222222 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTSqlStatement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTSqlStatement extends AbstractPLSQLNode {
private Type type;
public enum Type { COMMIT, ROLLBACK, SAVEPOINT, SET_TRANSACTION, LOCK_TABLE, MERGE }
ASTSqlStatement(int id) {
super(id);
}
void setType(Type type) {
this.type = type;
}
public Type getType() {
return this.type;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 653 | 20.8 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTSubqueryOperation.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTSubqueryOperation extends AbstractPLSQLNode {
private boolean union;
private boolean all;
private boolean intersect;
private boolean minus;
ASTSubqueryOperation(int id) {
super(id);
}
public boolean isAll() {
return all;
}
void setAll(boolean all) {
this.all = all;
}
public boolean isIntersect() {
return intersect;
}
void setIntersect(boolean intersect) {
this.intersect = intersect;
}
public boolean isMinus() {
return minus;
}
void setMinus(boolean minus) {
this.minus = minus;
}
public boolean isUnion() {
return union;
}
void setUnion(boolean union) {
this.union = union;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 1,067 | 18.777778 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/PLSQLParserVisitorAdapter.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.annotation.DeprecatedUntil700;
@Deprecated
@DeprecatedUntil700
public class PLSQLParserVisitorAdapter extends PlsqlVisitorBase<Object, Object> implements PLSQLParserVisitor {
}
| 338 | 25.076923 | 111 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTProgramUnit.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTProgramUnit extends AbstractPLSQLNode implements ExecutableCode, OracleObject {
ASTProgramUnit(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Gets the name of the method.
*
* @return a String representing the name of the method
*/
@Override
public String getMethodName() {
ASTMethodDeclarator md = getFirstChildOfType(ASTMethodDeclarator.class);
if (md != null) {
return md.getImage();
}
return null;
}
public String getName() {
return getMethodName();
}
/**
* Gets the name of the Oracle Object.
*
* @return a String representing the name of the Oracle Object
*/
@Override
public String getObjectName() {
// This _IS_ a schema-level Program Unit
if (null == this.getParent()) {
return this.getImage();
} else {
return this.getImage();
}
}
}
| 1,248 | 23.490196 | 101 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ConstraintType.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public enum ConstraintType {
UNIQUE,
PRIMARY,
FOREIGN,
CHECK;
}
| 213 | 15.461538 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/OracleObject.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
/**
* All nodes that represent an Oracle object.
*/
public interface OracleObject extends PLSQLNode {
/**
* Gets the name of the Oracle object.
*
* @return a String representing the name of the Oracle object.
*/
String getObjectName();
}
| 402 | 20.210526 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTMethodDeclaration.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTMethodDeclaration extends AbstractPLSQLNode implements ExecutableCode {
ASTMethodDeclaration(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Gets the name of the method.
*
* @return a String representing the name of the method
*/
@Override
public String getMethodName() {
ASTMethodDeclarator md = getFirstDescendantOfType(ASTMethodDeclarator.class);
if (md != null) {
return md.getImage();
}
return null;
}
}
| 804 | 24.15625 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTOuterJoinClause.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTOuterJoinClause extends AbstractPLSQLNode {
private boolean natural;
ASTOuterJoinClause(int id) {
super(id);
}
public boolean isNatural() {
return natural;
}
void setNatural(boolean natural) {
this.natural = natural;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 592 | 20.962963 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTTypeSpecification.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTTypeSpecification extends AbstractPLSQLNode implements OracleObject {
ASTTypeSpecification(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Gets the name of the Oracle Object.
*
* @return a String representing the name of the Oracle Object
*/
@Override
public String getObjectName() {
return this.getImage();
}
}
| 671 | 23 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTSelectStatement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTSelectStatement extends AbstractSelectStatement {
public ASTSelectStatement(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public ASTFromClause getFromClause() {
return getFirstChildOfType(ASTFromClause.class);
}
}
| 541 | 23.636364 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTStringLiteral.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTStringLiteral extends AbstractPLSQLNode {
ASTStringLiteral(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Gets the plain string from the string literal.
* @return the plain string value from the string literal.
*/
public String getString() {
String image = getImage();
if (image.charAt(0) == 'N' || image.charAt(0) == 'n') {
image = image.substring(1);
}
if (image.charAt(0) == '\'') {
image = image.substring(1, image.length() - 1);
} else if (image.charAt(0) == 'Q' || image.charAt(0) == 'q') {
image = image.substring("q'x".length(), image.length() - 2);
}
return image;
}
}
| 1,017 | 25.102564 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTFetchStatement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTFetchStatement extends AbstractPLSQLNode {
private boolean bulkcollect;
private boolean limit;
ASTFetchStatement(int id) {
super(id);
}
void setBulkCollect(boolean bulkcollect) {
this.bulkcollect = bulkcollect;
}
public boolean isBulkCollect() {
return this.bulkcollect;
}
void setLimit(boolean limit) {
this.limit = limit;
}
public boolean isLimit() {
return this.limit;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 786 | 20.27027 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTTypeMethod.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTTypeMethod extends AbstractPLSQLNode implements ExecutableCode {
ASTTypeMethod(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Gets the name of the method.
*
* @return a String representing the name of the method
*/
@Override
public String getMethodName() {
ASTMethodDeclarator md = getFirstChildOfType(ASTMethodDeclarator.class);
if (md != null) {
return md.getImage();
}
return null;
}
public String getName() {
return getMethodName();
}
}
| 854 | 22.75 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTPrimarySuffix.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTPrimarySuffix extends AbstractPLSQLNode {
private boolean isArguments;
private boolean isArrayDereference;
ASTPrimarySuffix(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
void setIsArrayDereference() {
isArrayDereference = true;
}
public boolean isArrayDereference() {
return isArrayDereference;
}
void setIsArguments() {
this.isArguments = true;
}
public boolean isArguments() {
return this.isArguments;
}
/**
* Get the number of arguments for this primary suffix. One should call
* {@link #isArguments()} to see if there are arguments. If this method is
* called when there are no arguments it returns <code>-1</code>.
*
* @return A non-negative argument number when there are arguments,
* <code>-1</code> otherwise.
*/
public int getArgumentCount() {
if (!this.isArguments()) {
return -1;
}
return ((ASTArguments) getChild(getNumChildren() - 1)).getArgumentCount();
}
}
| 1,351 | 25 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTIfStatement.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTIfStatement extends AbstractPLSQLNode {
private boolean hasElse;
ASTIfStatement(int id) {
super(id);
}
void setHasElse() {
this.hasElse = true;
}
public boolean hasElse() {
return this.hasElse;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 569 | 20.111111 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTRegexpLikeCondition.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTRegexpLikeCondition extends AbstractPLSQLNode {
private String matchParam;
ASTRegexpLikeCondition(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
void setMatchParam(String matchParam) {
this.matchParam = matchParam;
}
public String getMatchParam() {
return this.matchParam;
}
public ASTSqlExpression getSourceChar() {
return (ASTSqlExpression) getChild(0);
}
public ASTSqlExpression getPattern() {
return (ASTSqlExpression) getChild(1);
}
}
| 821 | 22.485714 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTPrimaryPrefix.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTPrimaryPrefix extends AbstractPLSQLNode {
private boolean usesSelfModifier;
ASTPrimaryPrefix(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
void setUsesSelfModifier() {
usesSelfModifier = true;
}
public boolean usesSelfModifier() {
return this.usesSelfModifier;
}
}
| 613 | 21.740741 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTArguments.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTArguments extends AbstractPLSQLNode {
ASTArguments(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public int getArgumentCount() {
if (this.getNumChildren() == 0) {
return 0;
}
return this.getChild(0).getNumChildren();
}
}
| 576 | 22.08 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTInlineConstraint.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public final class ASTInlineConstraint extends AbstractPLSQLNode {
private ConstraintType type;
ASTInlineConstraint(int id) {
super(id);
}
void setType(ConstraintType type) {
this.type = type;
}
public ConstraintType getType() {
return type;
}
public boolean isUnique() {
return type == ConstraintType.UNIQUE;
}
public boolean isPrimaryKey() {
return type == ConstraintType.PRIMARY;
}
public boolean isCheck() {
return type == ConstraintType.CHECK;
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
}
| 853 | 20.897436 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTCompoundCondition.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import java.util.Locale;
public final class ASTCompoundCondition extends AbstractPLSQLNode {
private String type;
ASTCompoundCondition(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
public String getType() {
return type;
}
void setType(String type) {
this.type = type;
if (this.type != null) {
this.type = this.type.toUpperCase(Locale.ROOT);
}
}
}
| 702 | 20.96875 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/ASTPackageBody.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
public class ASTPackageBody extends AbstractPLSQLNode implements OracleObject {
ASTPackageBody(int id) {
super(id);
}
@Override
protected <P, R> R acceptPlsqlVisitor(PlsqlVisitor<? super P, ? extends R> visitor, P data) {
return visitor.visit(this, data);
}
/**
* Gets the name of the Oracle Object.
*
* @return a String representing the name of the Oracle Object
*/
@Override
public String getObjectName() {
return this.getImage();
}
}
| 653 | 22.357143 | 97 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/PLSQLParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast;
import net.sourceforge.pmd.benchmark.TimeTracker;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior;
import net.sourceforge.pmd.lang.ast.impl.javacc.JjtreeParserAdapter;
import net.sourceforge.pmd.lang.plsql.symboltable.SymbolFacade;
public class PLSQLParser extends JjtreeParserAdapter<ASTInput> {
private static final TokenDocumentBehavior TOKEN_BEHAVIOR = new TokenDocumentBehavior(PLSQLTokenKinds.TOKEN_NAMES);
@Override
protected TokenDocumentBehavior tokenBehavior() {
return TOKEN_BEHAVIOR;
}
@Override
protected ASTInput parseImpl(CharStream cs, ParserTask task) throws ParseException {
ASTInput root = new PLSQLParserImpl(cs).Input().addTaskInfo(task);
TimeTracker.bench("PLSQL symbols", () -> SymbolFacade.process(root));
return root;
}
}
| 1,099 | 34.483871 | 119 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/ast/internal/ParsingExclusion.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.ast.internal;
import java.util.Locale;
/**
* This represents an exclusion of a line range from parsing.
*/
public final class ParsingExclusion {
private static final String BEGIN_MARKER = "PMD-EXCLUDE-BEGIN";
//private static final String END_MARKER = "PMD-EXCLUDE-END";
private static final int LEN_BEGIN_MARKER = BEGIN_MARKER.length();
private final int beginLine;
private final int endLine;
private final String excludedSource;
private final String reason;
public ParsingExclusion(int beginLine, int endLine, String source) {
this.beginLine = beginLine;
this.endLine = endLine;
this.excludedSource = source;
final String sourceUpper = source.toUpperCase(Locale.ROOT);
int i1 = sourceUpper.indexOf(BEGIN_MARKER);
int i2 = sourceUpper.indexOf("\n");
String reason = source.substring(i1 + LEN_BEGIN_MARKER, i2).trim();
if (reason.startsWith(":")) {
this.reason = reason.substring(2).trim();
} else {
this.reason = null;
}
}
public String getExcludedSource() {
return excludedSource;
}
public int getBeginLine() {
return beginLine;
}
public int getEndLine() {
return endLine;
}
/**
* The reason is the comment text in the first line after the beginMarker.
*/
public String getReason() {
return reason;
}
}
| 1,562 | 26.421053 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/AbstractPLSQLRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageBody;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTProgramUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ExecutableCode;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLParserVisitor;
import net.sourceforge.pmd.lang.rule.AbstractRule;
public abstract class AbstractPLSQLRule extends AbstractRule implements PLSQLParserVisitor {
@Override
public void apply(Node target, RuleContext ctx) {
target.acceptVisitor(this, ctx);
}
/**
* Gets the Image of the first parent node of type
* ASTClassOrInterfaceDeclaration or <code>null</code>
*
* @param node
* the node which will be searched
*/
protected final String getDeclaringType(Node node) {
Node c;
/*
* Choose the Object Type
*/
c = node.getFirstParentOfType(ASTPackageSpecification.class);
if (c != null) {
return c.getImage();
}
c = node.getFirstParentOfType(ASTTypeSpecification.class);
if (c != null) {
return c.getImage();
}
c = node.getFirstParentOfType(ASTPackageBody.class);
if (c != null) {
return c.getImage();
}
c = node.getFirstParentOfType(ASTTriggerUnit.class);
if (c != null) {
return c.getImage();
}
// Finally Schema-level Methods
c = node.getFirstParentOfType(ASTProgramUnit.class);
if (c != null) {
return c.getImage();
}
return null;
}
public static boolean isQualifiedName(Node node) {
return node.getImage().indexOf('.') != -1;
}
public static boolean importsPackage(ASTInput node, String packageName) {
return false;
}
/*
* Treat all Executable Code
*/
public Object visit(ExecutableCode node, Object data) {
return visitPlsqlNode(node, data);
}
}
| 2,406 | 27.317647 | 92 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/codestyle/AvoidTabCharacterRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.codestyle;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
import net.sourceforge.pmd.lang.plsql.rule.AbstractPLSQLRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
public class AvoidTabCharacterRule extends AbstractPLSQLRule {
private static final PropertyDescriptor<Boolean> EACH_LINE = PropertyFactory.booleanProperty("eachLine")
.desc("Whether to report each line with a tab character or only the first line")
.defaultValue(false)
.build();
public AvoidTabCharacterRule() {
definePropertyDescriptor(EACH_LINE);
addRuleChainVisit(ASTInput.class);
}
@Override
public Object visit(ASTInput node, Object data) {
boolean eachLine = getProperty(EACH_LINE);
int lineNumber = 1;
for (Chars line : node.getText().lines()) {
if (line.indexOf('\t', 0) != -1) {
addViolationWithMessage(data, node,
"Tab characters are not allowed. Use spaces for indentation",
lineNumber, lineNumber);
if (!eachLine) {
break;
}
}
lineNumber++;
}
return data;
}
}
| 1,499 | 32.333333 | 108 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/codestyle/LineLengthRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.codestyle;
import net.sourceforge.pmd.lang.document.Chars;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
import net.sourceforge.pmd.lang.plsql.rule.AbstractPLSQLRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
import net.sourceforge.pmd.properties.constraints.NumericConstraints;
public class LineLengthRule extends AbstractPLSQLRule {
private static final PropertyDescriptor<Integer> MAX_LINE_LENGTH = PropertyFactory.intProperty("maxLineLength")
.desc("The maximum allowed line length")
.defaultValue(80)
.require(NumericConstraints.inRange(10, 200))
.build();
private static final PropertyDescriptor<Boolean> EACH_LINE = PropertyFactory.booleanProperty("eachLine")
.desc("Whether to report each line that is longer only the first line")
.defaultValue(false)
.build();
public LineLengthRule() {
definePropertyDescriptor(MAX_LINE_LENGTH);
definePropertyDescriptor(EACH_LINE);
addRuleChainVisit(ASTInput.class);
}
@Override
public Object visit(ASTInput node, Object data) {
boolean eachLine = getProperty(EACH_LINE);
int maxLineLength = getProperty(MAX_LINE_LENGTH);
int lineNumber = 1;
for (Chars line : node.getText().lines()) {
if (line.length() > maxLineLength) {
addViolationWithMessage(data, node, "The line is too long. Only " + maxLineLength + " characters are allowed.",
lineNumber, lineNumber);
if (!eachLine) {
break;
}
}
lineNumber++;
}
return data;
}
}
| 1,910 | 35.75 | 127 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/codestyle/CodeFormatRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.codestyle;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange;
import java.util.List;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTArgument;
import net.sourceforge.pmd.lang.plsql.ast.ASTArgumentList;
import net.sourceforge.pmd.lang.plsql.ast.ASTBulkCollectIntoClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTDatatype;
import net.sourceforge.pmd.lang.plsql.ast.ASTDeclarativeSection;
import net.sourceforge.pmd.lang.plsql.ast.ASTEqualityExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.plsql.ast.ASTFormalParameters;
import net.sourceforge.pmd.lang.plsql.ast.ASTFromClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
import net.sourceforge.pmd.lang.plsql.ast.ASTJoinClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTSelectList;
import net.sourceforge.pmd.lang.plsql.ast.ASTSubqueryOperation;
import net.sourceforge.pmd.lang.plsql.ast.ASTUnqualifiedID;
import net.sourceforge.pmd.lang.plsql.ast.ASTVariableOrConstantDeclarator;
import net.sourceforge.pmd.lang.plsql.rule.AbstractPLSQLRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
public class CodeFormatRule extends AbstractPLSQLRule {
private static final PropertyDescriptor<Integer> INDENTATION_PROPERTY =
PropertyFactory.intProperty("indentation")
.desc("Indentation to be used for blocks")
.defaultValue(2)
.require(inRange(0, 32))
.build();
private int indentation = INDENTATION_PROPERTY.defaultValue();
public CodeFormatRule() {
definePropertyDescriptor(INDENTATION_PROPERTY);
}
@Override
public Object visit(ASTInput node, Object data) {
indentation = getProperty(INDENTATION_PROPERTY);
return super.visit(node, data);
}
@Override
public Object visit(ASTSelectList node, Object data) {
Node parent = node.getParent();
checkEachChildOnNextLine(data, node, parent.getBeginLine(), parent.getBeginColumn() + 7);
return super.visit(node, data);
}
@Override
public Object visit(ASTBulkCollectIntoClause node, Object data) {
Node parent = node.getParent();
checkIndentation(data, node, parent.getBeginColumn() + indentation, "BULK COLLECT INTO");
checkEachChildOnNextLine(data, node, node.getBeginLine(), parent.getBeginColumn() + 7);
return super.visit(node, data);
}
@Override
public Object visit(ASTFromClause node, Object data) {
checkIndentation(data, node, node.getParent().getBeginColumn() + indentation, "FROM");
return super.visit(node, data);
}
@Override
public Object visit(ASTJoinClause node, Object data) {
// first child is the table reference
Node tableReference = node.getChild(0);
// remaining children are joins
int lineNumber = tableReference.getBeginLine();
for (int i = 1; i < node.getNumChildren(); i++) {
lineNumber++;
Node child = node.getChild(i);
if (child.getBeginLine() != lineNumber) {
addViolationWithMessage(data, child, child.getXPathNodeName() + " should be on line " + lineNumber);
}
List<ASTEqualityExpression> conditions = child.findDescendantsOfType(ASTEqualityExpression.class);
if (conditions.size() == 1) {
// one condition should be on the same line
ASTEqualityExpression singleCondition = conditions.get(0);
if (singleCondition.getBeginLine() != lineNumber) {
addViolationWithMessage(data, child,
"Join condition \"" + singleCondition.getImage() + "\" should be on line " + lineNumber);
}
} else {
// each condition on a separate line
for (ASTEqualityExpression singleCondition : conditions) {
lineNumber++;
if (singleCondition.getBeginLine() != lineNumber) {
addViolationWithMessage(data, child,
"Join condition \"" + singleCondition.getImage() + "\" should be on line "
+ lineNumber);
}
}
}
}
return super.visit(node, data);
}
@Override
public Object visit(ASTSubqueryOperation node, Object data) {
// get previous sibling
int thisIndex = node.getIndexInParent();
Node prevSibling = node.getParent().getChild(thisIndex - 1);
checkIndentation(data, node, prevSibling.getBeginColumn(), node.getImage());
// it should also be on the next line
if (node.getBeginLine() != prevSibling.getEndLine() + 1) {
addViolationWithMessage(data, node,
node.getImage() + " should be on line " + (prevSibling.getEndLine() + 1));
}
return super.visit(node, data);
}
private int checkEachChildOnNextLine(Object data, Node parent, int firstLine, int indentation) {
int currentLine = firstLine;
for (int i = 0; i < parent.getNumChildren(); i++) {
Node child = parent.getChild(i);
String image = child.getImage();
if (image == null && child.getNumChildren() > 0) {
image = child.getChild(0).getImage();
}
if (child.getBeginLine() != currentLine) {
addViolationWithMessage(data, child, image + " should be on line " + currentLine);
} else if (i > 0 && child.getBeginColumn() != indentation) {
addViolationWithMessage(data, child, image + " should begin at column " + indentation);
}
// next entry needs to be on the next line
currentLine++;
}
return currentLine;
}
private void checkLineAndIndentation(Object data, Node node, int line, int indentation, String name) {
if (node.getBeginLine() != line) {
addViolationWithMessage(data, node, name + " should be on line " + line);
} else if (node.getBeginColumn() != indentation) {
addViolationWithMessage(data, node, name + " should begin at column " + indentation);
}
}
private void checkIndentation(Object data, Node node, int indentation, String name) {
if (node.getBeginColumn() != indentation) {
addViolationWithMessage(data, node, name + " should begin at column " + indentation);
}
}
@Override
public Object visit(ASTFormalParameters node, Object data) {
int parameterIndentation = node.getParent().getBeginColumn() + indentation;
checkEachChildOnNextLine(data, node, node.getBeginLine() + 1, parameterIndentation);
// check the data type alignment
List<ASTFormalParameter> parameters = node.findChildrenOfType(ASTFormalParameter.class);
if (parameters.size() > 1) {
ASTDatatype first = parameters.get(0).getFirstChildOfType(ASTDatatype.class);
for (int i = 1; first != null && i < parameters.size(); i++) {
ASTDatatype nextType = parameters.get(i).getFirstChildOfType(ASTDatatype.class);
if (nextType != null) {
checkIndentation(data, nextType, first.getBeginColumn(), "Type " + nextType.getImage());
}
}
}
return super.visit(node, data);
}
@Override
public Object visit(ASTDeclarativeSection node, Object data) {
int variableIndentation = node.getNthParent(2).getBeginColumn() + 2 * indentation;
int line = node.getBeginLine();
List<ASTVariableOrConstantDeclarator> variables = node
.findDescendantsOfType(ASTVariableOrConstantDeclarator.class);
int datatypeIndentation = variableIndentation;
if (!variables.isEmpty()) {
ASTDatatype datatype = variables.get(0).getFirstChildOfType(ASTDatatype.class);
if (datatype != null) {
datatypeIndentation = datatype.getBeginColumn();
}
}
for (ASTVariableOrConstantDeclarator variable : variables) {
checkLineAndIndentation(data, variable, line, variableIndentation, variable.getImage());
ASTDatatype datatype = variable.getFirstChildOfType(ASTDatatype.class);
if (datatype != null) {
checkIndentation(data, datatype, datatypeIndentation, "Type " + datatype.getImage());
}
line++;
}
return super.visit(node, data);
}
@Override
public Object visit(ASTArgumentList node, Object data) {
List<ASTArgument> arguments = node.findChildrenOfType(ASTArgument.class);
// note: end column is exclusive
if (node.getEndColumn() >= 120) {
addViolationWithMessage(data, node, "Line is too long, please split parameters on separate lines");
return super.visit(node, data);
}
if (arguments.size() > 3) {
// procedure calls with more than 3 parameters should use named parameters
if (usesSimpleParameters(arguments)) {
addViolationWithMessage(data, node,
"Procedure call with more than three parameters should use named parameters.");
}
// more than three parameters -> each parameter on a separate line
int line = node.getBeginLine();
int indentation = node.getBeginColumn();
int longestParameterEndColumn = 0;
for (ASTArgument argument : arguments) {
checkLineAndIndentation(data, argument, line, indentation, "Parameter " + argument.getImage());
line++;
if (argument.getChild(0) instanceof ASTUnqualifiedID) {
if (argument.getChild(0).getEndColumn() > longestParameterEndColumn) {
longestParameterEndColumn = argument.getChild(0).getEndColumn() - 1;
}
}
}
// now check for the indentation of the expressions
int expectedBeginColumn = longestParameterEndColumn + 3 + "=> ".length();
// take the indentation from the first one, if it is greater
if (!arguments.isEmpty() && arguments.get(0).getNumChildren() == 2
&& arguments.get(0).getChild(1).getBeginColumn() > expectedBeginColumn) {
expectedBeginColumn = arguments.get(0).getChild(1).getBeginColumn();
}
for (ASTArgument argument : arguments) {
if (argument.getNumChildren() == 2 && argument.getChild(0) instanceof ASTUnqualifiedID) {
Node expr = argument.getChild(1);
checkIndentation(data, expr, expectedBeginColumn, expr.getImage());
}
}
// closing parenthesis should be on a new line
Node primaryExpression = node.getNthParent(3);
if (primaryExpression.getEndLine() != node.getEndLine() + 1) {
addViolationWithMessage(data, primaryExpression, "Closing parenthesis should be on a new line.");
}
}
return super.visit(node, data);
}
private boolean usesSimpleParameters(List<ASTArgument> arguments) {
for (ASTArgument argument : arguments) {
if (argument.getNumChildren() == 1) {
return true;
}
}
return false;
}
}
| 11,833 | 42.032727 | 117 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessiveMethodLengthRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.lang.plsql.ast.ExecutableCode;
/**
* This rule detects when a method exceeds a certain threshold. i.e. if a method
* has more than x lines of code.
*/
public class ExcessiveMethodLengthRule extends AbstractCounterCheckRule.AbstractLineLengthCheckRule<ExecutableCode> {
public ExcessiveMethodLengthRule() {
super(ExecutableCode.class
);
}
@Override
protected int defaultReportLevel() {
return 100;
}
}
| 619 | 24.833333 | 117 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/TooManyFieldsRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTVariableOrConstantDeclaration;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
import net.sourceforge.pmd.lang.plsql.rule.AbstractPLSQLRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
public class TooManyFieldsRule extends AbstractPLSQLRule {
private static final int DEFAULT_MAXFIELDS = 15;
private Map<String, Integer> stats;
private Map<String, PLSQLNode> nodes;
private static final PropertyDescriptor<Integer> MAX_FIELDS_DESCRIPTOR
= PropertyFactory.intProperty("maxfields")
.desc("Max allowable fields")
.defaultValue(DEFAULT_MAXFIELDS)
.require(positive())
.build();
public TooManyFieldsRule() {
definePropertyDescriptor(MAX_FIELDS_DESCRIPTOR);
}
@Override
public Object visit(ASTInput node, Object data) {
stats = new HashMap<>(5);
nodes = new HashMap<>(5);
return super.visit(node, data);
}
@Override
public Object visit(ASTPackageSpecification node, Object data) {
int maxFields = getProperty(MAX_FIELDS_DESCRIPTOR);
List<ASTVariableOrConstantDeclaration> l = node.findDescendantsOfType(ASTVariableOrConstantDeclaration.class);
for (ASTVariableOrConstantDeclaration fd : l) {
bumpCounterFor(fd);
}
for (String k : stats.keySet()) {
int val = stats.get(k);
Node n = nodes.get(k);
if (val > maxFields) {
addViolation(data, n);
}
}
return data;
}
@Override
public Object visit(ASTTypeSpecification node, Object data) {
int maxFields = getProperty(MAX_FIELDS_DESCRIPTOR);
List<ASTVariableOrConstantDeclaration> l = node.findDescendantsOfType(ASTVariableOrConstantDeclaration.class);
for (ASTVariableOrConstantDeclaration fd : l) {
bumpCounterFor(fd);
}
for (String k : stats.keySet()) {
int val = stats.get(k);
Node n = nodes.get(k);
if (val > maxFields) {
addViolation(data, n);
}
}
return data;
}
private void bumpCounterFor(PLSQLNode clazz) {
String key = clazz.getImage();
if (!stats.containsKey(key)) {
stats.put(key, 0);
nodes.put(key, clazz);
}
Integer i = stats.get(key) + 1;
stats.put(key, i);
}
}
| 3,132 | 30.33 | 118 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/NcssObjectCountRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.lang.plsql.ast.ASTGlobal;
import net.sourceforge.pmd.lang.plsql.ast.ASTProgramUnit;
import net.sourceforge.pmd.lang.plsql.ast.OracleObject;
/**
* Non-commented source statement counter for Oracle Object declarations.
*
* @author Stuart Turton
*/
public class NcssObjectCountRule extends AbstractNcssCountRule<OracleObject> {
/**
* Count type declarations. This includes Oracle Objects.
*/
public NcssObjectCountRule() {
super(OracleObject.class);
}
@Override
protected int defaultReportLevel() {
return 1500;
}
@Override
protected boolean isIgnored(OracleObject node) {
// Treat Schema-level ProgramUnits as Oracle Objects, otherwise as
// subprograms
return node instanceof ASTProgramUnit && !(node.getParent() instanceof ASTGlobal);
}
@Override
protected Object[] getViolationParameters(OracleObject node, int metric) {
String name = node.getObjectName();
return new Object[] {name == null ? "(unnamed)" : name, metric};
}
}
| 1,219 | 27.372093 | 90 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/AbstractNcssCountRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTCaseStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTCaseWhenClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTContinueStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTElseClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTElsifClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTExceptionHandler;
import net.sourceforge.pmd.lang.plsql.ast.ASTExitStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTFieldDeclaration;
import net.sourceforge.pmd.lang.plsql.ast.ASTForStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTGotoStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTLabelledStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTLoopStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTRaiseStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTReturnStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTWhileStatement;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLParserVisitorAdapter;
/**
* Abstract superclass for NCSS counting methods. Analogous to and cribbed from
* the Java version of the rule.
*
* @deprecated Internal API
*/
@Deprecated
@InternalApi
public abstract class AbstractNcssCountRule<T extends PLSQLNode> extends AbstractCounterCheckRule<T> {
/**
* Count the nodes of the given type using NCSS rules.
*
* @param nodeClass class of node to count
*/
AbstractNcssCountRule(Class<T> nodeClass) {
super(nodeClass);
}
@Override
protected int getMetric(T node) {
return 1 + (Integer) node.jjtAccept(new NcssVisitor(), null);
}
private static final class NcssVisitor extends PLSQLParserVisitorAdapter {
@Override
public Object visitPlsqlNode(PLSQLNode node, Object data) {
return countNodeChildren(node, data);
}
/**
* Count the number of children of the given node. Adds one to count the
* node itself.
*
* @param node node having children counted
* @param data node data
*
* @return count of the number of children of the node, plus one
*/
protected Integer countNodeChildren(Node node, Object data) {
int nodeCount = 0;
for (int i = 0; i < node.getNumChildren(); i++) {
nodeCount += (Integer) ((PLSQLNode) node.getChild(i)).jjtAccept(this, data);
}
return nodeCount;
}
@Override
public Object visit(ASTForStatement node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTLoopStatement node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTIfStatement node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTElsifClause node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTElseClause node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTWhileStatement node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTExitStatement node, Object data) {
return 1;
}
@Override
public Object visit(ASTExceptionHandler node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTContinueStatement node, Object data) {
return 1;
}
@Override
public Object visit(ASTGotoStatement node, Object data) {
return 1;
}
@Override
public Object visit(ASTReturnStatement node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTCaseStatement node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTRaiseStatement node, Object data) {
return 1;
}
@Override
public Object visit(ASTExpression node, Object data) {
// "For" update expressions do not count as separate lines of code
return node.getParent() instanceof ASTStatement ? 0 : 1;
}
@Override
public Object visit(ASTFieldDeclaration node, Object data) {
return 1;
}
@Override
public Object visit(ASTLabelledStatement node, Object data) {
return countNodeChildren(node, data) + 1;
}
@Override
public Object visit(ASTCaseWhenClause node, Object data) {
return countNodeChildren(node, data) + 1;
}
}
}
| 5,394 | 30.923077 | 102 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/NcssMethodCountRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.lang.plsql.ast.ExecutableCode;
/**
* Non-commented source statement counter for methods.
*
* <p>Analogous to and cribbed from Java version of the rule.</p>
*/
public class NcssMethodCountRule extends AbstractNcssCountRule<ExecutableCode> {
/**
* Count the size of all non-constructor methods.
*/
public NcssMethodCountRule() {
super(ExecutableCode.class);
}
@Override
protected int defaultReportLevel() {
return 100;
}
@Override
protected Object[] getViolationParameters(ExecutableCode node, int metric) {
String name = node.getMethodName();
return new Object[] {name == null ? "(unnamed)" : name, metric};
}
}
| 868 | 22.486486 | 80 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/NPathComplexityRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import java.util.List;
import net.sourceforge.pmd.lang.plsql.ast.ASTConditionalAndExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTConditionalOrExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTExpression;
import net.sourceforge.pmd.lang.plsql.ast.ExecutableCode;
/**
* NPath complexity is a measurement of the acyclic execution paths through a
* function. See Nejmeh, Communications of the ACM Feb 1988 pp 188-200.
*
* @author Jason Bennett
*/
public class NPathComplexityRule extends AbstractCounterCheckRule<ExecutableCode> {
public NPathComplexityRule() {
super(ExecutableCode.class);
}
@Override
protected int defaultReportLevel() {
return 200;
}
@Override
protected int getMetric(ExecutableCode node) {
return new NPathComplexityVisitor().compute(node);
}
@Override
protected Object[] getViolationParameters(ExecutableCode node, int metric) {
return new Object[] {node.getMethodName(), metric};
}
/**
* Calculate the boolean complexity of the given expression. NPath boolean
* complexity is the sum of && and || tokens. This is calculated by summing
* the number of children of the &&'s (minus one) and the children of the
* ||'s (minus one).
*
* <p>Note that this calculation applies to Cyclomatic Complexity as well.</p>
*
* @param expr control structure expression
*
* @return complexity of the boolean expression
*/
static int sumExpressionComplexity(ASTExpression expr) {
if (expr == null) {
return 0;
}
List<ASTConditionalAndExpression> andNodes = expr.findDescendantsOfType(ASTConditionalAndExpression.class);
List<ASTConditionalOrExpression> orNodes = expr.findDescendantsOfType(ASTConditionalOrExpression.class);
int children = 0;
for (ASTConditionalOrExpression element : orNodes) {
children += element.getNumChildren();
children--;
}
for (ASTConditionalAndExpression element : andNodes) {
children += element.getNumChildren();
children--;
}
return children;
}
}
| 2,353 | 29.571429 | 115 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/CyclomaticComplexityRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive;
import java.util.ArrayDeque;
import java.util.Deque;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.plsql.ast.ASTCaseStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTCaseWhenClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTConditionalOrExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTElsifClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTExceptionHandler;
import net.sourceforge.pmd.lang.plsql.ast.ASTExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTForStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
import net.sourceforge.pmd.lang.plsql.ast.ASTLoopStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTMethodDeclarator;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageBody;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTProgramUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerTimingPointSection;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeMethod;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTWhileStatement;
import net.sourceforge.pmd.lang.plsql.rule.AbstractPLSQLRule;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
/**
* @author Donald A. Leckie,
*
* @version $Revision: 5956 $, $Date: 2008-04-04 04:59:25 -0500 (Fri, 04 Apr
* 2008) $
* @since January 14, 2003
*/
public class CyclomaticComplexityRule extends AbstractPLSQLRule {
private static final Logger LOG = LoggerFactory.getLogger(CyclomaticComplexityRule.class);
public static final PropertyDescriptor<Integer> REPORT_LEVEL_DESCRIPTOR
= PropertyFactory.intProperty("reportLevel")
.desc("Cyclomatic Complexity reporting threshold")
.require(positive()).defaultValue(10).build();
public static final PropertyDescriptor<Boolean> SHOW_CLASSES_COMPLEXITY_DESCRIPTOR =
PropertyFactory.booleanProperty("showClassesComplexity")
.desc("Add class average violations to the report")
.defaultValue(true).build();
public static final PropertyDescriptor<Boolean> SHOW_METHODS_COMPLEXITY_DESCRIPTOR =
PropertyFactory.booleanProperty("showMethodsComplexity")
.desc("Add method average violations to the report")
.defaultValue(true).build();
private int reportLevel;
private boolean showClassesComplexity = true;
private boolean showMethodsComplexity = true;
private static final class Entry {
private int decisionPoints = 1;
public int highestDecisionPoints;
public int methodCount;
public void bumpDecisionPoints() {
decisionPoints++;
}
public void bumpDecisionPoints(int size) {
decisionPoints += size;
}
public int getComplexityAverage() {
return (double) methodCount == 0 ? 1 : (int) Math.rint((double) decisionPoints / (double) methodCount);
}
}
private Deque<Entry> entryStack = new ArrayDeque<>();
public CyclomaticComplexityRule() {
definePropertyDescriptor(REPORT_LEVEL_DESCRIPTOR);
definePropertyDescriptor(SHOW_CLASSES_COMPLEXITY_DESCRIPTOR);
definePropertyDescriptor(SHOW_METHODS_COMPLEXITY_DESCRIPTOR);
}
@Override
public Object visit(ASTInput node, Object data) {
reportLevel = getProperty(REPORT_LEVEL_DESCRIPTOR);
showClassesComplexity = getProperty(SHOW_CLASSES_COMPLEXITY_DESCRIPTOR);
showMethodsComplexity = getProperty(SHOW_METHODS_COMPLEXITY_DESCRIPTOR);
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTElsifClause node, Object data) {
int boolCompIf = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
// If statement always has a complexity of at least 1
boolCompIf++;
entryStack.peek().bumpDecisionPoints(boolCompIf);
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTIfStatement node, Object data) {
int boolCompIf = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
// If statement always has a complexity of at least 1
boolCompIf++;
entryStack.peek().bumpDecisionPoints(boolCompIf);
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTExceptionHandler node, Object data) {
entryStack.peek().bumpDecisionPoints();
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTForStatement node, Object data) {
int boolCompFor = NPathComplexityRule
.sumExpressionComplexity(node.getFirstDescendantOfType(ASTExpression.class));
// For statement always has a complexity of at least 1
boolCompFor++;
entryStack.peek().bumpDecisionPoints(boolCompFor);
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTLoopStatement node, Object data) {
int boolCompDo = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
// Do statement always has a complexity of at least 1
boolCompDo++;
entryStack.peek().bumpDecisionPoints(boolCompDo);
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTCaseStatement node, Object data) {
Entry entry = entryStack.peek();
int boolCompSwitch = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
entry.bumpDecisionPoints(boolCompSwitch);
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTCaseWhenClause node, Object data) {
Entry entry = entryStack.peek();
entry.bumpDecisionPoints();
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTWhileStatement node, Object data) {
int boolCompWhile = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
// While statement always has a complexity of at least 1
boolCompWhile++;
entryStack.peek().bumpDecisionPoints(boolCompWhile);
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTConditionalOrExpression node, Object data) {
return data;
}
@Override
public Object visit(ASTPackageSpecification node, Object data) {
// Treat Package Specification like an Interface
return data;
}
@Override
public Object visit(ASTTypeSpecification node, Object data) {
// Treat Type Specification like an Interface
return data;
}
@Override
public Object visit(ASTPackageBody node, Object data) {
entryStack.push(new Entry());
super.visit(node, data);
Entry classEntry = entryStack.pop();
LOG.debug("ASTPackageBody: ComplexityAverage=={}, highestDecisionPoint={}",
classEntry.getComplexityAverage(), classEntry.highestDecisionPoints);
if (showClassesComplexity) {
if (classEntry.getComplexityAverage() >= reportLevel || classEntry.highestDecisionPoints >= reportLevel) {
addViolation(data, node, new String[] { "class", node.getImage(),
classEntry.getComplexityAverage() + " (Highest = " + classEntry.highestDecisionPoints + ')', });
}
}
return data;
}
@Override
public Object visit(ASTTriggerUnit node, Object data) {
entryStack.push(new Entry());
super.visit(node, data);
Entry classEntry = entryStack.pop();
LOG.debug("ASTTriggerUnit: ComplexityAverage=={}, highestDecisionPoint={}",
classEntry.getComplexityAverage(),
classEntry.highestDecisionPoints);
if (showClassesComplexity) {
if (classEntry.getComplexityAverage() >= reportLevel || classEntry.highestDecisionPoints >= reportLevel) {
addViolation(data, node, new String[] { "class", node.getImage(),
classEntry.getComplexityAverage() + " (Highest = " + classEntry.highestDecisionPoints + ')', });
}
}
return data;
}
private void updateClassEntry(int methodDecisionPoints) {
Entry classEntry = entryStack.peek();
classEntry.methodCount++;
classEntry.bumpDecisionPoints(methodDecisionPoints);
if (methodDecisionPoints > classEntry.highestDecisionPoints) {
classEntry.highestDecisionPoints = methodDecisionPoints;
}
}
@Override
public Object visit(ASTProgramUnit node, Object data) {
entryStack.push(new Entry());
super.visit(node, data);
Entry methodEntry = entryStack.pop();
LOG.debug("ASTProgramUnit: ComplexityAverage=={}, highestDecisionPoint={}",
methodEntry.getComplexityAverage(),
methodEntry.highestDecisionPoints);
if (showMethodsComplexity) {
// Entry methodEntry = entryStack.pop();
int methodDecisionPoints = methodEntry.decisionPoints;
// PackageBody (including Object Type Body)
if (null != node.getFirstParentOfType(ASTPackageBody.class)
// Trigger of any form
|| null != node.getFirstParentOfType(ASTTriggerUnit.class)
// TODO || null != node.getFirstParentOfType(ASTProgramUnit.class)
// //Another Procedure
// TODO || null != node.getFirstParentOfType(ASTTypeMethod.class)
// //Another Type method
) {
/*
* TODO This does not cope with nested methods We need the
* outer most ASTPackageBody ASTTriggerUni ASTProgramUnit
* ASTTypeMethod
*
*/
updateClassEntry(methodDecisionPoints);
}
ASTMethodDeclarator methodDeclarator = node.getFirstChildOfType(ASTMethodDeclarator.class);
if (methodEntry.decisionPoints >= reportLevel) {
addViolation(data, node,
new String[] { "method", methodDeclarator == null ? "" : methodDeclarator.getImage(),
String.valueOf(methodEntry.decisionPoints), });
}
}
return data;
}
@Override
public Object visit(ASTTypeMethod node, Object data) {
entryStack.push(new Entry());
super.visit(node, data);
Entry methodEntry = entryStack.pop();
LOG.debug("ASTProgramUnit: ComplexityAverage=={}, highestDecisionPoint={}",
methodEntry.getComplexityAverage(),
methodEntry.highestDecisionPoints);
if (showMethodsComplexity) {
// Entry methodEntry = entryStack.pop();
int methodDecisionPoints = methodEntry.decisionPoints;
// PAckageBody (including Object Type Body)
if (null != node.getFirstParentOfType(ASTPackageBody.class)) {
/*
* TODO This does not cope with nested methods We need the
* outer most ASTPackageBody
*/
updateClassEntry(methodDecisionPoints);
}
ASTMethodDeclarator methodDeclarator = node.getFirstChildOfType(ASTMethodDeclarator.class);
if (methodEntry.decisionPoints >= reportLevel) {
addViolation(data, node,
new String[] { "method", methodDeclarator == null ? "" : methodDeclarator.getImage(),
String.valueOf(methodEntry.decisionPoints), });
}
}
return data;
}
@Override
public Object visit(ASTTriggerTimingPointSection node, Object data) {
entryStack.push(new Entry());
super.visit(node, data);
Entry methodEntry = entryStack.pop();
LOG.debug("ASTTriggerTimingPointSection: ComplexityAverage=={}, highestDecisionPoint={}",
methodEntry.getComplexityAverage(),
methodEntry.highestDecisionPoints);
if (showMethodsComplexity) {
int methodDecisionPoints = methodEntry.decisionPoints;
Entry classEntry = entryStack.peek();
classEntry.methodCount++;
classEntry.bumpDecisionPoints(methodDecisionPoints);
if (methodDecisionPoints > classEntry.highestDecisionPoints) {
classEntry.highestDecisionPoints = methodDecisionPoints;
}
ASTMethodDeclarator methodDeclarator = node.getFirstChildOfType(ASTMethodDeclarator.class);
if (methodEntry.decisionPoints >= reportLevel) {
addViolation(data, node,
new String[] { "method", methodDeclarator == null ? "" : methodDeclarator.getImage(),
String.valueOf(methodEntry.decisionPoints), });
}
}
return data;
}
}
| 13,687 | 38.790698 | 120 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessivePackageBodyLengthRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageBody;
/**
* This rule detects when a class exceeds a certain threshold. i.e. if a class
* has more than 1000 lines of code.
*/
public class ExcessivePackageBodyLengthRule extends AbstractCounterCheckRule.AbstractLineLengthCheckRule<ASTPackageBody> {
public ExcessivePackageBodyLengthRule() {
super(ASTPackageBody.class);
}
@Override
protected int defaultReportLevel() {
return 1000;
}
}
| 622 | 26.086957 | 122 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessivePackageSpecificationLengthRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageSpecification;
/**
* This rule detects when a class exceeds a certain threshold. i.e. if a class
* has more than 1000 lines of code.
*/
public class ExcessivePackageSpecificationLengthRule extends AbstractCounterCheckRule.AbstractLineLengthCheckRule<ASTPackageSpecification> {
public ExcessivePackageSpecificationLengthRule() {
super(ASTPackageSpecification.class);
}
@Override
protected int defaultReportLevel() {
return 1000;
}
}
| 668 | 26.875 | 140 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessiveTypeLengthRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeSpecification;
/**
* This rule detects when a class exceeds a certain threshold. i.e. if a class
* has more than 1000 lines of code.
*/
public class ExcessiveTypeLengthRule extends AbstractCounterCheckRule.AbstractLineLengthCheckRule<ASTTypeSpecification> {
public ExcessiveTypeLengthRule() {
super(ASTTypeSpecification.class);
}
@Override
protected int defaultReportLevel() {
return 1000;
}
}
| 626 | 26.26087 | 121 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessiveParameterListRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.lang.plsql.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.plsql.ast.ASTFormalParameters;
/**
* This rule detects an abnormally long parameter list. Note: This counts Nodes,
* and not necessarily parameters, so the numbers may not match up. (But
* topcount and sigma should work.)
*/
public class ExcessiveParameterListRule extends AbstractCounterCheckRule<ASTFormalParameters> {
public ExcessiveParameterListRule() {
super(ASTFormalParameters.class);
}
@Override
protected int defaultReportLevel() {
return 10;
}
@Override
protected int getMetric(ASTFormalParameters node) {
return node.findChildrenOfType(ASTFormalParameter.class).size();
}
}
| 886 | 27.612903 | 95 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/AbstractCounterCheckRule.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive;
import java.lang.reflect.Modifier;
import net.sourceforge.pmd.lang.plsql.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageBody;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTProgramUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerTimingPointSection;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeMethod;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ExecutableCode;
import net.sourceforge.pmd.lang.plsql.ast.OracleObject;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
import net.sourceforge.pmd.lang.plsql.rule.AbstractPLSQLRule;
import net.sourceforge.pmd.lang.rule.internal.CommonPropertyDescriptors;
import net.sourceforge.pmd.properties.PropertyDescriptor;
/**
* Abstract class for rules counting the length of some node.
*
* @author Clément Fournier
* @since 6.7.0
*/
// PACKAGE PRIVATE or move in internal package at most
abstract class AbstractCounterCheckRule<T extends PLSQLNode> extends AbstractPLSQLRule {
private final PropertyDescriptor<Integer> reportLevel =
CommonPropertyDescriptors.reportLevelProperty()
.desc("Threshold above which a node is reported")
.require(positive())
.defaultValue(defaultReportLevel()).build();
AbstractCounterCheckRule(Class<T> nodeType) {
definePropertyDescriptor(reportLevel);
if (!(Modifier.isAbstract(nodeType.getModifiers()) || nodeType.isInterface())) {
addRuleChainVisit(nodeType);
} else {
determineRulechainVisits(nodeType);
}
}
// FIXME find a generic way to add a rulechain visit on an abstract node type
private void determineRulechainVisits(Class<T> abstractNodeType) {
if (abstractNodeType == OracleObject.class) {
addRuleChainVisit(ASTPackageBody.class);
addRuleChainVisit(ASTPackageSpecification.class);
addRuleChainVisit(ASTProgramUnit.class);
addRuleChainVisit(ASTTriggerUnit.class);
addRuleChainVisit(ASTTypeSpecification.class);
} else if (abstractNodeType == ExecutableCode.class) {
addRuleChainVisit(ASTMethodDeclaration.class);
addRuleChainVisit(ASTProgramUnit.class);
addRuleChainVisit(ASTTriggerTimingPointSection.class);
addRuleChainVisit(ASTTriggerUnit.class);
addRuleChainVisit(ASTTypeMethod.class);
}
}
protected abstract int defaultReportLevel();
/** Return true if the node should be ignored. */
protected boolean isIgnored(T node) {
return false;
}
protected Object[] getViolationParameters(T node, int metric) {
return new Object[] {metric};
}
protected abstract int getMetric(T node);
@Override
public Object visitPlsqlNode(PLSQLNode node, Object data) {
@SuppressWarnings("unchecked")
T t = (T) node;
// since we only visit this node, it's ok
if (!isIgnored(t)) {
int metric = getMetric(t);
if (metric >= getProperty(reportLevel)) {
addViolation(data, node, getViolationParameters(t, metric));
}
}
return data;
}
abstract static class AbstractLineLengthCheckRule<T extends PLSQLNode> extends AbstractCounterCheckRule<T> {
AbstractLineLengthCheckRule(Class<T> nodeType) {
super(nodeType);
}
@Override
protected int getMetric(T node) {
return node.getEndLine() - node.getBeginLine();
}
}
}
| 4,015 | 33.033898 | 112 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/NPathComplexityVisitor.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.pmd.lang.plsql.ast.ASTCaseStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTCaseWhenClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTConditionalOrExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTElseClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTElsifClause;
import net.sourceforge.pmd.lang.plsql.ast.ASTExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTForStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTIfStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTLoopStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTMethodDeclaration;
import net.sourceforge.pmd.lang.plsql.ast.ASTProgramUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTReturnStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerTimingPointSection;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeMethod;
import net.sourceforge.pmd.lang.plsql.ast.ASTWhileStatement;
import net.sourceforge.pmd.lang.plsql.ast.ExecutableCode;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLParserVisitorAdapter;
/**
* @author Clément Fournier
*/
class NPathComplexityVisitor extends PLSQLParserVisitorAdapter {
public int compute(ExecutableCode root) {
return (int) root.jjtAccept(this, null);
}
private int complexityMultipleOf(PLSQLNode node, Object data) {
int npath = 1;
PLSQLNode n;
for (int i = 0; i < node.getNumChildren(); i++) {
n = (PLSQLNode) node.getChild(i);
npath *= (Integer) n.jjtAccept(this, data);
}
return npath;
}
@Override
public Object visit(ASTMethodDeclaration node, Object data) {
return complexityMultipleOf(node, data);
}
@Override
public Object visit(ASTProgramUnit node, Object data) {
return complexityMultipleOf(node, data);
}
@Override
public Object visit(ASTTypeMethod node, Object data) {
return complexityMultipleOf(node, data);
}
@Override
public Object visit(ASTTriggerUnit node, Object data) {
return complexityMultipleOf(node, data);
}
@Override
public Object visit(ASTTriggerTimingPointSection node, Object data) {
return complexityMultipleOf(node, data);
}
@Override
public Object visitPlsqlNode(PLSQLNode node, Object data) {
return complexityMultipleOf(node, data);
}
@Override
public Object visit(ASTIfStatement node, Object data) {
// (npath of if + npath of else (or 1) + bool_comp of if) * npath of
// next
int boolCompIf = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
int complexity = 0;
List<PLSQLNode> statementChildren = new ArrayList<>();
for (int i = 0; i < node.getNumChildren(); i++) {
if (node.getChild(i).getClass() == ASTStatement.class
|| node.getChild(i).getClass() == ASTElsifClause.class
|| node.getChild(i).getClass() == ASTElseClause.class) {
statementChildren.add(node.getChild(i));
}
}
/*
* SRT if (statementChildren.isEmpty() || statementChildren.size() == 1
* && ( null != node.getFirstChildOfType(ASTElseClause.class) )
* //.hasElse() || statementChildren.size() != 1 && ( null ==
* node.getFirstChildOfType(ASTElseClause.class) ) // !node.hasElse() )
* { throw new
* IllegalStateException("If node has wrong number of children"); }
*/
/*
* @TODO Any explicit Elsif clause(s) and Else clause are included in
* the list of statements // add path for not taking if if (null ==
* node.getFirstChildOfType(ASTElsifClause.class) ) //
* !node.hasElse()!node.hasElse()) { complexity++; }
*
* if (null == node.getFirstChildOfType(ASTElseClause.class) ) //
* !node.hasElse()!node.hasElse()) { complexity++; }
*/
for (PLSQLNode element : statementChildren) {
complexity += (Integer) element.jjtAccept(this, data);
}
return boolCompIf + complexity;
}
@Override
public Object visit(ASTElsifClause node, Object data) {
// (npath of if + npath of else (or 1) + bool_comp of if) * npath of
// next
int boolCompIf = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
int complexity = 0;
List<PLSQLNode> statementChildren = new ArrayList<>();
for (int i = 0; i < node.getNumChildren(); i++) {
if (node.getChild(i).getClass() == ASTStatement.class) {
statementChildren.add((PLSQLNode) node.getChild(i));
}
}
/*
* SRT if (statementChildren.isEmpty() || statementChildren.size() == 1
* && ( null != node.getFirstChildOfType(ASTElseClause.class) )
* //.hasElse() || statementChildren.size() != 1 && ( null ==
* node.getFirstChildOfType(ASTElseClause.class) ) // !node.hasElse() )
* { throw new
* IllegalStateException("If node has wrong number of children"); }
*/
for (PLSQLNode element : statementChildren) {
complexity += (Integer) element.jjtAccept(this, data);
}
return boolCompIf + complexity;
}
@Override
public Object visit(ASTElseClause node, Object data) {
// (npath of if + npath of else (or 1) + bool_comp of if) * npath of
// next
int complexity = 0;
List<PLSQLNode> statementChildren = new ArrayList<>();
for (int i = 0; i < node.getNumChildren(); i++) {
if (node.getChild(i).getClass() == ASTStatement.class) {
statementChildren.add((PLSQLNode) node.getChild(i));
}
}
for (PLSQLNode element : statementChildren) {
complexity += (Integer) element.jjtAccept(this, data);
}
return complexity;
}
@Override
public Object visit(ASTWhileStatement node, Object data) {
// (npath of while + bool_comp of while + 1) * npath of next
int boolCompWhile = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
Integer nPathWhile = (Integer) ((PLSQLNode) node.getFirstChildOfType(ASTStatement.class)).jjtAccept(this, data);
return boolCompWhile + nPathWhile + 1;
}
@Override
public Object visit(ASTLoopStatement node, Object data) {
// (npath of do + bool_comp of do + 1) * npath of next
int boolCompDo = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
Integer nPathDo = (Integer) ((PLSQLNode) node.getFirstChildOfType(ASTStatement.class)).jjtAccept(this, data);
return boolCompDo + nPathDo + 1;
}
@Override
public Object visit(ASTForStatement node, Object data) {
// (npath of for + bool_comp of for + 1) * npath of next
int boolCompFor = NPathComplexityRule.sumExpressionComplexity(node.getFirstDescendantOfType(ASTExpression.class));
Integer nPathFor = (Integer) ((PLSQLNode) node.getFirstChildOfType(ASTStatement.class)).jjtAccept(this, data);
return boolCompFor + nPathFor + 1;
}
@Override
public Object visit(ASTReturnStatement node, Object data) {
// return statements are valued at 1, or the value of the boolean
// expression
ASTExpression expr = node.getFirstChildOfType(ASTExpression.class);
if (expr == null) {
return 1;
}
int boolCompReturn = NPathComplexityRule.sumExpressionComplexity(expr);
int conditionalExpressionComplexity = complexityMultipleOf(expr, data);
if (conditionalExpressionComplexity > 1) {
boolCompReturn += conditionalExpressionComplexity;
}
if (boolCompReturn > 0) {
return boolCompReturn;
}
return 1;
}
@Override
public Object visit(ASTCaseWhenClause node, Object data) {
// bool_comp of switch + sum(npath(case_range))
int boolCompSwitch = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
int npath = 1;
int caseRange = 0;
for (int i = 0; i < node.getNumChildren(); i++) {
PLSQLNode n = (PLSQLNode) node.getChild(i);
// Fall-through labels count as 1 for complexity
Integer complexity = (Integer) n.jjtAccept(this, data);
caseRange *= complexity;
}
// add in npath of last label
npath += caseRange;
return boolCompSwitch + npath;
}
@Override
public Object visit(ASTCaseStatement node, Object data) {
// bool_comp of switch + sum(npath(case_range))
int boolCompSwitch = NPathComplexityRule.sumExpressionComplexity(node.getFirstChildOfType(ASTExpression.class));
int npath = 0;
int caseRange = 0;
for (int i = 0; i < node.getNumChildren(); i++) {
PLSQLNode n = (PLSQLNode) node.getChild(i);
// Fall-through labels count as 1 for complexity
Integer complexity = (Integer) n.jjtAccept(this, data);
caseRange *= complexity;
}
// add in npath of last label
npath += caseRange;
return boolCompSwitch + npath;
}
@Override
public Object visit(ASTConditionalOrExpression node, Object data) {
return 1;
}
}
| 9,890 | 33.827465 | 122 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/rule/design/ExcessiveObjectLengthRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.rule.design;
import net.sourceforge.pmd.lang.plsql.ast.OracleObject;
/**
* This rule detects when an Oracle object exceeds a certain threshold. i.e. if
* a object has more than 1000 lines of code.
*/
public class ExcessiveObjectLengthRule extends AbstractCounterCheckRule.AbstractLineLengthCheckRule<OracleObject> {
public ExcessiveObjectLengthRule() {
super(OracleObject.class);
}
@Override
protected int defaultReportLevel() {
return 1000;
}
}
| 616 | 25.826087 | 115 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/NameFinder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTArguments;
import net.sourceforge.pmd.lang.plsql.ast.ASTName;
import net.sourceforge.pmd.lang.plsql.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTPrimaryPrefix;
import net.sourceforge.pmd.lang.plsql.ast.ASTPrimarySuffix;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
public class NameFinder {
private List<PLSQLNameOccurrence> names = new ArrayList<>();
public NameFinder(ASTPrimaryExpression node) {
Node simpleNode = node.getChild(0);
if (simpleNode instanceof ASTPrimaryPrefix) {
ASTPrimaryPrefix prefix = (ASTPrimaryPrefix) simpleNode;
// if (prefix.usesSuperModifier()) {
// add(new NameOccurrence(prefix, "super"));
// } else
if (prefix.usesSelfModifier()) {
add(new PLSQLNameOccurrence(prefix, "this"));
}
}
for (int i = 0; i < node.getNumChildren(); i++) {
checkForNameChild(node.getChild(i));
}
}
public List<PLSQLNameOccurrence> getNames() {
return names;
}
private void checkForNameChild(Node node) {
if (node.getImage() != null) {
add(new PLSQLNameOccurrence((PLSQLNode) node, node.getImage()));
}
if (node.getNumChildren() > 0 && node.getChild(0) instanceof ASTName) {
ASTName grandchild = (ASTName) node.getChild(0);
for (StringTokenizer st = new StringTokenizer(grandchild.getImage(), "."); st.hasMoreTokens();) {
add(new PLSQLNameOccurrence(grandchild, st.nextToken()));
}
}
if (node instanceof ASTPrimarySuffix) {
ASTPrimarySuffix suffix = (ASTPrimarySuffix) node;
if (suffix.isArguments()) {
PLSQLNameOccurrence occurrence = names.get(names.size() - 1);
occurrence.setIsMethodOrConstructorInvocation();
ASTArguments args = (ASTArguments) ((ASTPrimarySuffix) node).getChild(0);
occurrence.setArgumentCount(args.getArgumentCount());
} // else if (suffix.getNumChildren() == 1
// && suffix.getChild(0) instanceof ASTMemberSelector)
// {
// add(new NameOccurrence((SimpleNode)suffix.getChild(0),
// suffix.getChild(0).getImage()));
// }
}
}
private void add(PLSQLNameOccurrence name) {
names.add(name);
if (names.size() > 1) {
PLSQLNameOccurrence qualifiedName = names.get(names.size() - 2);
qualifiedName.setNameWhichThisQualifies(name);
}
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (PLSQLNameOccurrence occ : names) {
result.append(occ.getImage());
}
return result.toString();
}
}
| 3,155 | 35.697674 | 109 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/TypeSet.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Keeps track of the types encountered in a ASTinput
*/
public class TypeSet {
/**
* TODO should Resolver provide a canResolve() and a resolve()? Requiring 2
* calls seems clunky... but so does this throwing an exception for flow
* control...
*/
public interface Resolver {
Class<?> resolve(String name) throws ClassNotFoundException;
}
public static class ExplicitImportResolver implements Resolver {
private Set<String> importStmts;
public ExplicitImportResolver(Set<String> importStmts) {
this.importStmts = importStmts;
}
@Override
public Class<?> resolve(String name) throws ClassNotFoundException {
for (String importStmt : importStmts) {
if (importStmt.endsWith(name)) {
return Class.forName(importStmt);
}
}
throw new ClassNotFoundException("Type " + name + " not found");
}
}
public static class CurrentPackageResolver implements Resolver {
private String pkg;
public CurrentPackageResolver(String pkg) {
this.pkg = pkg;
}
@Override
public Class<?> resolve(String name) throws ClassNotFoundException {
return Class.forName(pkg + name);
}
}
// TODO cite the JLS section on implicit imports
public static class ImplicitImportResolver implements Resolver {
@Override
public Class<?> resolve(String name) throws ClassNotFoundException {
return Class.forName("java.lang." + name);
}
}
public static class ImportOnDemandResolver implements Resolver {
private Set<String> importStmts;
public ImportOnDemandResolver(Set<String> importStmts) {
this.importStmts = importStmts;
}
@Override
public Class<?> resolve(String name) throws ClassNotFoundException {
for (String importStmt : importStmts) {
if (importStmt.endsWith("*")) {
try {
String importPkg = importStmt.substring(0, importStmt.indexOf('*') - 1);
return Class.forName(importPkg + '.' + name);
} catch (ClassNotFoundException ignored) {
// Ignored, we'll throw a custom exception later, after all import possibilities have
// been checked
}
}
}
throw new ClassNotFoundException("Type " + name + " not found");
}
}
public static class PrimitiveTypeResolver implements Resolver {
private Map<String, Class<?>> primitiveTypes = new HashMap<>();
@SuppressWarnings("PMD.AvoidUsingShortType")
public PrimitiveTypeResolver() {
primitiveTypes.put("int", int.class);
primitiveTypes.put("float", float.class);
primitiveTypes.put("double", double.class);
primitiveTypes.put("long", long.class);
primitiveTypes.put("boolean", boolean.class);
primitiveTypes.put("byte", byte.class);
primitiveTypes.put("short", short.class);
primitiveTypes.put("char", char.class);
}
@Override
public Class<?> resolve(String name) throws ClassNotFoundException {
if (!primitiveTypes.containsKey(name)) {
throw new ClassNotFoundException();
}
return primitiveTypes.get(name);
}
}
public static class VoidResolver implements Resolver {
@Override
public Class<?> resolve(String name) throws ClassNotFoundException {
if ("void".equals(name)) {
return void.class;
}
throw new ClassNotFoundException();
}
}
public static class FullyQualifiedNameResolver implements Resolver {
@Override
public Class<?> resolve(String name) throws ClassNotFoundException {
return Class.forName(name);
}
}
private String pkg;
private Set<String> imports = new HashSet<>();
private List<Resolver> resolvers = new ArrayList<>();
public void setASTinputPackage(String pkg) {
this.pkg = pkg;
}
public String getASTinputPackage() {
return pkg;
}
public void addImport(String importString) {
imports.add(importString);
}
public int getImportsCount() {
return imports.size();
}
public Class<?> findClass(String name) throws ClassNotFoundException {
// we don't build the resolvers until now since we first want to get all
// the imports
if (resolvers.isEmpty()) {
buildResolvers();
}
for (Resolver resolver : resolvers) {
try {
return resolver.resolve(name);
} catch (ClassNotFoundException ignored) {
// Ignored, maybe another resolver might find the class
}
}
throw new ClassNotFoundException("Type " + name + " not found");
}
private void buildResolvers() {
resolvers.add(new PrimitiveTypeResolver());
resolvers.add(new VoidResolver());
resolvers.add(new ExplicitImportResolver(imports));
resolvers.add(new CurrentPackageResolver(pkg));
resolvers.add(new ImplicitImportResolver());
resolvers.add(new ImportOnDemandResolver(imports));
resolvers.add(new FullyQualifiedNameResolver());
}
}
| 5,850 | 31.325967 | 109 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/ClassScope.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTName;
import net.sourceforge.pmd.lang.plsql.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
import net.sourceforge.pmd.lang.symboltable.AbstractScope;
import net.sourceforge.pmd.lang.symboltable.Applier;
import net.sourceforge.pmd.lang.symboltable.ImageFinderFunction;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
public class ClassScope extends AbstractScope {
private static final Logger LOG = LoggerFactory.getLogger(ClassScope.class);
// FIXME - this breaks given sufficiently nested code
private static ThreadLocal<Integer> anonymousInnerClassCounter = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return Integer.valueOf(1);
}
};
private String className;
public ClassScope(String className) {
this.className = PLSQLNode.getCanonicalImage(className);
anonymousInnerClassCounter.set(Integer.valueOf(1));
}
/**
* This is only for anonymous inner classes.
*
* <p>FIXME - should have name like Foo$1, not Anonymous$1 to get this working
* right, the parent scope needs to be passed in when instantiating a
* ClassScope</p>
*/
public ClassScope() {
// this.className = getParent().getEnclosingClassScope().getClassName()
// + "$" + String.valueOf(anonymousInnerClassCounter);
int v = anonymousInnerClassCounter.get().intValue();
this.className = "Anonymous$" + v;
anonymousInnerClassCounter.set(v + 1);
}
@Override
public void addDeclaration(NameDeclaration declaration) {
if (declaration instanceof VariableNameDeclaration && getDeclarations().keySet().contains(declaration)) {
throw new RuntimeException(declaration + " is already in the symbol table");
}
super.addDeclaration(declaration);
}
@Override
public Set<NameDeclaration> addNameOccurrence(NameOccurrence occ) {
PLSQLNameOccurrence occurrence = (PLSQLNameOccurrence) occ;
Set<NameDeclaration> declarations = findVariableHere(occurrence);
Map<MethodNameDeclaration, List<NameOccurrence>> methodNames = getMethodDeclarations();
if (!declarations.isEmpty() && occurrence.isMethodOrConstructorInvocation()) {
for (NameDeclaration decl : declarations) {
List<NameOccurrence> nameOccurrences = methodNames.get(decl);
if (nameOccurrences == null) {
// TODO may be a class name: Foo.this.super();
} else {
nameOccurrences.add(occurrence);
Node n = occurrence.getLocation();
if (n instanceof ASTName) {
InternalApiBridge.setNameDeclaration((ASTName) n, decl);
} // TODO what to do with PrimarySuffix case?
}
}
} else if (!declarations.isEmpty() && !occurrence.isThisOrSuper()) {
Map<VariableNameDeclaration, List<NameOccurrence>> variableNames = getVariableDeclarations();
for (NameDeclaration decl : declarations) {
List<NameOccurrence> nameOccurrences = variableNames.get(decl);
if (nameOccurrences == null) {
// TODO may be a class name
} else {
nameOccurrences.add(occurrence);
Node n = occurrence.getLocation();
if (n instanceof ASTName) {
InternalApiBridge.setNameDeclaration((ASTName) n, decl);
} // TODO what to do with PrimarySuffix case?
}
}
}
return declarations;
}
public Map<VariableNameDeclaration, List<NameOccurrence>> getVariableDeclarations() {
return getDeclarations(VariableNameDeclaration.class);
}
public Map<MethodNameDeclaration, List<NameOccurrence>> getMethodDeclarations() {
return getDeclarations(MethodNameDeclaration.class);
}
public Map<ClassNameDeclaration, List<NameOccurrence>> getClassDeclarations() {
return getDeclarations(ClassNameDeclaration.class);
}
public ClassScope getEnclosingClassScope() {
return this;
}
public String getClassName() {
return this.className;
}
protected Set<NameDeclaration> findVariableHere(PLSQLNameOccurrence occurrence) {
Set<NameDeclaration> result = new HashSet<>();
Map<VariableNameDeclaration, List<NameOccurrence>> variableDeclarations = getVariableDeclarations();
Map<MethodNameDeclaration, List<NameOccurrence>> methodDeclarations = getMethodDeclarations();
if (occurrence.isThisOrSuper() || occurrence.getImage().equals(className)) {
if (variableDeclarations.isEmpty() && methodDeclarations.isEmpty()) {
// this could happen if you do this:
// public class Foo {
// private String x = super.toString();
// }
return result;
}
// return any name declaration, since all we really want is to get
// the scope
// for example, if there's a
// public class Foo {
// private static final int X = 2;
// private int y = Foo.X;
// }
// we'll look up Foo just to get a handle to the class scope
// and then we'll look up X.
if (!variableDeclarations.isEmpty()) {
result.add(variableDeclarations.keySet().iterator().next());
return result;
}
result.add(methodDeclarations.keySet().iterator().next());
return result;
}
if (occurrence.isMethodOrConstructorInvocation()) {
for (MethodNameDeclaration mnd : methodDeclarations.keySet()) {
if (mnd.getImage().equals(occurrence.getImage())) {
int args = occurrence.getArgumentCount();
if (args == mnd.getParameterCount() || mnd.isVarargs() && args >= mnd.getParameterCount() - 1) {
// FIXME if several methods have the same name
// and parameter count, only one will get caught here
// we need to make some attempt at type lookup and
// discrimination
// or, failing that, mark this as a usage of all those
// methods
result.add(mnd);
}
}
}
return result;
}
List<String> images = new ArrayList<>();
images.add(occurrence.getImage());
if (null == occurrence.getImage()) {
LOG.trace("occurrence=={} with Argument Count == {} for className={}",
occurrence.toString(),
occurrence.getArgumentCount(),
className);
}
if (occurrence.getImage().startsWith(className)) {
images.add(clipClassName(occurrence.getImage()));
}
ImageFinderFunction finder = new ImageFinderFunction(images);
Applier.apply(finder, getVariableDeclarations().keySet().iterator());
if (finder.getDecl() != null) {
result.add(finder.getDecl());
}
return result;
}
@Override
public String toString() {
StringBuilder res = new StringBuilder("ClassScope (").append(className).append("): ");
Map<ClassNameDeclaration, List<NameOccurrence>> classNames = getClassDeclarations();
Map<MethodNameDeclaration, List<NameOccurrence>> methodNames = getMethodDeclarations();
Map<VariableNameDeclaration, List<NameOccurrence>> variableNames = getVariableDeclarations();
if (!classNames.isEmpty()) {
res.append('(').append(classNames.keySet()).append(')');
}
if (!methodNames.isEmpty()) {
for (MethodNameDeclaration mnd : methodNames.keySet()) {
res.append(mnd.toString());
int usages = methodNames.get(mnd).size();
res.append("(begins at line ").append(mnd.getNode().getBeginLine()).append(", ").append(usages).append(" usages)");
res.append(',');
}
}
if (!variableNames.isEmpty()) {
res.append('(').append(variableNames.keySet()).append(')');
}
return res.toString();
}
private String clipClassName(String s) {
return s.substring(s.indexOf('.') + 1);
}
}
| 9,078 | 40.646789 | 131 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/MethodNameDeclaration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTFormalParameter;
import net.sourceforge.pmd.lang.plsql.ast.ASTFormalParameters;
import net.sourceforge.pmd.lang.plsql.ast.ASTMethodDeclarator;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerTimingPointSection;
import net.sourceforge.pmd.lang.symboltable.AbstractNameDeclaration;
public class MethodNameDeclaration extends AbstractNameDeclaration {
private static final Logger LOG = LoggerFactory.getLogger(MethodNameDeclaration.class);
public MethodNameDeclaration(ASTMethodDeclarator node) {
super(node);
}
/**
* Treat a TimingPointSection within a Compound Trigger like a packaged
* FUNCTION or PROCEDURE. SRT
*
* @param node
*/
public MethodNameDeclaration(ASTTriggerTimingPointSection node) {
super(node);
}
public int getParameterCount() {
return ((ASTMethodDeclarator) node).getParameterCount();
}
/**
* PL/SQL does not currently allow varargs outside the STANDARD package.
*
* @return false
*/
public boolean isVarargs() {
return false;
}
public ASTMethodDeclarator getMethodNameDeclaratorNode() {
return (ASTMethodDeclarator) node;
}
public String getParameterDisplaySignature() {
StringBuilder sb = new StringBuilder("(");
ASTFormalParameters params = (ASTFormalParameters) node.getChild(0);
// TODO - this can be optimized - add [0] then ,[n] in a loop.
// no need to trim at the end
for (int i = 0; i < ((ASTMethodDeclarator) node).getParameterCount(); i++) {
ASTFormalParameter p = (ASTFormalParameter) params.getChild(i);
sb.append(p.getTypeNode().getTypeImage());
// if (p.isVarargs()) {
// sb.append("...");
// }
sb.append(',');
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(')');
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof MethodNameDeclaration)) {
return false;
}
MethodNameDeclaration other = (MethodNameDeclaration) o;
// compare name
if (!other.node.getImage().equals(node.getImage())) {
return false;
}
// compare parameter count - this catches the case where there are no
// params, too
if (((ASTMethodDeclarator) other.node).getParameterCount() != ((ASTMethodDeclarator) node)
.getParameterCount()) {
return false;
}
// compare parameter types
// SRT ASTFormalParameters myParams = (ASTFormalParameters)
// node.getChild(0);
// SRT ASTFormalParameters otherParams = (ASTFormalParameters)
// other.node.getChild(0);
ASTFormalParameters myParams = node.getFirstDescendantOfType(ASTFormalParameters.class);
ASTFormalParameters otherParams = other.node.getFirstDescendantOfType(ASTFormalParameters.class);
for (int i = 0; i < ((ASTMethodDeclarator) node).getParameterCount(); i++) {
ASTFormalParameter myParam = (ASTFormalParameter) myParams.getChild(i);
ASTFormalParameter otherParam = (ASTFormalParameter) otherParams.getChild(i);
// Compare vararg
// if (myParam.isVarargs() != otherParam.isVarargs()) {
// return false;
// }
Node myTypeNode = myParam.getTypeNode().getChild(0);
Node otherTypeNode = otherParam.getTypeNode().getChild(0);
// compare primitive vs reference type
if (myTypeNode.getClass() != otherTypeNode.getClass()) {
return false;
}
// simple comparison of type images
// this can be fooled by one method using "String"
// and the other method using "java.lang.String"
// once we get real types in here that should get fixed
String myTypeImg;
String otherTypeImg;
// if (myTypeNode instanceof ASTPrimitiveType) {
// myTypeImg = myTypeNode.getImage();
// otherTypeImg = otherTypeNode.getImage();
// } else {
myTypeImg = myTypeNode.getChild(0).getImage();
otherTypeImg = otherTypeNode.getChild(0).getImage();
// }
if (!myTypeImg.equals(otherTypeImg)) {
return false;
}
// if type is ASTPrimitiveType and is an array, make sure the other
// one is also
}
return true;
}
@Override
public int hashCode() {
try {
// SRT node.getImage().hashCode() + ((ASTMethodDeclarator)node).getParameterCount();
return node.hashCode();
} catch (Exception e) {
LOG.trace(
"MethodNameDeclaration problem for {} of class {} => {}/{}",
node, node.getClass().getCanonicalName(),
node.getBeginLine(), node.getBeginColumn());
// @TODO SRT restore the thrown exception - throw e;
return 0;
}
}
@Override
public String toString() {
// SRT return "Method " + node.getImage() + ", line " +
// node.getBeginLine() + ", params = " + ((ASTMethodDeclarator)
// node).getParameterCount();
return node.toString();
}
}
| 5,736 | 34.41358 | 105 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/MethodScope.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.Set;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTName;
import net.sourceforge.pmd.lang.plsql.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
public class MethodScope extends MethodOrLocalScope {
private final PLSQLNode node;
public MethodScope(PLSQLNode node) {
this.node = node;
}
public MethodScope getEnclosingMethodScope() {
return this;
}
@Override
public Set<NameDeclaration> addNameOccurrence(NameOccurrence occ) {
PLSQLNameOccurrence occurrence = (PLSQLNameOccurrence) occ;
Set<NameDeclaration> declarations = findVariableHere(occurrence);
if (!declarations.isEmpty() && !occurrence.isThisOrSuper()) {
for (NameDeclaration decl : declarations) {
getVariableDeclarations().get(decl).add(occurrence);
Node n = occurrence.getLocation();
if (n instanceof ASTName) {
InternalApiBridge.setNameDeclaration((ASTName) n, decl);
} // TODO what to do with PrimarySuffix case?
}
}
return declarations;
}
public String getName() {
return node.getChild(1).getCanonicalImage();
}
@Override
public String toString() {
return "MethodScope:" + getVariableDeclarations().keySet();
}
}
| 1,664 | 30.415094 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/Search.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.Scope;
public class Search {
private static final Logger LOG = LoggerFactory.getLogger(Search.class);
private PLSQLNameOccurrence occ;
private Set<NameDeclaration> declarations = new HashSet<>();
public Search(PLSQLNameOccurrence occ) {
LOG.trace(
"new search for {} {}",
occ.isMethodOrConstructorInvocation() ? "method" : "variable",
occ);
this.occ = occ;
}
public void execute() {
Set<NameDeclaration> found = searchUpward(occ, occ.getLocation().getScope());
LOG.trace("found {}", found);
declarations.addAll(found);
}
public void execute(Scope startingScope) {
Set<NameDeclaration> found = searchUpward(occ, startingScope);
LOG.trace("found {}", found);
declarations.addAll(found);
}
public Set<NameDeclaration> getResult() {
return declarations;
}
private Set<NameDeclaration> searchUpward(PLSQLNameOccurrence nameOccurrence, Scope scope) {
LOG.trace("checking scope {} for name occurrence {}", scope, nameOccurrence);
if (!scope.contains(nameOccurrence) && scope.getParent() != null) {
LOG.trace("moving up fm {} to {}", scope, scope.getParent());
return searchUpward(nameOccurrence, scope.getParent());
}
if (scope.contains(nameOccurrence)) {
LOG.trace("found it!");
return scope.addNameOccurrence(nameOccurrence);
}
return new HashSet<>();
}
}
| 1,880 | 30.881356 | 96 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/VariableNameDeclaration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.plsql.ast.ASTVariableOrConstantDeclaratorId;
import net.sourceforge.pmd.lang.symboltable.AbstractNameDeclaration;
import net.sourceforge.pmd.lang.symboltable.Scope;
public class VariableNameDeclaration extends AbstractNameDeclaration {
private static final Logger LOG = LoggerFactory.getLogger(VariableNameDeclaration.class);
public VariableNameDeclaration(ASTVariableOrConstantDeclaratorId node) {
super(node);
}
@Override
public Scope getScope() {
try {
return node.getScope().getEnclosingScope(ClassScope.class);
} catch (Exception e) {
LOG.trace("This Node does not have an enclosing Class: {}/{} => {}",
node.getBeginLine(), node.getBeginColumn(),
this.getImage());
return null; // @TODO SRT a cop-out
}
}
public ASTVariableOrConstantDeclaratorId getDeclaratorId() {
return (ASTVariableOrConstantDeclaratorId) node;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof VariableNameDeclaration)) {
return false;
}
VariableNameDeclaration n = (VariableNameDeclaration) o;
try {
return n.getImage().equals(this.getImage());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
LOG.debug("n.node={}", n.node);
LOG.debug("n.getImage={}", n.getImage());
LOG.debug("node={}", node);
LOG.debug("this.getImage={}", this.getImage());
return false;
}
}
@Override
public int hashCode() {
try {
return this.getImage().hashCode();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
LOG.debug("VariableNameDeclaration: node={}", node);
LOG.debug("VariableNameDeclaration: node,getImage={}", this.getImage());
return 0;
}
}
@Override
public String toString() {
return "Variable: image = '" + node.getImage() + "', line = " + node.getBeginLine();
}
}
| 2,315 | 30.726027 | 93 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/ClassNameDeclaration.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageBody;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTQualifiedName;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeSpecification;
import net.sourceforge.pmd.lang.symboltable.AbstractNameDeclaration;
public class ClassNameDeclaration extends AbstractNameDeclaration {
public ClassNameDeclaration(ASTQualifiedName node) {
super(node);
}
public ClassNameDeclaration(ASTPackageSpecification node) {
super(node);
}
public ClassNameDeclaration(ASTPackageBody node) {
super(node);
}
public ClassNameDeclaration(ASTTriggerUnit node) {
super(node);
}
public ClassNameDeclaration(ASTTypeSpecification node) {
super(node);
}
@Override
public String toString() {
return "Object " + node.getImage();
}
}
| 1,118 | 25.642857 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/ScopeAndDeclarationFinder.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.ArrayDeque;
import java.util.Deque;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.plsql.ast.ASTBlock;
import net.sourceforge.pmd.lang.plsql.ast.ASTDeclarativeUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTForAllStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTForStatement;
import net.sourceforge.pmd.lang.plsql.ast.ASTID;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
import net.sourceforge.pmd.lang.plsql.ast.ASTMethodDeclarator;
import net.sourceforge.pmd.lang.plsql.ast.ASTObjectDeclaration;
import net.sourceforge.pmd.lang.plsql.ast.ASTObjectNameDeclaration;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageBody;
import net.sourceforge.pmd.lang.plsql.ast.ASTPackageSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTProgramUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerTimingPointSection;
import net.sourceforge.pmd.lang.plsql.ast.ASTTriggerUnit;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeMethod;
import net.sourceforge.pmd.lang.plsql.ast.ASTTypeSpecification;
import net.sourceforge.pmd.lang.plsql.ast.ASTVariableOrConstantDeclaratorId;
import net.sourceforge.pmd.lang.plsql.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLParserVisitorAdapter;
import net.sourceforge.pmd.lang.symboltable.Scope;
/**
* Visitor for scope creation. Visits all nodes of an AST and creates scope
* objects for nodes representing syntactic entities which may contain
* declarations. For example, a block may contain variable definitions (which
* are declarations) and therefore needs a scope object where these declarations
* can be associated, whereas an expression can't contain declarations and
* therefore doesn't need a scope object. With the exception of global scopes,
* each scope object is linked to its parent scope, which is the scope object of
* the next embedding syntactic entity that has a scope.
*/
public class ScopeAndDeclarationFinder extends PLSQLParserVisitorAdapter {
private static final Logger LOG = LoggerFactory.getLogger(ScopeAndDeclarationFinder.class);
/**
* A stack of scopes reflecting the scope hierarchy when a node is visited.
* This is used to set the parents of the created scopes correctly.
*/
private Deque<Scope> scopes = new ArrayDeque<>();
/**
* Sets the scope of a node and adjusts the scope stack accordingly. The
* scope on top of the stack is set as the parent of the given scope, which
* is then also stored on the scope stack.
*
* @param newScope
* the scope for the node.
* @param node
* the AST node for which the scope is to be set.
* @throws java.util.EmptyStackException
* if the scope stack is empty.
*/
private void addScope(Scope newScope, PLSQLNode node) {
newScope.setParent(scopes.peek());
scopes.push(newScope);
InternalApiBridge.setScope(node, newScope);
}
/**
* Creates a new local scope for an AST node. The scope on top of the stack
* is set as the parent of the new scope, which is then also stored on the
* scope stack.
*
* @param node
* the AST node for which the scope has to be created.
* @throws java.util.EmptyStackException
* if the scope stack is empty.
*/
private void createLocalScope(PLSQLNode node) {
addScope(new LocalScope(), node);
}
/**
* Creates a new method scope for an AST node. The scope on top of the stack
* is set as the parent of the new scope, which is then also stored on the
* scope stack.
*
* @param node
* the AST node for which the scope has to be created.
* @throws java.util.EmptyStackException
* if the scope stack is empty.
*/
private void createMethodScope(PLSQLNode node) {
addScope(new MethodScope(node), node);
}
/**
* Creates a new class scope for an AST node. The scope on top of the stack
* is set as the parent of the new scope, which is then also stored on the
* scope stack.
*
* @param node
* the AST node for which the scope has to be created.
* @throws java.util.EmptyStackException
* if the scope stack is empty.
*/
private void createClassScope(PLSQLNode node) {
if (node instanceof ASTDeclarativeUnit) {
addScope(new ClassScope(), node);
} else {
addScope(new ClassScope(node.getImage()), node);
}
}
/**
* Creates a new global scope for an AST node. The new scope is stored on
* the scope stack.
*
* @param node
* the AST node for which the scope has to be created.
*/
private void createSourceFileScope(ASTInput node) {
// When we do full symbol resolution, we'll need to add a truly
// top-level GlobalScope.
Scope scope;
// %TODO generate a SchemaScope, based on inferred or explicitly
// specified SchemaName
ASTObjectDeclaration n = null; // node.getPackageDeclaration();
if (n != null) {
scope = new SourceFileScope(n.getChild(0).getImage());
} else {
scope = new SourceFileScope();
}
scopes.push(scope);
InternalApiBridge.setScope(node, scope);
}
@Override
public Object visit(ASTInput node, Object data) {
createSourceFileScope(node);
cont(node);
return data;
}
@Override
public Object visit(ASTPackageSpecification node, Object data) {
createClassScope(node);
Scope s = ((PLSQLNode) node.getParent()).getScope();
s.addDeclaration(new ClassNameDeclaration(node));
cont(node);
return data;
}
@Override
public Object visit(ASTPackageBody node, Object data) {
createClassScope(node);
Scope s = ((PLSQLNode) node.getParent()).getScope();
s.addDeclaration(new ClassNameDeclaration(node));
cont(node);
return data;
}
@Override
public Object visit(ASTTypeSpecification node, Object data) {
createClassScope(node);
Scope s = ((PLSQLNode) node.getParent()).getScope();
s.addDeclaration(new ClassNameDeclaration(node));
cont(node);
return data;
}
@Override
public Object visit(ASTTriggerUnit node, Object data) {
createClassScope(node);
Scope s = ((PLSQLNode) node.getParent()).getScope();
s.addDeclaration(new ClassNameDeclaration(node));
cont(node);
return data;
}
/*
* @Override public Object visit(ASTCompoundTriggerBlock node, Object data)
* { createMethodScope(node); ASTMethodDeclarator md =
* node.getFirstChildOfType(ASTMethodDeclarator.class);
* node.getScope().getEnclosingClassScope().addDeclaration(new
* MethodNameDeclaration(md)); cont(node); return data; }
*/
@Override
public Object visit(ASTTriggerTimingPointSection node, Object data) {
createMethodScope(node);
// Treat a Timing Point Section like a packaged FUNCTION or PROCEDURE
node.getScope().getEnclosingScope(ClassScope.class).addDeclaration(new MethodNameDeclaration(node));
cont(node);
return data;
}
// @Override
// public Object visit(ASTEnumDeclaration node, Object data) {
// createClassScope(node);
// cont(node);
// return data;
// }
// @Override
// public Object visit(ASTAnnotationTypeDeclaration node, Object data) {
// createClassScope(node);
// cont(node);
// return data;
// }
@Override
public Object visit(ASTObjectDeclaration node, Object data) {
super.visit(node, data);
return data;
}
@Override
public Object visit(ASTBlock node, Object data) {
createLocalScope(node);
cont(node);
return data;
}
/*
* @Override public Object visit(ASTMethodDeclaration node, Object data) {
* createMethodScope(node); // // A method declaration my be- //
* ASTProgramUnit - a standalone or packaged FUNCTION or PROCEDURE //
* ASTTypeMethod - an OBJECT TYPE method // // The Method declarator is
* below the ASTProgramUnit / ASTTypeMethod /// List<ASTMethodDeclarator>
* methodDeclarators =
* node.findDescendantsOfType(ASTMethodDeclarator.class); if
* (!methodDeclarators.isEmpty() ) { //Use first Declarator in the list
* ASTMethodDeclarator md = methodDeclarators.get(0);
* LOGGER.finest("ClassScope skipped for Schema-level method: methodName=" +
* node.getMethodName() + "; Image=" + node.getImage() );
*
* } //ASTMethodDeclarator md =
* node.getFirstChildOfType(ASTMethodDeclarator.class); // A PLSQL Method
* (FUNCTION|PROCEDURE) may be schema-level try {
* node.getScope().getEnclosingClassScope().addDeclaration(new
* MethodNameDeclaration(md)); } catch (Exception e) { //@TODO possibly add
* to a pseudo-ClassScope equivalent to the Schema name
* LOGGER.finest("ProgramUnit getEnclosingClassScope Exception string=\""+e.
* getMessage()+"\"");
* if("getEnclosingClassScope() called on SourceFileScope".equals(e.
* getMessage())) {
* LOGGER.finest("ClassScope skipped for Schema-level method: methodName=" +
* node.getMethodName() + "; Image=" + node.getImage() );
*
* //A File-level/Schema-level object may have a Schema-name explicitly
* specified in the declaration ASTObjectNameDeclaration on =
* md.getFirstChildOfType(ASTObjectNameDeclaration.class); if( 1 <
* on.getNumChildren()) { ASTID schemaName =
* on.getFirstChildOfType(ASTID.class);
* LOGGER.finest("SchemaName for Schema-level method: methodName=" +
* node.getMethodName() + "; Image=" + node.getImage() + "is " +
* schemaName.getImage() );
*
* } } } cont(node); return data; }
*/
private Object visitMethodLike(PLSQLNode node, Object data) {
createMethodScope(node);
final ASTMethodDeclarator md = node.getFirstChildOfType(ASTMethodDeclarator.class);
// A PLSQL Method (FUNCTION|PROCEDURE) may be schema-level
try {
node.getScope().getEnclosingScope(ClassScope.class).addDeclaration(new MethodNameDeclaration(md));
} catch (Exception e) {
// @TODO possibly add to a pseudo-ClassScope equivalent to the
// Schema name
LOG.trace("ProgramUnit getEnclosingClassScope Exception string=\"{}\"", e.getMessage());
if ("getEnclosingClassScope() called on SourceFileScope".equals(e.getMessage())) {
LOG.trace("ClassScope skipped for Schema-level method: methodName={}; Image={}",
md.getImage(), node.getImage());
// A File-level/Schema-level object may have a Schema-name
// explicitly specified in the declaration
ASTObjectNameDeclaration on = md.getFirstChildOfType(ASTObjectNameDeclaration.class);
if (1 < on.getNumChildren()) {
ASTID schemaName = on.getFirstChildOfType(ASTID.class);
LOG.trace("SchemaName for Schema-level method: methodName={}; Image={} is {}",
md.getImage(), node.getImage(), schemaName.getImage());
}
}
}
cont(node);
return data;
}
@Override
public Object visit(ASTTypeMethod node, Object data) {
return visitMethodLike(node, data);
}
@Override
public Object visit(ASTProgramUnit node, Object data) {
return visitMethodLike(node, data);
}
// TODO - what about while loops and do loops?
@Override
public Object visit(ASTForStatement node, Object data) {
createLocalScope(node);
cont(node);
return data;
}
@Override
public Object visit(ASTForAllStatement node, Object data) {
createLocalScope(node);
cont(node);
return data;
}
@Override
public Object visit(ASTVariableOrConstantDeclaratorId node, Object data) {
VariableNameDeclaration decl = new VariableNameDeclaration(node);
node.getScope().addDeclaration(decl);
InternalApiBridge.setNameDeclaration(node, decl);
return super.visit(node, data);
}
// @Override
// public Object visit(ASTSwitchStatement node, Object data) {
// createLocalScope(node);
// cont(node);
// return data;
// }
private void cont(PLSQLNode node) {
super.visitPlsqlNode(node, null);
scopes.pop();
}
}
| 12,941 | 37.064706 | 110 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/OccurrenceFinder.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.lang.plsql.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLParserVisitorAdapter;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.Scope;
public class OccurrenceFinder extends PLSQLParserVisitorAdapter {
private static final Logger LOG = LoggerFactory.getLogger(OccurrenceFinder.class);
@Override
public Object visit(ASTPrimaryExpression node, Object data) {
NameFinder nameFinder = new NameFinder(node);
// Maybe do some sort of State pattern thingy for when NameDeclaration
// is empty/not empty
Set<NameDeclaration> declarations = new HashSet<>();
List<PLSQLNameOccurrence> names = nameFinder.getNames();
for (PLSQLNameOccurrence occ : names) {
Search search = new Search(occ);
if (declarations.isEmpty()) {
// doing the first name lookup
search.execute();
declarations.addAll(search.getResult());
if (declarations.isEmpty()) {
// we can't find it, so just give up
// when we decide to do full symbol resolution
// force this to either find a symbol or throw a
// SymbolNotFoundException
break;
}
} else {
Set<NameDeclaration> additionalDeclarations = new HashSet<>();
for (NameDeclaration decl : declarations) {
// now we've got a scope we're starting with, so work from
// there
Scope scope = decl.getScope();
if (null == scope) {
LOG.trace("NameOccurrence has no Scope:{}=>{}",
decl.getClass().getCanonicalName(), decl.getImage());
break;
}
search.execute(scope);
Set<NameDeclaration> found = search.getResult();
additionalDeclarations.addAll(found);
if (found.isEmpty()) {
// nothing found
// This seems to be a lack of type resolution here.
// Theoretically we have the previous declaration node
// and know from there the Type of
// the variable. The current occurrence (occ) should
// then be found in the declaration of
// this type. The type however may or may not be known
// to PMD (see aux classpath).
// we can't find it, so just give up
// when we decide to do full symbol resolution
// force this to either find a symbol or throw a
// SymbolNotFoundException
break;
}
}
declarations.addAll(additionalDeclarations);
}
}
return super.visit(node, data);
}
}
| 3,422 | 40.743902 | 86 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/LocalScope.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.List;
import java.util.Set;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTName;
import net.sourceforge.pmd.lang.plsql.ast.InternalApiBridge;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
public class LocalScope extends MethodOrLocalScope {
@Override
public Set<NameDeclaration> addNameOccurrence(NameOccurrence occ) {
PLSQLNameOccurrence occurrence = (PLSQLNameOccurrence) occ;
Set<NameDeclaration> declarations = findVariableHere(occurrence);
if (!declarations.isEmpty() && !occurrence.isThisOrSuper()) {
for (NameDeclaration decl : declarations) {
List<NameOccurrence> nameOccurrences = getVariableDeclarations().get(decl);
nameOccurrences.add(occurrence);
Node n = occurrence.getLocation();
if (n instanceof ASTName) {
InternalApiBridge.setNameDeclaration((ASTName) n, decl);
} // TODO what to do with PrimarySuffix case?
}
}
return declarations;
}
@Override
public String toString() {
return "LocalScope:" + getVariableDeclarations().keySet();
}
}
| 1,426 | 34.675 | 91 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/SymbolFacade.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import net.sourceforge.pmd.lang.plsql.ast.ASTInput;
public final class SymbolFacade {
private SymbolFacade() {
}
public static void process(ASTInput node) {
ScopeAndDeclarationFinder sc = new ScopeAndDeclarationFinder();
node.acceptVisitor(sc, null);
OccurrenceFinder of = new OccurrenceFinder();
node.acceptVisitor(of, null);
}
}
| 525 | 22.909091 | 79 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/PLSQLNameOccurrence.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.plsql.ast.ASTExpression;
import net.sourceforge.pmd.lang.plsql.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLNode;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
public class PLSQLNameOccurrence implements NameOccurrence {
private PLSQLNode location;
private String image;
private PLSQLNameOccurrence qualifiedName;
private boolean isMethodOrConstructorInvocation;
private int argumentCount;
private static final String THIS = "this";
private static final String SUPER = "super";
public PLSQLNameOccurrence(PLSQLNode location, String image) {
this.location = location;
this.image = image;
}
public void setIsMethodOrConstructorInvocation() {
isMethodOrConstructorInvocation = true;
}
public void setArgumentCount(int count) {
argumentCount = count;
}
public int getArgumentCount() {
return argumentCount;
}
public boolean isMethodOrConstructorInvocation() {
return isMethodOrConstructorInvocation;
}
public void setNameWhichThisQualifies(PLSQLNameOccurrence qualifiedName) {
this.qualifiedName = qualifiedName;
}
public PLSQLNameOccurrence getNameForWhichThisIsAQualifier() {
return qualifiedName;
}
public boolean isPartOfQualifiedName() {
return qualifiedName != null;
}
@Override
public PLSQLNode getLocation() {
return location;
}
public boolean isOnRightHandSide() {
Node node = location.getParent().getParent().getParent();
return node instanceof ASTExpression && node.getNumChildren() == 3;
}
public boolean isOnLeftHandSide() {
// I detest this method with every atom of my being
Node primaryExpression;
if (location.getParent() instanceof ASTPrimaryExpression) {
primaryExpression = location.getParent().getParent();
} else if (location.getParent().getParent() instanceof ASTPrimaryExpression) {
primaryExpression = location.getParent().getParent().getParent();
} else {
throw new RuntimeException(
"Found a NameOccurrence that didn't have an ASTPrimaryExpression as parent or grandparent. "
+ " Node = " + location.getClass().getCanonicalName() + ", Parent = "
+ location.getParent().getClass().getCanonicalName() + " and grandparent = "
+ location.getParent().getParent().getClass().getCanonicalName() + " @ line = "
+ location.getBeginLine() + ", column = " + location.getBeginColumn());
}
/*
* if (isStandAlonePostfix(primaryExpression)) { return true; }
*/
/*
* if (!(primaryExpression.getChild(1) instanceof
* ASTAssignmentOperator)) { return false; }
*/
/*
* if (isCompoundAssignment(primaryExpression)) { return false; }
*/
return primaryExpression.getNumChildren() > 1 && !isPartOfQualifiedName() /* and not is an array type */;
}
/*
* private boolean isCompoundAssignment(Node primaryExpression) { return
* ((ASTAssignmentOperator) primaryExpression.getChild(1)).isCompound();
* }
*
* private boolean isStandAlonePostfix(Node primaryExpression) { if
* (!(primaryExpression instanceof ASTPostfixExpression) ||
* !(primaryExpression.getParent() instanceof ASTStatementExpression)) {
* return false; }
*
* ASTPrimaryPrefix pf = (ASTPrimaryPrefix) ((ASTPrimaryExpression)
* primaryExpression.getChild(0)).getChild(0); if
* (pf.usesThisModifier()) { return true; }
*
* return thirdChildHasDottedName(primaryExpression); }
*
* private boolean thirdChildHasDottedName(Node primaryExpression) { Node
* thirdChild =
* primaryExpression.getChild(0).getChild(0).getChild(0); return
* thirdChild instanceof ASTName && ((ASTName)
* thirdChild).getImage().indexOf('.') == -1; }
*/
/**
* Assert it the occurrence is a self assignment such as:
* <code>
* i += 3;
* </code>
*
* @return true, if the occurrence is self-assignment, false, otherwise.
*/
/*
* @SuppressWarnings("PMD.AvoidBranchingStatementAsLastInLoop") public
* boolean isSelfAssignment() { Node l = location; while (true) { Node p =
* l.getParent(); Node gp = p.getParent(); Node node =
* gp.getParent(); if (node instanceof ASTPreDecrementExpression || node
* instanceof ASTPreIncrementExpression || node instanceof
* ASTPostfixExpression) { return true; }
*
* if (hasAssignmentOperator(gp)) { return isCompoundAssignment(gp); }
*
* if (hasAssignmentOperator(node)) { return isCompoundAssignment(node); }
*
* // deal with extra parenthesis: "(i)++" if (p instanceof ASTPrimaryPrefix
* && p.getNumChildren() == 1 && gp instanceof ASTPrimaryExpression &&
* gp.getNumChildren() == 1&& node instanceof ASTExpression &&
* node.getNumChildren() == 1 && node.getParent() instanceof
* ASTPrimaryPrefix && node.getParent().getNumChildren() == 1) { l =
* node; continue; }
*
* // catch this.i++ or ++this.i return gp instanceof
* ASTPreDecrementExpression || gp instanceof ASTPreIncrementExpression ||
* gp instanceof ASTPostfixExpression; } }
*/
/*
* private boolean hasAssignmentOperator(Node node) { if (node instanceof
* ASTStatementExpression || node instanceof ASTExpression) { if
* (node.getNumChildren() >= 2 && node.getChild(1) instanceof
* ASTAssignmentOperator) { return true; } } return false; }
*/
/**
* Simply return true is the image is equal to keyword 'this' or 'super'.
*
* @return return true if image equal to 'this' or 'super'.
*/
public boolean isThisOrSuper() {
return THIS.equals(image) || SUPER.equals(image);
}
/**
* Simply return if the image start with keyword 'this' or 'super'.
*
* @return true, if keyword is used, false otherwise.
*/
/*
* public boolean useThisOrSuper() { Node node = location.getParent(); if
* ( node instanceof ASTPrimaryExpression ) { ASTPrimaryExpression
* primaryExpression = (ASTPrimaryExpression)node; ASTPrimaryPrefix prefix =
* (ASTPrimaryPrefix) primaryExpression.getChild(0); if ( prefix != null
* ) { return prefix.usesSuperModifier() || prefix.usesThisModifier(); } }
* return image.startsWith(THIS_DOT) || image.startsWith(SUPER_DOT); }
*/
@Override
public boolean equals(Object o) {
if (o instanceof PLSQLNameOccurrence) {
PLSQLNameOccurrence n = (PLSQLNameOccurrence) o;
return n.getImage().equals(getImage());
}
return false;
}
@Override
public int hashCode() {
return getImage().hashCode();
}
@Override
public String getImage() {
return image;
}
@Override
public String toString() {
return getImage() + ":" + location.getReportLocation().startPosToString() + ":" + location.getClass()
+ (this.isMethodOrConstructorInvocation() ? "(method call)" : "");
}
}
| 7,522 | 34.82381 | 113 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/SourceFileScope.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import net.sourceforge.pmd.lang.symboltable.AbstractScope;
import net.sourceforge.pmd.lang.symboltable.Applier;
import net.sourceforge.pmd.lang.symboltable.ImageFinderFunction;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
public class SourceFileScope extends AbstractScope {
private String packageImage;
public SourceFileScope() {
this("");
}
public SourceFileScope(String image) {
this.packageImage = image;
}
public String getPackageName() {
return packageImage;
}
/**
*
*
* @throws IllegalArgumentException
* if declaration is not a {@link ClassNameDeclaration}
*/
@Override
public void addDeclaration(NameDeclaration declaration) {
if (!(declaration instanceof ClassNameDeclaration)) {
throw new IllegalArgumentException("A SourceFileScope can only contain classes.");
}
super.addDeclaration(declaration);
}
@Override
public String toString() {
return "SourceFileScope: " + getDeclarations().keySet();
}
protected NameDeclaration findVariableHere(NameOccurrence occ) {
ImageFinderFunction finder = new ImageFinderFunction(occ.getImage());
Applier.apply(finder, getDeclarations().keySet().iterator());
return finder.getDecl();
}
}
| 1,554 | 27.272727 | 94 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/lang/plsql/symboltable/MethodOrLocalScope.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.plsql.symboltable;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sourceforge.pmd.lang.symboltable.AbstractScope;
import net.sourceforge.pmd.lang.symboltable.Applier;
import net.sourceforge.pmd.lang.symboltable.ImageFinderFunction;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.lang.symboltable.NameOccurrence;
abstract class MethodOrLocalScope extends AbstractScope {
@Override
public void addDeclaration(NameDeclaration declaration) {
if (declaration instanceof VariableNameDeclaration && getDeclarations().keySet().contains(declaration)) {
throw new RuntimeException(declaration + " is already in the symbol table");
}
super.addDeclaration(declaration);
}
public Map<VariableNameDeclaration, List<NameOccurrence>> getVariableDeclarations() {
return getDeclarations(VariableNameDeclaration.class);
}
public Set<NameDeclaration> findVariableHere(PLSQLNameOccurrence occurrence) {
Set<NameDeclaration> result = new HashSet<>();
if (occurrence.isThisOrSuper() || occurrence.isMethodOrConstructorInvocation()) {
return result;
}
ImageFinderFunction finder = new ImageFinderFunction(occurrence.getImage());
Applier.apply(finder, getVariableDeclarations().keySet().iterator());
if (finder.getDecl() != null) {
result.add(finder.getDecl());
}
return result;
}
}
| 1,642 | 36.340909 | 113 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/cpd/PLSQLLanguage.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import net.sourceforge.pmd.lang.plsql.PLSQLLanguageModule;
/**
*
* @author Stuart Turton sturton@users.sourceforge.net
*/
public class PLSQLLanguage extends AbstractLanguage {
public PLSQLLanguage() {
super(PLSQLLanguageModule.NAME, PLSQLLanguageModule.TERSE_NAME, new PLSQLTokenizer(), PLSQLLanguageModule.EXTENSIONS);
}
@Override
public final void setProperties(Properties properties) {
((PLSQLTokenizer) getTokenizer()).setProperties(properties);
}
}
| 648 | 24.96 | 126 | java |
pmd | pmd-master/pmd-plsql/src/main/java/net/sourceforge/pmd/cpd/PLSQLTokenizer.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import net.sourceforge.pmd.cpd.impl.JavaCCTokenizer;
import net.sourceforge.pmd.lang.TokenManager;
import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream;
import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken;
import net.sourceforge.pmd.lang.plsql.ast.PLSQLTokenKinds;
public class PLSQLTokenizer extends JavaCCTokenizer {
// This is actually useless, the comments are special tokens, never taken into account by CPD
@Deprecated
public static final String IGNORE_COMMENTS = "ignore_comments";
public static final String IGNORE_IDENTIFIERS = "ignore_identifiers";
public static final String IGNORE_LITERALS = "ignore_literals";
private boolean ignoreIdentifiers;
private boolean ignoreLiterals;
public void setProperties(Properties properties) {
/*
* The Tokenizer is derived from PLDoc, in which comments are very
* important When looking for duplication, we are probably not
* interested in comment variation, so we shall default ignoreComments
* to true
*/
ignoreIdentifiers = Boolean.parseBoolean(properties.getProperty(IGNORE_IDENTIFIERS, "false"));
ignoreLiterals = Boolean.parseBoolean(properties.getProperty(IGNORE_LITERALS, "false"));
}
@Deprecated
public void setIgnoreComments(boolean ignore) {
// This is actually useless, the comments are special tokens, never taken into account by CPD
}
public void setIgnoreLiterals(boolean ignore) {
this.ignoreLiterals = ignore;
}
public void setIgnoreIdentifiers(boolean ignore) {
this.ignoreIdentifiers = ignore;
}
@Override
protected String getImage(JavaccToken plsqlToken) {
String image = plsqlToken.getImage();
if (ignoreIdentifiers && plsqlToken.kind == PLSQLTokenKinds.IDENTIFIER) {
image = String.valueOf(plsqlToken.kind);
}
if (ignoreLiterals && (plsqlToken.kind == PLSQLTokenKinds.UNSIGNED_NUMERIC_LITERAL
|| plsqlToken.kind == PLSQLTokenKinds.FLOAT_LITERAL
|| plsqlToken.kind == PLSQLTokenKinds.INTEGER_LITERAL
|| plsqlToken.kind == PLSQLTokenKinds.CHARACTER_LITERAL
|| plsqlToken.kind == PLSQLTokenKinds.STRING_LITERAL
|| plsqlToken.kind == PLSQLTokenKinds.QUOTED_LITERAL)) {
image = String.valueOf(plsqlToken.kind);
}
return image;
}
@Override
protected TokenManager<JavaccToken> makeLexerImpl(CharStream sourceCode) {
return PLSQLTokenKinds.newTokenManager(sourceCode);
}
}
| 2,732 | 36.438356 | 102 | java |
pmd | pmd-master/pmd-cli/src/test/java/net/sourceforge/pmd/cli/TreeExportCliTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cli;
import static org.hamcrest.Matchers.equalTo;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class TreeExportCliTest extends BaseCliTest {
@TempDir
private Path tmp;
@Test
void testReadStandardInput() throws Exception {
SystemLambda.withTextFromSystemIn("(a(b))").execute(() -> {
final CliExecutionResult output = runCliSuccessfully("-i", "-f", "xml", "-PlineSeparator=LF");
output.checkStdOut(equalTo("<?xml version='1.0' encoding='UTF-8' ?>\n"
+ "<dummyRootNode Image=''>\n"
+ " <dummyNode Image='a'>\n"
+ " <dummyNode Image='b' />\n"
+ " </dummyNode>\n"
+ "</dummyRootNode>\n"));
});
}
@Test
void testReadFile() throws Exception {
File file = newFileWithContents("(a(b))");
final CliExecutionResult result = runCliSuccessfully("--file", file.getAbsolutePath(), "-f", "xml", "-PlineSeparator=LF");
result.checkStdOut(equalTo("<?xml version='1.0' encoding='UTF-8' ?>\n"
+ "<dummyRootNode Image=''>\n"
+ " <dummyNode Image='a'>\n"
+ " <dummyNode Image='b' />\n"
+ " </dummyNode>\n"
+ "</dummyRootNode>\n"));
}
private File newFileWithContents(String data) throws IOException {
File file = Files.createTempFile(tmp, "TreeExportCliTest", "data").toFile();
try (BufferedWriter br = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
br.write(data);
}
return file;
}
@Override
protected List<String> cliStandardArgs() {
final List<String> argList = new ArrayList<>();
// Set program name and set dummy language
argList.add("ast-dump");
argList.add("-l");
argList.add("dummy");
return argList;
}
}
| 2,617 | 34.378378 | 130 | java |
pmd | pmd-master/pmd-cli/src/test/java/net/sourceforge/pmd/cli/BaseCliTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cli;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.function.ThrowingConsumer;
import org.opentest4j.AssertionFailedError;
import net.sourceforge.pmd.cli.internal.CliExitCode;
import com.github.stefanbirkner.systemlambda.SystemLambda;
abstract class BaseCliTest {
@BeforeAll
static void disablePicocliAnsi() {
System.setProperty("picocli.ansi", "false");
}
@AfterAll
static void resetPicocliAnsi() {
System.clearProperty("picocli.ansi");
}
protected CliExecutionResult runCliSuccessfully(String... args) throws Exception {
return runCli(CliExitCode.OK, args);
}
protected CliExecutionResult runCli(CliExitCode expectedExitCode, String... args) throws Exception {
final List<String> argList = new ArrayList<>();
argList.addAll(cliStandardArgs());
argList.addAll(Arrays.asList(args));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
final PrintStream formerOut = System.out;
final PrintStream formerErr = System.err;
CliExitCode exitCode;
try {
System.out.println("running: pmd " + String.join(" ", argList));
System.setOut(new PrintStream(out));
System.setErr(new PrintStream(err));
int actualExitCode = SystemLambda.catchSystemExit(
// restoring system properties: --debug might change logging properties
() -> SystemLambda.restoreSystemProperties(
() -> PmdCli.main(argList.toArray(new String[0]))
)
);
exitCode = CliExitCode.fromInt(actualExitCode);
} finally {
System.setOut(formerOut);
System.setErr(formerErr);
}
return new CliExecutionResult(
out, err, exitCode
).verify(e -> assertEquals(expectedExitCode, e.exitCode));
}
protected abstract List<String> cliStandardArgs();
public static Matcher<String> containsPattern(final String regex) {
return new BaseMatcher<String>() {
final Pattern pattern = Pattern.compile(regex);
@Override
public void describeTo(Description description) {
description.appendText("a string containing the pattern '" + this.pattern + "'");
}
@Override
public boolean matches(Object o) {
return o instanceof String && pattern.matcher((String) o).find();
}
};
}
public static Matcher<String> containsStringNTimes(final int times, final String substring) {
return new BaseMatcher<String>() {
@Override
public void describeTo(Description description) {
description.appendText("a string containing " + times + " times the substring '" + substring + "'");
}
@Override
public boolean matches(Object o) {
return o instanceof String
&& StringUtils.countMatches((String) o, substring) == times;
}
};
}
static class CliExecutionResult {
private final ByteArrayOutputStream out;
private final ByteArrayOutputStream err;
private final CliExitCode exitCode;
CliExecutionResult(ByteArrayOutputStream out,
ByteArrayOutputStream err,
CliExitCode exitCode) {
this.out = out;
this.err = err;
this.exitCode = exitCode;
}
public String getOut() {
return out.toString();
}
public String getErr() {
return err.toString();
}
public void checkOk() {
assertEquals(CliExitCode.OK, exitCode);
}
public void checkFailed() {
assertEquals(CliExitCode.ERROR, exitCode);
}
public void checkNoErrorOutput() {
checkStdErr(equalTo(""));
}
public void checkStdOut(Matcher<? super String> matcher) {
assertThat(getOut(), matcher);
}
public void checkStdErr(Matcher<? super String> matcher) {
assertThat(getErr(), matcher);
}
/**
* Use this method to wrap assertions.
*/
public CliExecutionResult verify(ThrowingConsumer<CliExecutionResult> actions) {
try {
actions.accept(this);
} catch (Throwable e) {
System.out.println("TEST FAILED");
System.out.println("> Return code: " + exitCode);
System.out.println("> Standard output -------------------------");
System.err.println(out.toString());
System.err.flush();
System.out.println("> Standard error --------------------------");
System.err.println(err.toString());
System.err.flush();
System.out.println("> -----------------------------------------");
if (e instanceof Exception) {
throw new AssertionFailedError("Expected no exception to be thrown", e);
}
throw (Error) e;
}
return this;
}
}
}
| 5,982 | 30.994652 | 116 | java |
pmd | pmd-master/pmd-cli/src/test/java/net/sourceforge/pmd/cli/CpdCliTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cli;
import static net.sourceforge.pmd.cli.internal.CliExitCode.OK;
import static net.sourceforge.pmd.cli.internal.CliExitCode.VIOLATIONS_FOUND;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.equalTo;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.cli.internal.CliExitCode;
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
import com.github.stefanbirkner.systemlambda.SystemLambda;
import com.google.common.collect.ImmutableMap;
class CpdCliTest extends BaseCliTest {
private static final String BASE_RES_PATH = "src/test/resources/net/sourceforge/pmd/cli/cpd/";
private static final String SRC_DIR = BASE_RES_PATH + "files/";
private static final Map<String, Integer> NUMBER_OF_TOKENS = ImmutableMap.of(
new File(SRC_DIR, "dup1.java").getAbsolutePath(), 89,
new File(SRC_DIR, "dup2.java").getAbsolutePath(), 89,
new File(SRC_DIR, "file_with_ISO-8859-1_encoding.java").getAbsolutePath(), 8,
new File(SRC_DIR, "file_with_utf8_bom.java").getAbsolutePath(), 9
);
@TempDir
private Path tempDir;
@Override
protected List<String> cliStandardArgs() {
return listOf("cpd");
}
@AfterAll
static void resetLogging() {
// reset logging in case "--debug" changed the logging properties
// See also Slf4jSimpleConfigurationForAnt
Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(null);
}
@Test
void testEmptyResultRendering() throws Exception {
final String expectedFilesXml = getExpectedFileEntriesXml(NUMBER_OF_TOKENS.keySet());
runCliSuccessfully("--minimum-tokens", "340", "--language", "java", "--dir", SRC_DIR, "--format", "xml")
.verify(result -> result.checkStdOut(equalTo(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" + "<pmd-cpd>\n" + expectedFilesXml + "</pmd-cpd>\n"
)));
}
private String getExpectedFileEntryXml(final String filename) {
final int numberOfTokens = NUMBER_OF_TOKENS.get(filename);
return String.format(" <file path=\"%s\"\n totalNumberOfTokens=\"%d\"/>\n",
new File(filename).getAbsolutePath(),
numberOfTokens);
}
private String getExpectedFileEntriesXml(final Collection<String> filenames) {
final StringBuilder expectedFilesXmlBuilder = new StringBuilder();
for (final String filename : filenames) {
expectedFilesXmlBuilder.append(getExpectedFileEntryXml(filename));
}
return expectedFilesXmlBuilder.toString();
}
@Test
void debugLogging() throws Exception {
CliExecutionResult result = runCliSuccessfully("--debug", "--minimum-tokens", "340", "--dir", SRC_DIR);
result.checkStdErr(containsString("[main] INFO net.sourceforge.pmd.cli.commands.internal.AbstractPmdSubcommand - Log level is at TRACE"));
}
@Test
void defaultLogging() throws Exception {
CliExecutionResult result = runCliSuccessfully("--minimum-tokens", "340", "--dir", SRC_DIR);
result.checkStdErr(containsString("[main] INFO net.sourceforge.pmd.cli.commands.internal.AbstractPmdSubcommand - Log level is at INFO"));
}
@Test
void testMissingMinimumTokens() throws Exception {
final CliExecutionResult result = runCli(CliExitCode.USAGE_ERROR);
result.checkStdErr(containsString("Missing required option: '--minimum-tokens=<minimumTokens>'"));
}
@Test
void testMissingSource() throws Exception {
final CliExecutionResult result = runCli(CliExitCode.USAGE_ERROR, "--minimum-tokens", "340");
result.checkStdErr(containsString("Please provide a parameter for source root directory"));
}
@Test
void testWrongCliOptionsDoPrintUsage() throws Exception {
final CliExecutionResult result = runCli(CliExitCode.USAGE_ERROR, "--invalid", "--minimum-tokens", "340", "-d", SRC_DIR);
result.checkStdErr(containsString("Unknown option: '--invalid'"));
result.checkStdErr(containsString("Usage: pmd cpd"));
}
@Test
void testFindJavaDuplication() throws Exception {
runCli(VIOLATIONS_FOUND, "--minimum-tokens", "7", "--dir", SRC_DIR)
.verify(result -> result.checkStdOut(containsString(
"Found a 14 line (86 tokens) duplication in the following files:"
)));
}
/**
* Test ignore identifiers argument.
*/
@Test
void testIgnoreIdentifiers() throws Exception {
runCli(VIOLATIONS_FOUND, "--minimum-tokens", "34", "--dir", SRC_DIR, "--ignore-identifiers")
.verify(result -> result.checkStdOut(containsString(
"Found a 14 line (89 tokens) duplication"
)));
}
@Test
void testNoFailOnViolation() throws Exception {
runCli(CliExitCode.OK, "--minimum-tokens", "7", "--dir", SRC_DIR, "--no-fail-on-violation")
.verify(result -> result.checkStdOut(containsString(
"Found a 14 line (86 tokens) duplication in the following files:"
)));
}
@Test
void testExcludeFiles() throws Exception {
runCliSuccessfully("--minimum-tokens", "7", "--dir", SRC_DIR,
"--exclude", SRC_DIR + "/dup2.java",
SRC_DIR + "/dup1.java")
.verify(result -> result.checkStdOut(emptyString()));
}
@Test
void testNoDuplicatesResultRendering() throws Exception {
final Path absoluteSrcDir = Paths.get(SRC_DIR).toAbsolutePath();
String expectedReport = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<pmd-cpd>\n"
+ " <file path=\"" + absoluteSrcDir.resolve("dup1.java") + "\"\n"
+ " totalNumberOfTokens=\"89\"/>\n"
+ " <file path=\"" + absoluteSrcDir.resolve("dup2.java") + "\"\n"
+ " totalNumberOfTokens=\"89\"/>\n"
+ " <file path=\"" + absoluteSrcDir.resolve("file_with_ISO-8859-1_encoding.java")
+ "\"\n"
+ " totalNumberOfTokens=\"8\"/>\n"
+ " <file path=\"" + absoluteSrcDir.resolve("file_with_utf8_bom.java") + "\"\n"
+ " totalNumberOfTokens=\"9\"/>\n"
+ "</pmd-cpd>\n";
runCliSuccessfully("--minimum-tokens", "340", "--language", "java", "--dir", SRC_DIR, "--format", "xml")
.verify(result -> result.checkStdOut(equalTo(expectedReport)));
}
/**
* #1144 CPD encoding argument has no effect
*/
@Test
void testEncodingOption() throws Exception {
SystemLambda.restoreSystemProperties(() -> {
// set the default encoding under Windows
System.setProperty("file.encoding", "Cp1252");
runCli(VIOLATIONS_FOUND, "--minimum-tokens", "34",
"-d", BASE_RES_PATH + "encodingTest/",
"--ignore-identifiers", "--format", "xml",
// request UTF-8 for CPD
"--encoding", "UTF-8")
.verify(r -> {
r.checkStdOut(startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
r.checkStdOut(containsPattern("System\\.out\\.println\\([ij] \\+ \"ä\"\\);"));
});
});
}
/**
* See: https://sourceforge.net/p/pmd/bugs/1178/
*/
@Test
void testSkipLexicalErrors() throws Exception {
runCli(VIOLATIONS_FOUND,
"--minimum-tokens", "10",
"-d", BASE_RES_PATH + "badandgood/",
"--format", "text",
"--skip-lexical-errors")
.verify(r -> {
r.checkStdErr(containsPattern("Skipping .*?BadFile\\.java\\. Reason: Lexical error in file"));
r.checkStdOut(containsString("Found a 5 line (13 tokens) duplication"));
});
}
@Test
void jsShouldFindDuplicatesWithDifferentFileExtensions() throws Exception {
runCli(VIOLATIONS_FOUND, "--minimum-tokens", "5", "--language", "js",
"-d", BASE_RES_PATH + "tsFiles/File1.ts", BASE_RES_PATH + "tsFiles/File2.ts")
.checkStdOut(containsString("Found a 9 line (32 tokens) duplication in the following files"));
}
@Test
void jsShouldFindNoDuplicatesWithDifferentFileExtensions() throws Exception {
runCli(OK, "--minimum-tokens", "5", "--language", "js",
"-d", BASE_RES_PATH + "tsFiles/")
.checkStdOut(emptyString());
}
@Test
void renderEmptyReportXml() throws Exception {
runCli(OK, "--minimum-tokens", "5", "--language", "js",
"-f", "xml",
"-d", BASE_RES_PATH + "tsFiles/")
.checkStdOut(equalTo(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<pmd-cpd/>\n"
));
}
}
| 9,473 | 40.012987 | 146 | java |
pmd | pmd-master/pmd-cli/src/test/java/net/sourceforge/pmd/cli/PmdCliTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cli;
import static net.sourceforge.pmd.cli.internal.CliExitCode.ERROR;
import static net.sourceforge.pmd.cli.internal.CliExitCode.OK;
import static net.sourceforge.pmd.cli.internal.CliExitCode.USAGE_ERROR;
import static net.sourceforge.pmd.cli.internal.CliExitCode.VIOLATIONS_FOUND;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.containsStringIgnoringCase;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
import net.sourceforge.pmd.internal.util.IOUtil;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.MockRule;
import com.github.stefanbirkner.systemlambda.SystemLambda;
class PmdCliTest extends BaseCliTest {
private static final String DUMMY_RULESET_WITH_VIOLATIONS = "net/sourceforge/pmd/cli/FakeRuleset2.xml";
static final String RULESET_WITH_VIOLATION = "net/sourceforge/pmd/cli/RuleSetWithViolations.xml";
private static final String RULESET_NO_VIOLATIONS = "net/sourceforge/pmd/cli/FakeRuleset.xml";
private static final String NOT_A_RULESET = "ThisRuleSetDoesNotExist.xml";
private static final String STRING_TO_REPLACE = "__should_be_replaced__";
@TempDir
private Path tempDir;
private Path srcDir;
@AfterEach
void resetLogging() {
// reset logging in case "--debug" changed the logging properties
// See also Slf4jSimpleConfigurationForAnt
Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(null);
}
@BeforeEach
void setup() throws IOException {
// create a few files
srcDir = Files.createDirectories(tempRoot().resolve("src"));
writeString(srcDir.resolve("someSource.dummy"), "dummy text");
}
@Test
void testPreExistingReportFile() throws Exception {
Path reportFile = tempRoot().resolve("out/reportFile.txt");
// now we create the file
Files.createDirectories(reportFile.getParent());
writeString(reportFile, STRING_TO_REPLACE);
assertTrue(Files.exists(reportFile), "Report file should exist");
runCliSuccessfully("-d", srcDir.toString(), "-R", RULESET_NO_VIOLATIONS, "-r", reportFile.toString());
assertNotEquals(readString(reportFile), STRING_TO_REPLACE);
}
@Test
void testPreExistingReportFileLongOption() throws Exception {
Path reportFile = tempRoot().resolve("out/reportFile.txt");
// now we create the file
Files.createDirectories(reportFile.getParent());
writeString(reportFile, STRING_TO_REPLACE);
assertTrue(Files.exists(reportFile), "Report file should exist");
runCliSuccessfully("--dir", srcDir.toString(), "--rulesets", RULESET_NO_VIOLATIONS, "--report-file", reportFile.toString());
assertNotEquals(readString(reportFile), STRING_TO_REPLACE, "Report file should have been overwritten");
}
@Test
void testNonExistentReportFile() throws Exception {
Path reportFile = tempRoot().resolve("out/reportFile.txt");
assertFalse(Files.exists(reportFile), "Report file should not exist");
try {
runCliSuccessfully("-d", srcDir.toString(), "-R", RULESET_NO_VIOLATIONS, "-r", reportFile.toString());
assertTrue(Files.exists(reportFile), "Report file should have been created");
} finally {
Files.deleteIfExists(reportFile);
}
}
@Test
void testNonExistentReportFileLongOption() throws Exception {
Path reportFile = tempRoot().resolve("out/reportFile.txt");
assertFalse(Files.exists(reportFile), "Report file should not exist");
runCliSuccessfully("--dir", srcDir.toString(), "--rulesets", RULESET_NO_VIOLATIONS, "--report-file", reportFile.toString());
assertTrue(Files.exists(reportFile), "Report file should have been created");
}
@Test
void testFileCollectionWithUnknownFiles() throws Exception {
Path reportFile = tempRoot().resolve("out/reportFile.txt");
Files.createFile(srcDir.resolve("foo.not_analysable"));
assertFalse(Files.exists(reportFile), "Report file should not exist");
// restoring system properties: --debug might change logging properties
SystemLambda.restoreSystemProperties(() -> {
runCliSuccessfully("--dir", srcDir.toString(), "--rulesets", RULESET_NO_VIOLATIONS, "--report-file", reportFile.toString(), "--debug");
});
assertTrue(Files.exists(reportFile), "Report file should have been created");
String reportText = readString(reportFile);
assertThat(reportText, not(containsStringIgnoringCase("error")));
}
/**
* This tests to create the report file in the current working directory.
*
* <p>Note: We can't change the cwd in the running VM, so the file will not be created
* in the temporary folder, but really in the cwd. The test fails if a file already exists
* and makes sure to cleanup the file afterwards.
*/
@Test
void testRelativeReportFile() throws Exception {
String reportFile = "reportFile.txt";
Path absoluteReportFile = FileSystems.getDefault().getPath(reportFile).toAbsolutePath();
// verify the file doesn't exist yet - we will delete the file at the end!
assertFalse(Files.exists(absoluteReportFile), "Report file must not exist yet! " + absoluteReportFile);
try {
runCliSuccessfully("-d", srcDir.toString(), "-R", RULESET_NO_VIOLATIONS, "-r", reportFile);
assertTrue(Files.exists(absoluteReportFile), "Report file should have been created");
} finally {
Files.deleteIfExists(absoluteReportFile);
}
}
@Test
void testRelativeReportFileLongOption() throws Exception {
String reportFile = "reportFile.txt";
Path absoluteReportFile = FileSystems.getDefault().getPath(reportFile).toAbsolutePath();
// verify the file doesn't exist yet - we will delete the file at the end!
assertFalse(Files.exists(absoluteReportFile), "Report file must not exist yet!");
try {
runCliSuccessfully("--dir", srcDir.toString(), "--rulesets", RULESET_NO_VIOLATIONS, "--report-file", reportFile.toString());
assertTrue(Files.exists(absoluteReportFile), "Report file should have been created");
} finally {
Files.deleteIfExists(absoluteReportFile);
}
}
@Test
void debugLogging() throws Exception {
CliExecutionResult result = runCliSuccessfully("--debug", "--dir", srcDir.toString(), "--rulesets", RULESET_NO_VIOLATIONS);
result.checkStdErr(containsString("[main] INFO net.sourceforge.pmd.cli.commands.internal.AbstractPmdSubcommand - Log level is at TRACE"));
}
@Test
void defaultLogging() throws Exception {
CliExecutionResult result = runCliSuccessfully("--dir", srcDir.toString(), "--rulesets", RULESET_NO_VIOLATIONS);
result.checkStdErr(containsString("[main] INFO net.sourceforge.pmd.cli.commands.internal.AbstractPmdSubcommand - Log level is at INFO"));
result.checkStdErr(not(containsPattern("Adding file .*"))); // not in debug mode
}
@Test
void testDeprecatedRulesetSyntaxOnCommandLine() throws Exception {
CliExecutionResult result = runCli(VIOLATIONS_FOUND, "--dir", srcDir.toString(), "--rulesets", "dummy-basic");
result.checkStdErr(containsString("Ruleset reference 'dummy-basic' uses a deprecated form, use 'rulesets/dummy/basic.xml' instead"));
}
@Test
void testReportToStdoutNotClosing() throws Exception {
PrintStream originalOut = System.out;
PrintStream out = new PrintStream(new FilterOutputStream(originalOut) {
@Override
public void close() {
fail("Stream must not be closed");
}
});
try {
System.setOut(out);
runCli(VIOLATIONS_FOUND, "--dir", srcDir.toString(), "--rulesets", "rulesets/dummy/basic.xml");
} finally {
System.setOut(originalOut);
}
}
@Test
void testMissingRuleset() throws Exception {
CliExecutionResult result = runCli(USAGE_ERROR);
result.checkStdErr(containsString("Missing required option: '--rulesets=<rulesets>'"));
}
@Test
void testMissingSource() throws Exception {
CliExecutionResult result = runCli(USAGE_ERROR, "--rulesets", RULESET_NO_VIOLATIONS);
result.checkStdErr(containsString("Please provide a parameter for source root directory"));
}
/**
* @see <a href="https://github.com/pmd/pmd/issues/3427">[core] Stop printing CLI usage text when exiting due to invalid parameters #3427</a>
*/
@Test
void testWrongCliOptionsDoPrintUsage() throws Exception {
runCli(USAGE_ERROR, "--invalid", "--rulesets", RULESET_NO_VIOLATIONS, "-d", srcDir.toString())
.verify(result -> {
result.checkStdErr(containsString("Unknown option: '--invalid'"));
result.checkStdErr(containsString("Usage: pmd check"));
result.checkStdErr(not(containsStringIgnoringCase("Available report formats and")));
});
}
/**
* See https://sourceforge.net/p/pmd/bugs/1231/
*/
@Test
void testWrongRuleset() throws Exception {
runCli(ERROR, "-d", srcDir.toString(), "-f", "text", "-R", NOT_A_RULESET)
.verify(result -> result.checkStdErr(
containsString("Cannot resolve rule/ruleset reference"
+ " '" + NOT_A_RULESET + "'")));
}
/**
* See https://sourceforge.net/p/pmd/bugs/1231/
*/
@Test
void testWrongRulesetWithRulename() throws Exception {
runCli(ERROR, "-d", srcDir.toString(), "-f", "text", "-R", NOT_A_RULESET + "/NotARule")
.verify(result -> result.checkStdErr(
containsString("Cannot resolve rule/ruleset reference"
+ " '" + NOT_A_RULESET + "/NotARule'")));
}
/**
* See https://sourceforge.net/p/pmd/bugs/1231/
*/
@Test
void testWrongRulename() throws Exception {
runCli(OK, "-d", srcDir.toString(), "-f", "text", "-R", RULESET_NO_VIOLATIONS + "/ThisRuleDoesNotExist")
.verify(result -> result.checkStdErr(
containsString(
"No rules found. Maybe you misspelled a rule name?"
+ " (" + RULESET_NO_VIOLATIONS + "/ThisRuleDoesNotExist)"
)
));
}
@Test
void changeSourceVersion() throws Exception {
runCli(OK, "-d", srcDir.toString(), "-f", "text", "-R", RULESET_NO_VIOLATIONS, "--debug",
"--use-version", "dummy-1.2")
.verify(result -> result.checkStdErr(
containsPattern("Adding file .*\\.dummy \\(lang: dummy 1\\.2\\)"))
);
}
@Test
void exitStatusWithViolationsAndWithoutFailOnViolations() throws Exception {
runCli(OK, "-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION, "--no-fail-on-violation")
.verify(r -> r.checkStdOut(
containsString("Violation from ReportAllRootNodes")
));
}
@Test
void exitStatusWithNoViolations() throws Exception {
runCli(OK, "-d", srcDir.toString(), "-f", "text", "-R", RULESET_NO_VIOLATIONS)
.verify(r -> r.checkStdOut(equalTo("")));
}
@Test
void exitStatusWithViolations() throws Exception {
runCli(VIOLATIONS_FOUND, "-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION)
.verify(r -> r.checkStdOut(
containsString("Violation from ReportAllRootNodes")
));
}
@Test
void testZipFileAsSource() throws Exception {
Path zipArchive = createTemporaryZipArchive("sources.zip");
CliExecutionResult result = runCli(VIOLATIONS_FOUND, "--dir", zipArchive.toString(), "--rulesets", "rulesets/dummy/basic.xml");
result.checkStdErr(not(containsStringIgnoringCase("Cannot open zip file")));
String reportPath = IOUtil.normalizePath(zipArchive.toString()) + "!/someSource.dummy";
result.checkStdOut(containsString(reportPath + ":1:\tSampleXPathRule:\tTest Rule 2"));
}
@Test
void testJarFileAsSource() throws Exception {
Path jarArchive = createTemporaryZipArchive("sources.jar");
CliExecutionResult result = runCli(VIOLATIONS_FOUND, "--dir", jarArchive.toString(), "--rulesets", "rulesets/dummy/basic.xml");
result.checkStdErr(not(containsStringIgnoringCase("Cannot open zip file")));
String reportPath = IOUtil.normalizePath(jarArchive.toString()) + "!/someSource.dummy";
result.checkStdOut(containsString(reportPath + ":1:\tSampleXPathRule:\tTest Rule 2"));
}
private Path createTemporaryZipArchive(String name) throws Exception {
Path zipArchive = tempRoot().resolve(name);
try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipArchive))) {
ZipEntry zipEntry = new ZipEntry("someSource.dummy");
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write("dummy text".getBytes(StandardCharsets.UTF_8));
zipOutputStream.closeEntry();
}
return zipArchive;
}
@Test
void testNoRelativizeWithAbsoluteSrcDir() throws Exception {
assertTrue(srcDir.isAbsolute(), "srcDir should be absolute");
runCli(VIOLATIONS_FOUND, "--dir", srcDir.toString(), "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS)
.verify(result -> result.checkStdOut(
containsString(srcDir.resolve("someSource.dummy").toString())));
}
@Test
void testNoRelativizeWithRelativeSrcDir() throws Exception {
// Note, that we can't reliably change the current working directory for the current java process
// therefore we use the current directory and make sure, we are at the correct place - in pmd-core
Path cwd = Paths.get(".").toRealPath();
assertThat(cwd.toString(), endsWith("pmd-cli"));
String relativeSrcDir = "src/test/resources/net/sourceforge/pmd/cli/src";
assertTrue(Files.isDirectory(cwd.resolve(relativeSrcDir)));
runCli(VIOLATIONS_FOUND, "--dir", relativeSrcDir, "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS)
.verify(result -> result.checkStdOut(
containsString("\n" + IOUtil.normalizePath(relativeSrcDir + "/somefile.dummy"))));
}
@Test
void testNoRelativizeWithRelativeSrcDirParent() throws Exception {
// Note, that we can't reliably change the current working directory for the current java process
// therefore we use the current directory and make sure, we are at the correct place - in pmd-core
Path cwd = Paths.get(".").toRealPath();
assertThat(cwd.toString(), endsWith("pmd-cli"));
String relativeSrcDir = IOUtil.normalizePath("src/test/resources/net/sourceforge/pmd/cli/src");
assertTrue(Files.isDirectory(cwd.resolve(relativeSrcDir)));
// use the parent directory
String relativeSrcDirWithParent = relativeSrcDir + File.separator + "..";
runCli(VIOLATIONS_FOUND, "--dir", relativeSrcDirWithParent, "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS)
.verify(result -> result.checkStdOut(
containsString("\n" + relativeSrcDirWithParent + IOUtil.normalizePath("/src/somefile.dummy"))));
}
@Test
void testRelativizeWithRootRelativeSrcDir() throws Exception {
// Note, that we can't reliably change the current working directory for the current java process
// therefore we use the current directory and make sure, we are at the correct place - in pmd-core
Path cwd = Paths.get(".").toRealPath();
assertThat(cwd.toString(), endsWith("pmd-cli"));
String relativeSrcDir = "src/test/resources/net/sourceforge/pmd/cli/src";
assertTrue(Files.isDirectory(cwd.resolve(relativeSrcDir)));
String root = cwd.getRoot().toString();
String absoluteSrcPath = cwd.resolve(relativeSrcDir).resolve("somefile.dummy").toString();
runCli(VIOLATIONS_FOUND, "--dir", relativeSrcDir, "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS, "--relativize-paths-with", root)
.verify(result -> result.checkStdOut(
containsString("\n" + absoluteSrcPath))
);
}
@Test
void testRelativizeWith() throws Exception {
runCli(VIOLATIONS_FOUND, "--dir", srcDir.toString(), "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS, "-z", srcDir.getParent().toString())
.verify(result -> {
result.checkStdOut(not(containsString(srcDir.resolve("someSource.dummy").toString())));
result.checkStdOut(startsWith(IOUtil.normalizePath("src/someSource.dummy")));
});
}
@Test
void testRelativizeWithSymLink() throws Exception {
// srcDir = /tmp/junit123/src
// symlinkedSrcDir = /tmp/junit123/sources -> /tmp/junit123/src
Path symlinkedSrcDir = Files.createSymbolicLink(tempRoot().resolve("sources"), srcDir);
runCli(VIOLATIONS_FOUND, "--dir", symlinkedSrcDir.toString(), "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS, "-z", symlinkedSrcDir.toString())
.verify(result -> {
result.checkStdOut(not(containsString(srcDir.resolve("someSource.dummy").toString())));
result.checkStdOut(not(containsString(symlinkedSrcDir.resolve("someSource.dummy").toString())));
result.checkStdOut(startsWith("someSource.dummy"));
});
}
@Test
void testRelativizeWithSymLinkParent() throws Exception {
// srcDir = /tmp/junit123/src
// symlinkedSrcDir = /tmp/junit-relativize-with-123 -> /tmp/junit123/src
Path tempPath = Files.createTempDirectory("junit-relativize-with-");
Files.delete(tempPath);
Path symlinkedSrcDir = Files.createSymbolicLink(tempPath, srcDir);
// relativizing against parent of symlinkedSrcDir: /tmp
runCli(VIOLATIONS_FOUND, "--dir", symlinkedSrcDir.toString(), "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS, "-z", symlinkedSrcDir.getParent().toString())
.verify(result -> {
result.checkStdOut(not(containsString(srcDir.resolve("someSource.dummy").toString())));
result.checkStdOut(not(containsString(symlinkedSrcDir.resolve("someSource.dummy").toString())));
// base path is symlinkedSrcDir without /tmp: e.g. junit-relativize-with-123
String basePath = symlinkedSrcDir.getParent().relativize(symlinkedSrcDir).toString();
result.checkStdOut(startsWith(basePath + File.separator + "someSource.dummy"));
});
}
@Test
void testRelativizeWithMultiple() throws Exception {
runCli(VIOLATIONS_FOUND, "--dir", srcDir.toString(), "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS, "-z", srcDir.getParent().toString() + "," + srcDir.toString())
.verify(result -> {
result.checkStdOut(not(containsString(srcDir.resolve("someSource.dummy").toString())));
result.checkStdOut(startsWith("someSource.dummy"));
});
}
@Test
void testRelativizeWithFileIsError() throws Exception {
runCli(USAGE_ERROR, "--dir", srcDir.toString(), "--rulesets",
DUMMY_RULESET_WITH_VIOLATIONS, "-z", srcDir.resolve("someSource.dummy").toString())
.verify(result -> result.checkStdErr(
containsString(
"Expected a directory path for option '--relativize-paths-with', found a file: "
+ srcDir.resolve("someSource.dummy"))
));
}
@Test
void testFileListOnly() throws Exception {
Path filelist = tempDir.resolve("filelist.txt");
writeString(filelist, srcDir.resolve("someSource.dummy") + System.lineSeparator());
runCli(VIOLATIONS_FOUND, "--file-list", filelist.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION)
.verify(r -> r.checkStdOut(
containsString("Violation from ReportAllRootNodes")
));
}
@Test
void minimumPriorityOption() throws Exception {
runCli(VIOLATIONS_FOUND, "-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION, "--minimum-priority", "Medium")
.verify(r -> r.checkStdOut(
containsString("Violation from ReportAllRootNodes")
));
runCliSuccessfully("-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION, "--minimum-priority", "High");
runCliSuccessfully("-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION, "--minimum-priority", "medium HIGH");
runCliSuccessfully("-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION, "--minimum-priority", "Medium_High");
}
@Test
void minimumPriorityOptionNumeric() throws Exception {
runCli(VIOLATIONS_FOUND, "-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION, "--minimum-priority", "3")
.verify(r -> r.checkStdOut(
containsString("Violation from ReportAllRootNodes")
));
runCliSuccessfully("-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION, "--minimum-priority", "1");
runCliSuccessfully("-d", srcDir.toString(), "-f", "text", "-R", RULESET_WITH_VIOLATION, "--minimum-priority", "2");
}
// utilities
private Path tempRoot() {
return tempDir;
}
// available in Files on java 11+
private static void writeString(Path path, String text) throws IOException {
ByteBuffer encoded = StandardCharsets.UTF_8.encode(text);
Files.write(path, encoded.array());
}
// available in Files on java 11+
private static String readString(Path path) throws IOException {
byte[] bytes = Files.readAllBytes(path);
ByteBuffer buf = ByteBuffer.wrap(bytes);
return StandardCharsets.UTF_8.decode(buf).toString();
}
@Override
protected List<String> cliStandardArgs() {
return listOf(
"check", "--no-cache", "--no-progress"
);
}
public static class FooRule extends MockRule {
@Override
public void apply(Node node, RuleContext ctx) {
ctx.addViolation(node);
}
}
}
| 24,137 | 44.37218 | 147 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.