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-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTUserClassOrInterface.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.ast.NodeStream; import apex.jorje.semantic.ast.compilation.Compilation; /** * An Apex type declaration. * * @author Clément Fournier */ public interface ASTUserClassOrInterface<T extends Compilation> extends ApexQualifiableNode, ApexNode<T> { /** Return the simple name of the type defined by this node. */ String getSimpleName(); /** * Return the modifier node for this type declaration. */ default ASTModifierNode getModifiers() { return firstChild(ASTModifierNode.class); } /** * Returns the (non-synthetic) methods defined in this type. */ default @NonNull NodeStream<ASTMethod> getMethods() { return children(ASTMethod.class).filterNot(it -> it.getImage().matches("(<clinit>|<init>|clone)")); } }
1,005
24.794872
107
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTSwitchStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.SwitchStatement; public final class ASTSwitchStatement extends AbstractApexNode<SwitchStatement> { ASTSwitchStatement(SwitchStatement node) { super(node); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
512
21.304348
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/AccessNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import net.sourceforge.pmd.lang.ast.Node; /** * This interface captures access modifiers. */ public interface AccessNode extends Node { int PUBLIC = 0x0001; int PRIVATE = 0x0002; int PROTECTED = 0x0004; int STATIC = 0x0008; int FINAL = 0x0010; int TRANSIENT = 0x0080; int ABSTRACT = 0x0400; int getModifiers(); boolean isPublic(); boolean isProtected(); boolean isPrivate(); boolean isAbstract(); boolean isStatic(); boolean isFinal(); boolean isTransient(); }
665
16.526316
79
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTDmlUpsertStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.DmlUpsertStatement; public final class ASTDmlUpsertStatement extends AbstractApexNode<DmlUpsertStatement> { ASTDmlUpsertStatement(DmlUpsertStatement dmlUpsertStatement) { super(dmlUpsertStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
553
25.380952
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTPackageVersionExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.expression.PackageVersionExpression; public final class ASTPackageVersionExpression extends AbstractApexNode<PackageVersionExpression> { ASTPackageVersionExpression(PackageVersionExpression packageVersionExpression) { super(packageVersionExpression); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
596
27.428571
99
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTJavaVariableExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.expression.JavaVariableExpression; public final class ASTJavaVariableExpression extends AbstractApexNode<JavaVariableExpression> { ASTJavaVariableExpression(JavaVariableExpression javaVariableExpression) { super(javaVariableExpression); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
582
26.761905
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTLiteralExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import java.util.Optional; import org.apache.commons.lang3.reflect.FieldUtils; import apex.jorje.data.Identifier; import apex.jorje.data.ast.LiteralType; import apex.jorje.semantic.ast.expression.LiteralExpression; import apex.jorje.semantic.ast.expression.NewKeyValueObjectExpression.NameValueParameter; public final class ASTLiteralExpression extends AbstractApexNode<LiteralExpression> { ASTLiteralExpression(LiteralExpression literalExpression) { super(literalExpression); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public LiteralType getLiteralType() { return node.getLiteralType(); } public boolean isString() { return node.getLiteralType() == LiteralType.STRING; } public boolean isBoolean() { return node.getLiteralType() == LiteralType.TRUE || node.getLiteralType() == LiteralType.FALSE; } public boolean isInteger() { return node.getLiteralType() == LiteralType.INTEGER; } public boolean isDouble() { return node.getLiteralType() == LiteralType.DOUBLE; } public boolean isLong() { return node.getLiteralType() == LiteralType.LONG; } public boolean isDecimal() { return node.getLiteralType() == LiteralType.DECIMAL; } public boolean isNull() { return node.getLiteralType() == LiteralType.NULL; } @Override public String getImage() { if (node.getLiteral() != null) { return String.valueOf(node.getLiteral()); } return null; } public String getName() { if (getParent() instanceof ASTNewKeyValueObjectExpression) { ASTNewKeyValueObjectExpression parent = (ASTNewKeyValueObjectExpression) getParent(); Optional<NameValueParameter> parameter = parent.node.getParameters().stream().filter(p -> { try { return this.node.equals(FieldUtils.readDeclaredField(p, "expression", true)); } catch (IllegalArgumentException | ReflectiveOperationException e) { return false; } }).findFirst(); return parameter.map(p -> { try { return (Identifier) FieldUtils.readDeclaredField(p, "name", true); } catch (IllegalArgumentException | ReflectiveOperationException e) { return null; } }).map(Identifier::getValue).orElse(null); } return null; } }
2,761
29.021739
103
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTNewListInitExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.expression.NewListInitExpression; public final class ASTNewListInitExpression extends AbstractApexNode<NewListInitExpression> { ASTNewListInitExpression(NewListInitExpression newListInitExpression) { super(newListInitExpression); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
575
26.428571
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/BaseApexClass.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import apex.jorje.semantic.ast.compilation.Compilation; abstract class BaseApexClass<T extends Compilation> extends AbstractApexNode<T> implements ASTUserClassOrInterface<T> { private ApexQualifiedName qname; protected BaseApexClass(T node) { super(node); } @Override public boolean isFindBoundary() { return true; } /** * @deprecated Use {@link #getSimpleName()} */ @Override @Deprecated @DeprecatedUntil700 public String getImage() { return getSimpleName(); } @Override public String getSimpleName() { String apexName = getDefiningType(); return apexName.substring(apexName.lastIndexOf('.') + 1); } @Override public ApexQualifiedName getQualifiedName() { if (qname == null) { ASTUserClass parent = this.getFirstParentOfType(ASTUserClass.class); if (parent != null) { qname = ApexQualifiedName.ofNestedClass(parent.getQualifiedName(), this); } else { qname = ApexQualifiedName.ofOuterClass(this); } } return qname; } }
1,349
22.275862
119
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTIfElseBlockStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.IfElseBlockStatement; public final class ASTIfElseBlockStatement extends AbstractApexNode<IfElseBlockStatement> { ASTIfElseBlockStatement(IfElseBlockStatement ifElseBlockStatement) { super(ifElseBlockStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public boolean hasElseStatement() { return node.hasElseStatement(); } }
654
25.2
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTAnnotationParameter.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.modifier.AnnotationParameter; public final class ASTAnnotationParameter extends AbstractApexNode<AnnotationParameter> { public static final String SEE_ALL_DATA = "seeAllData"; ASTAnnotationParameter(AnnotationParameter annotationParameter) { super(annotationParameter); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public String getName() { if (node.getProperty() != null) { return node.getProperty().getName(); } return null; } public String getValue() { if (node.getValue() != null) { return node.getValueAsString(); } return null; } public Boolean getBooleanValue() { return node.getBooleanValue(); } @Override @Deprecated public String getImage() { return getValue(); } }
1,110
23.152174
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTVariableDeclaration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.VariableDeclaration; public final class ASTVariableDeclaration extends AbstractApexNode<VariableDeclaration> { ASTVariableDeclaration(VariableDeclaration variableDeclaration) { super(variableDeclaration); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public String getImage() { if (node.getLocalInfo() != null) { return node.getLocalInfo().getName(); } return null; } public String getType() { if (node.getLocalInfo() != null) { return node.getLocalInfo().getType().getApexName(); } return null; } }
912
23.675676
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexTreeBuilder.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import java.util.AbstractList; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.RandomAccess; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.apex.ApexLanguageProcessor; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.document.Chars; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextRegion; import apex.jorje.data.Location; import apex.jorje.data.Locations; import apex.jorje.semantic.ast.AstNode; import apex.jorje.semantic.ast.compilation.AnonymousClass; import apex.jorje.semantic.ast.compilation.Compilation; import apex.jorje.semantic.ast.compilation.ConstructorPreamble; import apex.jorje.semantic.ast.compilation.InvalidDependentCompilation; import apex.jorje.semantic.ast.compilation.UserClass; import apex.jorje.semantic.ast.compilation.UserClassMethods; import apex.jorje.semantic.ast.compilation.UserEnum; import apex.jorje.semantic.ast.compilation.UserExceptionMethods; import apex.jorje.semantic.ast.compilation.UserInterface; import apex.jorje.semantic.ast.compilation.UserTrigger; import apex.jorje.semantic.ast.condition.StandardCondition; import apex.jorje.semantic.ast.expression.ArrayLoadExpression; import apex.jorje.semantic.ast.expression.ArrayStoreExpression; import apex.jorje.semantic.ast.expression.AssignmentExpression; import apex.jorje.semantic.ast.expression.BinaryExpression; import apex.jorje.semantic.ast.expression.BindExpressions; import apex.jorje.semantic.ast.expression.BooleanExpression; import apex.jorje.semantic.ast.expression.CastExpression; import apex.jorje.semantic.ast.expression.ClassRefExpression; import apex.jorje.semantic.ast.expression.EmptyReferenceExpression; import apex.jorje.semantic.ast.expression.Expression; import apex.jorje.semantic.ast.expression.IllegalStoreExpression; import apex.jorje.semantic.ast.expression.InstanceOfExpression; import apex.jorje.semantic.ast.expression.JavaMethodCallExpression; import apex.jorje.semantic.ast.expression.JavaVariableExpression; import apex.jorje.semantic.ast.expression.LiteralExpression; import apex.jorje.semantic.ast.expression.MapEntryNode; import apex.jorje.semantic.ast.expression.MethodCallExpression; import apex.jorje.semantic.ast.expression.NestedExpression; import apex.jorje.semantic.ast.expression.NestedStoreExpression; import apex.jorje.semantic.ast.expression.NewKeyValueObjectExpression; import apex.jorje.semantic.ast.expression.NewListInitExpression; import apex.jorje.semantic.ast.expression.NewListLiteralExpression; import apex.jorje.semantic.ast.expression.NewMapInitExpression; import apex.jorje.semantic.ast.expression.NewMapLiteralExpression; import apex.jorje.semantic.ast.expression.NewObjectExpression; import apex.jorje.semantic.ast.expression.NewSetInitExpression; import apex.jorje.semantic.ast.expression.NewSetLiteralExpression; import apex.jorje.semantic.ast.expression.PackageVersionExpression; import apex.jorje.semantic.ast.expression.PostfixExpression; import apex.jorje.semantic.ast.expression.PrefixExpression; import apex.jorje.semantic.ast.expression.ReferenceExpression; import apex.jorje.semantic.ast.expression.SoqlExpression; import apex.jorje.semantic.ast.expression.SoslExpression; import apex.jorje.semantic.ast.expression.SuperMethodCallExpression; import apex.jorje.semantic.ast.expression.SuperVariableExpression; import apex.jorje.semantic.ast.expression.TernaryExpression; import apex.jorje.semantic.ast.expression.ThisMethodCallExpression; import apex.jorje.semantic.ast.expression.ThisVariableExpression; import apex.jorje.semantic.ast.expression.TriggerVariableExpression; import apex.jorje.semantic.ast.expression.VariableExpression; import apex.jorje.semantic.ast.member.Field; import apex.jorje.semantic.ast.member.Method; import apex.jorje.semantic.ast.member.Parameter; import apex.jorje.semantic.ast.member.Property; import apex.jorje.semantic.ast.member.bridge.BridgeMethodCreator; import apex.jorje.semantic.ast.modifier.Annotation; import apex.jorje.semantic.ast.modifier.AnnotationParameter; import apex.jorje.semantic.ast.modifier.Modifier; import apex.jorje.semantic.ast.modifier.ModifierNode; import apex.jorje.semantic.ast.modifier.ModifierOrAnnotation; import apex.jorje.semantic.ast.statement.BlockStatement; import apex.jorje.semantic.ast.statement.BreakStatement; import apex.jorje.semantic.ast.statement.CatchBlockStatement; import apex.jorje.semantic.ast.statement.ConstructorPreambleStatement; import apex.jorje.semantic.ast.statement.ContinueStatement; import apex.jorje.semantic.ast.statement.DmlDeleteStatement; import apex.jorje.semantic.ast.statement.DmlInsertStatement; import apex.jorje.semantic.ast.statement.DmlMergeStatement; import apex.jorje.semantic.ast.statement.DmlUndeleteStatement; import apex.jorje.semantic.ast.statement.DmlUpdateStatement; import apex.jorje.semantic.ast.statement.DmlUpsertStatement; import apex.jorje.semantic.ast.statement.DoLoopStatement; import apex.jorje.semantic.ast.statement.ElseWhenBlock; import apex.jorje.semantic.ast.statement.ExpressionStatement; import apex.jorje.semantic.ast.statement.FieldDeclaration; import apex.jorje.semantic.ast.statement.FieldDeclarationStatements; import apex.jorje.semantic.ast.statement.ForEachStatement; import apex.jorje.semantic.ast.statement.ForLoopStatement; import apex.jorje.semantic.ast.statement.IfBlockStatement; import apex.jorje.semantic.ast.statement.IfElseBlockStatement; import apex.jorje.semantic.ast.statement.MethodBlockStatement; import apex.jorje.semantic.ast.statement.MultiStatement; import apex.jorje.semantic.ast.statement.ReturnStatement; import apex.jorje.semantic.ast.statement.RunAsBlockStatement; import apex.jorje.semantic.ast.statement.Statement; import apex.jorje.semantic.ast.statement.StatementExecuted; import apex.jorje.semantic.ast.statement.SwitchStatement; import apex.jorje.semantic.ast.statement.ThrowStatement; import apex.jorje.semantic.ast.statement.TryCatchFinallyBlockStatement; import apex.jorje.semantic.ast.statement.TypeWhenBlock; import apex.jorje.semantic.ast.statement.ValueWhenBlock; import apex.jorje.semantic.ast.statement.VariableDeclaration; import apex.jorje.semantic.ast.statement.VariableDeclarationStatements; import apex.jorje.semantic.ast.statement.WhenCases.IdentifierCase; import apex.jorje.semantic.ast.statement.WhenCases.LiteralCase; import apex.jorje.semantic.ast.statement.WhileLoopStatement; import apex.jorje.semantic.ast.visitor.AdditionalPassScope; import apex.jorje.semantic.ast.visitor.AstVisitor; import apex.jorje.semantic.exception.Errors; final class ApexTreeBuilder extends AstVisitor<AdditionalPassScope> { private static final Pattern COMMENT_PATTERN = // we only need to check for \n as the input is normalized Pattern.compile("/\\*([^*]++|\\*(?!/))*+\\*/|//[^\n]++\n"); private static final Map<Class<? extends AstNode>, Function<AstNode, ? extends AbstractApexNode<?>>> NODE_TYPE_TO_NODE_ADAPTER_TYPE = new HashMap<>(); static { register(Annotation.class, ASTAnnotation::new); register(AnnotationParameter.class, ASTAnnotationParameter::new); register(AnonymousClass.class, ASTAnonymousClass::new); register(ArrayLoadExpression.class, ASTArrayLoadExpression::new); register(ArrayStoreExpression.class, ASTArrayStoreExpression::new); register(AssignmentExpression.class, ASTAssignmentExpression::new); register(BinaryExpression.class, ASTBinaryExpression::new); register(BindExpressions.class, ASTBindExpressions::new); register(BlockStatement.class, ASTBlockStatement::new); register(BooleanExpression.class, ASTBooleanExpression::new); register(BreakStatement.class, ASTBreakStatement::new); register(BridgeMethodCreator.class, ASTBridgeMethodCreator::new); register(CastExpression.class, ASTCastExpression::new); register(CatchBlockStatement.class, ASTCatchBlockStatement::new); register(ClassRefExpression.class, ASTClassRefExpression::new); register(ConstructorPreamble.class, ASTConstructorPreamble::new); register(ConstructorPreambleStatement.class, ASTConstructorPreambleStatement::new); register(ContinueStatement.class, ASTContinueStatement::new); register(DmlDeleteStatement.class, ASTDmlDeleteStatement::new); register(DmlInsertStatement.class, ASTDmlInsertStatement::new); register(DmlMergeStatement.class, ASTDmlMergeStatement::new); register(DmlUndeleteStatement.class, ASTDmlUndeleteStatement::new); register(DmlUpdateStatement.class, ASTDmlUpdateStatement::new); register(DmlUpsertStatement.class, ASTDmlUpsertStatement::new); register(DoLoopStatement.class, ASTDoLoopStatement::new); register(ElseWhenBlock.class, ASTElseWhenBlock::new); register(EmptyReferenceExpression.class, ASTEmptyReferenceExpression::new); register(Expression.class, ASTExpression::new); register(ExpressionStatement.class, ASTExpressionStatement::new); register(Field.class, ASTField::new); register(FieldDeclaration.class, ASTFieldDeclaration::new); register(FieldDeclarationStatements.class, ASTFieldDeclarationStatements::new); register(ForEachStatement.class, ASTForEachStatement::new); register(ForLoopStatement.class, ASTForLoopStatement::new); register(IdentifierCase.class, ASTIdentifierCase::new); register(IfBlockStatement.class, ASTIfBlockStatement::new); register(IfElseBlockStatement.class, ASTIfElseBlockStatement::new); register(IllegalStoreExpression.class, ASTIllegalStoreExpression::new); register(InstanceOfExpression.class, ASTInstanceOfExpression::new); register(InvalidDependentCompilation.class, ASTInvalidDependentCompilation::new); register(JavaMethodCallExpression.class, ASTJavaMethodCallExpression::new); register(JavaVariableExpression.class, ASTJavaVariableExpression::new); register(LiteralCase.class, ASTLiteralCase::new); register(LiteralExpression.class, ASTLiteralExpression::new); register(MapEntryNode.class, ASTMapEntryNode::new); register(Method.class, ASTMethod::new); register(MethodBlockStatement.class, ASTMethodBlockStatement::new); register(MethodCallExpression.class, ASTMethodCallExpression::new); register(Modifier.class, ASTModifier::new); register(ModifierNode.class, ASTModifierNode::new); register(ModifierOrAnnotation.class, ASTModifierOrAnnotation::new); register(MultiStatement.class, ASTMultiStatement::new); register(NestedExpression.class, ASTNestedExpression::new); register(NestedStoreExpression.class, ASTNestedStoreExpression::new); register(NewKeyValueObjectExpression.class, ASTNewKeyValueObjectExpression::new); register(NewListInitExpression.class, ASTNewListInitExpression::new); register(NewListLiteralExpression.class, ASTNewListLiteralExpression::new); register(NewMapInitExpression.class, ASTNewMapInitExpression::new); register(NewMapLiteralExpression.class, ASTNewMapLiteralExpression::new); register(NewObjectExpression.class, ASTNewObjectExpression::new); register(NewSetInitExpression.class, ASTNewSetInitExpression::new); register(NewSetLiteralExpression.class, ASTNewSetLiteralExpression::new); register(PackageVersionExpression.class, ASTPackageVersionExpression::new); register(Parameter.class, ASTParameter::new); register(PostfixExpression.class, ASTPostfixExpression::new); register(PrefixExpression.class, ASTPrefixExpression::new); register(Property.class, ASTProperty::new); register(ReferenceExpression.class, ASTReferenceExpression::new); register(ReturnStatement.class, ASTReturnStatement::new); register(RunAsBlockStatement.class, ASTRunAsBlockStatement::new); register(SoqlExpression.class, ASTSoqlExpression::new); register(SoslExpression.class, ASTSoslExpression::new); register(StandardCondition.class, ASTStandardCondition::new); register(Statement.class, ASTStatement::new); register(StatementExecuted.class, ASTStatementExecuted::new); register(SuperMethodCallExpression.class, ASTSuperMethodCallExpression::new); register(SuperVariableExpression.class, ASTSuperVariableExpression::new); register(SwitchStatement.class, ASTSwitchStatement::new); register(TernaryExpression.class, ASTTernaryExpression::new); register(ThisMethodCallExpression.class, ASTThisMethodCallExpression::new); register(ThisVariableExpression.class, ASTThisVariableExpression::new); register(ThrowStatement.class, ASTThrowStatement::new); register(TriggerVariableExpression.class, ASTTriggerVariableExpression::new); register(TryCatchFinallyBlockStatement.class, ASTTryCatchFinallyBlockStatement::new); register(TypeWhenBlock.class, ASTTypeWhenBlock::new); register(UserClass.class, ASTUserClass::new); register(UserClassMethods.class, ASTUserClassMethods::new); register(UserExceptionMethods.class, ASTUserExceptionMethods::new); register(UserEnum.class, ASTUserEnum::new); register(UserInterface.class, ASTUserInterface::new); register(UserTrigger.class, ASTUserTrigger::new); register(ValueWhenBlock.class, ASTValueWhenBlock::new); register(VariableDeclaration.class, ASTVariableDeclaration::new); register(VariableDeclarationStatements.class, ASTVariableDeclarationStatements::new); register(VariableExpression.class, ASTVariableExpression::new); register(WhileLoopStatement.class, ASTWhileLoopStatement::new); } @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T extends AstNode> void register(Class<T> nodeType, Function<T, ? extends AbstractApexNode<T>> nodeAdapterType) { NODE_TYPE_TO_NODE_ADAPTER_TYPE.put(nodeType, (Function) nodeAdapterType); } // The nodes having children built. private final Deque<AbstractApexNode<?>> nodes = new ArrayDeque<>(); // The Apex nodes with children to build. private final Deque<AstNode> parents = new ArrayDeque<>(); private final AdditionalPassScope scope = new AdditionalPassScope(Errors.createErrors()); private final TextDocument sourceCode; private final ParserTask task; private final ApexLanguageProcessor proc; private final CommentInformation commentInfo; ApexTreeBuilder(ParserTask task, ApexLanguageProcessor proc) { this.sourceCode = task.getTextDocument(); this.task = task; this.proc = proc; commentInfo = extractInformationFromComments(sourceCode, proc.getProperties().getSuppressMarker()); } static <T extends AstNode> AbstractApexNode<T> createNodeAdapter(T node) { // the signature of the register function makes sure this cast is safe @SuppressWarnings("unchecked") Function<T, ? extends AbstractApexNode<T>> constructor = (Function<T, ? extends AbstractApexNode<T>>) NODE_TYPE_TO_NODE_ADAPTER_TYPE.get(node.getClass()); if (constructor == null) { throw new IllegalStateException( "There is no Node adapter class registered for the Node class: " + node.getClass()); } return constructor.apply(node); } ASTApexFile buildTree(Compilation astNode) { assert nodes.isEmpty() : "stack should be empty"; ASTApexFile root = new ASTApexFile(task, astNode, commentInfo.suppressMap, proc); nodes.push(root); parents.push(astNode); build(astNode); nodes.pop(); parents.pop(); addFormalComments(); closeTree(root); return root; } private <T extends AstNode> void build(T astNode) { // Create a Node AbstractApexNode<T> node = createNodeAdapter(astNode); // Append to parent AbstractApexNode<?> parent = nodes.peek(); parent.addChild(node, parent.getNumChildren()); // Build the children... nodes.push(node); parents.push(astNode); astNode.traverse(this, scope); nodes.pop(); parents.pop(); if (nodes.isEmpty()) { // add the comments only at the end of the processing as the last step addFormalComments(); } // If appropriate, determine whether this node contains comments or not if (node instanceof AbstractApexCommentContainerNode) { AbstractApexCommentContainerNode<?> commentContainer = (AbstractApexCommentContainerNode<?>) node; if (containsComments(commentContainer)) { commentContainer.setContainsComment(true); } } } private void closeTree(AbstractApexNode<?> node) { node.closeNode(sourceCode); for (ApexNode<?> child : node.children()) { closeTree((AbstractApexNode<?>) child); } } private boolean containsComments(ASTCommentContainer<?> commentContainer) { Location loc = commentContainer.getNode().getLoc(); if (!Locations.isReal(loc)) { // Synthetic nodes don't have a location and can't have comments return false; } List<TokenLocation> allComments = commentInfo.allCommentTokens; // find the first comment after the start of the container node int index = Collections.binarySearch(commentInfo.allCommentTokensByStartIndex, loc.getStartIndex()); // no exact hit found - this is expected: there is no comment token starting at the very same index as the node assert index < 0 : "comment token is at the same position as non-comment token"; // extract "insertion point" index = ~index; // now check whether the next comment after the node is still inside the node return index >= 0 && index < allComments.size() && loc.getStartIndex() < allComments.get(index).region.getStartOffset() && loc.getEndIndex() >= allComments.get(index).region.getEndOffset(); } private void addFormalComments() { for (ApexDocTokenLocation tokenLocation : commentInfo.docTokenLocations) { AbstractApexNode<?> parent = tokenLocation.nearestNode; if (parent != null) { parent.insertChild(new ASTFormalComment(tokenLocation.region, tokenLocation.image), 0); } } } private void buildFormalComment(AstNode node) { if (node.equals(parents.peek())) { assignApexDocTokenToNode(node, nodes.peek()); } } /** * Only remembers the node, to which the comment could belong. * Since the visiting order of the nodes does not match the source order, * the nodes appearing later in the source might be visiting first. * The correct node will then be visited afterwards, and since the distance * to the comment is smaller, it overrides the remembered node. * * @param jorjeNode the original node * @param node the potential parent node, to which the comment could belong */ private void assignApexDocTokenToNode(AstNode jorjeNode, AbstractApexNode<?> node) { Location loc = jorjeNode.getLoc(); if (!Locations.isReal(loc)) { // Synthetic nodes such as "<clinit>" don't have a location in the // source code, since they are generated by the compiler return; } // find the token, that appears as close as possible before the node TextRegion nodeRegion = node.getTextRegion(); for (ApexDocTokenLocation comment : commentInfo.docTokenLocations) { if (comment.region.compareTo(nodeRegion) > 0) { // this and all remaining tokens are after the node // so no need to check the remaining tokens. break; } int distance = nodeRegion.getStartOffset() - comment.region.getStartOffset(); if (comment.nearestNode == null || distance < comment.nearestNodeDistance) { comment.nearestNode = node; comment.nearestNodeDistance = distance; } } } private static CommentInformation extractInformationFromComments(TextDocument source, String suppressMarker) { Chars text = source.getText(); boolean checkForCommentSuppression = suppressMarker != null; @SuppressWarnings("PMD.LooseCoupling") // allCommentTokens must be ArrayList explicitly to guarantee RandomAccess ArrayList<TokenLocation> allCommentTokens = new ArrayList<>(); List<ApexDocTokenLocation> tokenLocations = new ArrayList<>(); Map<Integer, String> suppressMap = new HashMap<>(); Matcher matcher = COMMENT_PATTERN.matcher(text); while (matcher.find()) { int startIdx = matcher.start(); int endIdx = matcher.end(); Chars commentText = text.subSequence(startIdx, endIdx); TextRegion commentRegion = TextRegion.fromBothOffsets(startIdx, endIdx); final TokenLocation tok; if (commentText.startsWith("/**")) { ApexDocTokenLocation doctok = new ApexDocTokenLocation(commentRegion, commentText); tokenLocations.add(doctok); // TODO #3953 - if this is an FP, just uncomment the code and remove the continue statement // tok = doctok; continue; } else { tok = new TokenLocation(commentRegion); } allCommentTokens.add(tok); if (checkForCommentSuppression && commentText.startsWith("//")) { Chars trimmed = commentText.removePrefix("//").trimStart(); if (trimmed.startsWith(suppressMarker)) { Chars userMessage = trimmed.removePrefix(suppressMarker).trim(); suppressMap.put(source.lineColumnAtOffset(startIdx).getLine(), userMessage.toString()); } } } return new CommentInformation(suppressMap, allCommentTokens, tokenLocations); } private static class CommentInformation { final Map<Integer, String> suppressMap; final List<TokenLocation> allCommentTokens; @SuppressWarnings("PMD.LooseCoupling") // must be concrete class in order to guarantee RandomAccess final TokenListByStartIndex allCommentTokensByStartIndex; final List<ApexDocTokenLocation> docTokenLocations; <T extends List<TokenLocation> & RandomAccess> CommentInformation(Map<Integer, String> suppressMap, T allCommentTokens, List<ApexDocTokenLocation> docTokenLocations) { this.suppressMap = suppressMap; this.allCommentTokens = allCommentTokens; this.docTokenLocations = docTokenLocations; this.allCommentTokensByStartIndex = new TokenListByStartIndex(allCommentTokens); } } /** * List that maps comment tokens to their start index without copy. * This is used to implement a "binary search by key" routine which unfortunately isn't in the stdlib. * * <p> * Note that the provided token list must implement {@link RandomAccess}. */ private static final class TokenListByStartIndex extends AbstractList<Integer> implements RandomAccess { private final List<TokenLocation> tokens; <T extends List<TokenLocation> & RandomAccess> TokenListByStartIndex(T tokens) { this.tokens = tokens; } @Override public Integer get(int index) { return tokens.get(index).region.getStartOffset(); } @Override public int size() { return tokens.size(); } } private static class TokenLocation { final TextRegion region; TokenLocation(TextRegion region) { this.region = region; } } private static class ApexDocTokenLocation extends TokenLocation { private final Chars image; private AbstractApexNode<?> nearestNode; private int nearestNodeDistance; ApexDocTokenLocation(TextRegion commentRegion, Chars image) { super(commentRegion); this.image = image; } } private boolean visit(AstNode node) { if (node.equals(parents.peek())) { return true; } else { build(node); return false; } } @Override public boolean visit(UserEnum node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(UserInterface node, AdditionalPassScope scope) { final boolean ret = visit(node); buildFormalComment(node); return ret; } @Override public boolean visit(UserTrigger node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ArrayLoadExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ArrayStoreExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(AssignmentExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(BinaryExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(BooleanExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ClassRefExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(InstanceOfExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(JavaMethodCallExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(JavaVariableExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(LiteralExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ReferenceExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(MethodCallExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(NewListInitExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(NewMapInitExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(NewSetInitExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(NewListLiteralExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(NewObjectExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(NewSetLiteralExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(PackageVersionExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(PostfixExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(PrefixExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(TernaryExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(StandardCondition node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(TriggerVariableExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(VariableExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(BlockStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(BreakStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ContinueStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(DmlDeleteStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(DmlInsertStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(DmlMergeStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(DmlUndeleteStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(DmlUpdateStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(DmlUpsertStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(DoLoopStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ExpressionStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ForEachStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ForLoopStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(FieldDeclaration node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(FieldDeclarationStatements node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(IfBlockStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(IfElseBlockStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ReturnStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(RunAsBlockStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ThrowStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(VariableDeclaration node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(VariableDeclarationStatements node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(WhileLoopStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(BindExpressions node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(SoqlExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(SoslExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(NewMapLiteralExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(MapEntryNode node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(CatchBlockStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(TryCatchFinallyBlockStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(Property node, AdditionalPassScope scope) { final boolean ret = visit(node); buildFormalComment(node); return ret; } @Override public boolean visit(Field node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(Parameter node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(BridgeMethodCreator node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(UserClassMethods node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(UserExceptionMethods node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(Annotation node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(AnnotationParameter node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ModifierNode node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(SuperMethodCallExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ThisMethodCallExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(SuperVariableExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ThisVariableExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(UserClass node, AdditionalPassScope scope) { final boolean ret = visit(node); buildFormalComment(node); return ret; } @Override public boolean visit(Method node, AdditionalPassScope scope) { final boolean ret = visit(node); buildFormalComment(node); return ret; } @Override public boolean visit(AnonymousClass node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(CastExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(NewKeyValueObjectExpression node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(SwitchStatement node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ElseWhenBlock node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(TypeWhenBlock node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(ValueWhenBlock node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(LiteralCase node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(IdentifierCase node, AdditionalPassScope scope) { return visit(node); } @Override public boolean visit(EmptyReferenceExpression node, AdditionalPassScope scope) { return visit(node); } }
35,924
37.258786
133
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTDmlUndeleteStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.DmlUndeleteStatement; public final class ASTDmlUndeleteStatement extends AbstractApexNode<DmlUndeleteStatement> { ASTDmlUndeleteStatement(DmlUndeleteStatement dmlUndeleteStatement) { super(dmlUndeleteStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
567
26.047619
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTDoLoopStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.DoLoopStatement; public final class ASTDoLoopStatement extends AbstractApexNode<DoLoopStatement> { ASTDoLoopStatement(DoLoopStatement doLoopStatement) { super(doLoopStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
532
24.380952
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTInvalidDependentCompilation.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.compilation.InvalidDependentCompilation; public final class ASTInvalidDependentCompilation extends AbstractApexNode<InvalidDependentCompilation> { ASTInvalidDependentCompilation(InvalidDependentCompilation userClass) { super(userClass); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public String getImage() { String apexName = getDefiningType(); return apexName.substring(apexName.lastIndexOf('.') + 1); } }
746
25.678571
105
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTCatchBlockStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.CatchBlockStatement; public final class ASTCatchBlockStatement extends AbstractApexCommentContainerNode<CatchBlockStatement> { ASTCatchBlockStatement(CatchBlockStatement catchBlockStatement) { super(catchBlockStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public String getExceptionType() { return String.valueOf(node.getTypeRef()); } public String getVariableName() { if (node.getVariable() != null) { return node.getVariable().getName(); } return null; } public ASTBlockStatement getBody() { return (ASTBlockStatement) getChild(0); } }
935
25
105
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTDmlDeleteStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.DmlDeleteStatement; public final class ASTDmlDeleteStatement extends AbstractApexNode<DmlDeleteStatement> { ASTDmlDeleteStatement(DmlDeleteStatement dmlDeleteStatement) { super(dmlDeleteStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
553
25.380952
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTDmlMergeStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.DmlMergeStatement; public final class ASTDmlMergeStatement extends AbstractApexNode<DmlMergeStatement> { ASTDmlMergeStatement(DmlMergeStatement dmlMergeStatement) { super(dmlMergeStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
546
25.047619
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTUserClassMethods.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.compilation.UserClassMethods; public final class ASTUserClassMethods extends AbstractApexNode<UserClassMethods> { ASTUserClassMethods(UserClassMethods userClassMethods) { super(userClassMethods); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
541
24.809524
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTDmlInsertStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.DmlInsertStatement; public final class ASTDmlInsertStatement extends AbstractApexNode<DmlInsertStatement> { ASTDmlInsertStatement(DmlInsertStatement dmlInsertStatement) { super(dmlInsertStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
553
25.380952
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/TestAccessEvaluator.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ // Note: taken from https://github.com/forcedotcom/idecore/blob/3083815933c2d015d03417986f57bd25786d58ce/com.salesforce.ide.apex.core/src/apex/jorje/semantic/common/TestAccessEvaluator.java /* * Copyright 2016 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.sourceforge.pmd.lang.apex.ast; import java.util.HashSet; import java.util.Objects; import java.util.Set; import apex.jorje.semantic.compiler.Namespace; import apex.jorje.semantic.compiler.StructuredVersion; import apex.jorje.semantic.compiler.sfdc.AccessEvaluator; import apex.jorje.semantic.compiler.sfdc.PlaceholderOrgPerm; import apex.jorje.semantic.symbol.type.SObjectTypeInfo; import apex.jorje.semantic.symbol.type.StandardTypeInfo; import apex.jorje.semantic.symbol.type.StandardTypeInfoImpl; import apex.jorje.semantic.symbol.type.TypeInfo; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.SetMultimap; /** * For now everything returns false. * If you actually need to override something, it would be easier to probably mock and adjust what you needed. * Otherwise this is simply to create a concrete representation and not force a mockito init. * * @author jspagnola */ class TestAccessEvaluator implements AccessEvaluator { private final SetMultimap<Namespace, StructuredVersion> validPageVersions; private final SetMultimap<SObjectTypeInfo, TypeInfo> visibleSetupEntitiesToTypes; private final Set<Namespace> accessibleSystemNamespaces; private final Set<PlaceholderOrgPerm> orgPerm; private final Set<AllowedPermGuard> allowedPermGuards; private final Set<Namespace> reservedNamespaces; private final Set<String> globalComponents; private final Set<Namespace> managedPackagesNotInstalled; private final Set<String> typesWithConnectApiDeserializers; private boolean hasInternalSfdc; private boolean isRunningTests; private boolean hasPrivateApi; private boolean isTrustedApplication; private boolean hasLocalizedTranslation; private boolean isSfdc; private boolean isReallyRunningTests; private boolean hasApexGenericTypes; private boolean hasRemoteActionPerm; private boolean hasPersonAccountApiAvailable; TestAccessEvaluator() { validPageVersions = HashMultimap.create(); visibleSetupEntitiesToTypes = HashMultimap.create(); managedPackagesNotInstalled = new HashSet<>(); accessibleSystemNamespaces = new HashSet<>(); orgPerm = new HashSet<>(); allowedPermGuards = new HashSet<>(); reservedNamespaces = new HashSet<>(); globalComponents = new HashSet<>(); typesWithConnectApiDeserializers = new HashSet<>(); hasRemoteActionPerm = true; hasPersonAccountApiAvailable = true; } @Override public boolean hasPermission(final PlaceholderOrgPerm orgPerm) { return this.orgPerm.contains(orgPerm); } @Override public boolean hasPermissionForPermGuard(final Namespace referencingNamespace, final String orgPerm) { return allowedPermGuards.contains(new AllowedPermGuard(referencingNamespace, orgPerm)); } @Override public boolean hasPersonAccountApiAvailable() { return hasPersonAccountApiAvailable; } @Override public boolean hasPrivateApi() { return hasPrivateApi; } @Override public boolean hasLocalizedTranslation() { return hasLocalizedTranslation; } @Override public boolean hasInternalSfdc() { return hasInternalSfdc; } @Override public boolean isTrustedApplication(TypeInfo arg0) { return isTrustedApplication; } @Override public boolean isReservedNamespace(final Namespace namespace) { return reservedNamespaces.contains(namespace); } @Override public boolean isReservedNamespace(final Namespace namespace, final boolean excludePackages) { return reservedNamespaces.contains(namespace); } /** * See {@link #isAccessibleOrTrustedNamespace(Namespace)} */ @Override public boolean isAccessibleSystemNamespace(final Namespace namespace) { return accessibleSystemNamespaces.contains(namespace); } /** * Okay so this check and its partner isAccessibleSystemNamespace are used slightly differently. * This is like a black list check, that prevents referencing code from seeing things in a reserved namespace. * The other check allows code to see certain things if the code's namespace is a reserved namespace. * <p> * Hence here we return true by default, and the {@link #isAccessibleSystemNamespace(Namespace)} returns false * by default. */ @Override public boolean isAccessibleOrTrustedNamespace(final Namespace namespace) { return true; } @Override public boolean isRunningTests() { return isRunningTests; } @Override public boolean isReallyRunningTests() { return isReallyRunningTests; } @Override public boolean isSfdc() { return isSfdc; } @Override public boolean hasApexParameterizedTypes() { return hasApexGenericTypes; } @Override public boolean isValidPackageVersion(final Namespace namespace, final StructuredVersion version) { return validPageVersions.containsEntry(namespace, version); } /** * @return 'true' for everything EXCEPT namespaces you've added through {@link #addManagedPackageNotInstalled(Namespace)} */ @Override public boolean isManagedPackageInstalled(final Namespace namespace) { return !managedPackagesNotInstalled.contains(namespace); } @Override public boolean isSetupEntityVisibleToType(final SObjectTypeInfo type, final TypeInfo referencingType) { final TypeInfo visibleReferencingType = Iterables.getFirst(visibleSetupEntitiesToTypes.get(type), null); return visibleReferencingType != null && visibleReferencingType.getBytecodeName().equals(referencingType.getBytecodeName()); } @Override public boolean hasConnectDeserializer(final TypeInfo type) { return typesWithConnectApiDeserializers.contains(type.getApexName()); } @Override public boolean hasRemoteAction(final TypeInfo type) { return false; } @Override public boolean hasRemoteActionPerm() { return hasRemoteActionPerm; } @Override public boolean isGlobalComponent(final TypeInfo type) { return globalComponents.contains(type.getApexName()); } /** * Things isManagedPackageInstalled will say 'false' to. */ public TestAccessEvaluator addManagedPackageNotInstalled(final Namespace namespace) { managedPackagesNotInstalled.add(namespace); return this; } public TestAccessEvaluator addReservedNamespace(final Namespace namespace) { reservedNamespaces.add(namespace); return this; } public TestAccessEvaluator addPermission(final PlaceholderOrgPerm orgPerm) { this.orgPerm.add(orgPerm); return this; } public TestAccessEvaluator setHasInternalSfdc(final boolean hasInternalSfdc) { this.hasInternalSfdc = hasInternalSfdc; return this; } public TestAccessEvaluator addValidPackageVersion(final Namespace namespace, final StructuredVersion version) { validPageVersions.put(namespace, version); return this; } public TestAccessEvaluator addSetupEntityVisibleToType( final SObjectTypeInfo type, final String typeName ) { final StandardTypeInfo typeInfo = StandardTypeInfoImpl.builder() .setApexName(typeName) .setBytecodeName(typeName) .buildResolved(); visibleSetupEntitiesToTypes.put(type, typeInfo); return this; } public TestAccessEvaluator setIsRunningTests(final boolean isRunningTests) { this.isRunningTests = isRunningTests; return this; } public TestAccessEvaluator setHasPrivateApi(final boolean hasPrivateApi) { this.hasPrivateApi = hasPrivateApi; return this; } public TestAccessEvaluator setIsTrustedApplication(final boolean isTrustedApplication) { this.isTrustedApplication = isTrustedApplication; return this; } public TestAccessEvaluator setHasLocalizedTranslation(final boolean hasLocalizedTranslation) { this.hasLocalizedTranslation = hasLocalizedTranslation; return this; } public TestAccessEvaluator setIsSfdc(final boolean isSfdc) { this.isSfdc = isSfdc; return this; } public TestAccessEvaluator setIsReallyRunningTests(final boolean isReallyRunningTests) { this.isReallyRunningTests = isReallyRunningTests; return this; } public TestAccessEvaluator setAccessibleSystemNamespace(final Namespace namespace) { accessibleSystemNamespaces.add(namespace); return this; } public TestAccessEvaluator setHasApexGenericType(final boolean hasApexGenericTypes) { this.hasApexGenericTypes = hasApexGenericTypes; return this; } public TestAccessEvaluator allowPermGuard(final Namespace namespace, final String permGuard) { allowedPermGuards.add(new AllowedPermGuard(namespace, permGuard)); return this; } /** * It appears that remote action is enabled by default in most orgs, at least test orgs. * So we will behave the same. */ public TestAccessEvaluator setHasRemoteActionPerm(final boolean hasRemoteActionPerm) { this.hasRemoteActionPerm = hasRemoteActionPerm; return this; } public TestAccessEvaluator setTypeWithConnectApiDeserializer(final String typeName) { typesWithConnectApiDeserializers.add(typeName); return this; } public void setGlobalComponent(final String globalComponent) { globalComponents.add(globalComponent); } private static class AllowedPermGuard { private final Namespace referencingNamespace; private final String permGuard; AllowedPermGuard(final Namespace namespace, final String permGuard) { referencingNamespace = namespace; this.permGuard = permGuard; } @Override public int hashCode() { return Objects.hash(referencingNamespace, permGuard); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final AllowedPermGuard other = (AllowedPermGuard) obj; return Objects.equals(referencingNamespace, other.referencingNamespace) && Objects.equals(permGuard, other.permGuard); } } @Override public boolean isSecondGenerationPackagingNamespace(Namespace namespace) { return false; } @Override public boolean useTestValueForAnonymousScriptLengthLimit() { return false; } @Override public boolean hasNamespaceGuardedAccess(Namespace namespace, String arg1) { return false; } @Override public boolean isNamespaceGuardNamespace(Namespace arg0) { return false; } @Override public boolean doesLightningWebComponentExist(String var1) { return false; } }
12,165
32.149864
189
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTField.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.member.Field; public final class ASTField extends AbstractApexNode<Field> { ASTField(Field field) { super(field); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public String getImage() { return getName(); } public String getType() { return node.getFieldInfo().getType().getApexName(); } public ASTModifierNode getModifiers() { return getFirstChildOfType(ASTModifierNode.class); } public String getName() { return node.getFieldInfo().getName(); } public String getValue() { if (node.getFieldInfo().getValue() != null) { return String.valueOf(node.getFieldInfo().getValue()); } return null; } }
1,018
21.152174
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/PostfixOperator.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.data.ast.PostfixOp; /** * Apex postfix operator */ public enum PostfixOperator { INCREMENT("++"), DECREMENT("--"); private final String symbol; PostfixOperator(String symbol) { this.symbol = symbol; } @Override public String toString() { return this.symbol; } /** * Returns a {@link PostfixOperator} corresponding to the given {@link PostfixOp}. */ public static PostfixOperator valueOf(PostfixOp op) { switch (op) { case INC: return INCREMENT; case DEC: return DECREMENT; default: throw new IllegalArgumentException("Invalid postfix operator " + op); } } }
862
20.04878
86
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTMethodBlockStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.MethodBlockStatement; public final class ASTMethodBlockStatement extends AbstractApexNode<MethodBlockStatement> { ASTMethodBlockStatement(MethodBlockStatement node) { super(node); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
535
24.52381
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTUserExceptionMethods.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.compilation.UserExceptionMethods; public final class ASTUserExceptionMethods extends AbstractApexNode<UserExceptionMethods> { ASTUserExceptionMethods(UserExceptionMethods userExceptionMethods) { super(userExceptionMethods); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
569
26.142857
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTCastExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.expression.CastExpression; public final class ASTCastExpression extends AbstractApexNode<CastExpression> { ASTCastExpression(CastExpression node) { super(node); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
506
23.142857
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTArrayStoreExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.expression.ArrayStoreExpression; public final class ASTArrayStoreExpression extends AbstractApexNode<ArrayStoreExpression> { ASTArrayStoreExpression(ArrayStoreExpression arrayStoreExpression) { super(arrayStoreExpression); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
568
26.095238
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTElseWhenBlock.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.ElseWhenBlock; public final class ASTElseWhenBlock extends AbstractApexNode<ElseWhenBlock> { ASTElseWhenBlock(ElseWhenBlock node) { super(node); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
502
20.869565
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/AbstractApexNode.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.ast.AstVisitor; import net.sourceforge.pmd.lang.ast.FileAnalysisException; import net.sourceforge.pmd.lang.ast.impl.AbstractNode; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextRegion; import apex.jorje.data.Location; import apex.jorje.data.Locations; import apex.jorje.semantic.ast.AstNode; import apex.jorje.semantic.exception.UnexpectedCodePathException; import apex.jorje.semantic.symbol.type.TypeInfo; abstract class AbstractApexNode<T extends AstNode> extends AbstractNode<AbstractApexNode<?>, ApexNode<?>> implements ApexNode<T> { protected final T node; private TextRegion region; protected AbstractApexNode(T node) { this.node = node; } // overridden to make them visible @Override protected void addChild(AbstractApexNode<?> child, int index) { super.addChild(child, index); } @Override protected void insertChild(AbstractApexNode<?> child, int index) { super.insertChild(child, index); } @Override @SuppressWarnings("unchecked") public final <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) { if (visitor instanceof ApexVisitor) { return this.acceptApexVisitor((ApexVisitor<? super P, ? extends R>) visitor, data); } return visitor.cannotVisit(this, data); } protected abstract <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data); @Override public @NonNull ASTApexFile getRoot() { return getParent().getRoot(); } @Override public @NonNull TextRegion getTextRegion() { if (region == null) { if (!hasRealLoc()) { AbstractApexNode<?> parent = (AbstractApexNode<?>) getParent(); if (parent == null) { throw new FileAnalysisException("Unable to determine location of " + this); } region = parent.getTextRegion(); } else { Location loc = node.getLoc(); region = TextRegion.fromBothOffsets(loc.getStartIndex(), loc.getEndIndex()); } } return region; } @Override public final String getXPathNodeName() { return this.getClass().getSimpleName().replaceFirst("^AST", ""); } /** * Note: in this routine, the node has not been added to its parents, * but its children have been populated (except comments). */ void closeNode(TextDocument positioner) { // do nothing } protected void setRegion(TextRegion region) { this.region = region; } @Deprecated @InternalApi @Override public T getNode() { return node; } @Override public boolean hasRealLoc() { try { Location loc = node.getLoc(); return loc != null && Locations.isReal(loc); } catch (UnexpectedCodePathException e) { return false; } catch (IndexOutOfBoundsException | NullPointerException e) { // bug in apex-jorje? happens on some ReferenceExpression nodes return false; } } private TypeInfo getDefiningTypeOrNull() { try { return node.getDefiningType(); } catch (UnsupportedOperationException e) { return null; } } @Override public String getDefiningType() { TypeInfo definingType = getDefiningTypeOrNull(); if (definingType != null) { return definingType.getApexName(); } return null; } @Override public String getNamespace() { TypeInfo definingType = getDefiningTypeOrNull(); if (definingType != null) { return definingType.getNamespace().toString(); } return null; } }
4,130
28.934783
130
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTFieldDeclaration.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.FieldDeclaration; public final class ASTFieldDeclaration extends AbstractApexNode<FieldDeclaration> { ASTFieldDeclaration(FieldDeclaration fieldDeclaration) { super(fieldDeclaration); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public String getImage() { return getName(); } public String getName() { if (node.getFieldInfo() != null) { return node.getFieldInfo().getName(); } ASTVariableExpression variable = getFirstChildOfType(ASTVariableExpression.class); if (variable != null) { return variable.getImage(); } return null; } }
951
24.72973
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTValueWhenBlock.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.ValueWhenBlock; public final class ASTValueWhenBlock extends AbstractApexNode<ValueWhenBlock> { ASTValueWhenBlock(ValueWhenBlock node) { super(node); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
507
21.086957
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTJavaMethodCallExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.expression.JavaMethodCallExpression; public final class ASTJavaMethodCallExpression extends AbstractApexNode<JavaMethodCallExpression> { ASTJavaMethodCallExpression(JavaMethodCallExpression javaMethodCallExpression) { super(javaMethodCallExpression); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
596
27.428571
99
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTConstructorPreamble.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.compilation.ConstructorPreamble; public final class ASTConstructorPreamble extends AbstractApexNode<ConstructorPreamble> { ASTConstructorPreamble(ConstructorPreamble node) { super(node); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
532
24.380952
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTNewObjectExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.expression.NewObjectExpression; public final class ASTNewObjectExpression extends AbstractApexNode<NewObjectExpression> { ASTNewObjectExpression(NewObjectExpression newObjectExpression) { super(newObjectExpression); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public String getType() { return String.valueOf(node.getTypeRef()); } }
648
24.96
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTFormalComment.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import net.sourceforge.pmd.lang.apex.ast.ASTFormalComment.AstComment; import net.sourceforge.pmd.lang.document.Chars; import net.sourceforge.pmd.lang.document.TextRegion; import apex.jorje.data.Location; import apex.jorje.data.Locations; import apex.jorje.semantic.ast.AstNode; import apex.jorje.semantic.ast.context.Emitter; import apex.jorje.semantic.ast.visitor.AstVisitor; import apex.jorje.semantic.ast.visitor.Scope; import apex.jorje.semantic.ast.visitor.ValidationScope; import apex.jorje.semantic.symbol.resolver.SymbolResolver; import apex.jorje.semantic.symbol.type.TypeInfo; import apex.jorje.semantic.symbol.type.TypeInfos; public final class ASTFormalComment extends AbstractApexNode<AstComment> { private final Chars image; ASTFormalComment(TextRegion token, Chars image) { super(new AstComment(token)); this.image = image; } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } @Override public String getImage() { return image.toString(); } public Chars getToken() { return image; } static final class AstComment implements AstNode { private final Location loc; private AstComment(TextRegion region) { this.loc = Locations.index(region.getStartOffset(), region.getLength()); } @Override public Location getLoc() { return loc; } @Override public <T extends Scope> void traverse(AstVisitor<T> astVisitor, T t) { // do nothing } @Override public void validate(SymbolResolver symbolResolver, ValidationScope validationScope) { // do nothing } @Override public void emit(Emitter emitter) { // do nothing } @Override public TypeInfo getDefiningType() { return TypeInfos.VOID; } } }
2,137
24.759036
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTBridgeMethodCreator.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.member.bridge.BridgeMethodCreator; public final class ASTBridgeMethodCreator extends AbstractApexNode<BridgeMethodCreator> { ASTBridgeMethodCreator(BridgeMethodCreator bridgeMethodCreator) { super(bridgeMethodCreator); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
564
25.904762
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import java.util.Collections; import java.util.List; import net.sourceforge.pmd.lang.document.TextDocument; import apex.jorje.semantic.ast.compilation.Compilation; import apex.jorje.semantic.compiler.ApexCompiler; import apex.jorje.semantic.compiler.CompilationInput; import apex.jorje.semantic.compiler.CompilerStage; import apex.jorje.semantic.compiler.SourceFile; import apex.jorje.semantic.compiler.sfdc.AccessEvaluator; import apex.jorje.semantic.compiler.sfdc.NoopCompilerProgressCallback; import apex.jorje.semantic.compiler.sfdc.QueryValidator; import apex.jorje.semantic.compiler.sfdc.SymbolProvider; import apex.jorje.services.exception.CompilationException; import apex.jorje.services.exception.ParseException; /** * Central point for interfacing with the compiler. Based on <a href= * "https://github.com/forcedotcom/idecore/blob/master/com.salesforce.ide.apex.core/src/com/salesforce/ide/apex/internal/core/CompilerService.java" * > CompilerService</a> but with Eclipse dependencies removed. * * @author nchen * */ class CompilerService { public static final CompilerService INSTANCE = new CompilerService(); private final SymbolProvider symbolProvider; private final AccessEvaluator accessEvaluator; private final QueryValidator queryValidator; /** * Configure a compiler with the default configurations: */ CompilerService() { this(EmptySymbolProvider.get(), new TestAccessEvaluator(), new TestQueryValidators.Noop()); } /** * Configure a compiler with the following configurations: * * @param symbolProvider * A way to retrieve symbols, where symbols are names of types. * @param accessEvaluator * A way to check for accesses to certain fields in types. * @param queryValidator * A way to validate your queries. */ CompilerService(SymbolProvider symbolProvider, AccessEvaluator accessEvaluator, QueryValidator queryValidator) { this.symbolProvider = symbolProvider; this.accessEvaluator = accessEvaluator; this.queryValidator = queryValidator; } /** @throws ParseException If the code is unparsable */ public Compilation parseApex(TextDocument document) { SourceFile sourceFile = SourceFile.builder() .setBody(document.getText().toString()) .setKnownName(document.getFileId().getUriString()) .build(); ApexCompiler compiler = ApexCompiler.builder().setInput(createCompilationInput(Collections.singletonList(sourceFile))).build(); compiler.compile(CompilerStage.POST_TYPE_RESOLVE); throwParseErrorIfAny(compiler); return compiler.getCodeUnits().get(0).getNode(); } private void throwParseErrorIfAny(ApexCompiler compiler) { // this ignores semantic errors ParseException parseError = null; for (CompilationException error : compiler.getErrors()) { if (error instanceof ParseException) { if (parseError == null) { parseError = (ParseException) error; } else { parseError.addSuppressed(error); } } } if (parseError != null) { throw parseError; } } private CompilationInput createCompilationInput(List<SourceFile> sourceFiles) { return new CompilationInput(sourceFiles, symbolProvider, accessEvaluator, queryValidator, null, NoopCompilerProgressCallback.get()); } }
3,797
38.154639
147
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTExpressionStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import apex.jorje.semantic.ast.statement.ExpressionStatement; public final class ASTExpressionStatement extends AbstractApexNode<ExpressionStatement> { ASTExpressionStatement(ExpressionStatement expressionStatement) { super(expressionStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } }
561
24.545455
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTMethodCallExpression.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.document.TextRegion; import apex.jorje.data.Identifier; import apex.jorje.semantic.ast.expression.MethodCallExpression; public final class ASTMethodCallExpression extends AbstractApexNode<MethodCallExpression> { ASTMethodCallExpression(MethodCallExpression methodCallExpression) { super(methodCallExpression); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public String getMethodName() { return node.getMethodName(); } public String getFullMethodName() { final String methodName = getMethodName(); StringBuilder typeName = new StringBuilder(); for (Identifier identifier : node.getReferenceContext().getNames()) { typeName.append(identifier.getValue()).append('.'); } return typeName.toString() + methodName; } public int getInputParametersSize() { return node.getInputParameters().size(); } @Override public @NonNull TextRegion getTextRegion() { int fullLength = getFullMethodName().length(); int nameLength = getMethodName().length(); TextRegion base = super.getTextRegion(); if (fullLength > nameLength) { base = base.growLeft(fullLength - nameLength); } return base; } }
1,602
28.685185
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTBlockStatement.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import java.util.Objects; import net.sourceforge.pmd.lang.document.TextDocument; import apex.jorje.semantic.ast.statement.BlockStatement; public final class ASTBlockStatement extends AbstractApexNode<BlockStatement> { private boolean curlyBrace; ASTBlockStatement(BlockStatement blockStatement) { super(blockStatement); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public boolean hasCurlyBrace() { return curlyBrace; } @Override void closeNode(TextDocument document) { super.closeNode(document); if (!hasRealLoc()) { return; } // check, whether the this block statement really begins with a curly brace // unfortunately, for-loop and if-statements always contain a block statement, // regardless whether curly braces where present or not. curlyBrace = document.getText().startsWith('{', node.getLoc().getStartIndex()); } @Override public boolean hasRealLoc() { return super.hasRealLoc() && !Objects.equals(node.getLoc(), getParent().getNode().getLoc()); } }
1,351
27.166667
100
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTUserInterface.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.ast; import java.util.stream.Collectors; import apex.jorje.data.Identifier; import apex.jorje.data.ast.TypeRef; import apex.jorje.semantic.ast.compilation.UserInterface; public final class ASTUserInterface extends BaseApexClass<UserInterface> implements ASTUserClassOrInterface<UserInterface> { ASTUserInterface(UserInterface userInterface) { super(userInterface); } @Override protected <P, R> R acceptApexVisitor(ApexVisitor<? super P, ? extends R> visitor, P data) { return visitor.visit(this, data); } public String getSuperInterfaceName() { return node.getDefiningType().getCodeUnitDetails().getInterfaceTypeRefs().stream().map(TypeRef::getNames) .map(it -> it.stream().map(Identifier::getValue).collect(Collectors.joining("."))) .findFirst().orElse(""); } }
980
30.645161
124
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/metrics/ApexMetrics.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.metrics; import java.util.function.Function; import java.util.function.Predicate; import org.apache.commons.lang3.mutable.MutableInt; import net.sourceforge.pmd.internal.util.PredicateUtil; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserClassOrInterface; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.metrics.internal.CognitiveComplexityVisitor; import net.sourceforge.pmd.lang.apex.metrics.internal.CognitiveComplexityVisitor.State; import net.sourceforge.pmd.lang.apex.metrics.internal.StandardCycloVisitor; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.metrics.Metric; import net.sourceforge.pmd.lang.metrics.MetricOptions; import net.sourceforge.pmd.lang.metrics.MetricsUtil; /** * Built-in Apex metrics. See {@link Metric} and {@link MetricsUtil} * for usage doc. */ public final class ApexMetrics { @SuppressWarnings({"unchecked", "rawtypes"}) private static final Class<ApexNode<?>> GENERIC_APEX_NODE_CLASS = (Class) ApexNode.class; // this is a Class<ApexNode>, the raw type /** * Number of independent paths through a block of code. * Formally, given that the control flow graph of the block has n * vertices, e edges and p connected components, the cyclomatic complexity * of the block is given by {@code CYCLO = e - n + 2p}. In practice * it can be calculated by counting control flow statements following * the standard rules given below. * * * <p>The standard version of the metric complies with McCabe’s original definition: * <ul> * <li>Methods have a base complexity of 1. * <li>+1 for every control flow statement (if, catch, throw, do, while, for, break, continue) and conditional expression (?:). * <li>else, finally and default do not count; * <li>+1 for every boolean operator ({@code &&}, {@code ||}) in * the guard condition of a control flow statement. That’s because * Apex has short-circuit evaluation semantics for boolean operators, * which makes every boolean operator kind of a control flow statement in itself. * </ul> * * <p>Code example: * <pre>{@code * class Foo { * void baseCyclo() { // Cyclo = 1 * highCyclo(); * } * * void highCyclo() { // Cyclo = 10 * int x = 0, y = 2; * boolean a = false, b = true; * * if (a && (y == 1 ? b : true)) { // +3 * if (y == x) { // +1 * while (true) { // +1 * if (x++ < 20) { // +1 * break; // +1 * } * } * } else if (y == t && !d) { // +2 * x = a ? y : x; // +1 * } else { * x = 2; * } * } * } * } * }</pre> */ public static final Metric<ApexNode<?>, Integer> CYCLO = Metric.of(ApexMetrics::computeCyclo, isRegularApexNode(), "Cyclomatic Complexity", "Cyclo"); /** * See the corresponding {@link net.sourceforge.pmd.lang.java.metrics.JavaMetrics.COGNITIVE_COMPLEXITY Cognitive Complexity} * for a general description. * <p> * The rule {@link net.sourceforge.pmd.lang.apex.rule.design.CognitiveComplexityRule CognitiveComplexity} * by default reports methods with a complexity of 15 or more * and classes the have a total complexity (sum of all methods) of 50 or more. * These reported methods should be broken down into less complex components. */ public static final Metric<ApexNode<?>, Integer> COGNITIVE_COMPLEXITY = Metric.of(ApexMetrics::computeCognitiveComp, isRegularApexNode(), "Cognitive Complexity"); /** * Sum of the statistical complexity of the operations in the class. * We use CYCLO to quantify the complexity of an operation. * */ public static final Metric<ASTUserClassOrInterface<?>, Integer> WEIGHED_METHOD_COUNT = Metric.of(ApexMetrics::computeWmc, filterMapNode(ASTUserClass.class, PredicateUtil.always()), "Weighed Method Count", "WMC"); private ApexMetrics() { // utility class } private static Function<Node, ApexNode<?>> isRegularApexNode() { return filterMapNode(GENERIC_APEX_NODE_CLASS, n -> !(n instanceof ASTMethod && ((ASTMethod) n).isSynthetic())); } private static <T extends Node> Function<Node, T> filterMapNode(Class<? extends T> klass, Predicate<? super T> pred) { return n -> n.asStream().filterIs(klass).filter(pred).first(); } private static int computeCyclo(ApexNode<?> node, MetricOptions ignored) { MutableInt result = new MutableInt(1); node.acceptVisitor(new StandardCycloVisitor(), result); return result.getValue(); } private static int computeCognitiveComp(ApexNode<?> node, MetricOptions ignored) { State state = new State(); node.acceptVisitor(CognitiveComplexityVisitor.INSTANCE, state); return state.getComplexity(); } private static int computeWmc(ASTUserClassOrInterface<?> node, MetricOptions options) { return (int) MetricsUtil.computeStatistics(CYCLO, node.getMethods(), options).getSum(); } }
5,615
37.731034
132
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/metrics/internal/StandardCycloVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.metrics.internal; import org.apache.commons.lang3.mutable.MutableInt; import net.sourceforge.pmd.lang.apex.ast.ASTCatchBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDoLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForEachStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTIfBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTStandardCondition; import net.sourceforge.pmd.lang.apex.ast.ASTTernaryExpression; import net.sourceforge.pmd.lang.apex.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.apex.ast.ASTWhileLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ApexVisitorBase; /** * @author Clément Fournier */ public class StandardCycloVisitor extends ApexVisitorBase<MutableInt, Void> { @Override public Void visit(ASTIfBlockStatement node, MutableInt data) { data.add(1 + ApexMetricsHelper.booleanExpressionComplexity(node.getFirstDescendantOfType(ASTStandardCondition.class))); return super.visit(node, data); } @Override public Void visit(ASTCatchBlockStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTForLoopStatement node, MutableInt data) { data.add( 1 + ApexMetricsHelper.booleanExpressionComplexity(node.getFirstDescendantOfType(ASTStandardCondition.class))); return super.visit(node, data); } @Override public Void visit(ASTForEachStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTThrowStatement node, MutableInt data) { data.increment(); return super.visit(node, data); } @Override public Void visit(ASTWhileLoopStatement node, MutableInt data) { data.add( 1 + ApexMetricsHelper.booleanExpressionComplexity(node.getFirstDescendantOfType(ASTStandardCondition.class))); return super.visit(node, data); } @Override public Void visit(ASTDoLoopStatement node, MutableInt data) { data.add( 1 + ApexMetricsHelper.booleanExpressionComplexity(node.getFirstDescendantOfType(ASTStandardCondition.class))); return super.visit(node, data); } @Override public Void visit(ASTTernaryExpression node, MutableInt data) { data.add( 1 + ApexMetricsHelper.booleanExpressionComplexity(node.getFirstDescendantOfType(ASTStandardCondition.class))); return super.visit(node, data); } }
2,756
31.435294
127
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/metrics/internal/ApexMetricsHelper.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.metrics.internal; import java.util.HashSet; import java.util.Set; import net.sourceforge.pmd.lang.apex.ast.ASTBooleanExpression; import net.sourceforge.pmd.lang.apex.ast.ASTStandardCondition; import net.sourceforge.pmd.lang.apex.ast.BooleanOperator; /** * */ public final class ApexMetricsHelper { private ApexMetricsHelper() { // utility class } /** * Computes the number of control flow paths through that expression, which is the number of {@code ||} and {@code * &&} operators. Used both by Npath and Cyclo. * * @param expression Boolean expression * * @return The complexity of the expression */ static int booleanExpressionComplexity(ASTStandardCondition expression) { Set<ASTBooleanExpression> subs = new HashSet<>(expression.findDescendantsOfType(ASTBooleanExpression.class)); int complexity = 0; for (ASTBooleanExpression sub : subs) { BooleanOperator op = sub.getOp(); if (op == BooleanOperator.LOGICAL_AND || op == BooleanOperator.LOGICAL_OR) { complexity++; } } return complexity; } }
1,287
27.622222
118
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/metrics/internal/CognitiveComplexityVisitor.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.metrics.internal; import net.sourceforge.pmd.lang.apex.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTBooleanExpression; import net.sourceforge.pmd.lang.apex.ast.ASTCatchBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDoLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForEachStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTIfElseBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTPrefixExpression; import net.sourceforge.pmd.lang.apex.ast.ASTSwitchStatement; import net.sourceforge.pmd.lang.apex.ast.ASTTernaryExpression; import net.sourceforge.pmd.lang.apex.ast.ASTWhileLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.ast.ApexVisitorBase; import net.sourceforge.pmd.lang.apex.ast.BooleanOperator; import net.sourceforge.pmd.lang.apex.ast.PrefixOperator; import net.sourceforge.pmd.lang.apex.metrics.internal.CognitiveComplexityVisitor.State; /** * @author Gwilym Kuiper */ public class CognitiveComplexityVisitor extends ApexVisitorBase<State, Void> { public static final CognitiveComplexityVisitor INSTANCE = new CognitiveComplexityVisitor(); public static class State { private int complexity = 0; private int nestingLevel = 0; private BooleanOperator currentBooleanOperation = null; private String methodName = null; public int getComplexity() { return complexity; } void hybridComplexity() { complexity++; nestingLevel++; } void structureComplexity() { complexity++; complexity += nestingLevel; nestingLevel++; } void fundamentalComplexity() { complexity++; } void booleanOperation(BooleanOperator op) { if (currentBooleanOperation != op) { if (op != null) { fundamentalComplexity(); } currentBooleanOperation = op; } } void increaseNestingLevel() { nestingLevel++; } void decreaseNestingLevel() { nestingLevel--; } void methodCall(String methodCalledName) { if (methodCalledName.equals(methodName)) { structureComplexity(); } } void setMethodName(String name) { methodName = name; } } @Override public Void visit(ASTIfElseBlockStatement node, State state) { boolean hasElseStatement = node.hasElseStatement(); for (ApexNode<?> child : node.children()) { // If we don't have an else statement, we get an empty block statement which we shouldn't count if (!hasElseStatement && child instanceof ASTBlockStatement) { break; } if (child.getIndexInParent() == 0) { // the first IfBlock is the first "if" state.structureComplexity(); } else { // any other IfBlocks are "else if" state.hybridComplexity(); } child.acceptVisitor(this, state); state.decreaseNestingLevel(); } return null; } @Override public Void visit(ASTForLoopStatement node, State state) { state.structureComplexity(); super.visit(node, state); state.decreaseNestingLevel(); return null; } @Override public Void visit(ASTForEachStatement node, State state) { state.structureComplexity(); super.visit(node, state); state.decreaseNestingLevel(); return null; } @Override public Void visit(ASTWhileLoopStatement node, State state) { state.structureComplexity(); super.visit(node, state); state.decreaseNestingLevel(); return null; } @Override public Void visit(ASTCatchBlockStatement node, State state) { state.structureComplexity(); super.visit(node, state); state.decreaseNestingLevel(); return null; } @Override public Void visit(ASTDoLoopStatement node, State state) { state.structureComplexity(); super.visit(node, state); state.decreaseNestingLevel(); return null; } @Override public Void visit(ASTTernaryExpression node, State state) { state.structureComplexity(); super.visit(node, state); state.decreaseNestingLevel(); return null; } @Override public Void visit(ASTBooleanExpression node, State state) { BooleanOperator op = node.getOp(); if (op == BooleanOperator.LOGICAL_AND || op == BooleanOperator.LOGICAL_OR) { state.booleanOperation(op); } return super.visit(node, state); } @Override public Void visit(ASTPrefixExpression node, State state) { PrefixOperator op = node.getOp(); if (op == PrefixOperator.LOGICAL_NOT) { state.booleanOperation(null); } return super.visit(node, state); } @Override public Void visit(ASTBlockStatement node, State state) { for (ApexNode<?> child : node.children()) { // This needs to happen because the current 'run' of boolean operations is terminated // once we finish a statement. state.booleanOperation(null); child.acceptVisitor(this, state); } return null; } @Override public Void visit(ASTMethod node, State state) { state.setMethodName(node.getCanonicalName()); return super.visit(node, state); } @Override public Void visit(ASTMethodCallExpression node, State state) { state.methodCall(node.getMethodName()); return super.visit(node, state); } @Override public Void visit(ASTSwitchStatement node, State state) { state.structureComplexity(); super.visit(node, state); state.decreaseNestingLevel(); return null; } }
6,419
27.533333
107
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/AbstractApexUnitTestRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ApexNode; /** * Do special checks for apex unit test classes and methods * * @author a.subramanian * @deprecated Internal API */ @Deprecated @InternalApi public abstract class AbstractApexUnitTestRule extends AbstractApexRule { /** * Don't bother visiting this class if it's not a class with @isTest and * newer than API v24 (V176 internal). */ @Override public Object visit(final ASTUserClass node, final Object data) { if (!isTestMethodOrClass(node)) { return data; } return super.visit(node, data); } protected boolean isTestMethodOrClass(final ApexNode<?> node) { final ASTModifierNode modifierNode = node.getFirstChildOfType(ASTModifierNode.class); return modifierNode != null && modifierNode.isTest(); } }
1,149
28.487179
93
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/AbstractApexRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.apex.ast.ApexParserVisitor; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.rule.AbstractRule; public abstract class AbstractApexRule extends AbstractRule implements ApexParserVisitor { @Override public void apply(Node target, RuleContext ctx) { target.acceptVisitor(this, ctx); } }
544
26.25
79
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/Helper.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.List; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTNewKeyValueObjectExpression; import net.sourceforge.pmd.lang.apex.ast.ASTParameter; import net.sourceforge.pmd.lang.apex.ast.ASTReferenceExpression; import net.sourceforge.pmd.lang.apex.ast.ASTSoqlExpression; import net.sourceforge.pmd.lang.apex.ast.ASTSoslExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import apex.jorje.semantic.ast.member.Parameter; /** * Helper methods * * @author sergey.gorbaty * * @deprecated Use {@link net.sourceforge.pmd.lang.apex.rule.internal.Helper} instead. */ @Deprecated public final class Helper { static final String ANY_METHOD = "*"; private Helper() { throw new AssertionError("Can't instantiate helper classes"); } static boolean isTestMethodOrClass(final ApexNode<?> node) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.isTestMethodOrClass(node); } static boolean foundAnySOQLorSOSL(final ApexNode<?> node) { final List<ASTSoqlExpression> dmlSoqlExpression = node.findDescendantsOfType(ASTSoqlExpression.class); final List<ASTSoslExpression> dmlSoslExpression = node.findDescendantsOfType(ASTSoslExpression.class); return !dmlSoqlExpression.isEmpty() || !dmlSoslExpression.isEmpty(); } /** * Finds DML operations in a given node descendants' path * * @param node * * @return true if found DML operations in node descendants */ static boolean foundAnyDML(final ApexNode<?> node) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.foundAnyDML(node); } static boolean isMethodName(final ASTMethodCallExpression methodNode, final String className, final String methodName) { final ASTReferenceExpression reference = methodNode.getFirstChildOfType(ASTReferenceExpression.class); return reference != null && reference.getNames().size() == 1 && reference.getNames().get(0).equalsIgnoreCase(className) && (ANY_METHOD.equals(methodName) || isMethodName(methodNode, methodName)); } static boolean isMethodName(final ASTMethodCallExpression m, final String methodName) { return m.getMethodName().equalsIgnoreCase(methodName); } static boolean isMethodCallChain(final ASTMethodCallExpression methodNode, final String... methodNames) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.isMethodCallChain(methodNode, methodNames); } static String getFQVariableName(final ASTVariableExpression variable) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.getFQVariableName(variable); } static String getFQVariableName(final ASTVariableDeclaration variable) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.getFQVariableName(variable); } static String getFQVariableName(final ASTField variable) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.getFQVariableName(variable); } static String getVariableType(final ASTField variable) { StringBuilder sb = new StringBuilder().append(variable.getDefiningType()).append(":") .append(variable.getName()); return sb.toString(); } static String getFQVariableName(final ASTFieldDeclaration variable) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.getFQVariableName(variable); } static String getFQVariableName(final ASTNewKeyValueObjectExpression variable) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.getFQVariableName(variable); } static boolean isSystemLevelClass(ASTUserClass node) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.isSystemLevelClass(node); } @Deprecated public static String getFQVariableName(Parameter p) { StringBuilder sb = new StringBuilder(); sb.append(p.getDefiningType()).append(":").append(p.getName().getValue()); return sb.toString(); } static String getFQVariableName(ASTParameter p) { return net.sourceforge.pmd.lang.apex.rule.internal.Helper.getFQVariableName(p); } }
4,687
38.066667
110
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexCRUDViolationRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import static net.sourceforge.pmd.properties.PropertyFactory.intProperty; import static net.sourceforge.pmd.properties.PropertyFactory.stringProperty; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.apex.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.apex.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlDeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlInsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlMergeStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUndeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpdateStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclarationStatements; import net.sourceforge.pmd.lang.apex.ast.ASTForEachStatement; import net.sourceforge.pmd.lang.apex.ast.ASTIfElseBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTNewKeyValueObjectExpression; import net.sourceforge.pmd.lang.apex.ast.ASTNewListInitExpression; import net.sourceforge.pmd.lang.apex.ast.ASTNewListLiteralExpression; import net.sourceforge.pmd.lang.apex.ast.ASTNewObjectExpression; import net.sourceforge.pmd.lang.apex.ast.ASTParameter; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.apex.ast.ASTReferenceExpression; import net.sourceforge.pmd.lang.apex.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.apex.ast.ASTSoqlExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.properties.PropertyDescriptor; import com.google.common.base.Objects; import com.google.common.collect.HashMultimap; /** * Finding missed CRUD checks for SOQL and DML operations. * * @author sergey.gorbaty * */ public class ApexCRUDViolationRule extends AbstractApexRule { private static final Pattern SELECT_FROM_PATTERN = Pattern.compile("[\\S|\\s]+?FROM[\\s]+?(\\w+)", Pattern.CASE_INSENSITIVE); private static final String IS_CREATEABLE = "isCreateable"; private static final String IS_DELETABLE = "isDeletable"; private static final String IS_UNDELETABLE = "isUndeletable"; private static final String IS_UPDATEABLE = "isUpdateable"; private static final String IS_MERGEABLE = "isMergeable"; private static final String IS_ACCESSIBLE = "isAccessible"; private static final String ANY = "ANY"; private static final String S_OBJECT_TYPE = "sObjectType"; private static final String GET_DESCRIBE = "getDescribe"; private static final String ACCESS_LEVEL = "AccessLevel"; // ESAPI.accessController().isAuthorizedToView(Lead.sObject, fields) private static final String[] ESAPI_ISAUTHORIZED_TO_VIEW = new String[] { "ESAPI", "accessController", "isAuthorizedToView", }; private static final String[] ESAPI_ISAUTHORIZED_TO_CREATE = new String[] { "ESAPI", "accessController", "isAuthorizedToCreate", }; private static final String[] ESAPI_ISAUTHORIZED_TO_UPDATE = new String[] { "ESAPI", "accessController", "isAuthorizedToUpdate", }; private static final String[] ESAPI_ISAUTHORIZED_TO_DELETE = new String[] { "ESAPI", "accessController", "isAuthorizedToDelete", }; // ESAPI doesn't provide support for undelete or merge private static final String[] RESERVED_KEYS_FLS = new String[] { "Schema", S_OBJECT_TYPE, }; private static final Pattern WITH_SECURITY_ENFORCED = Pattern.compile("(?is).*[^']\\s*WITH\\s+SECURITY_ENFORCED\\s*[^']*"); //Added For USER MODE private static final Pattern WITH_USER_MODE = Pattern.compile("(?is).*[^']\\s*WITH\\s+USER_MODE\\s*[^']*"); //Added For SYSTEM MODE private static final Pattern WITH_SYSTEM_MODE = Pattern.compile("(?is).*[^']\\s*WITH\\s+SYSTEM_MODE\\s*[^']*"); // <operation>AuthMethodPattern config properties; these are string properties instead of regex properties to help // ensure that the compiled patterns are case-insensitive vs. requiring the pattern author to use "(?i)" private static final PropertyDescriptor<String> CREATE_AUTH_METHOD_PATTERN_DESCRIPTOR = authMethodPatternProperty("create"); private static final PropertyDescriptor<String> READ_AUTH_METHOD_PATTERN_DESCRIPTOR = authMethodPatternProperty("read"); private static final PropertyDescriptor<String> UPDATE_AUTH_METHOD_PATTERN_DESCRIPTOR = authMethodPatternProperty("update"); private static final PropertyDescriptor<String> DELETE_AUTH_METHOD_PATTERN_DESCRIPTOR = authMethodPatternProperty("delete"); private static final PropertyDescriptor<String> UNDELETE_AUTH_METHOD_PATTERN_DESCRIPTOR = authMethodPatternProperty("undelete"); private static final PropertyDescriptor<String> MERGE_AUTH_METHOD_PATTERN_DESCRIPTOR = authMethodPatternProperty("merge"); // <operation>AuthMethodTypeParamIndex config properties private static final PropertyDescriptor<Integer> CREATE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR = authMethodTypeParamIndexProperty("create"); private static final PropertyDescriptor<Integer> READ_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR = authMethodTypeParamIndexProperty("read"); private static final PropertyDescriptor<Integer> UPDATE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR = authMethodTypeParamIndexProperty("update"); private static final PropertyDescriptor<Integer> DELETE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR = authMethodTypeParamIndexProperty("delete"); private static final PropertyDescriptor<Integer> UNDELETE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR = authMethodTypeParamIndexProperty("undelete"); private static final PropertyDescriptor<Integer> MERGE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR = authMethodTypeParamIndexProperty("merge"); // Auth method config property correlation information private static final Map<PropertyDescriptor<String>, PropertyDescriptor<Integer>> AUTH_METHOD_TO_TYPE_PARAM_INDEX_MAP = new HashMap<PropertyDescriptor<String>, PropertyDescriptor<Integer>>() { { put(CREATE_AUTH_METHOD_PATTERN_DESCRIPTOR, CREATE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR); put(READ_AUTH_METHOD_PATTERN_DESCRIPTOR, READ_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR); put(UPDATE_AUTH_METHOD_PATTERN_DESCRIPTOR, UPDATE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR); put(DELETE_AUTH_METHOD_PATTERN_DESCRIPTOR, DELETE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR); put(UNDELETE_AUTH_METHOD_PATTERN_DESCRIPTOR, UNDELETE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR); put(MERGE_AUTH_METHOD_PATTERN_DESCRIPTOR, MERGE_AUTH_METHOD_TYPE_PARAM_INDEX_DESCRIPTOR); } }; private static final Map<PropertyDescriptor<String>, String> AUTH_METHOD_TO_DML_OPERATION_MAP = new HashMap<PropertyDescriptor<String>, String>() { { put(CREATE_AUTH_METHOD_PATTERN_DESCRIPTOR, IS_CREATEABLE); put(READ_AUTH_METHOD_PATTERN_DESCRIPTOR, IS_ACCESSIBLE); put(UPDATE_AUTH_METHOD_PATTERN_DESCRIPTOR, IS_UPDATEABLE); put(DELETE_AUTH_METHOD_PATTERN_DESCRIPTOR, IS_DELETABLE); put(UNDELETE_AUTH_METHOD_PATTERN_DESCRIPTOR, IS_UNDELETABLE); put(MERGE_AUTH_METHOD_PATTERN_DESCRIPTOR, IS_MERGEABLE); } }; // Compiled pattern cache for configured method name patterns private final Map<String, Pattern> compiledAuthMethodPatternCache = new HashMap<>(); private Map<String, String> varToTypeMapping; private HashMultimap<String, String> typeToDMLOperationMapping; private Map<String, String> checkedTypeToDMLOperationViaESAPI; private HashMultimap<String, String> checkedTypeToDMLOperationsViaAuthPattern; private Map<String, ASTMethod> classMethods; private String className; public ApexCRUDViolationRule() { // Register auth method config properties for (Map.Entry<PropertyDescriptor<String>, PropertyDescriptor<Integer>> entry : AUTH_METHOD_TO_TYPE_PARAM_INDEX_MAP.entrySet()) { PropertyDescriptor<String> authMethodPatternDescriptor = entry.getKey(); PropertyDescriptor<Integer> authMethodTypeParamIndexDescriptor = entry.getValue(); definePropertyDescriptor(authMethodPatternDescriptor); definePropertyDescriptor(authMethodTypeParamIndexDescriptor); } } @Override public void start(RuleContext ctx) { // At the start of each rule execution, these member variables need to be fresh. So they're initialized in the // .start() method instead of the constructor, since .start() is called before every execution. varToTypeMapping = new HashMap<>(); typeToDMLOperationMapping = HashMultimap.create(); checkedTypeToDMLOperationViaESAPI = new HashMap<>(); checkedTypeToDMLOperationsViaAuthPattern = HashMultimap.create(); classMethods = new WeakHashMap<>(); className = null; super.start(ctx); } @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node) || Helper.isSystemLevelClass(node)) { return data; // stops all the rules } className = node.getImage(); for (ASTMethod n : node.findDescendantsOfType(ASTMethod.class)) { StringBuilder sb = new StringBuilder().append(n.getDefiningType()).append(":") .append(n.getCanonicalName()).append(":") .append(n.getArity()); classMethods.put(sb.toString(), n); } return super.visit(node, data); } @Override public Object visit(ASTMethodCallExpression node, Object data) { if (Helper.isAnyDatabaseMethodCall(node)) { if (hasAccessLevelArgument(node)) { return data; } switch (node.getMethodName().toLowerCase(Locale.ROOT)) { case "insert": case "insertasync": case "insertimmediate": checkForCRUD(node, data, IS_CREATEABLE); break; case "update": case "updateasync": case "updateimmediate": checkForCRUD(node, data, IS_UPDATEABLE); break; case "delete": case "deleteasync": case "deleteimmediate": checkForCRUD(node, data, IS_DELETABLE); break; case "undelete": checkForCRUD(node, data, IS_UNDELETABLE); break; case "upsert": checkForCRUD(node, data, IS_CREATEABLE); checkForCRUD(node, data, IS_UPDATEABLE); break; case "merge": checkForCRUD(node, data, IS_MERGEABLE); break; default: break; } } else { collectCRUDMethodLevelChecks(node); } return data; } /** * Checks whether any parameter is of type "AccessLevel". It doesn't check * whether it is "USER_MODE" or "SYSTEM_MODE", because this rule doesn't * report a violation for neither. * * @param node the Database DML method call */ private boolean hasAccessLevelArgument(ASTMethodCallExpression node) { for (int i = 0; i < node.getNumChildren(); i++) { ApexNode<?> argument = node.getChild(i); if (argument instanceof ASTVariableExpression && argument.getFirstChildOfType(ASTReferenceExpression.class) != null) { ASTReferenceExpression ref = argument.getFirstChildOfType(ASTReferenceExpression.class); List<String> names = ref.getNames(); if (names.size() == 1 && ACCESS_LEVEL.equalsIgnoreCase(names.get(0))) { return true; } else if (names.size() == 2 && "System".equalsIgnoreCase(names.get(0)) && ACCESS_LEVEL.equalsIgnoreCase(names.get(1))) { return true; } } } return false; } @Override public Object visit(ASTDmlInsertStatement node, Object data) { checkForCRUD(node, data, IS_CREATEABLE); return data; } @Override public Object visit(ASTDmlDeleteStatement node, Object data) { checkForCRUD(node, data, IS_DELETABLE); return data; } @Override public Object visit(ASTDmlUndeleteStatement node, Object data) { checkForCRUD(node, data, IS_UNDELETABLE); return data; } @Override public Object visit(ASTDmlUpdateStatement node, Object data) { checkForCRUD(node, data, IS_UPDATEABLE); return data; } @Override public Object visit(ASTDmlUpsertStatement node, Object data) { checkForCRUD(node, data, IS_CREATEABLE); checkForCRUD(node, data, IS_UPDATEABLE); return data; } @Override public Object visit(ASTDmlMergeStatement node, Object data) { checkForCRUD(node, data, IS_MERGEABLE); return data; } @Override public Object visit(final ASTAssignmentExpression node, Object data) { final ASTSoqlExpression soql = node.getFirstChildOfType(ASTSoqlExpression.class); if (soql != null) { checkForAccessibility(soql, data); } return data; } @Override public Object visit(final ASTVariableDeclaration node, Object data) { String type = node.getType(); addVariableToMapping(Helper.getFQVariableName(node), type); final ASTSoqlExpression soql = node.getFirstChildOfType(ASTSoqlExpression.class); if (soql != null) { checkForAccessibility(soql, data); } return data; } @Override public Object visit(ASTParameter node, Object data) { String type = node.getType(); addVariableToMapping(Helper.getFQVariableName(node), type); return data; } @Override public Object visit(final ASTFieldDeclaration node, Object data) { ASTFieldDeclarationStatements field = node.getFirstParentOfType(ASTFieldDeclarationStatements.class); if (field != null) { String namesString = field.getTypeName(); switch (namesString.toLowerCase(Locale.ROOT)) { case "list": case "map": for (String typeArg : field.getTypeArguments()) { varToTypeMapping.put(Helper.getFQVariableName(node), typeArg); } break; default: varToTypeMapping.put(Helper.getFQVariableName(node), getSimpleType(namesString)); break; } } final ASTSoqlExpression soql = node.getFirstChildOfType(ASTSoqlExpression.class); if (soql != null) { checkForAccessibility(soql, data); } return data; } @Override public Object visit(final ASTReturnStatement node, Object data) { final ASTSoqlExpression soql = node.getFirstChildOfType(ASTSoqlExpression.class); if (soql != null) { checkForAccessibility(soql, data); } return data; } @Override public Object visit(final ASTForEachStatement node, Object data) { final ASTSoqlExpression soql = node.getFirstChildOfType(ASTSoqlExpression.class); if (soql != null) { checkForAccessibility(soql, data); } return super.visit(node, data); } private void addVariableToMapping(final String variableName, final String type) { switch (type.toLowerCase(Locale.ROOT)) { case "list": case "map": break; default: varToTypeMapping.put(variableName, getSimpleType(type)); break; } } private String getSimpleType(final String type) { String typeToUse = type; Pattern pattern = Pattern.compile("^[list<]?list<(\\S+?)>[>]?$", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(typeToUse); if (matcher.find()) { typeToUse = matcher.group(1); } return typeToUse; } @Override public Object visit(final ASTProperty node, Object data) { ASTField field = node.getFirstChildOfType(ASTField.class); if (field != null) { String fieldType = field.getType(); addVariableToMapping(Helper.getFQVariableName(field), fieldType); } return data; } private void collectCRUDMethodLevelChecks(final ASTMethodCallExpression node) { final String method = node.getMethodName(); final ASTReferenceExpression ref = node.getFirstChildOfType(ASTReferenceExpression.class); if (ref == null) { return; } List<String> a = ref.getNames(); if (!a.isEmpty()) { extractObjectAndFields(a, method, node.getDefiningType()); } else { // see if ESAPI if (Helper.isMethodCallChain(node, ESAPI_ISAUTHORIZED_TO_VIEW)) { extractObjectTypeFromESAPI(node, IS_ACCESSIBLE); } if (Helper.isMethodCallChain(node, ESAPI_ISAUTHORIZED_TO_CREATE)) { extractObjectTypeFromESAPI(node, IS_CREATEABLE); } if (Helper.isMethodCallChain(node, ESAPI_ISAUTHORIZED_TO_UPDATE)) { extractObjectTypeFromESAPI(node, IS_UPDATEABLE); } if (Helper.isMethodCallChain(node, ESAPI_ISAUTHORIZED_TO_DELETE)) { extractObjectTypeFromESAPI(node, IS_DELETABLE); } // ESAPI doesn't provide support for undelete or merge // see if getDescribe() final ASTMethodCallExpression nestedMethodCall = ref .getFirstChildOfType(ASTMethodCallExpression.class); if (nestedMethodCall != null) { if (isLastMethodName(nestedMethodCall, S_OBJECT_TYPE, GET_DESCRIBE)) { String resolvedType = getType(nestedMethodCall); if (!typeToDMLOperationMapping.get(resolvedType).contains(method)) { typeToDMLOperationMapping.put(resolvedType, method); } } } } // Check any configured authorization class library patterns for (PropertyDescriptor<String> authMethodPatternDescriptor : AUTH_METHOD_TO_TYPE_PARAM_INDEX_MAP.keySet()) { extractObjectTypeFromConfiguredMethodPatternInvocation(node, authMethodPatternDescriptor); } } private boolean isLastMethodName(final ASTMethodCallExpression methodNode, final String className, final String methodName) { final ASTReferenceExpression reference = methodNode.getFirstChildOfType(ASTReferenceExpression.class); if (reference != null && !reference.getNames().isEmpty()) { if (reference.getNames().get(reference.getNames().size() - 1) .equalsIgnoreCase(className) && Helper.isMethodName(methodNode, methodName)) { return true; } } return false; } private boolean isWithSecurityEnforced(final ApexNode<?> node) { return node instanceof ASTSoqlExpression && WITH_SECURITY_ENFORCED.matcher(((ASTSoqlExpression) node).getQuery()).matches(); } //For USER_MODE private boolean isWithUserMode(final ApexNode<?> node) { return node instanceof ASTSoqlExpression && WITH_USER_MODE.matcher(((ASTSoqlExpression) node).getQuery()).matches(); } //For System Mode private boolean isWithSystemMode(final ApexNode<?> node) { return node instanceof ASTSoqlExpression && WITH_SYSTEM_MODE.matcher(((ASTSoqlExpression) node).getQuery()).matches(); } private String getType(final ASTMethodCallExpression methodNode) { final ASTReferenceExpression reference = methodNode.getFirstChildOfType(ASTReferenceExpression.class); if (!reference.getNames().isEmpty()) { return new StringBuilder().append(reference.getDefiningType()).append(":") .append(reference.getNames().get(0)).toString(); } return ""; } private void extractObjectAndFields(final List<String> listIdentifiers, final String method, final String definingType) { int flsIndex = Collections.lastIndexOfSubList(listIdentifiers, Arrays.asList(RESERVED_KEYS_FLS)); if (flsIndex != -1) { String objectTypeName = listIdentifiers.get(flsIndex + RESERVED_KEYS_FLS.length); if (!typeToDMLOperationMapping.get(definingType + ":" + objectTypeName).contains(method)) { typeToDMLOperationMapping.put(definingType + ":" + objectTypeName, method); } } } private void checkForCRUD(final ApexNode<?> node, final Object data, final String crudMethod) { final Set<ASTMethodCallExpression> prevCalls = getPreviousMethodCalls(node); for (ASTMethodCallExpression prevCall : prevCalls) { collectCRUDMethodLevelChecks(prevCall); } final ASTMethod wrappingMethod = node.getFirstParentOfType(ASTMethod.class); final ASTUserClass wrappingClass = node.getFirstParentOfType(ASTUserClass.class); if (wrappingClass != null && Helper.isTestMethodOrClass(wrappingClass) || wrappingMethod != null && Helper.isTestMethodOrClass(wrappingMethod)) { return; } checkInlineObject(node, data, crudMethod); checkInlineNonArgsObject(node, data, crudMethod); final ASTVariableExpression variable = node.getFirstChildOfType(ASTVariableExpression.class); if (variable != null) { final String type = varToTypeMapping.get(Helper.getFQVariableName(variable)); if (type != null) { StringBuilder typeCheck = new StringBuilder().append(node.getDefiningType()) .append(":").append(type); validateCRUDCheckPresent(node, data, crudMethod, typeCheck.toString()); } } final ASTNewListLiteralExpression inlineListLiteral = node.getFirstChildOfType(ASTNewListLiteralExpression.class); if (inlineListLiteral != null) { checkInlineObject(inlineListLiteral, data, crudMethod); checkInlineNonArgsObject(inlineListLiteral, data, crudMethod); } final ASTNewListInitExpression inlineListInit = node.getFirstChildOfType(ASTNewListInitExpression.class); if (inlineListInit != null) { checkInlineObject(inlineListInit, data, crudMethod); checkInlineNonArgsObject(inlineListInit, data, crudMethod); } } private void checkInlineObject(final ApexNode<?> node, final Object data, final String crudMethod) { final ASTNewKeyValueObjectExpression newObj = node.getFirstChildOfType(ASTNewKeyValueObjectExpression.class); if (newObj != null) { final String type = Helper.getFQVariableName(newObj); validateCRUDCheckPresent(node, data, crudMethod, type); } } private void checkInlineNonArgsObject(final ApexNode<?> node, final Object data, final String crudMethod) { final ASTNewObjectExpression newEmptyObj = node.getFirstChildOfType(ASTNewObjectExpression.class); if (newEmptyObj != null) { final String type = Helper.getFQVariableName(newEmptyObj); validateCRUDCheckPresent(node, data, crudMethod, type); } } private Set<ASTMethodCallExpression> getPreviousMethodCalls(final ApexNode<?> self) { final Set<ASTMethodCallExpression> innerMethodCalls = new HashSet<>(); final ASTMethod outerMethod = self.getFirstParentOfType(ASTMethod.class); if (outerMethod != null) { final ASTBlockStatement blockStatement = outerMethod.getFirstChildOfType(ASTBlockStatement.class); recursivelyEvaluateCRUDMethodCalls(self, innerMethodCalls, blockStatement); final List<ASTMethod> constructorMethods = findConstructorMethods(); for (ASTMethod method : constructorMethods) { innerMethodCalls.addAll(method.findDescendantsOfType(ASTMethodCallExpression.class)); } // some methods might be within this class mapCallToMethodDecl(self, innerMethodCalls, new ArrayList<>(innerMethodCalls)); } return innerMethodCalls; } private void recursivelyEvaluateCRUDMethodCalls(final ApexNode<?> self, final Set<ASTMethodCallExpression> innerMethodCalls, final ASTBlockStatement blockStatement) { if (blockStatement != null) { int numberOfStatements = blockStatement.getNumChildren(); for (int i = 0; i < numberOfStatements; i++) { Node n = blockStatement.getChild(i); if (n instanceof ASTIfElseBlockStatement) { List<ASTBlockStatement> innerBlocks = n.findDescendantsOfType(ASTBlockStatement.class); for (ASTBlockStatement innerBlock : innerBlocks) { recursivelyEvaluateCRUDMethodCalls(self, innerMethodCalls, innerBlock); } } ApexNode<?> match = n.getFirstDescendantOfType(self.getClass()); if (Objects.equal(match, self)) { break; } ASTMethodCallExpression methodCall = n.getFirstDescendantOfType(ASTMethodCallExpression.class); if (methodCall != null) { mapCallToMethodDecl(self, innerMethodCalls, Arrays.asList(methodCall)); } } } } private void mapCallToMethodDecl(final ApexNode<?> self, final Set<ASTMethodCallExpression> innerMethodCalls, final List<ASTMethodCallExpression> nodes) { for (ASTMethodCallExpression node : nodes) { if (Objects.equal(node, self)) { break; } final ASTMethod methodBody = resolveMethodCalls(node); if (methodBody != null) { innerMethodCalls.addAll(methodBody.findDescendantsOfType(ASTMethodCallExpression.class)); } else { // If we couldn't resolve it locally, add any calls for configured authorization patterns if (isAuthMethodInvocation(node)) { innerMethodCalls.add(node); } } } } private List<ASTMethod> findConstructorMethods() { final List<ASTMethod> ret = new ArrayList<>(); final Set<String> constructors = classMethods.keySet().stream() .filter(p -> p.contains("<init>") || p.contains("<clinit>") || p.startsWith(className + ":" + className + ":")).collect(Collectors.toSet()); for (String c : constructors) { ret.add(classMethods.get(c)); } return ret; } private ASTMethod resolveMethodCalls(final ASTMethodCallExpression node) { StringBuilder sb = new StringBuilder().append(node.getDefiningType()).append(":") .append(node.getMethodName()).append(":").append(node.getInputParametersSize()); return classMethods.get(sb.toString()); } private boolean isProperESAPICheckForDML(final String typeToCheck, final String dmlOperation) { final boolean hasMapping = checkedTypeToDMLOperationViaESAPI.containsKey(typeToCheck); if (hasMapping) { if (ANY.equals(dmlOperation)) { return true; } String dmlChecked = checkedTypeToDMLOperationViaESAPI.get(typeToCheck); return dmlChecked.equals(dmlOperation); } return false; } private void extractObjectTypeFromESAPI(final ASTMethodCallExpression node, final String dmlOperation) { final ASTVariableExpression var = node.getFirstChildOfType(ASTVariableExpression.class); if (var != null) { final ASTReferenceExpression reference = var.getFirstChildOfType(ASTReferenceExpression.class); if (reference != null) { List<String> identifiers = reference.getNames(); if (identifiers.size() == 1) { StringBuilder sb = new StringBuilder().append(node.getDefiningType()) .append(":").append(identifiers.get(0)); checkedTypeToDMLOperationViaESAPI.put(sb.toString(), dmlOperation); } } } } private boolean validateCRUDCheckPresent(final ApexNode<?> node, final Object data, final String crudMethod, final String typeCheck) { boolean missingKey = !typeToDMLOperationMapping.containsKey(typeCheck); boolean isImproperDMLCheck = !isProperESAPICheckForDML(typeCheck, crudMethod) && !isProperAuthPatternBasedCheckForDML(typeCheck, crudMethod); boolean noSecurityEnforced = !isWithSecurityEnforced(node); boolean noUserMode = !isWithUserMode(node); boolean noSystemMode = !isWithSystemMode(node); if (missingKey) { if (isImproperDMLCheck) { if (noSecurityEnforced && noUserMode && noSystemMode) { addViolation(data, node); return true; } } } else { boolean properChecksHappened = false; Set<String> dmlOperationsChecked = typeToDMLOperationMapping.get(typeCheck); for (String dmlOp : dmlOperationsChecked) { if (dmlOp.equalsIgnoreCase(crudMethod)) { properChecksHappened = true; break; } if (ANY.equals(crudMethod)) { properChecksHappened = true; break; } } if (!properChecksHappened) { addViolation(data, node); return true; } } return false; } private void checkForAccessibility(final ASTSoqlExpression node, Object data) { // TODO: This includes sub-relation queries which are incorrectly flagged because you authorize the type // and not the sub-relation name. Should we (optionally) exclude sub-relations until/unless they can be // resolved to the proper SObject type? final Set<String> typesFromSOQL = getTypesFromSOQLQuery(node); final Set<ASTMethodCallExpression> prevCalls = getPreviousMethodCalls(node); for (ASTMethodCallExpression prevCall : prevCalls) { collectCRUDMethodLevelChecks(prevCall); } String returnType = null; final ASTMethod wrappingMethod = node.getFirstParentOfType(ASTMethod.class); final ASTUserClass wrappingClass = node.getFirstParentOfType(ASTUserClass.class); if (wrappingClass != null && Helper.isTestMethodOrClass(wrappingClass) || wrappingMethod != null && Helper.isTestMethodOrClass(wrappingMethod)) { return; } if (wrappingMethod != null) { returnType = getReturnType(wrappingMethod); } boolean violationAdded = false; final ASTVariableDeclaration variableDecl = node.getFirstParentOfType(ASTVariableDeclaration.class); if (variableDecl != null) { String type = variableDecl.getType(); type = getSimpleType(type); StringBuilder typeCheck = new StringBuilder().append(variableDecl.getDefiningType()) .append(":").append(type); if (typesFromSOQL.isEmpty()) { violationAdded = validateCRUDCheckPresent(node, data, ANY, typeCheck.toString()); } else { for (String typeFromSOQL : typesFromSOQL) { violationAdded |= validateCRUDCheckPresent(node, data, ANY, typeFromSOQL); } } } // If the node's already in violation, we don't need to keep checking. if (violationAdded) { return; } final ASTAssignmentExpression assignment = node.getFirstParentOfType(ASTAssignmentExpression.class); if (assignment != null) { final ASTVariableExpression variable = assignment.getFirstChildOfType(ASTVariableExpression.class); if (variable != null) { String variableWithClass = Helper.getFQVariableName(variable); if (varToTypeMapping.containsKey(variableWithClass)) { String type = varToTypeMapping.get(variableWithClass); if (typesFromSOQL.isEmpty()) { violationAdded = validateCRUDCheckPresent(node, data, ANY, type); } else { for (String typeFromSOQL : typesFromSOQL) { violationAdded |= validateCRUDCheckPresent(node, data, ANY, typeFromSOQL); } } } } } // If the node's already in violation, we don't need to keep checking. if (violationAdded) { return; } final ASTReturnStatement returnStatement = node.getFirstParentOfType(ASTReturnStatement.class); if (returnStatement != null) { if (typesFromSOQL.isEmpty()) { violationAdded = validateCRUDCheckPresent(node, data, ANY, returnType); } else { for (String typeFromSOQL : typesFromSOQL) { violationAdded |= validateCRUDCheckPresent(node, data, ANY, typeFromSOQL); } } } // If the node's already in violation, we don't need to keep checking. if (violationAdded) { return; } final ASTForEachStatement forEachStatement = node.getFirstParentOfType(ASTForEachStatement.class); if (forEachStatement != null) { if (typesFromSOQL.isEmpty()) { final ASTVariableDeclaration variableDeclFor = forEachStatement.getFirstParentOfType(ASTVariableDeclaration.class); if (variableDeclFor != null) { String type = variableDeclFor.getType(); type = getSimpleType(type); StringBuilder typeCheck = new StringBuilder().append(variableDeclFor.getDefiningType()) .append(":").append(type); validateCRUDCheckPresent(node, data, ANY, typeCheck.toString()); } } else { for (String typeFromSOQL : typesFromSOQL) { validateCRUDCheckPresent(node, data, ANY, typeFromSOQL); } } } } private Set<String> getTypesFromSOQLQuery(final ASTSoqlExpression node) { final Set<String> retVal = new HashSet<>(); final String canonQuery = node.getCanonicalQuery(); Matcher m = SELECT_FROM_PATTERN.matcher(canonQuery); while (m.find()) { retVal.add(new StringBuffer().append(node.getDefiningType()).append(":") .append(m.group(1)).toString()); } return retVal; } private String getReturnType(final ASTMethod method) { return new StringBuilder().append(method.getDefiningType()).append(":") .append(method.getReturnType()).toString(); } // Configured authorization method pattern support private static PropertyDescriptor<String> authMethodPatternProperty(String operation) { final String propertyName = operation + "AuthMethodPattern"; return stringProperty(propertyName) .desc("A regular expression for one or more custom " + operation + " authorization method name patterns.") .defaultValue("") .build(); } private static PropertyDescriptor<Integer> authMethodTypeParamIndexProperty(String operation) { final String propertyName = operation + "AuthMethodTypeParamIndex"; return intProperty(propertyName) .desc("The 0-based index of the " + S_OBJECT_TYPE + " parameter for the custom " + operation + " authorization method. Defaults to 0.") .defaultValue(0) .build(); } private boolean isAuthMethodInvocation(final ASTMethodCallExpression methodNode) { for (PropertyDescriptor<String> authMethodPatternDescriptor : AUTH_METHOD_TO_TYPE_PARAM_INDEX_MAP.keySet()) { if (isAuthMethodInvocation(methodNode, authMethodPatternDescriptor)) { return true; } } return false; } private void extractObjectTypeFromConfiguredMethodPatternInvocation(final ASTMethodCallExpression methodNode, final PropertyDescriptor<String> authMethodPatternDescriptor) { if (isAuthMethodInvocation(methodNode, authMethodPatternDescriptor)) { // See which parameter index contains the object type expression and try to find that invocation argument final PropertyDescriptor<Integer> authMethodTypeParamIndexDescriptor = AUTH_METHOD_TO_TYPE_PARAM_INDEX_MAP.get(authMethodPatternDescriptor); final Integer authMethodTypeParamIndex = authMethodTypeParamIndexDescriptor != null ? getProperty(authMethodTypeParamIndexDescriptor) : 0; final int numParameters = methodNode.getInputParametersSize(); if (numParameters > authMethodTypeParamIndex) { final List<ASTVariableExpression> parameters = new ArrayList<>(numParameters); for (int parameterIndex = 0, numChildren = methodNode.getNumChildren(); parameterIndex < numChildren; parameterIndex++) { final ApexNode<?> childNode = methodNode.getChild(parameterIndex); if (childNode instanceof ASTVariableExpression) { parameters.add((ASTVariableExpression) childNode); } } // Make sure that it looks like "sObjectType.<objectTypeName>" as VariableExpression > ReferenceExpression final ASTVariableExpression sobjectTypeParameterCandidate = parameters.size() > authMethodTypeParamIndex ? parameters.get(authMethodTypeParamIndex) : null; if (sobjectTypeParameterCandidate != null && S_OBJECT_TYPE.equalsIgnoreCase(sobjectTypeParameterCandidate.getImage())) { final ASTReferenceExpression objectTypeCandidate = sobjectTypeParameterCandidate.getFirstChildOfType(ASTReferenceExpression.class); if (objectTypeCandidate != null) { final String objectType = objectTypeCandidate.getImage(); if (StringUtils.isNotBlank(objectType)) { // Create a (relatively) unique key for this that is prefixed by the current invocation's containing type name final StringBuilder checkedTypeBuilder = new StringBuilder().append(methodNode.getDefiningType()) .append(":").append(objectType); final String checkedType = checkedTypeBuilder.toString(); // And get the appropriate DML operation based on this method pattern final String dmlOperation = AUTH_METHOD_TO_DML_OPERATION_MAP.get(authMethodPatternDescriptor); if (StringUtils.isNotBlank(dmlOperation)) { checkedTypeToDMLOperationsViaAuthPattern.put(checkedType, dmlOperation); } } } } } } } private boolean isAuthMethodInvocation(final ASTMethodCallExpression methodNode, final PropertyDescriptor<String> authMethodPatternDescriptor) { final String authMethodPattern = getProperty(authMethodPatternDescriptor); final Pattern compiledAuthMethodPattern = getCompiledAuthMethodPattern(authMethodPattern); if (compiledAuthMethodPattern != null) { final String fullMethodName = methodNode.getFullMethodName(); final Matcher authMethodMatcher = compiledAuthMethodPattern.matcher(fullMethodName); if (authMethodMatcher.matches()) { return true; } } return false; } private Pattern getCompiledAuthMethodPattern(final String authMethodPattern) { Pattern compiledAuthMethodPattern = null; if (StringUtils.isNotBlank(authMethodPattern)) { // If we haven't previously tried to to compile this pattern, do so now if (!compiledAuthMethodPatternCache.containsKey(authMethodPattern)) { try { compiledAuthMethodPattern = Pattern.compile(authMethodPattern, Pattern.CASE_INSENSITIVE); compiledAuthMethodPatternCache.put(authMethodPattern, compiledAuthMethodPattern); } catch (IllegalArgumentException e) { // Cache a null value so we don't try to compile this particular pattern again compiledAuthMethodPatternCache.put(authMethodPattern, null); throw e; } } else { // Otherwise use the cached value, either the successfully compiled pattern or null if pattern compilation failed compiledAuthMethodPattern = compiledAuthMethodPatternCache.get(authMethodPattern); } } return compiledAuthMethodPattern; } private boolean isProperAuthPatternBasedCheckForDML(final String typeToCheck, final String dmlOperation) { final boolean hasMapping = checkedTypeToDMLOperationsViaAuthPattern.containsKey(typeToCheck); if (hasMapping) { if (ANY.equals(dmlOperation)) { return true; } final Set<String> dmlOperationsChecked = checkedTypeToDMLOperationsViaAuthPattern.get(typeToCheck); return dmlOperationsChecked.contains(dmlOperation); } return false; } }
43,459
43.989648
196
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexInsecureEndpointRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.apex.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.apex.ast.ASTBinaryExpression; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTLiteralExpression; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; /** * Insecure HTTP endpoints passed to (req.setEndpoint) * req.setHeader('Authorization') should use named credentials * * @author sergey.gorbaty * */ public class ApexInsecureEndpointRule extends AbstractApexRule { private static final String SET_ENDPOINT = "setEndpoint"; private static final Pattern PATTERN = Pattern.compile("^http://.+?$", Pattern.CASE_INSENSITIVE); private final Set<String> httpEndpointStrings = new HashSet<>(); @Override public Object visit(ASTAssignmentExpression node, Object data) { findInsecureEndpoints(node); return data; } @Override public Object visit(ASTVariableDeclaration node, Object data) { findInsecureEndpoints(node); return data; } @Override public Object visit(ASTFieldDeclaration node, Object data) { findInsecureEndpoints(node); return data; } private void findInsecureEndpoints(ApexNode<?> node) { ASTVariableExpression variableNode = node.getFirstChildOfType(ASTVariableExpression.class); findInnerInsecureEndpoints(node, variableNode); ASTBinaryExpression binaryNode = node.getFirstChildOfType(ASTBinaryExpression.class); if (binaryNode != null) { findInnerInsecureEndpoints(binaryNode, variableNode); } } private void findInnerInsecureEndpoints(ApexNode<?> node, ASTVariableExpression variableNode) { ASTLiteralExpression literalNode = node.getFirstChildOfType(ASTLiteralExpression.class); if (literalNode != null && variableNode != null) { if (literalNode.isString()) { String literal = literalNode.getImage(); if (PATTERN.matcher(literal).matches()) { httpEndpointStrings.add(Helper.getFQVariableName(variableNode)); } } } } @Override public Object visit(ASTMethodCallExpression node, Object data) { processInsecureEndpoint(node, data); return data; } private void processInsecureEndpoint(ASTMethodCallExpression node, Object data) { if (!Helper.isMethodName(node, SET_ENDPOINT)) { return; } ASTBinaryExpression binaryNode = node.getFirstChildOfType(ASTBinaryExpression.class); if (binaryNode != null) { runChecks(binaryNode, data); } runChecks(node, data); } private void runChecks(ApexNode<?> node, Object data) { ASTLiteralExpression literalNode = node.getFirstChildOfType(ASTLiteralExpression.class); if (literalNode != null && literalNode.isString()) { String literal = literalNode.getImage(); if (PATTERN.matcher(literal).matches()) { addViolation(data, literalNode); } } ASTVariableExpression variableNode = node.getFirstChildOfType(ASTVariableExpression.class); if (variableNode != null) { if (httpEndpointStrings.contains(Helper.getFQVariableName(variableNode))) { addViolation(data, variableNode); } } } }
3,970
33.530435
101
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexOpenRedirectRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.HashSet; import java.util.List; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.apex.ast.ASTBinaryExpression; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTLiteralExpression; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTNewObjectExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; /** * Looking for potential Open redirect via PageReference variable input * * @author sergey.gorbaty */ public class ApexOpenRedirectRule extends AbstractApexRule { private static final String PAGEREFERENCE = "PageReference"; private final Set<String> listOfStringLiteralVariables = new HashSet<>(); @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node) || Helper.isSystemLevelClass(node)) { return data; // stops all the rules } List<ASTAssignmentExpression> assignmentExprs = node.findDescendantsOfType(ASTAssignmentExpression.class); for (ASTAssignmentExpression assignment : assignmentExprs) { findSafeLiterals(assignment); } List<ASTVariableDeclaration> variableDecls = node.findDescendantsOfType(ASTVariableDeclaration.class); for (ASTVariableDeclaration varDecl : variableDecls) { findSafeLiterals(varDecl); } List<ASTField> fieldDecl = node.findDescendantsOfType(ASTField.class); for (ASTField fDecl : fieldDecl) { findSafeLiterals(fDecl); } List<ASTNewObjectExpression> newObjects = node.findDescendantsOfType(ASTNewObjectExpression.class); for (ASTNewObjectExpression newObj : newObjects) { checkNewObjects(newObj, data); } listOfStringLiteralVariables.clear(); return data; } private void findSafeLiterals(ApexNode<?> node) { ASTBinaryExpression binaryExp = node.getFirstChildOfType(ASTBinaryExpression.class); if (binaryExp != null) { findSafeLiterals(binaryExp); } ASTLiteralExpression literal = node.getFirstChildOfType(ASTLiteralExpression.class); if (literal != null) { int index = literal.getIndexInParent(); if (index == 0) { if (node instanceof ASTVariableDeclaration) { addVariable((ASTVariableDeclaration) node); } else if (node instanceof ASTBinaryExpression) { ASTVariableDeclaration parent = node.getFirstParentOfType(ASTVariableDeclaration.class); if (parent != null) { addVariable(parent); } ASTAssignmentExpression assignment = node.getFirstParentOfType(ASTAssignmentExpression.class); if (assignment != null) { ASTVariableExpression var = assignment.getFirstChildOfType(ASTVariableExpression.class); if (var != null) { addVariable(var); } } } } } else { if (node instanceof ASTField) { ASTField field = (ASTField) node; if ("String".equalsIgnoreCase(field.getType())) { if (field.getValue() != null) { listOfStringLiteralVariables.add(Helper.getFQVariableName(field)); } } } } } private void addVariable(ASTVariableDeclaration node) { ASTVariableExpression variable = node.getFirstChildOfType(ASTVariableExpression.class); addVariable(variable); } private void addVariable(ASTVariableExpression node) { if (node != null) { listOfStringLiteralVariables.add(Helper.getFQVariableName(node)); } } /** * Traverses all new declarations to find PageReferences * * @param node * @param data */ private void checkNewObjects(ASTNewObjectExpression node, Object data) { ASTMethod method = node.getFirstParentOfType(ASTMethod.class); if (method != null && Helper.isTestMethodOrClass(method)) { return; } if (PAGEREFERENCE.equalsIgnoreCase(node.getType())) { getObjectValue(node, data); } } /** * Finds any variables being present in PageReference constructor * * @param node * - PageReference * @param data * */ private void getObjectValue(ApexNode<?> node, Object data) { // PageReference(foo); final List<ASTVariableExpression> variableExpressions = node.findChildrenOfType(ASTVariableExpression.class); for (ASTVariableExpression variable : variableExpressions) { if (variable.getIndexInParent() == 0 && !listOfStringLiteralVariables.contains(Helper.getFQVariableName(variable))) { addViolation(data, variable); } } // PageReference(foo + bar) final List<ASTBinaryExpression> binaryExpressions = node.findChildrenOfType(ASTBinaryExpression.class); for (ASTBinaryExpression z : binaryExpressions) { getObjectValue(z, data); } } }
6,140
35.553571
117
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexSharingViolationsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.Map; import java.util.Optional; import java.util.WeakHashMap; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.apex.ast.ASTDmlDeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlInsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlMergeStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUndeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpdateStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTSoqlExpression; import net.sourceforge.pmd.lang.apex.ast.ASTSoslExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; /** * Finds Apex class that do not define sharing * * @author sergey.gorbaty */ public class ApexSharingViolationsRule extends AbstractApexRule { /** * Keep track of previously reported violations to avoid duplicates. */ private Map<ApexNode<?>, Object> localCacheOfReportedNodes = new WeakHashMap<>(); public ApexSharingViolationsRule() { addRuleChainVisit(ASTDmlDeleteStatement.class); addRuleChainVisit(ASTDmlInsertStatement.class); addRuleChainVisit(ASTDmlMergeStatement.class); addRuleChainVisit(ASTDmlUndeleteStatement.class); addRuleChainVisit(ASTDmlUpdateStatement.class); addRuleChainVisit(ASTDmlUpsertStatement.class); addRuleChainVisit(ASTMethodCallExpression.class); addRuleChainVisit(ASTSoqlExpression.class); addRuleChainVisit(ASTSoslExpression.class); } @Override public void start(RuleContext ctx) { super.start(ctx); localCacheOfReportedNodes.clear(); } @Override public Object visit(ASTSoqlExpression node, Object data) { checkForViolation(node, data); return data; } @Override public Object visit(ASTSoslExpression node, Object data) { checkForViolation(node, data); return data; } @Override public Object visit(ASTDmlUpsertStatement node, Object data) { checkForViolation(node, data); return data; } @Override public Object visit(ASTDmlUpdateStatement node, Object data) { checkForViolation(node, data); return data; } @Override public Object visit(ASTDmlUndeleteStatement node, Object data) { checkForViolation(node, data); return data; } @Override public Object visit(ASTDmlMergeStatement node, Object data) { checkForViolation(node, data); return data; } @Override public Object visit(ASTDmlInsertStatement node, Object data) { checkForViolation(node, data); return data; } @Override public Object visit(ASTDmlDeleteStatement node, Object data) { checkForViolation(node, data); return data; } @Override public Object visit(ASTMethodCallExpression node, Object data) { if (Helper.isAnyDatabaseMethodCall(node)) { checkForViolation(node, data); } return data; } private void checkForViolation(ApexNode<?> node, Object data) { // The closest ASTUserClass class in the tree hierarchy is the node that requires the sharing declaration ASTUserClass sharingDeclarationClass = node.getFirstParentOfType(ASTUserClass.class); // This is null in the case of triggers if (sharingDeclarationClass != null) { // Apex allows a single level of class nesting. Check to see if sharingDeclarationClass has an outer class ASTUserClass outerClass = sharingDeclarationClass.getFirstParentOfType(ASTUserClass.class); // The test annotation needs to be on the outermost class ASTUserClass testAnnotationClass = Optional.ofNullable(outerClass).orElse(sharingDeclarationClass); if (!Helper.isTestMethodOrClass(testAnnotationClass) && !Helper.isSystemLevelClass(sharingDeclarationClass) && !isSharingPresent(sharingDeclarationClass)) { // The violation is reported on the class, not the node that performs data access reportViolation(sharingDeclarationClass, data); } } } private void reportViolation(ApexNode<?> node, Object data) { ASTModifierNode modifier = node.getFirstChildOfType(ASTModifierNode.class); if (modifier != null) { if (localCacheOfReportedNodes.put(modifier, data) == null) { addViolation(data, modifier); } } else { if (localCacheOfReportedNodes.put(node, data) == null) { addViolation(data, node); } } } /** * Does class have sharing keyword declared? * * @param node * @return */ private boolean isSharingPresent(ASTUserClass node) { return node.getModifiers().isWithoutSharing() || node.getModifiers().isWithSharing() || node.getModifiers().isInheritedSharing(); } }
5,458
33.770701
168
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexSuggestUsingNamedCredRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.HashSet; import java.util.List; import java.util.Set; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTBinaryExpression; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTLiteralExpression; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; /** * Flags usage of http request.setHeader('Authorization',..) and suggests using * named credentials which helps store credentials for the callout in a safe * place. * * @author sergey.gorbaty * */ public class ApexSuggestUsingNamedCredRule extends AbstractApexRule { private static final String SET_HEADER = "setHeader"; private static final String AUTHORIZATION = "Authorization"; private final Set<String> listOfAuthorizationVariables = new HashSet<>(); @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node)) { return data; } List<ASTVariableDeclaration> variableDecls = node.findDescendantsOfType(ASTVariableDeclaration.class); for (ASTVariableDeclaration varDecl : variableDecls) { findAuthLiterals(varDecl); } List<ASTField> fieldDecl = node.findDescendantsOfType(ASTField.class); for (ASTField fDecl : fieldDecl) { findFieldLiterals(fDecl); } List<ASTMethodCallExpression> methodCalls = node.findDescendantsOfType(ASTMethodCallExpression.class); for (ASTMethodCallExpression method : methodCalls) { flagAuthorizationHeaders(method, data); } listOfAuthorizationVariables.clear(); return data; } private void findFieldLiterals(final ASTField fDecl) { if ("String".equals(fDecl.getType()) && AUTHORIZATION.equalsIgnoreCase(fDecl.getValue())) { listOfAuthorizationVariables.add(Helper.getFQVariableName(fDecl)); } } private void flagAuthorizationHeaders(final ASTMethodCallExpression node, Object data) { if (!Helper.isMethodName(node, SET_HEADER)) { return; } final ASTBinaryExpression binaryNode = node.getFirstChildOfType(ASTBinaryExpression.class); if (binaryNode != null) { runChecks(binaryNode, data); } runChecks(node, data); } private void findAuthLiterals(final ApexNode<?> node) { ASTLiteralExpression literal = node.getFirstChildOfType(ASTLiteralExpression.class); if (literal != null) { ASTVariableExpression variable = node.getFirstChildOfType(ASTVariableExpression.class); if (variable != null) { if (isAuthorizationLiteral(literal)) { listOfAuthorizationVariables.add(Helper.getFQVariableName(variable)); } } } } private void runChecks(final ApexNode<?> node, Object data) { ASTLiteralExpression literalNode = node.getFirstChildOfType(ASTLiteralExpression.class); if (literalNode != null) { if (isAuthorizationLiteral(literalNode)) { addViolation(data, literalNode); } } final ASTVariableExpression varNode = node.getFirstChildOfType(ASTVariableExpression.class); if (varNode != null) { if (listOfAuthorizationVariables.contains(Helper.getFQVariableName(varNode))) { addViolation(data, varNode); } } } private boolean isAuthorizationLiteral(final ASTLiteralExpression literal) { if (literal.isString()) { String lit = literal.getImage(); if (AUTHORIZATION.equalsIgnoreCase(lit)) { return true; } } return false; } }
4,519
34.03876
110
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexDangerousMethodsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; /** * Flags dangerous method calls, e.g. FinancialForce * Configuration.disableTriggerCRUDSecurity() or System.debug with sensitive * input * * * @author sergey.gorbaty * */ public class ApexDangerousMethodsRule extends AbstractApexRule { private static final String BOOLEAN = "boolean"; private static final Pattern REGEXP = Pattern.compile("^.*?(pass|pwd|crypt|auth|session|token|saml)(?!id|user).*?$", Pattern.CASE_INSENSITIVE); private static final String DISABLE_CRUD = "disableTriggerCRUDSecurity"; private static final String CONFIGURATION = "Configuration"; private static final String SYSTEM = "System"; private static final String DEBUG = "debug"; private final Set<String> whiteListedVariables = new HashSet<>(); @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node)) { return data; } collectBenignVariables(node); List<ASTMethodCallExpression> methodCalls = node.findDescendantsOfType(ASTMethodCallExpression.class); for (ASTMethodCallExpression methodCall : methodCalls) { if (Helper.isMethodName(methodCall, CONFIGURATION, DISABLE_CRUD)) { addViolation(data, methodCall); } if (Helper.isMethodName(methodCall, SYSTEM, DEBUG)) { validateParameters(methodCall, data); } } whiteListedVariables.clear(); return data; } private void collectBenignVariables(ASTUserClass node) { List<ASTField> fields = node.findDescendantsOfType(ASTField.class); for (ASTField field : fields) { if (BOOLEAN.equalsIgnoreCase(field.getType())) { whiteListedVariables.add(Helper.getFQVariableName(field)); } } List<ASTVariableDeclaration> declarations = node.findDescendantsOfType(ASTVariableDeclaration.class); for (ASTVariableDeclaration decl : declarations) { if (BOOLEAN.equalsIgnoreCase(decl.getType())) { whiteListedVariables.add(Helper.getFQVariableName(decl)); } } } private void validateParameters(ASTMethodCallExpression methodCall, Object data) { List<ASTVariableExpression> variables = methodCall.findDescendantsOfType(ASTVariableExpression.class); for (ASTVariableExpression var : variables) { if (REGEXP.matcher(var.getImage()).matches()) { if (!whiteListedVariables.contains(Helper.getFQVariableName(var))) { addViolation(data, methodCall); } } } } }
3,613
33.419048
120
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexSOQLInjectionRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.apex.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.apex.ast.ASTBinaryExpression; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTLiteralExpression; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTParameter; import net.sourceforge.pmd.lang.apex.ast.ASTStandardCondition; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; /** * Detects if variables in Database.query(variable) or Database.countQuery is escaped with * String.escapeSingleQuotes * * @author sergey.gorbaty * */ public class ApexSOQLInjectionRule extends AbstractApexRule { private static final String DOUBLE = "double"; private static final String LONG = "long"; private static final String DECIMAL = "decimal"; private static final String BOOLEAN = "boolean"; private static final String ID = "id"; private static final String INTEGER = "integer"; private static final String JOIN = "join"; private static final String ESCAPE_SINGLE_QUOTES = "escapeSingleQuotes"; private static final String STRING = "String"; private static final String DATABASE = "Database"; private static final String QUERY = "query"; private static final String COUNT_QUERY = "countQuery"; private static final Pattern SELECT_PATTERN = Pattern.compile("^select[\\s]+?.*?$", Pattern.CASE_INSENSITIVE); private final Set<String> safeVariables = new HashSet<>(); private final Map<String, Boolean> selectContainingVariables = new HashMap<>(); public ApexSOQLInjectionRule() { addRuleChainVisit(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node) || Helper.isSystemLevelClass(node)) { return data; // stops all the rules } final List<ASTMethod> methodExpr = node.findDescendantsOfType(ASTMethod.class); for (ASTMethod m : methodExpr) { findSafeVariablesInSignature(m); } final List<ASTFieldDeclaration> fieldExpr = node.findDescendantsOfType(ASTFieldDeclaration.class); for (ASTFieldDeclaration a : fieldExpr) { findSanitizedVariables(a); findSelectContainingVariables(a); } // String foo = String.escapeSignleQuotes(...); final List<ASTVariableDeclaration> variableDecl = node.findDescendantsOfType(ASTVariableDeclaration.class); for (ASTVariableDeclaration a : variableDecl) { findSanitizedVariables(a); findSelectContainingVariables(a); } // baz = String.escapeSignleQuotes(...); final List<ASTAssignmentExpression> assignmentCalls = node.findDescendantsOfType(ASTAssignmentExpression.class); for (ASTAssignmentExpression a : assignmentCalls) { findSanitizedVariables(a); findSelectContainingVariables(a); } // Database.query(...) check final List<ASTMethodCallExpression> potentialDbQueryCalls = node .findDescendantsOfType(ASTMethodCallExpression.class); for (ASTMethodCallExpression m : potentialDbQueryCalls) { if (!Helper.isTestMethodOrClass(m) && isQueryMethodCall(m)) { reportStrings(m, data); reportVariables(m, data); } } safeVariables.clear(); selectContainingVariables.clear(); return data; } private boolean isQueryMethodCall(ASTMethodCallExpression m) { return Helper.isMethodName(m, DATABASE, QUERY) || Helper.isMethodName(m, DATABASE, COUNT_QUERY); } private void findSafeVariablesInSignature(ASTMethod m) { for (ASTParameter p : m.findChildrenOfType(ASTParameter.class)) { switch (p.getType().toLowerCase(Locale.ROOT)) { case ID: case INTEGER: case BOOLEAN: case DECIMAL: case LONG: case DOUBLE: safeVariables.add(Helper.getFQVariableName(p)); break; default: break; } } } private void findSanitizedVariables(ApexNode<?> node) { final ASTVariableExpression left = node.getFirstChildOfType(ASTVariableExpression.class); final ASTLiteralExpression literal = node.getFirstChildOfType(ASTLiteralExpression.class); final ASTMethodCallExpression right = node.getFirstChildOfType(ASTMethodCallExpression.class); // look for String a = 'b'; if (literal != null) { if (left != null) { if (literal.isInteger() || literal.isBoolean() || literal.isDouble()) { safeVariables.add(Helper.getFQVariableName(left)); } if (literal.isString()) { if (SELECT_PATTERN.matcher(literal.getImage()).matches()) { selectContainingVariables.put(Helper.getFQVariableName(left), Boolean.TRUE); } else { safeVariables.add(Helper.getFQVariableName(left)); } } } } // look for String a = String.escapeSingleQuotes(foo); if (right != null) { if (Helper.isMethodName(right, STRING, ESCAPE_SINGLE_QUOTES)) { if (left != null) { safeVariables.add(Helper.getFQVariableName(left)); } } } if (node instanceof ASTVariableDeclaration) { switch (((ASTVariableDeclaration) node).getType().toLowerCase(Locale.ROOT)) { case INTEGER: case ID: case BOOLEAN: case DECIMAL: case LONG: case DOUBLE: safeVariables.add(Helper.getFQVariableName(left)); break; default: break; } } } private void findSelectContainingVariables(ApexNode<?> node) { final ASTVariableExpression left = node.getFirstChildOfType(ASTVariableExpression.class); final ASTBinaryExpression right = node.getFirstChildOfType(ASTBinaryExpression.class); if (left != null && right != null) { recursivelyCheckForSelect(left, right); } } private void recursivelyCheckForSelect(final ASTVariableExpression var, final ASTBinaryExpression node) { final ASTBinaryExpression right = node.getFirstChildOfType(ASTBinaryExpression.class); if (right != null) { recursivelyCheckForSelect(var, right); } final ASTVariableExpression concatenatedVar = node.getFirstChildOfType(ASTVariableExpression.class); boolean isSafeVariable = false; if (concatenatedVar != null) { if (safeVariables.contains(Helper.getFQVariableName(concatenatedVar))) { isSafeVariable = true; } } final ASTMethodCallExpression methodCall = node.getFirstChildOfType(ASTMethodCallExpression.class); if (methodCall != null) { if (Helper.isMethodName(methodCall, STRING, ESCAPE_SINGLE_QUOTES)) { isSafeVariable = true; } } final ASTLiteralExpression literal = node.getFirstChildOfType(ASTLiteralExpression.class); if (literal != null) { if (literal.isString()) { if (SELECT_PATTERN.matcher(literal.getImage()).matches()) { if (!isSafeVariable) { // select literal + other unsafe vars selectContainingVariables.put(Helper.getFQVariableName(var), Boolean.FALSE); } else { safeVariables.add(Helper.getFQVariableName(var)); } } } } else { if (!isSafeVariable) { selectContainingVariables.put(Helper.getFQVariableName(var), Boolean.FALSE); } } } private void reportStrings(ASTMethodCallExpression m, Object data) { final Set<ASTVariableExpression> setOfSafeVars = new HashSet<>(); final List<ASTStandardCondition> conditions = m.findDescendantsOfType(ASTStandardCondition.class); for (ASTStandardCondition c : conditions) { List<ASTVariableExpression> vars = c.findDescendantsOfType(ASTVariableExpression.class); setOfSafeVars.addAll(vars); } final List<ASTBinaryExpression> binaryExpr = m.findChildrenOfType(ASTBinaryExpression.class); for (ASTBinaryExpression b : binaryExpr) { List<ASTVariableExpression> vars = b.findDescendantsOfType(ASTVariableExpression.class); for (ASTVariableExpression v : vars) { String fqName = Helper.getFQVariableName(v); if (selectContainingVariables.containsKey(fqName)) { boolean isLiteral = selectContainingVariables.get(fqName); if (isLiteral) { continue; } } if (setOfSafeVars.contains(v) || safeVariables.contains(fqName)) { continue; } final ASTMethodCallExpression parentCall = v.getFirstParentOfType(ASTMethodCallExpression.class); boolean isSafeMethod = Helper.isMethodName(parentCall, STRING, ESCAPE_SINGLE_QUOTES) || Helper.isMethodName(parentCall, STRING, JOIN); if (!isSafeMethod) { addViolation(data, v); } } } } private void reportVariables(final ASTMethodCallExpression m, Object data) { final ASTVariableExpression var = m.getFirstChildOfType(ASTVariableExpression.class); if (var != null) { String nameFQ = Helper.getFQVariableName(var); if (selectContainingVariables.containsKey(nameFQ)) { boolean isLiteral = selectContainingVariables.get(nameFQ); if (!isLiteral) { addViolation(data, var); } } } } }
10,948
38.67029
120
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexXSSFromEscapeFalseRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.List; import net.sourceforge.pmd.lang.apex.ast.ASTLiteralExpression; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; /** * Finds all .addError method calls that are not HTML escaped on purpose * * @author sergey.gorbaty * */ public class ApexXSSFromEscapeFalseRule extends AbstractApexRule { private static final String ADD_ERROR = "addError"; public ApexXSSFromEscapeFalseRule() { addRuleChainVisit(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node) || Helper.isSystemLevelClass(node)) { return data; // stops all the rules } List<ASTMethodCallExpression> methodCalls = node.findDescendantsOfType(ASTMethodCallExpression.class); for (ASTMethodCallExpression methodCall : methodCalls) { if (Helper.isMethodName(methodCall, ADD_ERROR)) { validateBooleanParameter(methodCall, data); } } return data; } private void validateBooleanParameter(ASTMethodCallExpression methodCall, Object data) { int numberOfChildren = methodCall.getNumChildren(); if (numberOfChildren == 3) { // addError('',false) Object potentialLiteral = methodCall.getChild(2); if (potentialLiteral instanceof ASTLiteralExpression) { ASTLiteralExpression parameter = (ASTLiteralExpression) potentialLiteral; if (parameter.isBoolean()) { boolean paramValue = Boolean.parseBoolean(parameter.getImage()); if (!paramValue) { validateLiteralPresence(methodCall, data); } } } } } private void validateLiteralPresence(ASTMethodCallExpression methodCall, Object data) { List<ASTVariableExpression> variables = methodCall.findDescendantsOfType(ASTVariableExpression.class); for (ASTVariableExpression v : variables) { addViolation(data, v); } } }
2,480
35.485294
110
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexXSSFromURLParamRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.HashSet; import java.util.List; import java.util.Set; import net.sourceforge.pmd.lang.apex.ast.ASTAssignmentExpression; import net.sourceforge.pmd.lang.apex.ast.ASTBinaryExpression; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; /** * Detects potential XSS when controller extracts a variable from URL query and * uses it without escaping first * * @author sergey.gorbaty * */ public class ApexXSSFromURLParamRule extends AbstractApexRule { private static final String[] URL_PARAMETER_METHOD = new String[] { "ApexPages", "currentPage", "getParameters", "get", }; private static final String[] HTML_ESCAPING = new String[] { "ESAPI", "encoder", "SFDC_HTMLENCODE" }; private static final String[] JS_ESCAPING = new String[] { "ESAPI", "encoder", "SFDC_JSENCODE" }; private static final String[] JSINHTML_ESCAPING = new String[] { "ESAPI", "encoder", "SFDC_JSINHTMLENCODE" }; private static final String[] URL_ESCAPING = new String[] { "ESAPI", "encoder", "SFDC_URLENCODE" }; private static final String[] STRING_HTML3 = new String[] { "String", "escapeHtml3" }; private static final String[] STRING_HTML4 = new String[] { "String", "escapeHtml4" }; private static final String[] STRING_XML = new String[] { "String", "escapeXml" }; private static final String[] STRING_ECMASCRIPT = new String[] { "String", "escapeEcmaScript" }; private static final String[] INTEGER_VALUEOF = new String[] { "Integer", "valueOf" }; private static final String[] ID_VALUEOF = new String[] { "ID", "valueOf" }; private static final String[] DOUBLE_VALUEOF = new String[] { "Double", "valueOf" }; private static final String[] BOOLEAN_VALUEOF = new String[] { "Boolean", "valueOf" }; private static final String[] STRING_ISEMPTY = new String[] { "String", "isEmpty" }; private static final String[] STRING_ISBLANK = new String[] { "String", "isBlank" }; private static final String[] STRING_ISNOTBLANK = new String[] { "String", "isNotBlank" }; private final Set<String> urlParameterStrings = new HashSet<>(); @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node) || Helper.isSystemLevelClass(node)) { return data; // stops all the rules } return super.visit(node, data); } @Override public Object visit(ASTAssignmentExpression node, Object data) { findTaintedVariables(node, data); processVariableAssignments(node, data, false); return data; } @Override public Object visit(ASTVariableDeclaration node, Object data) { findTaintedVariables(node, data); processVariableAssignments(node, data, true); return data; } @Override public Object visit(ASTFieldDeclaration node, Object data) { findTaintedVariables(node, data); processVariableAssignments(node, data, true); return data; } @Override public Object visit(ASTMethodCallExpression node, Object data) { processEscapingMethodCalls(node, data); processInlineMethodCalls(node, data, false); return data; } @Override public Object visit(ASTReturnStatement node, Object data) { ASTBinaryExpression binaryExpression = node.getFirstChildOfType(ASTBinaryExpression.class); if (binaryExpression != null) { processBinaryExpression(binaryExpression, data); } ASTMethodCallExpression methodCall = node.getFirstChildOfType(ASTMethodCallExpression.class); if (methodCall != null) { String retType = getReturnType(node); if ("string".equalsIgnoreCase(retType)) { processInlineMethodCalls(methodCall, data, true); } } List<ASTVariableExpression> nodes = node.findChildrenOfType(ASTVariableExpression.class); for (ASTVariableExpression varExpression : nodes) { if (urlParameterStrings.contains(Helper.getFQVariableName(varExpression))) { addViolation(data, nodes.get(0)); } } return data; } private String getReturnType(ASTReturnStatement node) { ASTMethod method = node.getFirstParentOfType(ASTMethod.class); if (method != null) { return method.getReturnType(); } return ""; } private boolean isEscapingMethod(ASTMethodCallExpression methodNode) { // escaping methods return Helper.isMethodCallChain(methodNode, HTML_ESCAPING) || Helper.isMethodCallChain(methodNode, JS_ESCAPING) || Helper.isMethodCallChain(methodNode, JSINHTML_ESCAPING) || Helper.isMethodCallChain(methodNode, URL_ESCAPING) || Helper.isMethodCallChain(methodNode, STRING_HTML3) || Helper.isMethodCallChain(methodNode, STRING_HTML4) || Helper.isMethodCallChain(methodNode, STRING_XML) || Helper.isMethodCallChain(methodNode, STRING_ECMASCRIPT) // safe casts that eliminate injection || Helper.isMethodCallChain(methodNode, INTEGER_VALUEOF) || Helper.isMethodCallChain(methodNode, DOUBLE_VALUEOF) || Helper.isMethodCallChain(methodNode, BOOLEAN_VALUEOF) || Helper.isMethodCallChain(methodNode, ID_VALUEOF) // safe boolean methods || Helper.isMethodCallChain(methodNode, STRING_ISEMPTY) || Helper.isMethodCallChain(methodNode, STRING_ISBLANK) || Helper.isMethodCallChain(methodNode, STRING_ISNOTBLANK); } private void processInlineMethodCalls(ASTMethodCallExpression methodNode, Object data, final boolean isNested) { ASTMethodCallExpression nestedCall = methodNode.getFirstChildOfType(ASTMethodCallExpression.class); if (nestedCall != null) { if (!isEscapingMethod(methodNode)) { processInlineMethodCalls(nestedCall, data, true); } } if (Helper.isMethodCallChain(methodNode, URL_PARAMETER_METHOD)) { if (isNested) { addViolation(data, methodNode); } } } private void findTaintedVariables(ApexNode<?> node, Object data) { final ASTMethodCallExpression right = node.getFirstChildOfType(ASTMethodCallExpression.class); // Looks for: (String) foo = // ApexPages.currentPage().getParameters().get(..) if (right != null) { if (Helper.isMethodCallChain(right, URL_PARAMETER_METHOD)) { ASTVariableExpression left = node.getFirstChildOfType(ASTVariableExpression.class); String varType = null; if (node instanceof ASTVariableDeclaration) { varType = ((ASTVariableDeclaration) node).getType(); } if (left != null) { if (varType == null || !"id".equalsIgnoreCase(varType)) { urlParameterStrings.add(Helper.getFQVariableName(left)); } } } processEscapingMethodCalls(right, data); } } private void processEscapingMethodCalls(ASTMethodCallExpression methodNode, Object data) { ASTMethodCallExpression nestedCall = methodNode.getFirstChildOfType(ASTMethodCallExpression.class); if (nestedCall != null) { processEscapingMethodCalls(nestedCall, data); } final ASTVariableExpression variable = methodNode.getFirstChildOfType(ASTVariableExpression.class); if (variable != null) { if (urlParameterStrings.contains(Helper.getFQVariableName(variable))) { if (!isEscapingMethod(methodNode)) { addViolation(data, variable); } } } } private void processVariableAssignments(ApexNode<?> node, Object data, final boolean reverseOrder) { ASTMethodCallExpression methodCallAssignment = node.getFirstChildOfType(ASTMethodCallExpression.class); if (methodCallAssignment != null) { String varType = null; if (node instanceof ASTVariableDeclaration) { varType = ((ASTVariableDeclaration) node).getType(); } if (varType == null || !"id".equalsIgnoreCase(varType)) { processInlineMethodCalls(methodCallAssignment, data, false); } } List<ASTVariableExpression> nodes = node.findChildrenOfType(ASTVariableExpression.class); switch (nodes.size()) { case 1: { // Look for: foo + bar final List<ASTBinaryExpression> ops = node.findChildrenOfType(ASTBinaryExpression.class); if (!ops.isEmpty()) { for (ASTBinaryExpression o : ops) { processBinaryExpression(o, data); } } } break; case 2: { // Look for: foo = bar; final ASTVariableExpression right = reverseOrder ? nodes.get(0) : nodes.get(1); if (urlParameterStrings.contains(Helper.getFQVariableName(right))) { addViolation(data, right); } } break; default: break; } } private void processBinaryExpression(ApexNode<?> node, Object data) { ASTBinaryExpression nestedBinaryExpression = node.getFirstChildOfType(ASTBinaryExpression.class); if (nestedBinaryExpression != null) { processBinaryExpression(nestedBinaryExpression, data); } ASTMethodCallExpression methodCallAssignment = node.getFirstChildOfType(ASTMethodCallExpression.class); if (methodCallAssignment != null) { processInlineMethodCalls(methodCallAssignment, data, true); } final List<ASTVariableExpression> nodes = node.findChildrenOfType(ASTVariableExpression.class); for (ASTVariableExpression n : nodes) { if (urlParameterStrings.contains(Helper.getFQVariableName(n))) { addViolation(data, n); } } } }
10,913
39.422222
119
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/security/ApexBadCryptoRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.security; import java.util.HashSet; import java.util.List; import java.util.Set; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTLiteralExpression; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; /** * Finds encryption schemes using hardcoded IV, hardcoded key * * @author sergey.gorbaty * */ public class ApexBadCryptoRule extends AbstractApexRule { private static final String VALUE_OF = "valueOf"; private static final String BLOB = "Blob"; private static final String ENCRYPT = "encrypt"; private static final String DECRYPT = "decrypt"; private static final String CRYPTO = "Crypto"; private static final String ENCRYPT_WITH_MANAGED_IV = "encryptWithManagedIV"; private static final String DECRYPT_WITH_MANAGED_IV = "decryptWithManagedIV"; private final Set<String> potentiallyStaticBlob = new HashSet<>(); public ApexBadCryptoRule() { addRuleChainVisit(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node)) { return data; } List<ASTFieldDeclaration> fieldDecl = node.findDescendantsOfType(ASTFieldDeclaration.class); for (ASTFieldDeclaration var : fieldDecl) { findSafeVariables(var); } List<ASTVariableDeclaration> variableDecl = node.findDescendantsOfType(ASTVariableDeclaration.class); for (ASTVariableDeclaration var : variableDecl) { findSafeVariables(var); } List<ASTMethodCallExpression> methodCalls = node.findDescendantsOfType(ASTMethodCallExpression.class); for (ASTMethodCallExpression methodCall : methodCalls) { if (Helper.isMethodName(methodCall, CRYPTO, ENCRYPT) || Helper.isMethodName(methodCall, CRYPTO, DECRYPT) || Helper.isMethodName(methodCall, CRYPTO, ENCRYPT_WITH_MANAGED_IV) || Helper.isMethodName(methodCall, CRYPTO, DECRYPT_WITH_MANAGED_IV)) { validateStaticIVorKey(methodCall, data); } } potentiallyStaticBlob.clear(); return data; } private void findSafeVariables(ApexNode<?> var) { ASTMethodCallExpression methodCall = var.getFirstChildOfType(ASTMethodCallExpression.class); if (methodCall != null && Helper.isMethodName(methodCall, BLOB, VALUE_OF)) { ASTVariableExpression variable = var.getFirstChildOfType(ASTVariableExpression.class); if (variable != null) { potentiallyStaticBlob.add(Helper.getFQVariableName(variable)); } } } private void validateStaticIVorKey(ASTMethodCallExpression methodCall, Object data) { // .encrypt('AES128', key, exampleIv, data); int numberOfChildren = methodCall.getNumChildren(); switch (numberOfChildren) { // matching signature to encrypt( case 5: Object potentialIV = methodCall.getChild(3); reportIfHardCoded(data, potentialIV); Object potentialKey = methodCall.getChild(2); reportIfHardCoded(data, potentialKey); break; // matching signature to encryptWithManagedIV( case 4: Object key = methodCall.getChild(2); reportIfHardCoded(data, key); break; default: break; } } private void reportIfHardCoded(Object data, Object potentialIV) { if (potentialIV instanceof ASTMethodCallExpression) { ASTMethodCallExpression expression = (ASTMethodCallExpression) potentialIV; if (expression.getNumChildren() > 1) { Object potentialStaticIV = expression.getChild(1); if (potentialStaticIV instanceof ASTLiteralExpression) { ASTLiteralExpression variable = (ASTLiteralExpression) potentialStaticIV; if (variable.isString()) { addViolation(data, variable); } } } } else if (potentialIV instanceof ASTVariableExpression) { ASTVariableExpression variable = (ASTVariableExpression) potentialIV; if (potentiallyStaticBlob.contains(Helper.getFQVariableName(variable))) { addViolation(data, variable); } } } }
4,924
37.779528
116
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/documentation/ApexDocRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.documentation; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTAnnotation; import net.sourceforge.pmd.lang.apex.ast.ASTFormalComment; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTParameter; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserInterface; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.document.Chars; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.properties.PropertyDescriptor; public class ApexDocRule extends AbstractApexRule { private static final Pattern DESCRIPTION_PATTERN = Pattern.compile("@description\\s"); private static final Pattern RETURN_PATTERN = Pattern.compile("@return\\s"); private static final Pattern PARAM_PATTERN = Pattern.compile("@param\\s+(\\w+)\\s"); private static final String MISSING_COMMENT_MESSAGE = "Missing ApexDoc comment"; private static final String MISSING_DESCRIPTION_MESSAGE = "Missing ApexDoc @description"; private static final String MISSING_RETURN_MESSAGE = "Missing ApexDoc @return"; private static final String UNEXPECTED_RETURN_MESSAGE = "Unexpected ApexDoc @return"; private static final String MISMATCHED_PARAM_MESSAGE = "Missing or mismatched ApexDoc @param"; private static final PropertyDescriptor<Boolean> REPORT_PRIVATE_DESCRIPTOR = booleanProperty("reportPrivate") .desc("Report private classes, methods and properties").defaultValue(false).build(); private static final PropertyDescriptor<Boolean> REPORT_PROTECTED_DESCRIPTOR = booleanProperty("reportProtected") .desc("Report protected classes, methods and properties").defaultValue(false).build(); private static final PropertyDescriptor<Boolean> REPORT_MISSING_DESCRIPTION_DESCRIPTOR = booleanProperty("reportMissingDescription") .desc("Report missing @description").defaultValue(true).build(); private static final PropertyDescriptor<Boolean> REPORT_PROPERTY_DESCRIPTOR = booleanProperty("reportProperty") .desc("Report properties without comments").defaultValue(true).build(); public ApexDocRule() { definePropertyDescriptor(REPORT_PRIVATE_DESCRIPTOR); definePropertyDescriptor(REPORT_PROTECTED_DESCRIPTOR); definePropertyDescriptor(REPORT_MISSING_DESCRIPTION_DESCRIPTOR); definePropertyDescriptor(REPORT_PROPERTY_DESCRIPTOR); } @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserClass.class, ASTUserInterface.class, ASTMethod.class, ASTProperty.class); } @Override public Object visit(ASTUserClass node, Object data) { handleClassOrInterface(node, data); return data; } @Override public Object visit(ASTUserInterface node, Object data) { handleClassOrInterface(node, data); return data; } @Override public Object visit(ASTMethod node, Object data) { if (node.getParent() instanceof ASTProperty) { // Skip property methods, doc is required on the property itself return data; } ApexDocComment comment = getApexDocComment(node); if (comment == null) { if (shouldHaveApexDocs(node)) { asCtx(data).addViolationWithMessage(node, MISSING_COMMENT_MESSAGE); } } else { if (getProperty(REPORT_MISSING_DESCRIPTION_DESCRIPTOR) && !comment.hasDescription) { asCtx(data).addViolationWithMessage(node, MISSING_DESCRIPTION_MESSAGE); } String returnType = node.getReturnType(); boolean shouldHaveReturn = !(returnType.isEmpty() || "void".equalsIgnoreCase(returnType)); if (comment.hasReturn != shouldHaveReturn) { if (shouldHaveReturn) { asCtx(data).addViolationWithMessage(node, MISSING_RETURN_MESSAGE); } else { asCtx(data).addViolationWithMessage(node, UNEXPECTED_RETURN_MESSAGE); } } // Collect parameter names in order final List<String> params = node.findChildrenOfType(ASTParameter.class) .stream().map(p -> p.getImage()).collect(Collectors.toList()); if (!comment.params.equals(params)) { asCtx(data).addViolationWithMessage(node, MISMATCHED_PARAM_MESSAGE); } } return data; } @Override public Object visit(ASTProperty node, Object data) { ApexDocComment comment = getApexDocComment(node); if (comment == null) { if (shouldHaveApexDocs(node)) { asCtx(data).addViolationWithMessage(node, MISSING_COMMENT_MESSAGE); } } else { if (getProperty(REPORT_MISSING_DESCRIPTION_DESCRIPTOR) && !comment.hasDescription) { asCtx(data).addViolationWithMessage(node, MISSING_DESCRIPTION_MESSAGE); } } return data; } private void handleClassOrInterface(ApexNode<?> node, Object data) { ApexDocComment comment = getApexDocComment(node); if (comment == null) { if (shouldHaveApexDocs(node)) { asCtx(data).addViolationWithMessage(node, MISSING_COMMENT_MESSAGE); } } else { if (getProperty(REPORT_MISSING_DESCRIPTION_DESCRIPTOR) && !comment.hasDescription) { asCtx(data).addViolationWithMessage(node, MISSING_DESCRIPTION_MESSAGE); } } } private boolean shouldHaveApexDocs(ApexNode<?> node) { if (!node.hasRealLoc()) { return false; } // is this a test? for (final ASTAnnotation annotation : node.findDescendantsOfType(ASTAnnotation.class)) { if ("IsTest".equals(annotation.getImage())) { return false; } } // is it a property? if (node instanceof ASTProperty && !getProperty(REPORT_PROPERTY_DESCRIPTOR)) { return false; } ASTModifierNode modifier = node.getFirstChildOfType(ASTModifierNode.class); if (modifier != null) { boolean flagPrivate = getProperty(REPORT_PRIVATE_DESCRIPTOR) && modifier.isPrivate(); boolean flagProtected = getProperty(REPORT_PROTECTED_DESCRIPTOR) && modifier.isProtected(); return (modifier.isPublic() || modifier.isGlobal() || flagPrivate || flagProtected) && !modifier.isOverride(); } return false; } private ApexDocComment getApexDocComment(ApexNode<?> node) { ASTFormalComment comment = node.getFirstChildOfType(ASTFormalComment.class); if (comment != null) { Chars token = comment.getToken(); boolean hasDescription = DESCRIPTION_PATTERN.matcher(token).find(); boolean hasReturn = RETURN_PATTERN.matcher(token).find(); List<String> params = new ArrayList<>(); Matcher paramMatcher = PARAM_PATTERN.matcher(token); while (paramMatcher.find()) { params.add(paramMatcher.group(1)); } return new ApexDocComment(hasDescription, hasReturn, params); } return null; } private static class ApexDocComment { boolean hasDescription; boolean hasReturn; List<String> params; ApexDocComment(boolean hasDescription, boolean hasReturn, List<String> params) { this.hasDescription = hasDescription; this.hasReturn = hasReturn; this.params = params; } } }
8,397
38.990476
123
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/errorprone/AvoidNonExistentAnnotationsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.errorprone; import net.sourceforge.pmd.lang.apex.ast.ASTAnnotation; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserEnum; import net.sourceforge.pmd.lang.apex.ast.ASTUserInterface; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; /** * Apex supported non existent annotations for legacy reasons. * In the future, use of such non-existent annotations could result in broken apex code that will not compile. * This will prevent users of garbage annotations from being able to use legitimate annotations added to apex in the future. * A full list of supported annotations can be found at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation.htm * * @author a.subramanian */ public class AvoidNonExistentAnnotationsRule extends AbstractApexRule { @Override public Object visit(final ASTUserClass node, final Object data) { checkForNonExistentAnnotation(node, node.getModifiers(), data); return super.visit(node, data); } @Override public Object visit(final ASTUserInterface node, final Object data) { checkForNonExistentAnnotation(node, node.getModifiers(), data); return super.visit(node, data); } @Override public Object visit(final ASTUserEnum node, final Object data) { checkForNonExistentAnnotation(node, node.getModifiers(), data); return super.visit(node, data); } @Override public Object visit(final ASTMethod node, final Object data) { return checkForNonExistentAnnotation(node, node.getModifiers(), data); } @Override public Object visit(final ASTProperty node, final Object data) { // may have nested methods, don't visit children return checkForNonExistentAnnotation(node, node.getModifiers(), data); } @Override public Object visit(final ASTField node, final Object data) { return checkForNonExistentAnnotation(node, node.getModifiers(), data); } private Object checkForNonExistentAnnotation(final ApexNode<?> node, final ASTModifierNode modifierNode, final Object data) { for (ASTAnnotation annotation : modifierNode.findChildrenOfType(ASTAnnotation.class)) { if (!annotation.isResolved()) { addViolationWithMessage(data, node, "Use of non existent annotations will lead to broken Apex code which will not compile in the future."); } } return data; } }
2,910
40.585714
156
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/errorprone/InaccessibleAuraEnabledGetterRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.errorprone; import java.util.List; import net.sourceforge.pmd.lang.apex.ast.ASTAnnotation; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; /** * In the Summer '21 release, a mandatory security update enforces access * modifiers on Apex properties in Lightning component markup. The update * prevents access to private or protected Apex getters from Aura and Lightning * Web Components. * * @author p.ozil */ public class InaccessibleAuraEnabledGetterRule extends AbstractApexRule { public InaccessibleAuraEnabledGetterRule() { addRuleChainVisit(ASTProperty.class); } @Override public Object visit(ASTProperty node, Object data) { // Find @AuraEnabled property ASTModifierNode propModifiers = node.getModifiers(); if (hasAuraEnabledAnnotation(propModifiers)) { // Find getters/setters if any List<ASTMethod> methods = node.findChildrenOfType(ASTMethod.class); for (ASTMethod method : methods) { // Find getter method if (!"void".equals(method.getReturnType())) { // Ensure getter is not private or protected ASTModifierNode methodModifiers = method.getModifiers(); if (isPrivate(methodModifiers) || isProtected(methodModifiers)) { addViolation(data, node); } } } } return data; } private boolean isPrivate(ASTModifierNode modifierNode) { return modifierNode != null && modifierNode.isPrivate(); } private boolean isProtected(ASTModifierNode modifierNode) { return modifierNode != null && modifierNode.isProtected(); } private boolean hasAuraEnabledAnnotation(ASTModifierNode modifierNode) { List<ASTAnnotation> annotations = modifierNode.findChildrenOfType(ASTAnnotation.class); for (ASTAnnotation annotation : annotations) { if (annotation.hasImageEqualTo("AuraEnabled")) { return true; } } return false; } }
2,413
34.5
95
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/errorprone/AvoidHardcodingIdRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.errorprone; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTLiteralExpression; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class AvoidHardcodingIdRule extends AbstractApexRule { private static final Pattern PATTERN = Pattern.compile("^[a-zA-Z0-9]{5}0[a-zA-Z0-9]{9}([a-zA-Z0-5]{3})?$"); private static final Map<String, Character> CHECKSUM_LOOKUP; static { final Map<String, Character> lookup = new HashMap<>(); final char[] chartable = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345".toCharArray(); for (int i = 0; i < chartable.length; i++) { lookup.put(String.format("%5s", Integer.toBinaryString(i)).replace(' ', '0'), chartable[i]); } CHECKSUM_LOOKUP = Collections.unmodifiableMap(lookup); } @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTLiteralExpression.class); } @Override public Object visit(ASTLiteralExpression node, Object data) { if (node.isString()) { String literal = node.getImage(); if (PATTERN.matcher(literal).matches()) { // 18-digit ids are just 15 digit ids + checksums, validate it or it's not an id if (literal.length() == 18 && !validateChecksum(literal)) { return data; } addViolation(data, node); } } return data; } /* * ID validation - sources: * https://stackoverflow.com/questions/9742913/validating-a-salesforce-id#answer-29299786 * https://gist.github.com/jeriley/36b29f7c46527af4532aaf092c90dd56 */ private boolean validateChecksum(String literal) { final String part1 = literal.substring(0, 5); final String part2 = literal.substring(5, 10); final String part3 = literal.substring(10, 15); final char checksum1 = checksum(part1); final char checksum2 = checksum(part2); final char checksum3 = checksum(part3); return literal.charAt(15) == checksum1 && literal.charAt(16) == checksum2 && literal.charAt(17) == checksum3; } private char checksum(String part) { final StringBuilder sb = new StringBuilder(5); for (int i = 4; i >= 0; i--) { sb.append(Character.isUpperCase(part.charAt(i)) ? '1' : '0'); } return CHECKSUM_LOOKUP.get(sb.toString()); } }
2,824
34.3125
111
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/errorprone/OverrideBothEqualsAndHashcodeRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.errorprone; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTParameter; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; public class OverrideBothEqualsAndHashcodeRule extends AbstractApexRule { public OverrideBothEqualsAndHashcodeRule() { addRuleChainVisit(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { ApexNode<?> equalsNode = null; ApexNode<?> hashNode = null; for (ASTMethod method : node.findChildrenOfType(ASTMethod.class)) { if (equalsNode == null && isEquals(method)) { equalsNode = method; } if (hashNode == null && isHashCode(method)) { hashNode = method; } if (hashNode != null && equalsNode != null) { break; } } if (equalsNode != null && hashNode == null) { addViolation(data, equalsNode); } else if (hashNode != null && equalsNode == null) { addViolation(data, hashNode); } return data; } private boolean isEquals(ASTMethod node) { int numParams = 0; String paramType = null; for (int ix = 0; ix < node.getNumChildren(); ix++) { ApexNode<?> sn = node.getChild(ix); if (sn instanceof ASTParameter) { numParams++; paramType = ((ASTParameter) sn).getType(); } } return numParams == 1 && "equals".equalsIgnoreCase(node.getImage()) && "Object".equalsIgnoreCase(paramType); } private boolean isHashCode(ASTMethod node) { int numParams = 0; for (int ix = 0; ix < node.getNumChildren(); ix++) { ApexNode<?> sn = node.getChild(ix); if (sn instanceof ASTParameter) { numParams++; } } return numParams == 0 && "hashCode".equalsIgnoreCase(node.getImage()); } }
2,252
31.652174
116
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/errorprone/ApexCSRFRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.errorprone; import net.sourceforge.pmd.lang.apex.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; /** * Constructor and init method might contain DML, which constitutes a CSRF * vulnerability * * @author sergey.gorbaty * */ public class ApexCSRFRule extends AbstractApexRule { public static final String INIT = "init"; private static final String STATIC_INITIALIZER = "<clinit>"; @Override public Object visit(ASTUserClass node, Object data) { if (Helper.isTestMethodOrClass(node) || Helper.isSystemLevelClass(node)) { return data; // stops all the rules } return super.visit(node, data); } @Override public Object visit(ASTMethod node, Object data) { if (!Helper.isTestMethodOrClass(node)) { checkForCSRF(node, data); } return data; } @Override public Object visit(ASTBlockStatement node, Object data) { if (node.getParent() instanceof ASTUserClass && Helper.foundAnyDML(node)) { addViolation(data, node); } return data; } private void checkForCSRF(ASTMethod node, Object data) { if (node.isConstructor() && Helper.foundAnyDML(node)) { addViolation(data, node); } String name = node.getImage(); if (isInitializerMethod(name) && Helper.foundAnyDML(node)) { addViolation(data, node); } } private boolean isInitializerMethod(String name) { return INIT.equalsIgnoreCase(name) || STATIC_INITIALIZER.equals(name); } }
1,900
28.703125
83
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/errorprone/MethodWithSameNameAsEnclosingClassRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.errorprone; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class MethodWithSameNameAsEnclosingClassRule extends AbstractApexRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { String className = node.getImage(); List<ASTMethod> methods = node.findDescendantsOfType(ASTMethod.class); for (ASTMethod m : methods) { String methodName = m.getImage(); if (!m.isConstructor() && methodName.equalsIgnoreCase(className)) { addViolation(data, m); } } return data; } }
1,141
26.853659
79
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/bestpractices/UnusedLocalVariableRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.bestpractices; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTLiteralExpression; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTReferenceExpression; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class UnusedLocalVariableRule extends AbstractApexRule { private static final Set<String> DATABASE_QUERY_METHODS = new HashSet<>(Arrays.asList( "Database.query".toLowerCase(Locale.ROOT), "Database.getQueryLocator".toLowerCase(Locale.ROOT), "Database.countQuery".toLowerCase(Locale.ROOT) )); private static final Pattern BINDING_VARIABLE = Pattern.compile("(?i):([a-z0-9]+)"); @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTVariableDeclaration.class); } @Override public Object visit(ASTVariableDeclaration node, Object data) { String variableName = node.getImage(); ASTBlockStatement variableContext = node.getFirstParentOfType(ASTBlockStatement.class); if (variableContext == null) { // if there is no parent BlockStatement, e.g. in triggers return data; } List<ApexNode<?>> potentialUsages = new ArrayList<>(); // Variable expression catch things like the `a` in `a + b` potentialUsages.addAll(variableContext.findDescendantsOfType(ASTVariableExpression.class)); // Reference expressions catch things like the `a` in `a.foo()` potentialUsages.addAll(variableContext.findDescendantsOfType(ASTReferenceExpression.class)); for (ApexNode<?> usage : potentialUsages) { if (usage.getParent() == node) { continue; } if (StringUtils.equalsIgnoreCase(variableName, usage.getImage())) { return data; } } List<String> soqlBindingVariables = findBindingsInSOQLStringLiterals(variableContext); if (soqlBindingVariables.contains(variableName.toLowerCase(Locale.ROOT))) { return data; } addViolation(data, node, variableName); return data; } private List<String> findBindingsInSOQLStringLiterals(ASTBlockStatement variableContext) { List<String> bindingVariables = new ArrayList<>(); List<ASTMethodCallExpression> methodCalls = variableContext.findDescendantsOfType(ASTMethodCallExpression.class) .stream() .filter(m -> DATABASE_QUERY_METHODS.contains(m.getFullMethodName().toLowerCase(Locale.ROOT))) .collect(Collectors.toList()); methodCalls.forEach(databaseMethodCall -> { List<String> stringLiterals = new ArrayList<>(); stringLiterals.addAll(databaseMethodCall.findDescendantsOfType(ASTLiteralExpression.class) .stream() .filter(ASTLiteralExpression::isString) .map(ASTLiteralExpression::getImage) .collect(Collectors.toList())); databaseMethodCall.findDescendantsOfType(ASTVariableExpression.class).forEach(variableUsage -> { String referencedVariable = variableUsage.getImage(); // Search other usages of the same variable within this code block variableContext.findDescendantsOfType(ASTVariableExpression.class) .stream() .filter(usage -> referencedVariable.equalsIgnoreCase(usage.getImage())) .forEach(usage -> { stringLiterals.addAll(usage.getParent() .findChildrenOfType(ASTLiteralExpression.class) .stream() .filter(ASTLiteralExpression::isString) .map(ASTLiteralExpression::getImage) .collect(Collectors.toList())); }); }); stringLiterals.forEach(s -> { Matcher matcher = BINDING_VARIABLE.matcher(s); while (matcher.find()) { bindingVariables.add(matcher.group(1).toLowerCase(Locale.ROOT)); } }); }); return bindingVariables; } }
5,151
40.548387
120
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/bestpractices/AvoidLogicInTriggerRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.bestpractices; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTUserTrigger; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class AvoidLogicInTriggerRule extends AbstractApexRule { @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserTrigger.class); } @Override public Object visit(ASTUserTrigger node, Object data) { List<ASTBlockStatement> blockStatements = node.findDescendantsOfType(ASTBlockStatement.class); if (!blockStatements.isEmpty()) { addViolation(data, node); } return data; } }
983
27.941176
102
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/bestpractices/ApexUnitTestClassShouldHaveAssertsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.bestpractices; import static net.sourceforge.pmd.properties.PropertyFactory.stringProperty; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import net.sourceforge.pmd.lang.apex.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTStatement; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexUnitTestRule; import net.sourceforge.pmd.properties.PropertyDescriptor; /** * Apex unit tests should have System.assert methods in them * * @author a.subramanian */ public class ApexUnitTestClassShouldHaveAssertsRule extends AbstractApexUnitTestRule { private static final Set<String> ASSERT_METHODS = new HashSet<>(); static { ASSERT_METHODS.add("system.assert"); ASSERT_METHODS.add("system.assertequals"); ASSERT_METHODS.add("system.assertnotequals"); ASSERT_METHODS.add("assert.areequal"); ASSERT_METHODS.add("assert.arenotequal"); ASSERT_METHODS.add("assert.fail"); ASSERT_METHODS.add("assert.isfalse"); ASSERT_METHODS.add("assert.isinstanceoftype"); ASSERT_METHODS.add("assert.isnotinstanceoftype"); ASSERT_METHODS.add("assert.isnull"); ASSERT_METHODS.add("assert.isnotnull"); ASSERT_METHODS.add("assert.istrue"); // Fully-qualified variants...rare but still valid/possible ASSERT_METHODS.add("system.system.assert"); ASSERT_METHODS.add("system.system.assertequals"); ASSERT_METHODS.add("system.system.assertnotequals"); ASSERT_METHODS.add("system.assert.areequal"); ASSERT_METHODS.add("system.assert.arenotequal"); ASSERT_METHODS.add("system.assert.fail"); ASSERT_METHODS.add("system.assert.isfalse"); ASSERT_METHODS.add("system.assert.isinstanceoftype"); ASSERT_METHODS.add("system.assert.isnotinstanceoftype"); ASSERT_METHODS.add("system.assert.isnull"); ASSERT_METHODS.add("system.assert.isnotnull"); ASSERT_METHODS.add("system.assert.istrue"); } // Using a string property instead of a regex property to ensure that the // compiled pattern can be case-insensitive private static final PropertyDescriptor<String> ADDITIONAL_ASSERT_METHOD_PATTERN_DESCRIPTOR = stringProperty( "additionalAssertMethodPattern") .desc("A regular expression for one or more custom test assertion method patterns.").defaultValue("") .build(); // A simple compiled pattern cache to ensure that we only ever try to compile // the configured pattern once for a given run private Optional<Pattern> compiledAdditionalAssertMethodPattern = null; public ApexUnitTestClassShouldHaveAssertsRule() { definePropertyDescriptor(ADDITIONAL_ASSERT_METHOD_PATTERN_DESCRIPTOR); } @Override public Object visit(ASTMethod node, Object data) { if (!isTestMethodOrClass(node)) { return data; } return checkForAssertStatements(node, data); } private Object checkForAssertStatements(ApexNode<?> node, Object data) { final List<ASTBlockStatement> blockStatements = node.findDescendantsOfType(ASTBlockStatement.class); final List<ASTStatement> statements = new ArrayList<>(); final List<ASTMethodCallExpression> methodCalls = new ArrayList<>(); for (ASTBlockStatement blockStatement : blockStatements) { statements.addAll(blockStatement.findDescendantsOfType(ASTStatement.class)); methodCalls.addAll(blockStatement.findDescendantsOfType(ASTMethodCallExpression.class)); } boolean isAssertFound = false; for (final ASTMethodCallExpression methodCallExpression : methodCalls) { if (ASSERT_METHODS.contains(methodCallExpression.getFullMethodName().toLowerCase(Locale.ROOT))) { isAssertFound = true; break; } } // If we didn't find assert method invocations the simple way and we have a // configured pattern, try it if (!isAssertFound) { final String additionalAssertMethodPattern = getProperty(ADDITIONAL_ASSERT_METHOD_PATTERN_DESCRIPTOR); final Pattern compiledPattern = getCompiledAdditionalAssertMethodPattern(additionalAssertMethodPattern); if (compiledPattern != null) { for (final ASTMethodCallExpression methodCallExpression : methodCalls) { final String fullMethodName = methodCallExpression.getFullMethodName(); if (compiledPattern.matcher(fullMethodName).matches()) { isAssertFound = true; break; } } } } if (!isAssertFound) { addViolation(data, node); } return data; } private Pattern getCompiledAdditionalAssertMethodPattern(String additionalAssertMethodPattern) { if (StringUtils.isNotBlank(additionalAssertMethodPattern)) { // Check for presence first since we will cache a null value for patterns that // don't compile if (compiledAdditionalAssertMethodPattern == null) { try { compiledAdditionalAssertMethodPattern = Optional .of(Pattern.compile(additionalAssertMethodPattern, Pattern.CASE_INSENSITIVE)); } catch (IllegalArgumentException e) { // Cache a null compiled pattern so that we won't try to compile this one again // during the run compiledAdditionalAssertMethodPattern = Optional.ofNullable(null); throw e; } } } return compiledAdditionalAssertMethodPattern != null ? compiledAdditionalAssertMethodPattern.get() : null; } }
6,323
41.72973
116
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/bestpractices/ApexUnitTestShouldNotUseSeeAllDataTrueRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.bestpractices; import java.util.List; import net.sourceforge.pmd.lang.apex.ast.ASTAnnotationParameter; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexUnitTestRule; /** * <p> * It's a very bad practice to use @isTest(seeAllData=true) in Apex unit tests, * because it opens up the existing database data for unexpected modification by * tests. * </p> * * @author a.subramanian */ public class ApexUnitTestShouldNotUseSeeAllDataTrueRule extends AbstractApexUnitTestRule { @Override public Object visit(final ASTUserClass node, final Object data) { // @isTest(seeAllData) was introduced in v24, and was set to false by default if (!isTestMethodOrClass(node)) { return data; } checkForSeeAllData(node, data); return super.visit(node, data); } @Override public Object visit(ASTMethod node, Object data) { if (!isTestMethodOrClass(node)) { return data; } return checkForSeeAllData(node, data); } private Object checkForSeeAllData(final ApexNode<?> node, final Object data) { final ASTModifierNode modifierNode = node.getFirstChildOfType(ASTModifierNode.class); if (modifierNode != null) { List<ASTAnnotationParameter> annotationParameters = modifierNode.findDescendantsOfType(ASTAnnotationParameter.class); for (ASTAnnotationParameter parameter : annotationParameters) { if (ASTAnnotationParameter.SEE_ALL_DATA.equals(parameter.getName()) && parameter.getBooleanValue()) { addViolation(data, node); return data; } } } return data; } }
2,061
31.730159
129
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/bestpractices/ApexUnitTestClassShouldHaveRunAsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.bestpractices; import java.util.List; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTRunAsBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexUnitTestRule; /** * Apex unit tests should have System.runAs methods in them * * @author t.prouvot */ public class ApexUnitTestClassShouldHaveRunAsRule extends AbstractApexUnitTestRule { @Override public Object visit(ASTMethod node, Object data) { if (!isTestMethodOrClass(node)) { return data; } return checkForRunAsStatements(node, data); } private Object checkForRunAsStatements(ApexNode<?> node, Object data) { final List<ASTRunAsBlockStatement> runAsStatements = node.findDescendantsOfType(ASTRunAsBlockStatement.class); if (runAsStatements.isEmpty()) { addViolation(data, node); } return data; } }
1,107
27.410256
118
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/bestpractices/ApexAssertionsShouldIncludeMessageRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.bestpractices; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.rule.AbstractApexUnitTestRule; public class ApexAssertionsShouldIncludeMessageRule extends AbstractApexUnitTestRule { private static final String ASSERT = "System.assert"; private static final String ASSERT_EQUALS = "System.assertEquals"; private static final String ASSERT_NOT_EQUALS = "System.assertNotEquals"; private static final String ARE_EQUAL = "Assert.areEqual"; private static final String ARE_NOT_EQUAL = "Assert.areNotEqual"; private static final String IS_FALSE = "Assert.isFalse"; private static final String FAIL = "Assert.fail"; private static final String IS_INSTANCE_OF_TYPE = "Assert.isInstanceOfType"; private static final String IS_NOT_INSTANCE_OF_TYPE = "Assert.isNotInstanceOfType"; private static final String IS_NOT_NULL = "Assert.isNotNull"; private static final String IS_NULL = "Assert.isNull"; private static final String IS_TRUE = "Assert.isTrue"; @Override public Object visit(ASTMethodCallExpression node, Object data) { String methodName = node.getFullMethodName(); if (FAIL.equalsIgnoreCase(methodName) && node.getNumChildren() == 1) { addViolationWithMessage(data, node, "''{0}'' should have 1 parameters.", new Object[] { FAIL }); } else if ((ASSERT.equalsIgnoreCase(methodName) || IS_FALSE.equalsIgnoreCase(methodName) || IS_NOT_NULL.equalsIgnoreCase(methodName) || IS_NULL.equalsIgnoreCase(methodName) || IS_TRUE.equalsIgnoreCase(methodName)) && node.getNumChildren() == 2) { addViolationWithMessage(data, node, "''{0}'' should have 2 parameters.", new Object[] { methodName }); } else if ((ASSERT_EQUALS.equalsIgnoreCase(methodName) || ASSERT_NOT_EQUALS.equalsIgnoreCase(methodName) || ARE_EQUAL.equalsIgnoreCase(methodName) || ARE_NOT_EQUAL.equalsIgnoreCase(methodName) || IS_INSTANCE_OF_TYPE.equalsIgnoreCase(methodName) || IS_NOT_INSTANCE_OF_TYPE.equalsIgnoreCase(methodName)) && node.getNumChildren() == 3) { addViolationWithMessage(data, node, "''{0}'' should have 3 parameters.", new Object[] { methodName }); } return data; } }
2,669
46.678571
87
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/bestpractices/AvoidGlobalModifierRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.bestpractices; import java.util.List; import net.sourceforge.pmd.lang.apex.ast.ASTAnnotation; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserInterface; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; public class AvoidGlobalModifierRule extends AbstractApexRule { @Override public Object visit(ASTUserClass node, Object data) { return checkForGlobal(node, data); } @Override public Object visit(ASTUserInterface node, Object data) { return checkForGlobal(node, data); } private Object checkForGlobal(ApexNode<?> node, Object data) { ASTModifierNode modifierNode = node.getFirstChildOfType(ASTModifierNode.class); if (isGlobal(modifierNode) && !hasRestAnnotation(modifierNode) && !hasWebServices(node)) { addViolation(data, node); } // Note, the rule reports the whole class, since that's enough and stops to visit right here. // It also doesn't use rulechain, since it the top level type needs to global. // if a member is global, that class has to be global as well to be valid apex. // See also https://github.com/pmd/pmd/issues/2298 return data; } private boolean hasWebServices(ApexNode<?> node) { List<ASTMethod> methods = node.findChildrenOfType(ASTMethod.class); for (ASTMethod method : methods) { ASTModifierNode methodModifier = method.getFirstChildOfType(ASTModifierNode.class); if (isWebService(methodModifier)) { return true; } } return false; } private boolean isWebService(ASTModifierNode modifierNode) { return modifierNode != null && modifierNode.isWebService(); } private boolean isGlobal(ASTModifierNode modifierNode) { return modifierNode != null && modifierNode.isGlobal(); } private boolean hasRestAnnotation(ASTModifierNode modifierNode) { List<ASTAnnotation> annotations = modifierNode.findChildrenOfType(ASTAnnotation.class); for (ASTAnnotation annotation : annotations) { if (annotation.hasImageEqualTo("RestResource")) { return true; } } return false; } }
2,583
34.888889
101
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/performance/AvoidSoslInLoopsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.performance; import net.sourceforge.pmd.lang.apex.ast.ASTSoslExpression; /** * @deprecated use {@link OperationWithLimitsInLoopRule} */ @Deprecated public class AvoidSoslInLoopsRule extends AbstractAvoidNodeInLoopsRule { @Override public Object visit(ASTSoslExpression node, Object data) { return checkForViolation(node, data); } }
489
23.5
79
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/performance/AvoidSoqlInLoopsRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.performance; import net.sourceforge.pmd.lang.apex.ast.ASTSoqlExpression; /** * @deprecated use {@link OperationWithLimitsInLoopRule} */ @Deprecated public class AvoidSoqlInLoopsRule extends AbstractAvoidNodeInLoopsRule { @Override public Object visit(ASTSoqlExpression node, Object data) { return checkForViolation(node, data); } }
488
23.45
79
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/performance/AvoidDmlStatementsInLoopsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.performance; import net.sourceforge.pmd.lang.apex.ast.ASTDmlDeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlInsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlMergeStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUndeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpdateStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpsertStatement; /** * @deprecated use {@link OperationWithLimitsInLoopRule} */ @Deprecated public class AvoidDmlStatementsInLoopsRule extends AbstractAvoidNodeInLoopsRule { // CPD-OFF - the same visits are in the replacement rule OperationWithLimitsInLoopRule @Override public Object visit(ASTDmlDeleteStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlInsertStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlMergeStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlUndeleteStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlUpdateStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlUpsertStatement node, Object data) { return checkForViolation(node, data); } // CPD-ON }
1,603
29.846154
90
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/performance/AbstractAvoidNodeInLoopsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.performance; import net.sourceforge.pmd.lang.apex.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDoLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForEachStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.apex.ast.ASTWhileLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.ast.Node; /** * Base class for any rules that detect operations contained within a loop that could be more efficiently executed by * refactoring the code into a batched execution. */ abstract class AbstractAvoidNodeInLoopsRule extends AbstractApexRule { /** * Adds a violation if any parent of {@code node} is a looping construct that would cause {@code node} to execute * multiple times and {@code node} is not part of a return statement that short circuits the loop. */ protected Object checkForViolation(ApexNode<?> node, Object data) { if (insideLoop(node) && parentNotReturn(node)) { addViolation(data, node); } return data; } /** * @return false if {@code node} is a direct child of a return statement. Children of return statements should not * result in a violation because the return short circuits the loop's execution. */ private boolean parentNotReturn(ApexNode<?> node) { return !(node.getParent() instanceof ASTReturnStatement); } /** * @return true if any parent of {@code node} is a construct that would cause {@code node} to execute multiple * times. */ private boolean insideLoop(Node node) { Node n = node.getParent(); while (n != null) { if (n instanceof ASTBlockStatement && n.getParent() instanceof ASTForEachStatement) { // only consider the block of the for-each statement, not the iterator return true; } if (n instanceof ASTDoLoopStatement || n instanceof ASTWhileLoopStatement || n instanceof ASTForLoopStatement) { return true; } n = n.getParent(); } return false; } }
2,449
37.888889
118
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/performance/OperationWithLimitsInLoopRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.performance; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTDmlDeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlInsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlMergeStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUndeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpdateStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTRunAsBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTSoqlExpression; import net.sourceforge.pmd.lang.apex.ast.ASTSoslExpression; import net.sourceforge.pmd.lang.apex.rule.internal.Helper; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; /** * Warn users when code that could trigger governor limits is executing within a looping construct. */ public class OperationWithLimitsInLoopRule extends AbstractAvoidNodeInLoopsRule { private static final String APPROVAL_CLASS_NAME = "Approval"; private static final String MESSAGING_CLASS_NAME = "Messaging"; private static final String SYSTEM_CLASS_NAME = "System"; private static final String[] MESSAGING_LIMIT_METHODS = new String[] { "renderEmailTemplate", "renderStoredEmailTemplate", "sendEmail" }; private static final String[] SYSTEM_LIMIT_METHODS = new String[] { "enqueueJob", "schedule", "scheduleBatch" }; @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes( // DML ASTDmlDeleteStatement.class, ASTDmlInsertStatement.class, ASTDmlMergeStatement.class, ASTDmlUndeleteStatement.class, ASTDmlUpdateStatement.class, ASTDmlUpsertStatement.class, // SOQL ASTSoqlExpression.class, // SOSL ASTSoslExpression.class, // Other limit consuming methods ASTMethodCallExpression.class, ASTRunAsBlockStatement.class ); } // Begin DML Statements @Override public Object visit(ASTDmlDeleteStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlInsertStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlMergeStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlUndeleteStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlUpdateStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTDmlUpsertStatement node, Object data) { return checkForViolation(node, data); } // End DML Statements // Begin SOQL method invocations @Override public Object visit(ASTSoqlExpression node, Object data) { return checkForViolation(node, data); } // End SOQL method invocations // Begin SOSL method invocations @Override public Object visit(ASTSoslExpression node, Object data) { return checkForViolation(node, data); } // End SOSL method invocations // Begin general method invocations @Override public Object visit(ASTRunAsBlockStatement node, Object data) { return checkForViolation(node, data); } @Override public Object visit(ASTMethodCallExpression node, Object data) { if (Helper.isAnyDatabaseMethodCall(node) || Helper.isMethodName(node, APPROVAL_CLASS_NAME, Helper.ANY_METHOD) || checkLimitClassMethods(node, MESSAGING_CLASS_NAME, MESSAGING_LIMIT_METHODS) || checkLimitClassMethods(node, SYSTEM_CLASS_NAME, SYSTEM_LIMIT_METHODS)) { return checkForViolation(node, data); } else { return data; } } private boolean checkLimitClassMethods(ASTMethodCallExpression node, String className, String[] methodNames) { for (String method : methodNames) { if (Helper.isMethodName(node, className, method)) { return true; } } return false; } // End general method invocations }
4,546
33.18797
141
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/codestyle/FieldDeclarationsShouldBeAtStartRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.codestyle; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; public class FieldDeclarationsShouldBeAtStartRule extends AbstractApexRule { private static final Comparator<ApexNode<?>> NODE_BY_SOURCE_LOCATION_COMPARATOR = Comparator .<ApexNode<?>>comparingInt(ApexNode::getBeginLine) .thenComparing(ApexNode::getBeginColumn); public static final String STATIC_INITIALIZER_METHOD_NAME = "<clinit>"; @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { // Unfortunately the parser re-orders the AST to put field declarations before method declarations // so we have to rely on line numbers / positions to work out where the first non-field declaration starts // so we can check if the fields are in acceptable places. List<ASTField> fields = node.findChildrenOfType(ASTField.class); List<ApexNode<?>> nonFieldDeclarations = new ArrayList<>(); nonFieldDeclarations.addAll(getMethodNodes(node)); nonFieldDeclarations.addAll(node.findChildrenOfType(ASTUserClass.class)); nonFieldDeclarations.addAll(node.findChildrenOfType(ASTProperty.class)); nonFieldDeclarations.addAll(node.findChildrenOfType(ASTBlockStatement.class)); Optional<ApexNode<?>> firstNonFieldDeclaration = nonFieldDeclarations.stream() .filter(ApexNode::hasRealLoc) .min(NODE_BY_SOURCE_LOCATION_COMPARATOR); if (!firstNonFieldDeclaration.isPresent()) { // there is nothing except field declaration, so that has to come first return data; } for (ASTField field : fields) { if (NODE_BY_SOURCE_LOCATION_COMPARATOR.compare(field, firstNonFieldDeclaration.get()) > 0) { addViolation(data, field, field.getName()); } } return data; } private List<ApexNode<?>> getMethodNodes(ASTUserClass node) { // The method <clinit> represents static initializer blocks, of which there can be many. The // <clinit> method doesn't contain location information, however the containing ASTBlockStatements do, // so we fetch them for that method only. return node.findChildrenOfType(ASTMethod.class).stream() .<ApexNode<?>>flatMap(method -> STATIC_INITIALIZER_METHOD_NAME.equals(method.getImage()) ? method.findChildrenOfType(ASTBlockStatement.class).stream() : Stream.of(method)) .collect(Collectors.toList()); } }
3,421
42.316456
114
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/codestyle/FormalParameterNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.codestyle; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTParameter; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.properties.PropertyDescriptor; public class FormalParameterNamingConventionsRule extends AbstractNamingConventionsRule { private static final Map<String, String> DESCRIPTOR_TO_DISPLAY_NAME = new HashMap<>(); private static final PropertyDescriptor<Pattern> FINAL_METHOD_PARAMETER_REGEX = prop("finalMethodParameterPattern", "final method parameter", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); private static final PropertyDescriptor<Pattern> METHOD_PARAMETER_REGEX = prop("methodParameterPattern", "method parameter", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); public FormalParameterNamingConventionsRule() { definePropertyDescriptor(FINAL_METHOD_PARAMETER_REGEX); definePropertyDescriptor(METHOD_PARAMETER_REGEX); } @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTParameter.class); } @Override public Object visit(ASTParameter node, Object data) { // classes that extend Exception will contains methods that have parameters with null names if (node.getImage() == null) { return data; } if (node.getModifiers().isFinal()) { checkMatches(FINAL_METHOD_PARAMETER_REGEX, node, data); } else { checkMatches(METHOD_PARAMETER_REGEX, node, data); } return data; } @Override protected String displayName(String name) { return DESCRIPTOR_TO_DISPLAY_NAME.get(name); } }
1,996
34.035088
145
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/codestyle/PropertyNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.codestyle; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.properties.PropertyDescriptor; public class PropertyNamingConventionsRule extends AbstractNamingConventionsRule { private static final Map<String, String> DESCRIPTOR_TO_DISPLAY_NAME = new HashMap<>(); private static final PropertyDescriptor<Pattern> STATIC_REGEX = prop("staticPattern", "static property", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); private static final PropertyDescriptor<Pattern> INSTANCE_REGEX = prop("instancePattern", "instance property", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); public PropertyNamingConventionsRule() { definePropertyDescriptor(STATIC_REGEX); definePropertyDescriptor(INSTANCE_REGEX); } @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTField.class); } @Override public Object visit(ASTField node, Object data) { if (node.getFirstParentOfType(ASTProperty.class) == null) { return data; } if (node.getModifiers().isStatic()) { checkMatches(STATIC_REGEX, node, data); } else { checkMatches(INSTANCE_REGEX, node, data); } return data; } @Override protected String displayName(String name) { return DESCRIPTOR_TO_DISPLAY_NAME.get(name); } }
1,857
30.491525
114
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/codestyle/MethodNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.codestyle; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.apex.ast.ASTUserEnum; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.properties.PropertyDescriptor; public class MethodNamingConventionsRule extends AbstractNamingConventionsRule { private static final Map<String, String> DESCRIPTOR_TO_DISPLAY_NAME = new HashMap<>(); private static final PropertyDescriptor<Pattern> TEST_REGEX = prop("testPattern", "test method", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); private static final PropertyDescriptor<Pattern> STATIC_REGEX = prop("staticPattern", "static method", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); private static final PropertyDescriptor<Pattern> INSTANCE_REGEX = prop("instancePattern", "instance method", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); private static final PropertyDescriptor<Boolean> SKIP_TEST_METHOD_UNDERSCORES_DESCRIPTOR = booleanProperty("skipTestMethodUnderscores") .desc("deprecated! Skip underscores in test methods") .defaultValue(false) .build(); public MethodNamingConventionsRule() { definePropertyDescriptor(SKIP_TEST_METHOD_UNDERSCORES_DESCRIPTOR); definePropertyDescriptor(TEST_REGEX); definePropertyDescriptor(STATIC_REGEX); definePropertyDescriptor(INSTANCE_REGEX); } @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTMethod.class); } @Override public Object visit(ASTMethod node, Object data) { if (isOverriddenMethod(node) || isPropertyAccessor(node) || isConstructor(node)) { return data; } if ("<clinit>".equals(node.getImage()) || "clone".equals(node.getImage())) { return data; } if (node.getFirstParentOfType(ASTUserEnum.class) != null) { return data; } if (node.getModifiers().isTest()) { if (getProperty(SKIP_TEST_METHOD_UNDERSCORES_DESCRIPTOR)) { checkMatches(TEST_REGEX, CAMEL_CASE_WITH_UNDERSCORES, node, data); } else { checkMatches(TEST_REGEX, node, data); } } else if (node.getModifiers().isStatic()) { checkMatches(STATIC_REGEX, node, data); } else { checkMatches(INSTANCE_REGEX, node, data); } return data; } @Override protected String displayName(String name) { return DESCRIPTOR_TO_DISPLAY_NAME.get(name); } private boolean isOverriddenMethod(ASTMethod node) { return node.getModifiers().isOverride(); } private boolean isPropertyAccessor(ASTMethod node) { return !node.getParentsOfType(ASTProperty.class).isEmpty(); } private boolean isConstructor(ASTMethod node) { return node.isConstructor(); } }
3,442
33.777778
112
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/codestyle/LocalVariableNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.codestyle; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclarationStatements; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.properties.PropertyDescriptor; public class LocalVariableNamingConventionsRule extends AbstractNamingConventionsRule { private static final Map<String, String> DESCRIPTOR_TO_DISPLAY_NAME = new HashMap<>(); private static final PropertyDescriptor<Pattern> FINAL_REGEX = prop("finalLocalPattern", "final local variable", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); private static final PropertyDescriptor<Pattern> LOCAL_REGEX = prop("localPattern", "local variable", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); public LocalVariableNamingConventionsRule() { definePropertyDescriptor(FINAL_REGEX); definePropertyDescriptor(LOCAL_REGEX); } @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTVariableDeclaration.class); } @Override public Object visit(ASTVariableDeclaration node, Object data) { if (node.getFirstParentOfType(ASTVariableDeclarationStatements.class).getModifiers().isFinal()) { checkMatches(FINAL_REGEX, node, data); } else { checkMatches(LOCAL_REGEX, node, data); } return data; } @Override protected String displayName(String name) { return DESCRIPTOR_TO_DISPLAY_NAME.get(name); } }
1,877
33.145455
116
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/codestyle/AbstractNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.codestyle; import static net.sourceforge.pmd.properties.PropertyFactory.regexProperty; import java.util.Map; import java.util.Objects; import java.util.regex.Pattern; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.properties.PropertyBuilder; import net.sourceforge.pmd.properties.PropertyDescriptor; abstract class AbstractNamingConventionsRule extends AbstractApexRule { protected static final Pattern CAMEL_CASE = Pattern.compile("[a-z][a-zA-Z0-9]*"); protected static final Pattern CAMEL_CASE_WITH_UNDERSCORES = Pattern.compile("[a-z][a-zA-Z0-9_]*"); protected static final Pattern PASCAL_CASE_WITH_UNDERSCORES = Pattern.compile("[A-Z][a-zA-Z0-9_]*"); protected static final Pattern ALL_CAPS = Pattern.compile("[A-Z][A-Z0-9_]*"); abstract String displayName(String name); protected void checkMatches(PropertyDescriptor<Pattern> propertyDescriptor, ApexNode<?> node, Object data) { checkMatches(propertyDescriptor, getProperty(propertyDescriptor), node, data); } protected void checkMatches(PropertyDescriptor<Pattern> propertyDescriptor, Pattern overridePattern, ApexNode<?> node, Object data) { String name = Objects.requireNonNull(node.getImage()); if (!overridePattern.matcher(name).matches()) { String displayName = displayName(propertyDescriptor.name()); addViolation(data, node, new Object[] { displayName, name, overridePattern.toString() }); } } protected static PropertyBuilder.RegexPropertyBuilder prop(String name, String displayName, Map<String, String> descriptorToDisplayNames) { descriptorToDisplayNames.put(name, displayName); return regexProperty(name).desc("Regex which applies to " + displayName + " names"); } }
1,982
45.116279
143
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/codestyle/FieldNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.codestyle; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.apex.ast.ASTUserEnum; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.properties.PropertyDescriptor; public class FieldNamingConventionsRule extends AbstractNamingConventionsRule { private static final Map<String, String> DESCRIPTOR_TO_DISPLAY_NAME = new HashMap<>(); private static final PropertyDescriptor<Pattern> ENUM_CONSTANT_REGEX = prop("enumConstantPattern", "enum constant field", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(ALL_CAPS).build(); private static final PropertyDescriptor<Pattern> CONSTANT_REGEX = prop("constantPattern", "constant field", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(ALL_CAPS).build(); private static final PropertyDescriptor<Pattern> FINAL_REGEX = prop("finalPattern", "final field", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); private static final PropertyDescriptor<Pattern> STATIC_REGEX = prop("staticPattern", "static field", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); private static final PropertyDescriptor<Pattern> INSTANCE_REGEX = prop("instancePattern", "instance field", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(CAMEL_CASE).build(); public FieldNamingConventionsRule() { definePropertyDescriptor(ENUM_CONSTANT_REGEX); definePropertyDescriptor(CONSTANT_REGEX); definePropertyDescriptor(FINAL_REGEX); definePropertyDescriptor(STATIC_REGEX); definePropertyDescriptor(INSTANCE_REGEX); } @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTField.class); } @Override public Object visit(ASTField node, Object data) { if (node.getFirstParentOfType(ASTProperty.class) != null) { return data; } ASTModifierNode modifiers = node.getModifiers(); if (node.getFirstParentOfType(ASTUserEnum.class) != null) { checkMatches(ENUM_CONSTANT_REGEX, node, data); } else if (modifiers.isFinal() && modifiers.isStatic()) { checkMatches(CONSTANT_REGEX, node, data); } else if (modifiers.isFinal()) { checkMatches(FINAL_REGEX, node, data); } else if (modifiers.isStatic()) { checkMatches(STATIC_REGEX, node, data); } else { checkMatches(INSTANCE_REGEX, node, data); } return data; } @Override protected String displayName(String name) { return DESCRIPTOR_TO_DISPLAY_NAME.get(name); } }
3,065
37.325
125
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/codestyle/ClassNamingConventionsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.codestyle; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserEnum; import net.sourceforge.pmd.lang.apex.ast.ASTUserInterface; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.properties.PropertyDescriptor; public class ClassNamingConventionsRule extends AbstractNamingConventionsRule { private static final Map<String, String> DESCRIPTOR_TO_DISPLAY_NAME = new HashMap<>(); private static final PropertyDescriptor<Pattern> TEST_CLASS_REGEX = prop("testClassPattern", "test class", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(PASCAL_CASE_WITH_UNDERSCORES).build(); private static final PropertyDescriptor<Pattern> ABSTRACT_CLASS_REGEX = prop("abstractClassPattern", "abstract class", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(PASCAL_CASE_WITH_UNDERSCORES).build(); private static final PropertyDescriptor<Pattern> CLASS_REGEX = prop("classPattern", "class", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(PASCAL_CASE_WITH_UNDERSCORES).build(); private static final PropertyDescriptor<Pattern> INTERFACE_REGEX = prop("interfacePattern", "interface", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(PASCAL_CASE_WITH_UNDERSCORES).build(); private static final PropertyDescriptor<Pattern> ENUM_REGEX = prop("enumPattern", "enum", DESCRIPTOR_TO_DISPLAY_NAME).defaultValue(PASCAL_CASE_WITH_UNDERSCORES).build(); public ClassNamingConventionsRule() { definePropertyDescriptor(TEST_CLASS_REGEX); definePropertyDescriptor(ABSTRACT_CLASS_REGEX); definePropertyDescriptor(CLASS_REGEX); definePropertyDescriptor(INTERFACE_REGEX); definePropertyDescriptor(ENUM_REGEX); } @Override protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserClass.class, ASTUserInterface.class, ASTUserEnum.class); } @Override public Object visit(ASTUserClass node, Object data) { if (node.getModifiers().isTest()) { checkMatches(TEST_CLASS_REGEX, node, data); } else if (node.getModifiers().isAbstract()) { checkMatches(ABSTRACT_CLASS_REGEX, node, data); } else { checkMatches(CLASS_REGEX, node, data); } return data; } @Override public Object visit(ASTUserInterface node, Object data) { checkMatches(INTERFACE_REGEX, node, data); return data; } @Override public Object visit(ASTUserEnum node, Object data) { checkMatches(ENUM_REGEX, node, data); return data; } @Override protected String displayName(String name) { return DESCRIPTOR_TO_DISPLAY_NAME.get(name); } }
3,054
36.256098
122
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/CognitiveComplexityRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.util.ArrayDeque; import java.util.Deque; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserTrigger; import net.sourceforge.pmd.lang.apex.metrics.ApexMetrics; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.metrics.MetricsUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; public class CognitiveComplexityRule extends AbstractApexRule { private static final PropertyDescriptor<Integer> CLASS_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("classReportLevel") .desc("Total class cognitive complexity reporting threshold") .require(positive()) .defaultValue(50) .build(); private static final PropertyDescriptor<Integer> METHOD_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("methodReportLevel") .desc("Cognitive complexity reporting threshold") .require(positive()) .defaultValue(15) .build(); private Deque<String> classNames = new ArrayDeque<>(); private boolean inTrigger; public CognitiveComplexityRule() { definePropertyDescriptor(CLASS_LEVEL_DESCRIPTOR); definePropertyDescriptor(METHOD_LEVEL_DESCRIPTOR); } @Override public Object visit(ASTUserTrigger node, Object data) { inTrigger = true; super.visit(node, data); inTrigger = false; return data; } @Override public Object visit(ASTUserClass node, Object data) { classNames.push(node.getImage()); super.visit(node, data); classNames.pop(); if (ApexMetrics.COGNITIVE_COMPLEXITY.supports(node)) { int classCognitive = MetricsUtil.computeMetric(ApexMetrics.COGNITIVE_COMPLEXITY, node); Integer classLevelThreshold = getProperty(CLASS_LEVEL_DESCRIPTOR); if (classCognitive >= classLevelThreshold) { int classHighest = (int) MetricsUtil.computeStatistics(ApexMetrics.COGNITIVE_COMPLEXITY, node.getMethods()).getMax(); String[] messageParams = { "class", node.getImage(), " total", classCognitive + " (highest " + classHighest + ")", String.valueOf(classLevelThreshold), }; addViolation(data, node, messageParams); } } return data; } @Override public final Object visit(ASTMethod node, Object data) { if (ApexMetrics.COGNITIVE_COMPLEXITY.supports(node)) { int cognitive = MetricsUtil.computeMetric(ApexMetrics.COGNITIVE_COMPLEXITY, node); Integer methodLevelThreshold = getProperty(METHOD_LEVEL_DESCRIPTOR); if (cognitive >= methodLevelThreshold) { String opType = inTrigger ? "trigger" : node.getImage().equals(classNames.peek()) ? "constructor" : "method"; addViolation(data, node, new String[] { opType, node.getQualifiedName().getOperation(), "", "" + cognitive, String.valueOf(methodLevelThreshold), }); } } return data; } }
3,715
32.781818
133
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/TooManyFieldsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.util.List; import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; public class TooManyFieldsRule extends AbstractApexRule { private static final int DEFAULT_MAXFIELDS = 15; 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 protected @NonNull RuleTargetSelector buildTargetSelector() { return RuleTargetSelector.forTypes(ASTUserClass.class); } @Override public Object visit(ASTUserClass node, Object data) { List<ASTField> fields = node.findChildrenOfType(ASTField.class); int val = 0; for (ASTField field : fields) { if (field.getModifiers().isFinal() && field.getModifiers().isStatic()) { continue; } val++; } if (val > getProperty(MAX_FIELDS_DESCRIPTOR)) { addViolation(data, node); } return data; } }
1,850
28.854839
85
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/AbstractNcssCountRule.java
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.apex.ast.ASTBreakStatement; import net.sourceforge.pmd.lang.apex.ast.ASTContinueStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDoLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTForEachStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTIfBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTIfElseBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTReturnStatement; import net.sourceforge.pmd.lang.apex.ast.ASTStatement; import net.sourceforge.pmd.lang.apex.ast.ASTThrowStatement; import net.sourceforge.pmd.lang.apex.ast.ASTTryCatchFinallyBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserEnum; import net.sourceforge.pmd.lang.apex.ast.ASTUserInterface; import net.sourceforge.pmd.lang.apex.ast.ASTWhileLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ApexNode; import net.sourceforge.pmd.lang.apex.ast.ApexVisitorBase; import net.sourceforge.pmd.lang.apex.rule.internal.AbstractCounterCheckRule; import net.sourceforge.pmd.lang.ast.Node; /** * Abstract superclass for NCSS counting methods. Counts tokens according to * <a href="http://www.kclee.de/clemens/java/javancss/">JavaNCSS rules</a>. * * @author ported from Java original of Jason Bennett * @deprecated Internal API */ @Deprecated @InternalApi public abstract class AbstractNcssCountRule<T extends ApexNode<?>> extends AbstractCounterCheckRule<T> { /** * Count the nodes of the given type using NCSS rules. * * @param nodeClass class of node to count */ protected AbstractNcssCountRule(Class<T> nodeClass) { super(nodeClass); } @Override protected int getMetric(T node) { return node.acceptVisitor(NcssVisitor.INSTANCE, null) + 1; } private static final class NcssVisitor extends ApexVisitorBase<Void, Integer> { // todo this would be better with a <MutableInt, Void> signature static final NcssVisitor INSTANCE = new NcssVisitor(); @Override public Integer visitApexNode(ApexNode<?> node, Void data) { return countNodeChildren(node, data); } @Override protected Integer visitChildren(Node node, Void data) { int v = 0; for (Node child : node.children()) { v += child.acceptVisitor(this, data); } return v; } /** * 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(ApexNode<?> node, Void data) { return visitChildren(node, data); } @Override public Integer visit(ASTForLoopStatement node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTForEachStatement node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTDoLoopStatement node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTIfBlockStatement node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTIfElseBlockStatement node, Void data) { return countNodeChildren(node, data) + 2; } @Override public Integer visit(ASTWhileLoopStatement node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTBreakStatement node, Void data) { return 1; } @Override public Integer visit(ASTTryCatchFinallyBlockStatement node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTContinueStatement node, Void data) { return 1; } @Override public Integer visit(ASTReturnStatement node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTThrowStatement node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTStatement node, Void data) { return 1; } @Override public Integer visit(ASTMethodCallExpression node, Void data) { return 1; } @Override public Integer visit(ASTMethod node, Void data) { return node.isSynthetic() ? 0 : countNodeChildren(node, data); } @Override public Integer visit(ASTUserClass node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTUserEnum node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTUserInterface node, Void data) { return countNodeChildren(node, data) + 1; } @Override public Integer visit(ASTFieldDeclaration node, Void data) { return 1; } } }
5,878
31.480663
104
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/NcssMethodCountRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; /** * Non-commented source statement counter for methods. * * @author ported from Java original of Jason Bennett */ public class NcssMethodCountRule extends AbstractNcssCountRule<ASTMethod> { /** * Count the size of all non-constructor methods. */ public NcssMethodCountRule() { super(ASTMethod.class); } @Override protected int defaultReportLevel() { return 40; } @Override protected boolean isIgnored(ASTMethod node) { return node.isConstructor(); } @Override protected Object[] getViolationParameters(ASTMethod node, int metric, int limit) { return new Object[]{ node.getImage(), metric, limit }; } }
896
22.605263
86
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/NcssConstructorCountRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; /** * Non-commented source statement counter for constructors. * * @author ported from Java original by Jason Bennett */ public class NcssConstructorCountRule extends AbstractNcssCountRule<ASTMethod> { /** * Count constructor declarations. This includes any explicit super() calls. */ public NcssConstructorCountRule() { super(ASTMethod.class); } @Override protected int defaultReportLevel() { return 20; } @Override protected boolean isIgnored(ASTMethod node) { return !node.isConstructor(); } }
768
22.30303
80
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/CyclomaticComplexityRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import java.util.ArrayDeque; import java.util.Deque; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserTrigger; import net.sourceforge.pmd.lang.apex.metrics.ApexMetrics; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.lang.metrics.MetricsUtil; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Cyclomatic complexity rule using metrics. Uses Wmc to report classes. * * @author Clément Fournier */ public class CyclomaticComplexityRule extends AbstractApexRule { private static final PropertyDescriptor<Integer> CLASS_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("classReportLevel") .desc("Total class complexity reporting threshold") .require(positive()) .defaultValue(40) .build(); private static final PropertyDescriptor<Integer> METHOD_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("methodReportLevel") .desc("Cyclomatic complexity reporting threshold") .require(positive()) .defaultValue(10) .build(); private Deque<String> classNames = new ArrayDeque<>(); private boolean inTrigger; public CyclomaticComplexityRule() { definePropertyDescriptor(CLASS_LEVEL_DESCRIPTOR); definePropertyDescriptor(METHOD_LEVEL_DESCRIPTOR); } @Override public Object visit(ASTUserTrigger node, Object data) { inTrigger = true; super.visit(node, data); inTrigger = false; return data; } @Override public Object visit(ASTUserClass node, Object data) { classNames.push(node.getImage()); super.visit(node, data); classNames.pop(); if (ApexMetrics.WEIGHED_METHOD_COUNT.supports(node)) { int classWmc = MetricsUtil.computeMetric(ApexMetrics.WEIGHED_METHOD_COUNT, node); if (classWmc >= getProperty(CLASS_LEVEL_DESCRIPTOR)) { int classHighest = (int) MetricsUtil.computeStatistics(ApexMetrics.CYCLO, node.getMethods()).getMax(); String[] messageParams = {"class", node.getImage(), " total", classWmc + " (highest " + classHighest + ")", }; addViolation(data, node, messageParams); } } return data; } @Override public final Object visit(ASTMethod node, Object data) { if (ApexMetrics.CYCLO.supports(node)) { int cyclo = MetricsUtil.computeMetric(ApexMetrics.CYCLO, node); if (cyclo >= getProperty(METHOD_LEVEL_DESCRIPTOR)) { String opType = inTrigger ? "trigger" : node.getImage().equals(classNames.peek()) ? "constructor" : "method"; addViolation(data, node, new String[] {opType, node.getQualifiedName().getOperation(), "", "" + cyclo, }); } } return data; } }
3,777
33.66055
118
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/NcssTypeCountRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; /** * Non-commented source statement counter for type declarations. * * @author ported from Java original of Jason Bennett */ public class NcssTypeCountRule extends AbstractNcssCountRule { /** * Count type declarations. This includes classes as well as enums and * annotations. */ public NcssTypeCountRule() { super(ASTUserClass.class); } @Override protected int defaultReportLevel() { return 500; } }
661
21.066667
79
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/ExcessiveClassLengthRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.rule.internal.AbstractCounterCheckRule; /** * This rule detects when a class exceeds a certain threshold. i.e. if a class * has more than 1000 lines of code. */ public class ExcessiveClassLengthRule extends AbstractCounterCheckRule.AbstractLineLengthCheckRule<ASTUserClass> { public ExcessiveClassLengthRule() { super(ASTUserClass.class); } @Override protected int defaultReportLevel() { return 1000; } @Override protected boolean isIgnored(ASTUserClass node) { return node.getModifiers().isTest(); } }
799
25.666667
114
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/UnusedMethodRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; public class UnusedMethodRule extends AbstractApexRule { @Override public Object visit(ASTMethod node, Object data) { // Check if any 'Unused' Issues align with this method node.getRoot().getGlobalIssues().stream() .filter(issue -> "Unused".equals(issue.category())) .filter(issue -> issue.fileLocation().startLineNumber() == node.getBeginLine()) .filter(issue -> issue.fileLocation().endLineNumber() <= node.getBeginLine()) .forEach(issue -> addViolation(data, node)); return data; } }
827
33.5
91
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/StdCyclomaticComplexityRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import static net.sourceforge.pmd.properties.PropertyFactory.booleanProperty; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange; import java.util.ArrayDeque; import java.util.Deque; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.apex.ast.ASTBooleanExpression; import net.sourceforge.pmd.lang.apex.ast.ASTDoLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForEachStatement; import net.sourceforge.pmd.lang.apex.ast.ASTForLoopStatement; import net.sourceforge.pmd.lang.apex.ast.ASTIfBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTTernaryExpression; import net.sourceforge.pmd.lang.apex.ast.ASTTryCatchFinallyBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTUserEnum; import net.sourceforge.pmd.lang.apex.ast.ASTUserInterface; import net.sourceforge.pmd.lang.apex.ast.ASTUserTrigger; import net.sourceforge.pmd.lang.apex.ast.ASTWhileLoopStatement; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; /** * Implements the standard cyclomatic complexity rule * <p> * Standard rules: +1 for each decision point, but not including boolean * operators unlike CyclomaticComplexityRule. * * @author ported on Java version of Alan Hohn, based on work by Donald A. * Leckie * * @since June 18, 2014 */ public class StdCyclomaticComplexityRule extends AbstractApexRule { public static final PropertyDescriptor<Integer> REPORT_LEVEL_DESCRIPTOR = PropertyFactory.intProperty("reportLevel") .desc("Cyclomatic Complexity reporting threshold") .require(inRange(1, 30)) .defaultValue(10) .build(); public static final PropertyDescriptor<Boolean> SHOW_CLASSES_COMPLEXITY_DESCRIPTOR = booleanProperty("showClassesComplexity").desc("Add class average violations to the report").defaultValue(true).build(); public static final PropertyDescriptor<Boolean> SHOW_METHODS_COMPLEXITY_DESCRIPTOR = booleanProperty("showMethodsComplexity").desc("Add method average violations to the report").defaultValue(true).build(); private int reportLevel; private boolean showClassesComplexity = true; private boolean showMethodsComplexity = true; protected static final class Entry { private int decisionPoints = 1; public int highestDecisionPoints; public int methodCount; private Entry() { } 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); } } protected Deque<Entry> entryStack = new ArrayDeque<>(); public StdCyclomaticComplexityRule() { definePropertyDescriptor(REPORT_LEVEL_DESCRIPTOR); definePropertyDescriptor(SHOW_CLASSES_COMPLEXITY_DESCRIPTOR); definePropertyDescriptor(SHOW_METHODS_COMPLEXITY_DESCRIPTOR); } @Override public void start(RuleContext ctx) { reportLevel = getProperty(REPORT_LEVEL_DESCRIPTOR); showClassesComplexity = getProperty(SHOW_CLASSES_COMPLEXITY_DESCRIPTOR); showMethodsComplexity = getProperty(SHOW_METHODS_COMPLEXITY_DESCRIPTOR); } @Override public Object visit(ASTUserClass node, Object data) { entryStack.push(new Entry()); super.visit(node, data); Entry classEntry = entryStack.pop(); 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(ASTUserTrigger node, Object data) { entryStack.push(new Entry()); super.visit(node, data); Entry classEntry = entryStack.pop(); if (showClassesComplexity) { if (classEntry.getComplexityAverage() >= reportLevel || classEntry.highestDecisionPoints >= reportLevel) { addViolation(data, node, new String[] { "trigger", node.getImage(), classEntry.getComplexityAverage() + " (Highest = " + classEntry.highestDecisionPoints + ')', }); } } return data; } @Override public Object visit(ASTUserInterface node, Object data) { return data; } @Override public Object visit(ASTUserEnum node, Object data) { return data; } @Override public Object visit(ASTMethod node, Object data) { if (!node.isSynthetic()) { entryStack.push(new Entry()); super.visit(node, data); Entry methodEntry = entryStack.pop(); int methodDecisionPoints = methodEntry.decisionPoints; Entry classEntry = entryStack.peek(); classEntry.methodCount++; classEntry.bumpDecisionPoints(methodDecisionPoints); if (methodDecisionPoints > classEntry.highestDecisionPoints) { classEntry.highestDecisionPoints = methodDecisionPoints; } if (showMethodsComplexity && methodEntry.decisionPoints >= reportLevel) { String methodType = node.isConstructor() ? "constructor" : "method"; addViolation(data, node, new String[] { methodType, node.getImage(), String.valueOf(methodEntry.decisionPoints) }); } } return data; } @Override public Object visit(ASTIfBlockStatement node, Object data) { entryStack.peek().bumpDecisionPoints(); super.visit(node, data); return data; } @Override public Object visit(ASTTryCatchFinallyBlockStatement node, Object data) { entryStack.peek().bumpDecisionPoints(); super.visit(node, data); return data; } @Override public Object visit(ASTForLoopStatement node, Object data) { entryStack.peek().bumpDecisionPoints(); super.visit(node, data); return data; } @Override public Object visit(ASTForEachStatement node, Object data) { entryStack.peek().bumpDecisionPoints(); super.visit(node, data); return data; } @Override public Object visit(ASTWhileLoopStatement node, Object data) { entryStack.peek().bumpDecisionPoints(); super.visit(node, data); return data; } @Override public Object visit(ASTDoLoopStatement node, Object data) { entryStack.peek().bumpDecisionPoints(); super.visit(node, data); return data; } @Override public Object visit(ASTTernaryExpression node, Object data) { entryStack.peek().bumpDecisionPoints(); super.visit(node, data); return data; } @Override public Object visit(ASTBooleanExpression node, Object data) { return data; } }
7,627
34.981132
209
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/AvoidDeeplyNestedIfStmtsRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive; import net.sourceforge.pmd.lang.apex.ast.ASTIfBlockStatement; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.rule.AbstractApexRule; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; public class AvoidDeeplyNestedIfStmtsRule extends AbstractApexRule { private int depth; private int depthLimit; private static final PropertyDescriptor<Integer> PROBLEM_DEPTH_DESCRIPTOR = PropertyFactory.intProperty("problemDepth") .desc("The if statement depth reporting threshold") .require(positive()).defaultValue(3).build(); public AvoidDeeplyNestedIfStmtsRule() { definePropertyDescriptor(PROBLEM_DEPTH_DESCRIPTOR); } @Override public Object visit(ASTUserClass node, Object data) { depth = 0; depthLimit = getProperty(PROBLEM_DEPTH_DESCRIPTOR); return super.visit(node, data); } @Override public Object visit(ASTIfBlockStatement node, Object data) { depth++; super.visit(node, data); if (depth == depthLimit) { addViolation(data, node); } depth--; return data; } }
1,505
28.529412
85
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/ExcessiveParameterListRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.rule.internal.AbstractCounterCheckRule; /** * 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<ASTMethod> { public ExcessiveParameterListRule() { super(ASTMethod.class); } @Override protected int defaultReportLevel() { return 4; } @Override protected int getMetric(ASTMethod node) { return node.getNode().getMethodInfo().getParameters().size(); } }
856
25.78125
85
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/design/ExcessivePublicCountRule.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.design; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclarationStatements; import net.sourceforge.pmd.lang.apex.ast.ASTMethod; import net.sourceforge.pmd.lang.apex.ast.ASTProperty; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.rule.internal.AbstractCounterCheckRule; /** * Rule attempts to count all public methods and public attributes * defined in a class. * * <p>If a class has a high number of public operations, it might be wise * to consider whether it would be appropriate to divide it into * subclasses.</p> * * <p>A large proportion of public members and operations means the class * has high potential to be affected by external classes. Futhermore, * increased effort will be required to thoroughly test the class.</p> * * @author ported from Java original of aglover */ public class ExcessivePublicCountRule extends AbstractCounterCheckRule<ASTUserClass> { public ExcessivePublicCountRule() { super(ASTUserClass.class); } @Override protected int defaultReportLevel() { return 20; } @Override protected int getMetric(ASTUserClass node) { int publicMethods = node.children(ASTMethod.class) .filter(it -> it.getModifiers().isPublic() && !it.isSynthetic()) .count(); int publicFields = node.children(ASTFieldDeclarationStatements.class) .filter(it -> it.getModifiers().isPublic() && !it.getModifiers().isStatic()) .count(); int publicProperties = node.children(ASTProperty.class) .filter(it -> it.getModifiers().isPublic() && !it.getModifiers().isStatic()) .count(); return publicFields + publicMethods + publicProperties; } @Override protected Object[] getViolationParameters(ASTUserClass node, int metric, int limit) { return new Object[] { node.getSimpleName(), metric, limit }; } }
2,190
34.33871
100
java
pmd
pmd-master/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/rule/internal/Helper.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.apex.rule.internal; import java.util.Arrays; import java.util.List; import java.util.Locale; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.apex.ast.ASTDmlDeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlInsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlMergeStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUndeleteStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpdateStatement; import net.sourceforge.pmd.lang.apex.ast.ASTDmlUpsertStatement; import net.sourceforge.pmd.lang.apex.ast.ASTField; import net.sourceforge.pmd.lang.apex.ast.ASTFieldDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression; import net.sourceforge.pmd.lang.apex.ast.ASTModifierNode; import net.sourceforge.pmd.lang.apex.ast.ASTNewKeyValueObjectExpression; import net.sourceforge.pmd.lang.apex.ast.ASTNewObjectExpression; import net.sourceforge.pmd.lang.apex.ast.ASTParameter; import net.sourceforge.pmd.lang.apex.ast.ASTReferenceExpression; import net.sourceforge.pmd.lang.apex.ast.ASTSoqlExpression; import net.sourceforge.pmd.lang.apex.ast.ASTSoslExpression; import net.sourceforge.pmd.lang.apex.ast.ASTUserClass; import net.sourceforge.pmd.lang.apex.ast.ASTVariableDeclaration; import net.sourceforge.pmd.lang.apex.ast.ASTVariableExpression; import net.sourceforge.pmd.lang.apex.ast.ApexNode; /** * Helper methods * * @author sergey.gorbaty * */ @InternalApi public final class Helper { public static final String ANY_METHOD = "*"; private static final String DATABASE_CLASS_NAME = "Database"; private Helper() { throw new AssertionError("Can't instantiate helper classes"); } public static boolean isTestMethodOrClass(final ApexNode<?> node) { final List<ASTModifierNode> modifierNode = node.findChildrenOfType(ASTModifierNode.class); for (final ASTModifierNode m : modifierNode) { if (m.isTest()) { return true; } } final String className = node.getDefiningType(); return className.endsWith("Test"); } public static boolean foundAnySOQLorSOSL(final ApexNode<?> node) { final List<ASTSoqlExpression> dmlSoqlExpression = node.findDescendantsOfType(ASTSoqlExpression.class); final List<ASTSoslExpression> dmlSoslExpression = node.findDescendantsOfType(ASTSoslExpression.class); return !dmlSoqlExpression.isEmpty() || !dmlSoslExpression.isEmpty(); } /** * Finds DML operations in a given node descendants' path * * @param node * * @return true if found DML operations in node descendants */ public static boolean foundAnyDML(final ApexNode<?> node) { final List<ASTDmlUpsertStatement> dmlUpsertStatement = node.findDescendantsOfType(ASTDmlUpsertStatement.class); final List<ASTDmlUpdateStatement> dmlUpdateStatement = node.findDescendantsOfType(ASTDmlUpdateStatement.class); final List<ASTDmlUndeleteStatement> dmlUndeleteStatement = node .findDescendantsOfType(ASTDmlUndeleteStatement.class); final List<ASTDmlMergeStatement> dmlMergeStatement = node.findDescendantsOfType(ASTDmlMergeStatement.class); final List<ASTDmlInsertStatement> dmlInsertStatement = node.findDescendantsOfType(ASTDmlInsertStatement.class); final List<ASTDmlDeleteStatement> dmlDeleteStatement = node.findDescendantsOfType(ASTDmlDeleteStatement.class); return !dmlUpsertStatement.isEmpty() || !dmlUpdateStatement.isEmpty() || !dmlUndeleteStatement.isEmpty() || !dmlMergeStatement.isEmpty() || !dmlInsertStatement.isEmpty() || !dmlDeleteStatement.isEmpty(); } public static boolean isMethodName(final ASTMethodCallExpression methodNode, final String className, final String methodName) { final ASTReferenceExpression reference = methodNode.getFirstChildOfType(ASTReferenceExpression.class); return reference != null && reference.getNames().size() == 1 && reference.getNames().get(0).equalsIgnoreCase(className) && (ANY_METHOD.equals(methodName) || isMethodName(methodNode, methodName)); } public static boolean isMethodName(final ASTMethodCallExpression m, final String methodName) { return m.getMethodName().equalsIgnoreCase(methodName); } public static boolean isMethodCallChain(final ASTMethodCallExpression methodNode, final String... methodNames) { String methodName = methodNames[methodNames.length - 1]; if (Helper.isMethodName(methodNode, methodName)) { final ASTReferenceExpression reference = methodNode.getFirstChildOfType(ASTReferenceExpression.class); if (reference != null) { final ASTMethodCallExpression nestedMethod = reference .getFirstChildOfType(ASTMethodCallExpression.class); if (nestedMethod != null) { String[] newMethodNames = Arrays.copyOf(methodNames, methodNames.length - 1); return isMethodCallChain(nestedMethod, newMethodNames); } else { String[] newClassName = Arrays.copyOf(methodNames, methodNames.length - 1); if (newClassName.length == 1) { return Helper.isMethodName(methodNode, newClassName[0], methodName); } } } } return false; } public static String getFQVariableName(final ASTVariableExpression variable) { final ASTReferenceExpression ref = variable.getFirstChildOfType(ASTReferenceExpression.class); String objectName = ""; if (ref != null && ref.getNames().size() == 1) { objectName = ref.getNames().get(0) + "."; } StringBuilder sb = new StringBuilder().append(variable.getDefiningType()).append(":").append(objectName) .append(variable.getImage()); return sb.toString(); } public static String getFQVariableName(final ASTVariableDeclaration variable) { StringBuilder sb = new StringBuilder().append(variable.getDefiningType()).append(":") .append(variable.getImage()); return sb.toString(); } public static String getFQVariableName(final ASTField variable) { StringBuilder sb = new StringBuilder() .append(variable.getDefiningType()).append(":") .append(variable.getName()); return sb.toString(); } static String getVariableType(final ASTField variable) { StringBuilder sb = new StringBuilder().append(variable.getDefiningType()).append(":") .append(variable.getName()); return sb.toString(); } public static String getFQVariableName(final ASTFieldDeclaration variable) { StringBuilder sb = new StringBuilder() .append(variable.getDefiningType()).append(":") .append(variable.getImage()); return sb.toString(); } public static String getFQVariableName(final ASTNewKeyValueObjectExpression variable) { StringBuilder sb = new StringBuilder() .append(variable.getDefiningType()).append(":") .append(variable.getType()); return sb.toString(); } public static String getFQVariableName(final ASTNewObjectExpression variable) { StringBuilder sb = new StringBuilder() .append(variable.getDefiningType()).append(":") .append(variable.getType()); return sb.toString(); } public static boolean isSystemLevelClass(ASTUserClass node) { List<String> interfaces = node.getInterfaceNames(); return interfaces.stream().anyMatch(Helper::isAllowed); } private static boolean isAllowed(String identifier) { switch (identifier.toLowerCase(Locale.ROOT)) { case "queueable": case "database.batchable": case "installhandler": return true; default: break; } return false; } public static String getFQVariableName(ASTParameter p) { StringBuilder sb = new StringBuilder(); sb.append(p.getDefiningType()).append(":").append(p.getImage()); return sb.toString(); } /** * @return true if {@code node} is an invocation of a {@code Database} method. */ public static boolean isAnyDatabaseMethodCall(ASTMethodCallExpression node) { return isMethodName(node, DATABASE_CLASS_NAME, ANY_METHOD); } }
8,729
41.585366
119
java