From 2e1e333dad056d961665bf0dd51f351bf961ecfc Mon Sep 17 00:00:00 2001 From: Robin Maisch Date: Tue, 26 Mar 2024 15:22:12 +0100 Subject: [PATCH] Improve documentation and consistency of type parameter naming --- .../src/main/java/de/jplag/Language.java | 15 -- .../src/main/java/de/jplag/TokenType.java | 2 - .../jplag/options/DefaultLanguageOption.java | 2 - .../java/de/jplag/options/LanguageOption.java | 2 - .../de/jplag/options/LanguageOptions.java | 6 - .../main/java/de/jplag/util/FileUtils.java | 2 - .../java/de/jplag/java_cpg/CpgAdapter.java | 2 +- .../de/jplag/java_cpg/JavaCpgLanguage.java | 30 +--- .../de/jplag/java_cpg/passes/DfgSortPass.kt | 4 +- .../java_cpg/passes/JTokenizationPass.java | 13 +- .../de/jplag/java_cpg/passes/PrintPass.kt | 12 +- .../java_cpg/token/ACpgNodeListener.java | 4 +- .../de/jplag/java_cpg/token/CpgToken.java | 4 +- .../java_cpg/token/CpgTokenConsumer.java | 7 +- .../jplag/java_cpg/token/TokenConsumer.java | 6 +- ...IVisitorExitor.java => VisitorExitor.java} | 2 +- .../transformation/GraphTransformation.java | 6 +- .../TransformationException.java | 2 +- .../TransformationRepository.java | 12 +- .../matching/PatternRepository.java | 2 +- .../transformation/matching/edges/AEdge.java | 32 ++-- .../matching/edges/CpgAttributeEdge.java | 14 +- .../matching/edges/CpgEdge.java | 45 +++--- .../matching/edges/CpgMultiEdge.java | 6 +- .../matching/edges/CpgNthEdge.java | 18 +-- .../transformation/matching/edges/Edges.java | 28 ++-- .../transformation/matching/edges/IEdge.java | 18 +-- .../matching/pattern/GraphPatternBuilder.java | 60 ++++---- .../matching/pattern/GraphPatternImpl.java | 4 +- .../matching/pattern/Match.java | 28 ++-- .../matching/pattern/MatchProperty.java | 5 +- .../matching/pattern/NodePattern.java | 4 +- .../matching/pattern/PatternRegistry.java | 62 +++----- .../matching/pattern/PatternUtil.java | 113 +++++++------- .../matching/pattern/SimpleGraphPattern.java | 10 +- .../pattern/WildcardGraphPattern.java | 50 +++---- .../operations/GraphOperationImpl.java | 17 +-- .../operations/RemoveOperation.java | 8 +- .../operations/ReplaceOperation.java | 4 +- .../operations/SetOperation.java | 19 ++- .../operations/TransformationUtil.java | 139 +++++++++--------- .../java/de/jplag/java_cpg/JavaBlockTest.java | 7 +- 42 files changed, 359 insertions(+), 467 deletions(-) rename languages/java-cpg/src/main/java/de/jplag/java_cpg/token/{IVisitorExitor.java => VisitorExitor.java} (92%) diff --git a/language-api/src/main/java/de/jplag/Language.java b/language-api/src/main/java/de/jplag/Language.java index 7253c3b72..ed5c1b306 100644 --- a/language-api/src/main/java/de/jplag/Language.java +++ b/language-api/src/main/java/de/jplag/Language.java @@ -8,32 +8,26 @@ /** * Common interface for all languages. Each language-front end must provide a concrete language implementation. - * @author robin - * @version $Id: $Id */ public interface Language { /** * Suffixes for the files containing code of the language. An empty array means all suffixes are valid. - * @return an array of {@link java.lang.String} objects */ String[] suffixes(); /** * Descriptive name of the language. - * @return a {@link java.lang.String} object */ String getName(); /** * Identifier of the language used for CLI options and dynamic loading. You should use some name within {@code [a-z_-]+} - * @return a {@link java.lang.String} object */ String getIdentifier(); /** * Minimum number of tokens required for a match. - * @return a int */ int minimumTokenMatch(); @@ -41,7 +35,6 @@ public interface Language { * Parses a set of files. Override this method, if you don't require normalization. * @param files are the files to parse. * @return the list of parsed JPlag tokens. - * @throws de.jplag.ParsingException if an error during parsing the files occurred. * @deprecated Replaced by {@link #parse(Set, boolean)} */ @Deprecated(forRemoval = true) @@ -54,14 +47,12 @@ default List parse(Set files) throws ParsingException { * @param files are the files to parse. * @param normalize True, if the tokens should be normalized * @return the list of parsed JPlag tokens. - * @throws de.jplag.ParsingException if an error during parsing the files occurred. */ List parse(Set files, boolean normalize) throws ParsingException; /** * Indicates whether the tokens returned by parse have semantic information added to them, i.e. whether the token * attribute semantics is null or not. - * @return a boolean */ default boolean tokensHaveSemantics() { return false; @@ -69,7 +60,6 @@ default boolean tokensHaveSemantics() { /** * Determines whether a fixed-width font should be used to display that language. - * @return a boolean */ default boolean isPreformatted() { return true; @@ -78,7 +68,6 @@ default boolean isPreformatted() { /** * Indicates whether the input files (code) should be used as representation in the report, or different files that form * a view on the input files. - * @return a boolean */ default boolean useViewFiles() { return false; @@ -86,7 +75,6 @@ default boolean useViewFiles() { /** * If the language uses representation files, this method returns the suffix used for the representation files. - * @return a {@link java.lang.String} object */ default String viewFileSuffix() { return ""; @@ -118,9 +106,6 @@ default List customizeSubmissionOrder(List submissions) { } /** - *

- * supportsNormalization. - *

* @return True, if this language supports token sequence normalization. This does not include other normalization * mechanisms that might be part of the language modules. */ diff --git a/language-api/src/main/java/de/jplag/TokenType.java b/language-api/src/main/java/de/jplag/TokenType.java index 214ffb663..4ae97c661 100644 --- a/language-api/src/main/java/de/jplag/TokenType.java +++ b/language-api/src/main/java/de/jplag/TokenType.java @@ -5,8 +5,6 @@ * be extracted from code written in that language. A token type is expected to be stateless, thus it is recommended to * use an enum or record. * @see SharedTokenType - * @author robin - * @version $Id: $Id */ public interface TokenType { /** diff --git a/language-api/src/main/java/de/jplag/options/DefaultLanguageOption.java b/language-api/src/main/java/de/jplag/options/DefaultLanguageOption.java index 21f978440..69afa519a 100644 --- a/language-api/src/main/java/de/jplag/options/DefaultLanguageOption.java +++ b/language-api/src/main/java/de/jplag/options/DefaultLanguageOption.java @@ -3,8 +3,6 @@ /** * Default implementation for {@link de.jplag.options.LanguageOption} * @param The type of the option - * @author robin - * @version $Id: $Id */ public class DefaultLanguageOption implements LanguageOption { private final OptionType type; diff --git a/language-api/src/main/java/de/jplag/options/LanguageOption.java b/language-api/src/main/java/de/jplag/options/LanguageOption.java index 8b0cca52f..04c79dc04 100644 --- a/language-api/src/main/java/de/jplag/options/LanguageOption.java +++ b/language-api/src/main/java/de/jplag/options/LanguageOption.java @@ -3,8 +3,6 @@ /** * A single language specific option. * @param The type of the options value - * @author robin - * @version $Id: $Id */ public interface LanguageOption { /** diff --git a/language-api/src/main/java/de/jplag/options/LanguageOptions.java b/language-api/src/main/java/de/jplag/options/LanguageOptions.java index 147733916..8f0bf2a7e 100644 --- a/language-api/src/main/java/de/jplag/options/LanguageOptions.java +++ b/language-api/src/main/java/de/jplag/options/LanguageOptions.java @@ -6,11 +6,8 @@ /** * Container for a languages options. Should be implemented per language. - * @author robin - * @version $Id: $Id */ public abstract class LanguageOptions { - /** Constant EMPTY_OPTIONS */ public static final LanguageOptions EMPTY_OPTIONS = new LanguageOptions() { }; @@ -76,9 +73,6 @@ protected LanguageOption createOption(OptionType type, String name) { } /** - *

- * getOptionsAsList. - *

* @return The list of all options */ public List> getOptionsAsList() { diff --git a/language-api/src/main/java/de/jplag/util/FileUtils.java b/language-api/src/main/java/de/jplag/util/FileUtils.java index 40ba8402b..75326fc6a 100644 --- a/language-api/src/main/java/de/jplag/util/FileUtils.java +++ b/language-api/src/main/java/de/jplag/util/FileUtils.java @@ -29,8 +29,6 @@ /** * Encapsulates various interactions with files to prevent issues with file encodings. - * @author robin - * @version $Id: $Id */ public class FileUtils { private static final Charset DEFAULT_OUTPUT_CHARSET = StandardCharsets.UTF_8; diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/CpgAdapter.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/CpgAdapter.java index c31f90809..8d6fb3c88 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/CpgAdapter.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/CpgAdapter.java @@ -28,7 +28,7 @@ public class CpgAdapter { private boolean reorderingEnabled = true; /** - * Constructor for CpgAdapter. + * Constructs a new CpgAdapter. * @param transformations a list of {@link GraphTransformation}s */ public CpgAdapter(GraphTransformation... transformations) { diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/JavaCpgLanguage.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/JavaCpgLanguage.java index db7c5b365..0af8f065d 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/JavaCpgLanguage.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/JavaCpgLanguage.java @@ -99,13 +99,8 @@ private GraphTransformation[] obligatoryTransformations() { * @return the array of recommended transformations */ public GraphTransformation[] standardTransformations() { - return new GraphTransformation[] {removeOptionalOfCall, // 1 - removeOptionalGetCall, // 2 - moveConstantToOnlyUsingClass, // 5 - inlineSingleUseVariable, // 7 - removeLibraryRecord, // 10 - removeEmptyRecord, // 15 - }; + return new GraphTransformation[] {removeOptionalOfCall, removeOptionalGetCall, moveConstantToOnlyUsingClass, inlineSingleUseVariable, + removeLibraryRecord, removeEmptyRecord,}; } /** @@ -113,23 +108,10 @@ public GraphTransformation[] standardTransformations() { * @return the array of all transformations */ public GraphTransformation[] allTransformations() { - return new GraphTransformation[] {ifWithNegatedConditionResolution, // 0 - forStatementToWhileStatement, // 1 - removeOptionalOfCall, // 2 - removeOptionalGetCall, // 3 - removeGetterMethod, // 4 - moveConstantToOnlyUsingClass, // 5 - inlineSingleUseConstant, // 6 - inlineSingleUseVariable, // 7 - removeEmptyDeclarationStatement, // 8 - removeImplicitStandardConstructor, // 9 - removeLibraryRecord, // 10 - removeLibraryField, // 11 - removeEmptyConstructor, // 12 - removeUnsupportedConstructor, // 13 - removeUnsupportedMethod, // 14 - removeEmptyRecord, // 15 - }; + return new GraphTransformation[] {ifWithNegatedConditionResolution, forStatementToWhileStatement, removeOptionalOfCall, removeOptionalGetCall, + removeGetterMethod, moveConstantToOnlyUsingClass, inlineSingleUseConstant, inlineSingleUseVariable, removeEmptyDeclarationStatement, + removeImplicitStandardConstructor, removeLibraryRecord, removeLibraryField, removeEmptyConstructor, removeUnsupportedConstructor, + removeUnsupportedMethod, removeEmptyRecord,}; } @Override diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/DfgSortPass.kt b/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/DfgSortPass.kt index af98aa9bd..6bab7e298 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/DfgSortPass.kt +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/DfgSortPass.kt @@ -410,7 +410,7 @@ class DfgSortPass(ctx: TranslationContext) : TranslationUnitPass(ctx) { it.end.prevEOGEdges.remove(it) } - // eogPred may be DummyNeighbor if + //rebuild EOG edges into the block eogPred.filterNot { it is DummyNeighbor } .filterNot { TransformationUtil.isEogSuccessor(it, newEntry) } .forEach { @@ -420,7 +420,7 @@ class DfgSortPass(ctx: TranslationContext) : TranslationUnitPass(ctx) { newEntry.addPrevEOG(edge) } - + //rebuild EOG edges out of the block val newExit = TransformationUtil.getEogBorders((parent.statements.last())).exits[0] if (exit != newExit) { newExit.nextEOGEdges.filter { it.end is DummyNeighbor }.forEach { diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/JTokenizationPass.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/JTokenizationPass.java index 44736dbf9..8efe253dd 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/JTokenizationPass.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/JTokenizationPass.java @@ -35,16 +35,13 @@ public class JTokenizationPass extends TranslationResultPass { Consumer> callback = null; /** - *

- * Constructor for JTokenizationPass. - *

- * @param ctx a {@link de.fraunhofer.aisec.cpg.TranslationContext} object + * Constructs a new JTokenizationPass. + * @param ctx the current {@link de.fraunhofer.aisec.cpg.TranslationContext} */ public JTokenizationPass(@NotNull TranslationContext ctx) { super(ctx); } - /** {@inheritDoc} */ @Override public void accept(TranslationResult translationResult) { tokenList.clear(); @@ -57,11 +54,7 @@ public void accept(TranslationResult translationResult) { callback.accept(tokenList); } - /** - *

- * cleanup. - *

- */ + @Override public void cleanup() { logger.info("Found {} tokens", tokenList.size()); } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/PrintPass.kt b/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/PrintPass.kt index d14cad2a3..620173caa 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/PrintPass.kt +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/passes/PrintPass.kt @@ -6,20 +6,12 @@ import de.fraunhofer.aisec.cpg.graph.declarations.TranslationUnitDeclaration import de.fraunhofer.aisec.cpg.helpers.SubgraphWalker import de.fraunhofer.aisec.cpg.passes.TranslationUnitPass import java.util.* -import java.util.function.Consumer -import kotlin.reflect.KClass /** * A pass that prints all found nodes to the console. */ class PrintPass(ctx: TranslationContext) : TranslationUnitPass(ctx) { - companion object { - @JvmStatic - val KClass: KClass = PrintPass::class - } - - override fun cleanup() {} override fun accept(translationUnitDeclaration: TranslationUnitDeclaration) { val graphWalker = SubgraphWalker.IterativeGraphWalker() @@ -36,4 +28,8 @@ class PrintPass(ctx: TranslationContext) : TranslationUnitPass(ctx) { graphWalker.iterate(node) } } + + override fun cleanup() { + // Nothing to do + } } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/ACpgNodeListener.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/ACpgNodeListener.java index 871d6711a..518d4ec35 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/ACpgNodeListener.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/ACpgNodeListener.java @@ -6,9 +6,9 @@ import de.fraunhofer.aisec.cpg.graph.statements.expressions.*; /** - * This class provides empty dummy implementations for {@link de.jplag.java_cpg.token.CpgNodeListener}s. + * This class provides empty dummy implementations for {@link CpgNodeListener}s. */ -public abstract class ACpgNodeListener extends IVisitorExitor { +public abstract class ACpgNodeListener extends VisitorExitor { /** * Creates a new {@link ACpgNodeListener}. diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/CpgToken.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/CpgToken.java index 14df9591c..ae7df9c17 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/CpgToken.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/CpgToken.java @@ -16,8 +16,8 @@ public class CpgToken extends Token { /** * Creates a new {@link CpgToken}. - * @param tokenType the {@link de.jplag.TokenType} - * @param file the {@link java.io.File} that contains the represented piece of code + * @param tokenType the {@link TokenType} + * @param file the {@link File} that contains the represented piece of code * @param startLine the starting line of the represented code * @param startColumn the starting column of the represented code * @param length the length of the represented code diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/CpgTokenConsumer.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/CpgTokenConsumer.java index 7fb1728ba..5197e2182 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/CpgTokenConsumer.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/CpgTokenConsumer.java @@ -10,6 +10,7 @@ import de.fraunhofer.aisec.cpg.graph.Node; import de.fraunhofer.aisec.cpg.sarif.PhysicalLocation; import de.fraunhofer.aisec.cpg.sarif.Region; +import de.jplag.Token; import de.jplag.TokenType; /** @@ -33,9 +34,9 @@ private static int calculateLength(Region region) { } /** - * Adds a new {@link de.jplag.Token} for the given {@link TokenType} and {@link Node}. - * @param type the {@link de.jplag.TokenType} - * @param node the represented {@link de.fraunhofer.aisec.cpg.graph.Node} + * Adds a new {@link Token} for the given {@link TokenType} and {@link Node}. + * @param type the {@link TokenType} + * @param node the represented {@link Node} * @param isEndToken true iff the token represents the end of a block */ public void addToken(TokenType type, Node node, boolean isEndToken) { diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/TokenConsumer.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/TokenConsumer.java index 6e92132f5..0170d0518 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/TokenConsumer.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/TokenConsumer.java @@ -3,10 +3,12 @@ import java.io.File; import de.fraunhofer.aisec.cpg.graph.Name; +import de.fraunhofer.aisec.cpg.graph.Node; +import de.jplag.Token; import de.jplag.TokenType; /** - * This interface represents classes that can consume and save {@link de.jplag.Token}s. + * This interface represents classes that can consume and save {@link Token}s. */ public interface TokenConsumer { @@ -17,7 +19,7 @@ public interface TokenConsumer { * @param startLine the line where the represented code starts * @param startColumn the column where the represented code starts * @param length The length of the represented code - * @param name the name of the represented {@link de.fraunhofer.aisec.cpg.graph.Node} + * @param name the name of the represented {@link Node} */ void addToken(TokenType type, File file, int startLine, int startColumn, int length, Name name); diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/IVisitorExitor.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/VisitorExitor.java similarity index 92% rename from languages/java-cpg/src/main/java/de/jplag/java_cpg/token/IVisitorExitor.java rename to languages/java-cpg/src/main/java/de/jplag/java_cpg/token/VisitorExitor.java index f14f5455e..f8d74c9a9 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/IVisitorExitor.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/token/VisitorExitor.java @@ -12,7 +12,7 @@ * of {@link IVisitor}. * @param the object type to visit and exit */ -public abstract class IVisitorExitor> extends IVisitor { +public abstract class VisitorExitor> extends IVisitor { private static final String EXIT_METHOD_IDENTIFIER = "exit"; diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/GraphTransformation.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/GraphTransformation.java index e08085a00..8458194fa 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/GraphTransformation.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/GraphTransformation.java @@ -25,13 +25,13 @@ public interface GraphTransformation { * Applies the transformation to the Graph represented by the given {@link Match} which indicates which {@link Node}s * shall be involved in the transformation. * @param match the match of this {@link GraphTransformation}'s source pattern to a concrete graph - * @param ctx a {@link TranslationContext} object + * @param ctx the current {@link TranslationContext} */ void apply(Match match, TranslationContext ctx); /** - * Gets the {@link ExecutionPhase} for this {@link GraphTransformation} - * @return a {@link ExecutionOrder} object + * Gets the {@link ExecutionOrder} for this {@link GraphTransformation} + * @return the execution order */ ExecutionOrder getExecutionOrder(); diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/TransformationException.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/TransformationException.java index 41b1948a9..e0d505fd0 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/TransformationException.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/TransformationException.java @@ -1,7 +1,7 @@ package de.jplag.java_cpg.transformation; /** - * An {@link java.lang.Exception} that relates to the Transformation process. + * An {@link Exception} that relates to the Transformation process. */ public class TransformationException extends RuntimeException { diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/TransformationRepository.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/TransformationRepository.java index d313f0b3e..12ab626df 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/TransformationRepository.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/TransformationRepository.java @@ -19,9 +19,7 @@ import de.jplag.java_cpg.transformation.matching.pattern.SimpleGraphPattern; /** - * Contains factory methods to create different {@link de.jplag.java_cpg.transformation.GraphTransformation}s. - * @author robin - * @version $Id: $Id + * Contains factory methods to create different {@link GraphTransformation}s. */ public class TransformationRepository { /* @@ -158,14 +156,6 @@ public SimpleGraphPattern build() { /** * Creates a {@link GraphTransformation} that replaces a {@link VariableDeclaration} of an unused variable by an * {@link EmptyStatement}. - *

- * May target the following edges:
- *

    - *
  • Statement --LOCALS*--> VariableDeclaration
  • - *
  • AssignExpression --DECLARATIONS*--> VariableDeclaration
  • - *
  • CatchClause --PARAMETER--> VariableDeclaration
  • - *
  • MethodDeclaration --RECEIVER--> VariableDeclaration
  • - *
* @return the graph transformation object */ private static GraphTransformation removeUnusedVariableDeclaration() { diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/PatternRepository.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/PatternRepository.java index 2218b3da8..68e479a97 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/PatternRepository.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/PatternRepository.java @@ -48,7 +48,7 @@ public GraphPattern build() { /** * Creates a {@link GraphPatternBuilder} for a setter method - * @return a {@link de.jplag.java_cpg.transformation.matching.pattern.GraphPatternBuilder} object + * @return the {@link GraphPatternBuilder} */ public static GraphPatternBuilder setterMethod() { return new GraphPatternBuilder() { diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/AEdge.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/AEdge.java index ce92522b5..132912ca9 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/AEdge.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/AEdge.java @@ -6,16 +6,16 @@ /** * This abstract class contains the method implementations common to all {@link IEdge}s. - * @param the source node type - * @param the target node type + * @param the source node type + * @param the related node type */ -public abstract class AEdge implements IEdge { +public abstract class AEdge implements IEdge { /** * The {@link EdgeCategory} of the edge. */ protected final EdgeCategory category; - private Class sourceClass; - private Class targetClass; + private Class sourceClass; + private Class relatedClass; /** * Creates a new AEdge of the given category @@ -37,16 +37,16 @@ public EdgeCategory getCategory() { * Gets the source node class of this edge. * @return the source node class */ - public Class getSourceClass() { + public Class getSourceClass() { return this.sourceClass; } /** - * Gets the target node class of this edge. - * @return the target node class + * Gets the related node class of this edge. + * @return the related node class */ - public Class getTargetClass() { - return targetClass; + public Class getRelatedClass() { + return relatedClass; } /** @@ -70,17 +70,11 @@ public boolean isReference() { return category == REFERENCE; } - /** - * {@inheritDoc} - */ - public void setSourceClass(Class sourceClass) { + public void setSourceClass(Class sourceClass) { this.sourceClass = sourceClass; } - /** - * {@inheritDoc} - */ - public void setTargetClass(Class targetClass) { - this.targetClass = targetClass; + public void setRelatedClass(Class relatedClass) { + this.relatedClass = relatedClass; } } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgAttributeEdge.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgAttributeEdge.java index 0bb8019a9..0cc8d7e87 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgAttributeEdge.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgAttributeEdge.java @@ -6,20 +6,22 @@ import de.fraunhofer.aisec.cpg.graph.Node; /** - * This represents a property, an object related to a node other than another node, e.g. a String name. + * This represents the relation to a property, i.e. an object related to a node other than another node, e.g. a String + * name. To avoid confusion with a {@link de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge}, which is an edge that has + * properties itself, this is called {@link CpgAttributeEdge}. * @param getter function to get the property * @param setter function to set the property - * @param the node type of the source + * @param the node type of the source node * @param

the type of the property */ -public record CpgAttributeEdge(Function getter, BiConsumer setter) { +public record CpgAttributeEdge(Function getter, BiConsumer setter) { /** * Gets the property related to the given node. - * @param s the source node + * @param t the source node * @return the property */ - public P get(S s) { - return getter.apply(s); + public P get(T t) { + return getter.apply(t); } } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgEdge.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgEdge.java index cca333d65..e96b6f018 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgEdge.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgEdge.java @@ -11,68 +11,69 @@ /** * This is a wrapper for a graph edge (with a 1:1 relation). - * @param The type of the source node - * @param The type of the target node + * @param The type of the source node + * @param The type of the related node */ -public class CpgEdge extends AEdge { - private final Function getter; - private final BiConsumer setter; +public class CpgEdge extends AEdge { + private final Function getter; + private final BiConsumer setter; /** - * Creates a new {@link CpgEdge} with a getter and setter for the target node. + * Creates a new {@link CpgEdge} with a getter and setter for the related node. * @param getter the getter * @param setter the setter * @param category the edge category */ - public CpgEdge(Function getter, BiConsumer setter, EdgeCategory category) { + public CpgEdge(Function getter, BiConsumer setter, EdgeCategory category) { super(category); this.getter = getter; this.setter = setter; } /** - * Creates a new {@link CpgEdge} with a getter and setter for the target node. + * Creates a new {@link CpgEdge} with a getter and setter for the related node. * @param getter the getter * @param setter the setter */ - public CpgEdge(Function getter, BiConsumer setter) { + public CpgEdge(Function getter, BiConsumer setter) { this(getter, setter, AST); } /** - * Creates a new list-valued {@link CpgEdge} with a getter and setter for the target node list. + * Creates a new list-valued {@link CpgEdge} with a getter and setter for the related node list. * @param getter the getter * @param setter the setter - * @param The type of the source node - * @param The type of the target node - * @return a {@link CpgEdge} object + * @param The type of the source node + * @param The type of the related node + * @return the new {@link CpgEdge} */ - public static CpgEdge listValued(Function> getter, BiConsumer> setter) { - return new CpgEdge<>(node -> getter.apply(node).get(0), (node, value) -> setter.accept(node, List.of(value))); + public static CpgEdge listValued(Function> getter, BiConsumer> setter) { + // used only for assignment left-hand sides and right-hand sides, where in Java only one value is allowed + return new CpgEdge<>(node -> getter.apply(node).getFirst(), (node, value) -> setter.accept(node, List.of(value))); } /** - * Gets the target node of this edge starting from the given source node. + * Gets the related node of this edge starting from the given source node. * @param from the source node - * @return the target node + * @return the related node */ - public T getRelated(S from) { + public R getRelated(T from) { return getter.apply(from); } /** - * Gets the getter function of this {@link CpgEdge}, used to get the targets from a given source. + * Gets the getter function of this {@link CpgEdge}, used to get the relateds from a given source. * @return the getter */ - public Function getter() { + public Function getter() { return getter; } /** - * Gets the setter function of this {@link CpgEdge}, used to set the targets for a given source. + * Gets the setter function of this {@link CpgEdge}, used to set the relateds for a given source. * @return the setter */ - public BiConsumer setter() { + public BiConsumer setter() { return setter; } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgMultiEdge.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgMultiEdge.java index 6b5a06fdb..93dce6e31 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgMultiEdge.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgMultiEdge.java @@ -25,7 +25,7 @@ public final class CpgMultiEdge extends AEdge setter; private final Map, AnyOfNEdge> any1ofNEdges; private final ValueType valueType; - private HashMap, Integer> sequenceNodes; + private final HashMap, Integer> sequenceNodes; /** * Creates a new CpgMultiEdge. @@ -62,7 +62,7 @@ public static CpgMultiEdge edgeValued(Fun * A shorthand to create an edge-valued {@link CpgMultiEdge}. * @param getter a function to get all the edges * @param category the category of the edge - * @param The type of the target node + * @param The type of the target node * @param The type of the related node * @return the new {@link CpgMultiEdge} */ @@ -119,7 +119,7 @@ public void saveSequenceIndex(NodePattern pattern, int idx) { /** * Gets the setter function of this multi edge. - * @return a {@link TriConsumer} object + * @return the setter */ public TriConsumer setter() { return setter; diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgNthEdge.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgNthEdge.java index 02a0cc7ba..fbccdff70 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgNthEdge.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/CpgNthEdge.java @@ -1,15 +1,15 @@ package de.jplag.java_cpg.transformation.matching.edges; import de.fraunhofer.aisec.cpg.graph.Node; +import de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge; /** - * A {@link CpgNthEdge} represents an individual {@link de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge} out of a - * {@link CpgMultiEdge}. - * @param source node type - * @param target node type + * A {@link CpgNthEdge} represents an individual {@link PropertyEdge} out of a {@link CpgMultiEdge}. + * @param source node type + * @param target node type */ -public class CpgNthEdge extends CpgEdge { - private final CpgMultiEdge multiEdge; +public class CpgNthEdge extends CpgEdge { + private final CpgMultiEdge multiEdge; private final int index; /** @@ -17,12 +17,12 @@ public class CpgNthEdge extends CpgEdge { * @param edge The {@link CpgMultiEdge} that represents multiple edges * @param index The index of this edge */ - public CpgNthEdge(CpgMultiEdge edge, int index) { + public CpgNthEdge(CpgMultiEdge edge, int index) { super(t -> edge.getAllTargets(t).get(index), (t, r) -> edge.setter().accept(t, index, r), edge.getCategory()); this.multiEdge = edge; this.index = index; this.setSourceClass(edge.getSourceClass()); - this.setTargetClass(edge.getTargetClass()); + this.setRelatedClass(edge.getRelatedClass()); } @Override @@ -37,7 +37,7 @@ public boolean isEquivalentTo(IEdge other) { * Returns the multi edge object of which this edge is one. * @return the multi edge */ - public CpgMultiEdge getMultiEdge() { + public CpgMultiEdge getMultiEdge() { return multiEdge; } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/Edges.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/Edges.java index ffaeb22a3..1100cc9e0 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/Edges.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/Edges.java @@ -30,11 +30,11 @@ public class Edges { /** * A {@link Map} to retrieve all {@link IEdge}s with a specific source type. */ - private static final Map, List>> fromType; + private static final Map, List>> edgesBySourceType; /** * A {@link Map} to retrieve all {@link IEdge}s with a specific target type. */ - private static final Map, List>> toType; + private static final Map, List>> edgesByTargetType; public static final CpgEdge ASSIGN_EXPRESSION__LHS = CpgEdge.listValued(AssignExpression::getLhs, AssignExpression::setLhs); @@ -135,8 +135,8 @@ public class Edges { DoStatement::setCondition); static { - fromType = new HashMap<>(); - toType = new HashMap<>(); + edgesBySourceType = new HashMap<>(); + edgesByTargetType = new HashMap<>(); register(ASSIGN_EXPRESSION__LHS, AssignExpression.class, Expression.class); register(ASSIGN_EXPRESSION__RHS, AssignExpression.class, Expression.class); @@ -184,25 +184,25 @@ private Edges() { * @param edge the edge * @param sClass node class of the edge source * @param tClass node class of the edge target - * @param type of the edge source - * @param type of the edge target + * @param type of the edge source + * @param type of the related node */ - private static void register(IEdge edge, Class sClass, Class tClass) { + private static void register(IEdge edge, Class sClass, Class tClass) { edge.setSourceClass(sClass); - edge.setTargetClass(tClass); - fromType.computeIfAbsent(sClass, c -> new ArrayList<>()).add(edge); - toType.computeIfAbsent(tClass, c -> new ArrayList<>()).add(edge); + edge.setRelatedClass(tClass); + edgesBySourceType.computeIfAbsent(sClass, c -> new ArrayList<>()).add(edge); + edgesByTargetType.computeIfAbsent(tClass, c -> new ArrayList<>()).add(edge); } /** * Gets the list of edges with the given node class as target. * @param tClass the target node class - * @param the target node type + * @param the related node type */ - public static void getEdgesToType(Class tClass, Consumer> consumer) { - Class type = tClass; + public static void getEdgesToType(Class tClass, Consumer> consumer) { + Class type = tClass; while (Node.class.isAssignableFrom(type)) { - toType.getOrDefault(type, List.of()).stream().map(e -> (IEdge) e).forEach(consumer); + edgesByTargetType.getOrDefault(type, List.of()).stream().map(e -> (IEdge) e).forEach(consumer); type = getSuperclass(type); } } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/IEdge.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/IEdge.java index b3c7b690b..8213d9318 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/IEdge.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/edges/IEdge.java @@ -6,34 +6,34 @@ /** * This serves as an interface to wrap any kind of {@link PropertyEdge}. - * @param the source node type - * @param the target node type + * @param the source node type + * @param the related node type */ -public interface IEdge { +public interface IEdge { /** * Sets the class object representing the source {@link Node} type. * @param sourceClass the source {@link Node} class */ - void setSourceClass(Class sourceClass); + void setSourceClass(Class sourceClass); /** - * Sets the class object representing the target {@link Node} type. - * @param targetClass the target {@link Node} class + * Sets the class object representing the related {@link Node} type. + * @param relatedClass the related {@link Node} class */ - void setTargetClass(Class targetClass); + void setRelatedClass(Class relatedClass); /** * Gets the class object representing the source {@link Node} type. * @return the source {@link Node} class */ - Class getSourceClass(); + Class getSourceClass(); /** * Gets the class object representing the target {@link Node} type. * @return the target {@link Node} class */ - Class getTargetClass(); + Class getRelatedClass(); /** * If true, this edge should be treated as equivalent to this one in the context of stepping through the source and diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/GraphPatternBuilder.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/GraphPatternBuilder.java index 464b65be2..f1a3aa7c8 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/GraphPatternBuilder.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/GraphPatternBuilder.java @@ -56,11 +56,11 @@ private static NodePattern createNodePattern(Class tClass * attribute of a matching {@link Node} must be equal to the same attribute of another {@link Node}. * @param propertyEdge the property edge * @param otherRole the role of the other {@link NodePattern} - * @param the {@link Node} type + * @param the {@link Node} type * @param

the attribute type - * @return the {@link PatternModification} + * @return the pattern modification */ - public static PatternModification equalAttributes(CpgAttributeEdge propertyEdge, Class sClass, Role otherRole) { + public static PatternModification equalAttributes(CpgAttributeEdge propertyEdge, Class sClass, Role otherRole) { return new AddEqualAttributes<>(propertyEdge, sClass, otherRole); } @@ -69,10 +69,10 @@ public static PatternModification equalAttributes(CpgAttr * value is unchanged between the evaluation of the two given {@link Node}s. * @param startRole the role of the starting node role * @param endRole the role of the end node role - * @param the type of - * @return the {@link PatternModification} + * @param the type of + * @return the pattern modification */ - public static PatternModification assignedValueStableBetween(Role startRole, Role endRole) { + public static PatternModification assignedValueStableBetween(Role startRole, Role endRole) { return new AddAssignedValueStableBetween<>(startRole, endRole); } @@ -80,10 +80,10 @@ public static PatternModification assignedValueStableBetween * Creates a {@link PatternModification} that adds a {@link Predicate} property to a {@link NodePattern} that specifies * that matching {@link Node}s not be equal to the {@link Node} given by the role. * @param otherRole the role of the other {@link Node} - * @param the {@link Node} type of the target node + * @param the {@link Node} type of the target node * @return the pattern modification */ - public static PatternModification notEqualTo(Role otherRole) { + public static PatternModification notEqualTo(Role otherRole) { return new AddNotEqualTo<>(otherRole); } @@ -139,7 +139,7 @@ protected SimpleGraphPattern emptyWildcardParent() { * @param the type of source node * @param the type of related node, defined by the edge * @param the concrete type of related node - * @return the patterns modification + * @return the pattern modification */ @SafeVarargs public final PatternModification forAllRelated(CpgMultiEdge multiEdge, Class cClass, @@ -174,7 +174,7 @@ public final PatternListModification node(Class cClass, R * Creates a {@link PatternModification} to add a property to a {@link NodePattern}. * @param property the predicate establishing the property * @param the target {@link Node} type - * @return the patterns modification + * @return the pattern modification */ public final PatternModification property(Predicate property) { return new AddProperty<>(property); @@ -190,7 +190,7 @@ public final PatternModification property(Predicate prope * @param the type of the source node patterns * @param the type of the relation target, defined by the edge * @param the concrete type of the related node patterns - * @return the patterns modification object + * @return the pattern modification object */ @SafeVarargs public final PatternModification related(CpgEdge edge, Class rClass, Role role, @@ -208,7 +208,7 @@ public final PatternModification the type of the source node patterns * @param the type of the relation target, defined by the edge * @param the concrete type of the related node patterns - * @return the patterns modification object + * @return the pattern modification object */ @SafeVarargs public final PatternModification related1ToN(CpgMultiEdge edge, Class rClass, Role role, @@ -220,15 +220,15 @@ public final PatternModification the target {@link Node} type - * @param cClass a {@link Class} object - * @param modifications a {@link PatternModification} object - * @param a T class - * @param a C class - * @return the patterns modification + * @param cClass the class of the related node + * @param modifications modifications to the related node + * @param the target node type, as specified by the edge + * @param the related node type, as specified by the edge + * @param the concrete node type of the related node + * @return the pattern modification */ @SafeVarargs - public final PatternModification relatedExisting(CpgEdge edge, Class cClass, Role role, + public final PatternModification relatedExisting(CpgEdge edge, Class cClass, Role role, PatternModification... modifications) { return new AddRelatedExistingNode<>(edge, cClass, role, List.of(modifications)); } @@ -237,11 +237,11 @@ public final PatternModification the target {@link Node} type - * @param the related {@link Node} type - * @param modifications a {@link PatternModification} object - * @param a C class - * @return the patterns modification + * @param modifications modifications to the related node + * @param the target node type, as specified by the edge + * @param the related node type, as specified by the edge + * @param the concrete node type of the related node + * @return the pattern modification */ @SafeVarargs public final PatternModification relatedExisting1ToN(CpgMultiEdge edge, Class cClass, @@ -253,7 +253,7 @@ public final PatternModification the {@link Node} type - * @return the patterns modification + * @return the pattern modification */ public final PatternModification setRepresentingNode() { return new SetRepresentingNode<>(); @@ -263,7 +263,7 @@ public final PatternModification setRepresentingNode() { * Creates a {@link PatternModification} that sets a flag to indicate that the child patterns contained in this patterns * are not relevant for the transformation calculation, but only for the patterns matching. * @param the target node patterns type - * @return the patterns modification + * @return the pattern modification */ public final PatternModification stopRecursion() { return new StopRecursion<>(); @@ -623,14 +623,14 @@ public void apply(NodePattern target, PatternRegistry patterns) { } } - private record AddAssignedValueStableBetween(Role startRole, Role endRole) implements PatternModification { + private record AddAssignedValueStableBetween(Role startRole, Role endRole) implements PatternModification { @Override - public void apply(NodePattern target, PatternRegistry patterns) { + public void apply(NodePattern target, PatternRegistry patterns) { NodePattern startNP = patterns.getPattern(startRole, Node.class); NodePattern endNP = patterns.getPattern(endRole, Node.class); - MatchProperty matchProperty = (s, match) -> { - Set assignNodes = PatternUtil.dfgReferences(s); + MatchProperty matchProperty = (t, match) -> { + Set assignNodes = PatternUtil.dfgReferences(t); // s is a constant term if (assignNodes.isEmpty()) { return true; diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/GraphPatternImpl.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/GraphPatternImpl.java index 520e5cb5e..5f1b471b7 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/GraphPatternImpl.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/GraphPatternImpl.java @@ -15,7 +15,7 @@ public abstract class GraphPatternImpl implements GraphPattern { /** * Constructs a new {@link GraphPatternImpl} from a {@link PatternRegistry}. - * @param patterns a {@link PatternRegistry} object + * @param patterns the {@link PatternRegistry} for this graph pattern */ protected GraphPatternImpl(PatternRegistry patterns) { representingNode = patterns.getRepresentingNode(); @@ -59,7 +59,7 @@ public NodePattern addNode(Role roleName, NodePattern pat /** * Gets the representingNode of this {@link GraphPatternImpl}. - * @return the representative {@link de.jplag.java_cpg.transformation.matching.pattern.NodePattern} + * @return the representative {@link NodePattern} */ public NodePattern getRepresentingNode() { return (NodePattern) representingNode; diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/Match.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/Match.java index 56a41d629..8a32478b6 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/Match.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/Match.java @@ -145,12 +145,12 @@ public T get(NodePattern pattern) { * Gets the concrete {@link CpgNthEdge} for a {@link AnyOfNEdge} in this {@link Match}. * @param sourcePattern the source pattern * @param edge the any-of-n edge - * @param the source node type - * @param the target node type + * @param the source node type + * @param the related node type * @return the nth edge */ - public CpgNthEdge getEdge(NodePattern sourcePattern, AnyOfNEdge edge) { - return (CpgNthEdge) this.edgeMap.get(new EdgeMapKey<>(sourcePattern, edge)); + public CpgNthEdge getEdge(NodePattern sourcePattern, AnyOfNEdge edge) { + return (CpgNthEdge) this.edgeMap.get(new EdgeMapKey<>(sourcePattern, edge)); } private LinkedList getFullID() { @@ -224,11 +224,11 @@ public Match resolveAnyOfNEdge(Nod * @param parentPattern the parent node pattern * @param parent the concrete parent node * @param edge the edge - * @param the node type of the parent as specified by the edge - * @param the node type of the child as specified by the edge + * @param the node type of the parent as specified by the edge + * @param the node type of the child as specified by the edge */ - public void resolveWildcard(ParentNodePattern parentPattern, S parent, CpgEdge edge) { - NodePattern concreteRoot = NodePattern.forNodeType(edge.getSourceClass()); + public void resolveWildcard(ParentNodePattern parentPattern, T parent, CpgEdge edge) { + NodePattern concreteRoot = NodePattern.forNodeType(edge.getSourceClass()); concreteRoot.addRelation(new RelatedNode<>(parentPattern.getChildPattern(), edge)); this.wildcardMatches.put(parentPattern, new WildcardMatch<>(concreteRoot, edge)); @@ -243,17 +243,17 @@ public String toString() { /** * Saves the data related to a concrete occurrence of a {@link WildcardGraphPattern}. - * @param the concrete type of the child, specified by the edge + * @param the concrete type of the child, specified by the edge */ - public static final class WildcardMatch { - private final NodePattern parentPattern; - private final CpgEdge edge; + public static final class WildcardMatch { + private final NodePattern parentPattern; + private final CpgEdge edge; /** * @param parentPattern A concrete {@link NodePattern} for the parent * @param edge the edge */ - public WildcardMatch(NodePattern parentPattern, CpgEdge edge) { + public WildcardMatch(NodePattern parentPattern, CpgEdge edge) { this.parentPattern = parentPattern; this.edge = edge; } @@ -273,7 +273,7 @@ public int hashCode() { return Objects.hash(parentPattern, edge); } - public GraphOperation instantiateGraphOperation(BiFunction, CpgEdge, GraphOperation> factoryMethod) { + public GraphOperation instantiateGraphOperation(BiFunction, CpgEdge, GraphOperation> factoryMethod) { return factoryMethod.apply(this.parentPattern, this.edge); } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/MatchProperty.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/MatchProperty.java index 5fe3548f2..2af460a1f 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/MatchProperty.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/MatchProperty.java @@ -3,9 +3,8 @@ import de.fraunhofer.aisec.cpg.graph.Node; /** - * A {@link de.jplag.java_cpg.transformation.matching.pattern.MatchProperty} can be used to represent a property of a - * {@link de.jplag.java_cpg.transformation.matching.pattern.Match} involving multiple - * {@link de.fraunhofer.aisec.cpg.graph.Node}s and their relations. + * A {@link MatchProperty} can be used to represent a property of a {@link Match} involving multiple {@link Node}s and + * their relations. * @param The node type of the node that the property is assigned to */ @FunctionalInterface diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/NodePattern.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/NodePattern.java index 0dc1c9dc2..4f5fbf008 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/NodePattern.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/NodePattern.java @@ -60,8 +60,8 @@ static NodePattern forNodeType(Class tClass) { NodePattern deepCopy(); /** - * Gets the list of node classes of possible candidates for this node pattern. - * @return a {@link List} object + * Gets the list of node classes of potential candidates for this node pattern. + * @return the candidate classes */ List> getCandidateClasses(); diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/PatternRegistry.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/PatternRegistry.java index 21d2f4aa6..923466915 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/PatternRegistry.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/PatternRegistry.java @@ -3,7 +3,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; -import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,9 +30,7 @@ public class PatternRegistry { private int wildcardCounter; /** - *

- * Constructor for PatternRegistry. - *

+ * Creates a new {@link PatternRegistry}. */ public PatternRegistry() { this.patternByRole = new HashMap<>(); @@ -41,27 +38,14 @@ public PatternRegistry() { } /** - *

- * addAll. - *

- * @param patternByRoleName a {@link java.util.Map} object - */ - public void addAll(Map> patternByRoleName) { - this.patternByRole.putAll(patternByRoleName); - this.roleByPattern.putAll(patternByRoleName.keySet().stream().collect(Collectors.toMap(patternByRoleName::get, k -> k))); - } - - /** - *

- * getPattern. - *

- * @param nodePatternRole a {@link java.lang.String} object - * @return a {@link NodePattern} object + * Gets the {@link NodePattern} with the given {@link Role}, cast to the given {@link Node} class. + * @param role the role + * @return the node pattern associated to the role */ - public NodePattern getPattern(Role nodePatternRole, Class targetClass) { - NodePattern nodePattern = patternByRole.get(nodePatternRole); + public NodePattern getPattern(Role role, Class targetClass) { + NodePattern nodePattern = patternByRole.get(role); if (!targetClass.isAssignableFrom(nodePattern.getRootClass())) { - throw new ClassCastException("Pattern %s is incompatible with target class %s".formatted(nodePatternRole, targetClass)); + throw new ClassCastException("Pattern %s is incompatible with target class %s".formatted(role, targetClass)); } @SuppressWarnings("unchecked") NodePattern castNodePattern = (NodePattern) nodePattern; @@ -100,43 +84,35 @@ public void put(Role role, NodePattern pattern) { } /** - *

- * Setter for the field representingNode. - *

- * @param representingNode a {@link NodePattern} object + * Sets the representing node of the associated graph pattern. + * @param representingNode the representing node */ public void setRepresentingNode(NodePattern representingNode) { this.representingNode = (NodePattern) representingNode; } /** - *

- * Getter for the field representingNode. - *

- * @return a {@link NodePattern} object + * Gets the {@link NodePattern} of the associated {@link GraphPattern} that is marked representative. + * @return the representative node pattern */ public NodePattern getRepresentingNode() { return this.representingNode; } /** - *

- * createWildcardId. - *

- * @return a {@link java.lang.String} object + * Creates a new Role for a wildcard parent pattern. + * @return the role */ - public Role createWildcardId() { + public Role createWildcardRole() { return new Role(WILDCARD_PARENT_ID + wildcardCounter++); } /** - *

- * containsPattern. - *

- * @param notePatternRole a {@link java.lang.String} object - * @return a boolean + * Determines whether a pattern with the given role is present in this {@link PatternRegistry}. + * @param role the role + * @return true iff the pattern is in the registry */ - public boolean containsPattern(Role notePatternRole) { - return patternByRole.containsKey(notePatternRole); + public boolean containsPattern(Role role) { + return patternByRole.containsKey(role); } } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/PatternUtil.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/PatternUtil.java index cc04e5a98..98f597df6 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/PatternUtil.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/PatternUtil.java @@ -16,9 +16,7 @@ import de.jplag.java_cpg.transformation.matching.edges.CpgNthEdge; /** - * Contains convenience methods to create elements of - * {@link de.jplag.java_cpg.transformation.matching.pattern.GraphPattern}s and - * {@link de.jplag.java_cpg.transformation.matching.pattern.NodePattern}s. + * Contains convenience methods to create elements of {@link GraphPattern}s and {@link NodePattern}s. */ public class PatternUtil { @@ -29,22 +27,22 @@ private PatternUtil() { /** * Creates a Predicate that checks if a node has a non-null related Node via the given edge. * @param edge the edge - * @param the source node type - * @param the target node type + * @param the source node type + * @param the target node type * @return the predicate */ - public static Predicate notNull(CpgEdge edge) { + public static Predicate notNull(CpgEdge edge) { return s -> !Objects.isNull(edge.getRelated(s)); } /** * Creates a {@link Predicate} property for an edge that specifies that its target shall not be null. * @param edge the edge - * @param the source node type + * @param the source node type * @param

the target property type * @return the predicate */ - public static Predicate notNull(CpgAttributeEdge edge) { + public static Predicate notNull(CpgAttributeEdge edge) { return s -> !Objects.isNull(edge.getter().apply(s)); } @@ -53,12 +51,12 @@ public static Predicate notNull(CpgAttributeEdge ed * type. * @param edge the edge * @param clazz the concrete node class - * @param the source node type - * @param the target node type as specified by the edge + * @param the source node type + * @param the target node type as specified by the edge * @param the concrete target node type * @return the predicate */ - public static Predicate notInstanceOf(CpgEdge edge, Class clazz) { + public static Predicate notInstanceOf(CpgEdge edge, Class clazz) { return s -> !clazz.isInstance(edge.getter().apply(s)); } @@ -66,11 +64,11 @@ public static Predicate notInst * Creates a proxy for the nth element of a 1:n relation. * @param edge the 1:n relation edge * @param n the index of the edge - * @param the source node type - * @param the target node type + * @param the source node type + * @param the target node type * @return the nth edge */ - public static CpgEdge nthElement(CpgMultiEdge edge, int n) { + public static CpgEdge nthElement(CpgMultiEdge edge, int n) { return new CpgNthEdge<>(edge, n); } @@ -78,24 +76,24 @@ public static CpgEdge nthElement(CpgMulti * Creates a {@link Predicate} that checks if the related attribute is equal to the given value. * @param attributeEdge a function to get the related attribute * @param value the value to check against - * @param the source node type + * @param the source node type * @param

the predicate type * @return the predicate */ - public static Predicate attributeEquals(CpgAttributeEdge attributeEdge, P value) { - return s -> Objects.equals(attributeEdge.get(s), value); + public static Predicate attributeEquals(CpgAttributeEdge attributeEdge, P value) { + return t -> Objects.equals(attributeEdge.get(t), value); } /** * Creates a predicate property for an edge that specifies that its target attribute shall be equal to the given String. * @param attributeEdge the attribute edge * @param value the required value - * @param the source node type + * @param the source node type * @param

the attribute type * @return the predicate */ - public static Predicate attributeToStringEquals(CpgAttributeEdge attributeEdge, String value) { - return s -> Objects.equals(attributeEdge.get(s).toString(), value); + public static Predicate attributeToStringEquals(CpgAttributeEdge attributeEdge, String value) { + return t -> Objects.equals(attributeEdge.get(t).toString(), value); } /** @@ -103,12 +101,12 @@ public static Predicate attributeToStringEquals(CpgAttrib * with the given {@link String}. * @param attributeEdge the attribute edge * @param value the required starting substring - * @param the source node type + * @param the source node type * @param

the target attribute type * @return the predicate */ - public static Predicate attributeToStringStartsWith(CpgAttributeEdge attributeEdge, String value) { - return s -> attributeEdge.get(s).toString().startsWith(value); + public static Predicate attributeToStringStartsWith(CpgAttributeEdge attributeEdge, String value) { + return t -> attributeEdge.get(t).toString().startsWith(value); } /** @@ -116,68 +114,67 @@ public static Predicate attributeToStringStartsWith(CpgAt * value. * @param attributeEdge the attribute edge * @param value the required contained value - * @param the source node type + * @param the source node type * @param

The target attributes type * @return the predicate */ - public static Predicate attributeContains(CpgAttributeEdge> attributeEdge, P value) { - return s -> attributeEdge.get(s).contains(value); + public static Predicate attributeContains(CpgAttributeEdge> attributeEdge, P value) { + return t -> attributeEdge.get(t).contains(value); } /** * Creates a predicate property for an edge that specifies that the target node list is not empty. * @param edge the edge - * @param the source node type - * @param the target node type + * @param the source node type + * @param the target node type * @return the predicate */ - public static Predicate notEmpty(CpgMultiEdge edge) { - return s -> !edge.getAllTargets(s).isEmpty(); + public static Predicate notEmpty(CpgMultiEdge edge) { + return t -> !edge.getAllTargets(t).isEmpty(); } /** * Creates a {@link Predicate} property for an edge that specifies that the target node list is empty. * @param edge the edge - * @param the source node type - * @param the target node type + * @param the source node type + * @param the target node type * @return the predicate */ - public static Predicate isEmpty(CpgMultiEdge edge) { - return s -> edge.getAllTargets(s).isEmpty(); + public static Predicate isEmpty(CpgMultiEdge edge) { + return t -> edge.getAllTargets(t).isEmpty(); } /** * Creates a {@link Predicate} that checks if the 1:n relation targets exactly the number of nodes specified. * @param edge the 1:n edge * @param n the number to check against - * @param the source node type - * @param the target node type + * @param the source node type + * @param the target node type * @return the predicate */ - public static Predicate nElements(CpgMultiEdge edge, int n) { - return s -> edge.getAllTargets(s).size() == n; + public static Predicate nElements(CpgMultiEdge edge, int n) { + return t -> edge.getAllTargets(t).size() == n; } /** * Creates a {@link Predicate} that checks if the property value is contained in the list of values given. * @param getter a function to get the property value * @param acceptedValues a list of accepted values - * @param the source node type + * @param the source node type * @param

the property value type * @return the predicate */ - public static Predicate oneOf(CpgAttributeEdge getter, List

acceptedValues) { - return s -> acceptedValues.contains(getter.get(s)); + public static Predicate oneOf(CpgAttributeEdge getter, List

acceptedValues) { + return t -> acceptedValues.contains(getter.get(t)); } /** - * Creates a new {@link de.fraunhofer.aisec.cpg.graph.Node} of the type specified by the given - * {@link de.jplag.java_cpg.transformation.matching.pattern.NodePattern}. + * Creates a new {@link Node} of the type specified by the given {@link NodePattern}. * @param pattern the pattern - * @param the node pattern type - * @return the new {@link de.fraunhofer.aisec.cpg.graph.Node} + * @param the node pattern type + * @return the new {@link Node} */ - public static T instantiate(NodePattern pattern) { + public static R instantiate(NodePattern pattern) { try { // every Node type has a constructor without parameters return pattern.getRootClass().getDeclaredConstructor().newInstance(); @@ -197,17 +194,21 @@ public static Set dfgReferences(Node node) { while (!workList.isEmpty()) { Node candidate = workList.pop(); - if (candidate instanceof Literal) { - // Literal is constant - } else if (candidate instanceof CallExpression call) { - workList.addAll(call.getArguments()); - if (call instanceof MemberCallExpression memberCall) { - workList.add(memberCall.getBase()); + switch (candidate) { + case Literal ignored -> { + // Literal is constant + } + case null -> { + // do nothing + } + case CallExpression call -> { + workList.addAll(call.getArguments()); + if (call instanceof MemberCallExpression memberCall) { + workList.add(memberCall.getBase()); + } } - } else if (candidate instanceof Reference ref) { - references.add(ref.getRefersTo()); - } else { - workList.addAll(candidate.getPrevDFG()); + case Reference ref -> references.add(ref.getRefersTo()); + default -> workList.addAll(candidate.getPrevDFG()); } } return references.stream().flatMap(decl -> decl.getPrevDFG().stream()).collect(Collectors.toSet()); diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/SimpleGraphPattern.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/SimpleGraphPattern.java index aa8f4c635..2bed4dcf4 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/SimpleGraphPattern.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/SimpleGraphPattern.java @@ -18,7 +18,7 @@ public class SimpleGraphPattern extends GraphPatternImpl { /** * Creates a new {@link SimpleGraphPattern} with the given root {@link NodePattern}. * @param root the root {@link NodePattern} - * @param patterns a {@link PatternRegistry} object + * @param patterns the {@link PatternRegistry} for this graph pattern */ public SimpleGraphPattern(NodePattern root, PatternRegistry patterns) { super(patterns); @@ -52,11 +52,9 @@ public List match(Map, List> rootCandidate } /** - * Checks this {@link SimpleGraphPattern} against the given concrete {@link Node} for - * {@link de.jplag.java_cpg.transformation.matching.pattern.Match}es. - * @param rootCandidate the possible root {@link Node} of - * {@link de.jplag.java_cpg.transformation.matching.pattern.Match}es - * @return the list of {@link de.jplag.java_cpg.transformation.matching.pattern.Match}es found + * Checks this {@link SimpleGraphPattern} against the given concrete {@link Node} for {@link Match}es. + * @param rootCandidate the possible root {@link Node} of {@link Match}es + * @return the list of {@link Match}es found * @param a C class */ public List recursiveMatch(C rootCandidate) { diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/WildcardGraphPattern.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/WildcardGraphPattern.java index dd122a12b..e9de523bd 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/WildcardGraphPattern.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/matching/pattern/WildcardGraphPattern.java @@ -20,12 +20,10 @@ /** * This class represents a pattern where the root node's parent is unknown, but involved in a transformation (e.g. the * root node is moved/deleted). - * @param The node type of the child node of the wildcard parent - * @author robin - * @version $Id: $Id + * @param The node type of the child node of the wildcard parent */ -public class WildcardGraphPattern extends SimpleGraphPattern { - private final ParentNodePattern wildcardParent; +public class WildcardGraphPattern extends SimpleGraphPattern { + private final ParentNodePattern wildcardParent; /** * Creates a new {@link WildcardGraphPattern}. @@ -33,10 +31,10 @@ public class WildcardGraphPattern extends SimpleGraphPattern tClass, NodePattern child, PatternRegistry patterns) { + WildcardGraphPattern(Class tClass, NodePattern child, PatternRegistry patterns) { super(new ParentNodePattern<>(tClass, child), patterns); - this.wildcardParent = (ParentNodePattern) getRoot(); - patterns.put(patterns.createWildcardId(), wildcardParent); + this.wildcardParent = (ParentNodePattern) getRoot(); + patterns.put(patterns.createWildcardRole(), wildcardParent); } @Override @@ -59,22 +57,22 @@ public boolean validate(Match match) { /** * Pattern to describe the unknown AST context that a node may appear in. - * @param the child node type + * @param the child node type */ - public static class ParentNodePattern extends NodePatternImpl { - private final NodePattern childPattern; - private final List> edgesToType; + public static class ParentNodePattern extends NodePatternImpl { + private final NodePattern childPattern; + private final List> edgesToType; /** * Creates a new {@link ParentNodePattern} for the given child {@link NodePattern}. * @param tClass The {@link Node} type class of the child * @param child the child node pattern */ - public ParentNodePattern(Class tClass, NodePattern child) { + public ParentNodePattern(Class tClass, NodePattern child) { super(Node.class); this.childPattern = child; - Edge edge; + Edge edge; if (Objects.isNull(child)) { edgesToType = null; return; @@ -102,14 +100,14 @@ public void recursiveMatch(Node node, List matches) { /** * Checks for a match of the wild card pattern starting with the parent node. - * @param The parent {@link Node} type + * @param The parent {@link Node} type * @param e The edge from the parent to the child * @param parent the parent {@link Node} * @param matches the current set of open matches */ - private void wildCardMatch(IEdge e, Node parent, List matches) { - S from = (S) parent; - if (e instanceof CpgEdge singleEdge) { + private void wildCardMatch(IEdge e, Node parent, List matches) { + T from = (T) parent; + if (e instanceof CpgEdge singleEdge) { Node target = singleEdge.getRelated(from); if (Objects.isNull(target)) { // target is not part of the graph or empty @@ -118,13 +116,13 @@ private void wildCardMatch(IEdge e, Node parent, childPattern.recursiveMatch(target, matches); matches.forEach(match -> match.resolveWildcard(this, from, singleEdge)); } - } else if (e instanceof CpgMultiEdge multiEdge) { + } else if (e instanceof CpgMultiEdge multiEdge) { List targets = multiEdge.getAllTargets(from); var resultMatches = new ArrayList(); for (int i = 0; i < targets.size(); i++) { var matchesCopy = new ArrayList<>(matches.stream().map(Match::copy).toList()); Node target = targets.get(i); - CpgEdge edge = nthElement(multiEdge, i); + CpgEdge edge = nthElement(multiEdge, i); childPattern.recursiveMatch(target, matchesCopy); matchesCopy.forEach(match -> match.resolveWildcard(this, from, edge)); resultMatches.addAll(matchesCopy); @@ -139,7 +137,7 @@ public List> getCandidateClasses() { return edgesToType.stream().map(IEdge::getSourceClass).collect(Collectors.toCollection(ArrayList::new)); } - public NodePattern getChildPattern() { + public NodePattern getChildPattern() { return childPattern; } @@ -186,14 +184,14 @@ public int hashCode() { } /** - * This models an edge unknown at creation time, of which the target is a T node. - * @param the target node type + * This models a wildcard edge unknown at creation time, of which the target is an R node. + * @param the related node type */ - public static class Edge extends CpgEdge { + public static class Edge extends CpgEdge { - private Edge(Class tClass) { + private Edge(Class tClass) { super(null, null, AST); - this.setTargetClass(tClass); + this.setRelatedClass(tClass); } @Override diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/GraphOperationImpl.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/GraphOperationImpl.java index 8280ddfed..72fa4e15e 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/GraphOperationImpl.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/GraphOperationImpl.java @@ -7,22 +7,21 @@ import de.jplag.java_cpg.transformation.matching.pattern.WildcardGraphPattern; /** - * This class stores method implementations common to all types of - * {@link de.jplag.java_cpg.transformation.operations.GraphOperation}s. - * @param The type of the parent node where this GraphOperation happens - * @param The type of node related to the parent node + * This class stores method implementations common to all types of {@link GraphOperation}s. + * @param The type of the parent node where this GraphOperation happens + * @param The type of node related to the parent node */ -public abstract class GraphOperationImpl implements GraphOperation { +public abstract class GraphOperationImpl implements GraphOperation { - protected final NodePattern parentPattern; - protected final CpgEdge edge; + protected final NodePattern parentPattern; + protected final CpgEdge edge; /** * Creates a new GraphOperationImpl. * @param parentPattern the {@link NodePattern} where the {@link GraphOperation} sets in * @param edge the {@link CpgEdge} that this {@link GraphOperation} manipulates */ - protected GraphOperationImpl(NodePattern parentPattern, CpgEdge edge) { + protected GraphOperationImpl(NodePattern parentPattern, CpgEdge edge) { this.parentPattern = parentPattern; this.edge = edge; } @@ -37,5 +36,5 @@ public boolean isWildcarded() { return this.parentPattern instanceof WildcardGraphPattern.ParentNodePattern && this.edge instanceof WildcardGraphPattern.Edge; } - public abstract GraphOperationImpl fromWildcardMatch(NodePattern pattern, CpgEdge edge); + public abstract GraphOperationImpl fromWildcardMatch(NodePattern pattern, CpgEdge edge); } diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/RemoveOperation.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/RemoveOperation.java index 635a4c734..5225442bb 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/RemoveOperation.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/RemoveOperation.java @@ -19,11 +19,9 @@ import de.jplag.java_cpg.transformation.matching.pattern.WildcardGraphPattern; /** - * This operation removes a {@link de.fraunhofer.aisec.cpg.graph.Node} from its AST context. - * @param the parent {@link de.fraunhofer.aisec.cpg.graph.Node} type - * @param the target {@link de.fraunhofer.aisec.cpg.graph.Node} type - * @author robin - * @version $Id: $Id + * This operation removes a {@link Node} from its AST context. + * @param the parent {@link Node} type + * @param the target {@link Node} type */ public final class RemoveOperation extends GraphOperationImpl { diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/ReplaceOperation.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/ReplaceOperation.java index b2ac895ec..ad8cdcb7f 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/ReplaceOperation.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/ReplaceOperation.java @@ -31,9 +31,7 @@ public final class ReplaceOperation extends Grap private final boolean disconnectEog; /** - *

- * Constructor for ReplaceOperation. - *

+ * Constructs a new ReplaceOperation. * @param parentPattern source node of the edge * @param edge edge of which the target shall be replaced * @param newChildPattern replacement node diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/SetOperation.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/SetOperation.java index 50de96c52..a2bf63780 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/SetOperation.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/SetOperation.java @@ -15,16 +15,15 @@ import de.jplag.java_cpg.transformation.matching.pattern.WildcardGraphPattern; /** - * Sets the target {@link de.fraunhofer.aisec.cpg.graph.Node} of a previously newly created edge to a - * {@link de.fraunhofer.aisec.cpg.graph.Node}. - * @param type of the parent node, defined by the edge - * @param type of the related node, defined by the edge + * Sets the target {@link Node} of a previously newly created edge to a {@link Node}. + * @param type of the parent node, defined by the edge + * @param type of the related node, defined by the edge */ -public final class SetOperation extends GraphOperationImpl { +public final class SetOperation extends GraphOperationImpl { private static final Logger logger; public static final String WILDCARD_ERROR_MESSAGE = "Cannot apply SetOperation with WildcardGraphPattern.ParentPattern as parentPattern."; public static final String MULTI_EDGE_ERROR_MESSAGE = "Cannot apply SetOperation with Any1ofNEdge."; - private final NodePattern newChildPattern; + private final NodePattern newChildPattern; /** * Creates a new {@link SetOperation}. @@ -32,7 +31,7 @@ public final class SetOperation extends GraphOpe * @param edge the edge relating the parent and child * @param newChildPattern the new child node pattern */ - public SetOperation(NodePattern parentPattern, CpgEdge edge, NodePattern newChildPattern) { + public SetOperation(NodePattern parentPattern, CpgEdge edge, NodePattern newChildPattern) { super(parentPattern, edge); this.newChildPattern = newChildPattern; } @@ -42,15 +41,15 @@ public SetOperation(NodePattern parentPattern, CpgEdge edge, } @Override - public GraphOperationImpl fromWildcardMatch(NodePattern pattern, CpgEdge edge) { + public GraphOperationImpl fromWildcardMatch(NodePattern pattern, CpgEdge edge) { throw new TransformationException(WILDCARD_ERROR_MESSAGE); } @Override public void resolveAndApply(Match match, TranslationContext ctx) { - S parent = match.get(parentPattern); + T parent = match.get(parentPattern); // match should contain newChildPattern node because of Builder.createNewNodes() - T newChild = match.get(newChildPattern); + R newChild = match.get(newChildPattern); logger.debug("Set {} as AST child of {}", newChild, parent); assert Objects.isNull(edge.getter().apply(parent)); diff --git a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/TransformationUtil.java b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/TransformationUtil.java index 65d480cce..409fb1020 100644 --- a/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/TransformationUtil.java +++ b/languages/java-cpg/src/main/java/de/jplag/java_cpg/transformation/operations/TransformationUtil.java @@ -13,10 +13,10 @@ import de.fraunhofer.aisec.cpg.graph.statements.expressions.Block; import de.fraunhofer.aisec.cpg.graph.statements.expressions.UnaryOperator; import de.fraunhofer.aisec.cpg.helpers.SubgraphWalker; +import de.jplag.java_cpg.transformation.GraphTransformation; /** - * This class is a collection of auxiliary methods related to - * {@link de.jplag.java_cpg.transformation.GraphTransformation}s. + * This class is a collection of auxiliary methods related to {@link GraphTransformation}s. */ public final class TransformationUtil { @@ -28,10 +28,9 @@ private TransformationUtil() { } /** - * Gets the {@link de.fraunhofer.aisec.cpg.helpers.SubgraphWalker.Border} of the given node's sub-AST that links to - * outer nodes via EOG edges. + * Gets the {@link SubgraphWalker.Border} of the given node's sub-AST that links to outer nodes via EOG edges. * @param astRoot the root of the sub-AST - * @return the EOG {@link de.fraunhofer.aisec.cpg.helpers.SubgraphWalker.Border} of the AST + * @return the EOG {@link SubgraphWalker.Border} of the AST */ public static SubgraphWalker.Border getEogBorders(Node astRoot) { SubgraphWalker.Border result; @@ -95,15 +94,13 @@ static void transferEogPredecessor(Node oldSuccessor, Node newSuccessor) { } /** - *

- * disconnectFromSuccessor. - *

- * @param astRoot a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @return a {@link de.fraunhofer.aisec.cpg.graph.Node} object + * Disconnects the given {@link Node} from its EOG successor. + * @param node the node + * @return the EOG successor */ - public static Node disconnectFromSuccessor(Node astRoot) { - Node exit = getExit(astRoot); - List> exitEdges = new ArrayList<>(getExitEdges(astRoot, List.of(exit), true)); + public static Node disconnectFromSuccessor(Node node) { + Node exit = getExit(node); + List> exitEdges = new ArrayList<>(getExitEdges(node, List.of(exit), true)); exitEdges.removeIf(e -> Objects.equals(e.getEnd(), DUMMY)); exitEdges.removeIf(e -> Objects.equals(e.getStart(), DUMMY)); @@ -128,16 +125,22 @@ public static Node disconnectFromSuccessor(Node astRoot) { return entry; } - static Node connectNewSuccessor(Node target, Node newSuccessor, boolean enforceEogConnection) { + /** + * Connects the EOG exit edges of the given target {@link Node} to the entries of the newSuccessor {@link Node}. + * @param target the node to be connected + * @param newSuccessor the node to be connected to + * @param enforceEogConnection if true, the two nodes will be connected even if target has no exit edges. + */ + static void connectNewSuccessor(Node target, Node newSuccessor, boolean enforceEogConnection) { List exits = List.of(target); List> exitEdges = getExitEdges(target, exits, false); if (Objects.isNull(newSuccessor) || target == DUMMY) { - return null; + return; } if (target instanceof UnaryOperator unaryOperator && Objects.equals(unaryOperator.getOperatorCode(), "throw")) { target.clearNextEOG(); - return null; + return; } if (exitEdges.isEmpty()) { @@ -146,7 +149,7 @@ static Node connectNewSuccessor(Node target, Node newSuccessor, boolean enforceE target.addNextEOG(exitEdge); exitEdges = List.of(exitEdge); } else { - return target; + return; } } exitEdges = exitEdges.stream().filter(e -> e.getEnd().equals(DUMMY)).toList(); @@ -164,20 +167,17 @@ static Node connectNewSuccessor(Node target, Node newSuccessor, boolean enforceE entry.addPrevEOG(e); }); - return entry; } /** - *

- * disconnectFromPredecessor. - *

- * @param astRoot a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @return a {@link java.util.List} object + * Disconnects the given {@link Node} from its EOG predecessor. + * @param node the node + * @return the EOG predecessor */ - public static List disconnectFromPredecessor(Node astRoot) { - Node entry = getEntry(astRoot); + public static List disconnectFromPredecessor(Node node) { + Node entry = getEntry(node); - List> entryEdges = getEntryEdges(astRoot, entry, true); + List> entryEdges = getEntryEdges(node, entry, true); if (entryEdges.isEmpty()) return List.of(); @@ -200,18 +200,21 @@ public static List disconnectFromPredecessor(Node astRoot) { } /** - *

- * getEntry. - *

- * @param astRoot a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @return a {@link de.fraunhofer.aisec.cpg.graph.Node} object + * Gets the first EOG entry {@link Node} of the given {@link Node}. + * @param node the node + * @return the EOG entry node */ - public static Node getEntry(Node astRoot) { - return getEogBorders(astRoot).getEntries().getFirst(); + public static Node getEntry(Node node) { + return getEogBorders(node).getEntries().getFirst(); } - static Node getExit(Node astRoot) { - return getEogBorders(astRoot).getExits().getFirst(); + /** + * Gets the first EOG exit {@link Node} of the given {@link Node}. + * @param node the node + * @return the EOG entry node + */ + static Node getExit(Node node) { + return getEogBorders(node).getExits().getFirst(); } static Node connectNewPredecessor(Node target, Node newPredecessor) { @@ -238,13 +241,12 @@ static Node connectNewPredecessor(Node target, Node newPredecessor) { } /** - *

- * getEntryEdges. - *

- * @param astParent a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @param entry a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @param useDummies a boolean - * @return a {@link java.util.List} object + * Gets the EOG entry edges to the AST subtree represented by astParent, that connect to the given entry node. + * @param astParent the root of the AST subtree + * @param entry the EOG entry to the astParent + * @param useDummies if true, the returned edges may not be the current entries to the astParent, but instead earlier + * entry edges to the astParent that have been disconnected and saved for use later. + * @return the entry edges */ @NotNull public static List> getEntryEdges(Node astParent, Node entry, boolean useDummies) { @@ -267,13 +269,12 @@ public static List> getEntryEdges(Node astParent, Node entry, } /** - *

- * getExitEdges. - *

- * @param astParent a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @param exits a {@link java.util.List} object - * @param useDummies a boolean - * @return a {@link java.util.List} object + * Gets the EOG exit edges to the AST subtree represented by astParent, that connect to the given entry node. + * @param astParent the root of the AST subtree + * @param exits the EOG exit nodes of the astParent + * @param useDummies if true, the returned edges may not be the current exits of the astParent, but instead earlier exit + * edges of the astParent that have been disconnected and saved for use later. + * @return the exit edges */ @NotNull public static List> getExitEdges(Node astParent, List exits, boolean useDummies) { @@ -297,11 +298,9 @@ public static List> getExitEdges(Node astParent, List e } /** - *

- * insertBefore. - *

- * @param target a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @param newSuccessor a {@link de.fraunhofer.aisec.cpg.graph.Node} object + * Inserts the given {@link Node} before the given newSuccessor {@link Node} in the EOG graph. + * @param target the node + * @param newSuccessor the new successor node */ public static void insertBefore(Node target, Node newSuccessor) { Node entry = getEntry(target); @@ -316,11 +315,9 @@ public static void insertBefore(Node target, Node newSuccessor) { } /** - *

- * insertAfter. - *

- * @param target a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @param newPredecessor a {@link de.fraunhofer.aisec.cpg.graph.Node} object + * Inserts the given {@link Node} after the given newSuccessor {@link Node} in the EOG graph. + * @param target the node + * @param newPredecessor the new predecessor node */ public static void insertAfter(Node target, Node newPredecessor) { Node entry = getEntry(target); @@ -335,15 +332,14 @@ public static void insertAfter(Node target, Node newPredecessor) { } /** - *

- * isAstSuccessor. - *

- * @param element a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @param maybeSuccessor a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @return a boolean + * Returns true if the {@code maybeSuccessor} {@link Node} is the AST neighbor following the {@code element} node. + * @param element a {@link Node} object + * @param maybeSuccessor the potential successor {@link Node} + * @return true if {@code maybeSuccessor} is an AST successor of {@code element} */ public static boolean isAstSuccessor(Node element, Node maybeSuccessor) { - + // If maybeSuccessor is the AST successor of element, then an exit edge of element points to maybeSuccessor + // The exit is likely to be a child node, not element itself List exits = getEogBorders(element).getExits(); Node entry = getEntry(maybeSuccessor); List> entryEdges = getEntryEdges(maybeSuccessor, entry, false); @@ -352,14 +348,13 @@ public static boolean isAstSuccessor(Node element, Node maybeSuccessor) { } /** - *

- * isEogSuccessor. - *

- * @param exit a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @param maybeSuccessor a {@link de.fraunhofer.aisec.cpg.graph.Node} object - * @return a boolean + * Returns true if the {@code maybeSuccessor} {@link Node} is the EOG successor of the {@code element} node. + * @param exit a {@link Node} object + * @param maybeSuccessor the potential successor {@link Node} + * @return true if {@code maybeSuccessor} is the EOG successor of {@code element} */ public static boolean isEogSuccessor(Node exit, Node maybeSuccessor) { + // Unlike isAstSuccessor, we check for edges from exit directly Node entry = getEntry(maybeSuccessor); List> entryEdges = getEntryEdges(maybeSuccessor, entry, false); diff --git a/languages/java-cpg/src/test/java/de/jplag/java_cpg/JavaBlockTest.java b/languages/java-cpg/src/test/java/de/jplag/java_cpg/JavaBlockTest.java index c5011feee..289ca1ce7 100644 --- a/languages/java-cpg/src/test/java/de/jplag/java_cpg/JavaBlockTest.java +++ b/languages/java-cpg/src/test/java/de/jplag/java_cpg/JavaBlockTest.java @@ -2,13 +2,12 @@ import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import de.jplag.ParsingException; - /** * Test cases regarding the extraction edge implicit vs. explicit blocks in Java code. */ @@ -16,8 +15,8 @@ class JavaBlockTest extends AbstractJavaCpgLanguageTest { @ParameterizedTest @MethodSource("provideSrcDirectories") @DisplayName("Test pairs of classes with explicit vs. implicit blocks.") - void testJavaClassPair(String dir) throws ParsingException { - parseJavaFile(dir, false); + void testJavaClassPair(String dir) { + Assertions.assertDoesNotThrow(() -> parseJavaFile(dir, false)); } /**