Skip to content

Commit

Permalink
Add more documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
robinmaisch committed Mar 19, 2024
1 parent 88dd331 commit fc3d079
Show file tree
Hide file tree
Showing 10 changed files with 80 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public boolean requiresCoreNormalization() {
public void resetTransformations() {
this.cpgAdapter.clearTransformations();
this.cpgAdapter.addTransformations(this.obligatoryTransformations());
this.cpgAdapter.addTransformations(this.standardTransformations());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ class DfgSortPass(ctx: TranslationContext) : TranslationUnitPass(ctx) {
val block = parentInfo[it]!!.parent as Block
val index = block.statements.indexOf(it)
val cpgNthEdge: CpgNthEdge<Block, Statement> = CpgNthEdge(BLOCK__STATEMENTS, index)
RemoveOperation.apply(it, block, cpgNthEdge, true)
RemoveOperation.apply(block, it, cpgNthEdge, true)
if (it is DeclarationStatement) {
val deletedVariables = it.declarations.filterIsInstance<VariableDeclaration>()
block.localEdges.removeIf { it.end in deletedVariables }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import java.util.LinkedList;
import java.util.Objects;

import org.jetbrains.annotations.NotNull;

import de.fraunhofer.aisec.cpg.graph.Name;
import de.fraunhofer.aisec.cpg.graph.Node;
import de.fraunhofer.aisec.cpg.graph.declarations.*;
Expand Down Expand Up @@ -401,7 +403,7 @@ public void visit(MemberCallExpression memberCallExpression) {
* Visits a {@link Node}.
* @param node the node
*/
public void visit(Node node) {
public void visit(@NotNull Node node) {
super.visit(node);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,16 @@
* @param getter function to get the property
* @param setter function to set the property
* @param <S> the node type of the source
* @param <T> the type of the property
* @param <P> the type of the property
*/
public record CpgPropertyEdge<S extends Node, T>(Function<S, T> getter, BiConsumer<S, T> setter) {
public record CpgAttributeEdge<S extends Node, P>(Function<S, P> getter, BiConsumer<S, P> setter) {

public T get(S s) {
/**
* Gets the property related to the given node.
* @param s the source node
* @return the property
*/
public P get(S s) {
return getter.apply(s);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ public boolean isEdgeValued() {
return this.valueType == ValueType.EDGE_VALUED;
}

/** {@inheritDoc} */
@Override
public boolean isEquivalentTo(IEdge<?, ?> other) {
return Objects.equals(this, other);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import de.fraunhofer.aisec.cpg.graph.Node;
import de.jplag.java_cpg.transformation.matching.edges.CpgEdge;
import de.jplag.java_cpg.transformation.matching.edges.CpgMultiEdge;
import de.jplag.java_cpg.transformation.matching.edges.CpgMultiEdge.AnyOfNEdge;
import de.jplag.java_cpg.transformation.matching.edges.CpgNthEdge;
import de.jplag.java_cpg.transformation.matching.pattern.WildcardGraphPattern.ParentNodePattern;
Expand Down Expand Up @@ -130,7 +131,7 @@ public <T extends Node> WildcardMatch<?, T> getWildcardMatch(ParentNodePattern<T
*/
public <S extends Node, T extends Node> CpgNthEdge<S, T> resolveAnyOfNEdge(NodePattern<?> parent, NodePattern.RelatedOneToNNode<S, T> relation,
int index) {
AnyOfNEdge any1ofNEdge = relation.edge().getAnyOfNEdgeTo(relation.pattern());
CpgMultiEdge<S, T>.AnyOfNEdge any1ofNEdge = relation.edge().getAnyOfNEdgeTo(relation.pattern());
CpgNthEdge<S, T> concreteEdgePattern = new CpgNthEdge<>(any1ofNEdge.getMultiEdge(), index);
EdgeMapKey key = new EdgeMapKey(parent, any1ofNEdge);
this.edgeMap.put(key, concreteEdgePattern);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@
*/
public interface NodePattern<T extends Node> {

/**
* Creates a new {@link NodePattern} for the given {@link Node} type.
* @param tClass the node class
* @param <T> the node type
* @return the node pattern
*/
@NotNull
static <T extends Node> NodePattern<T> forNodeType(Class<T> tClass) {
return new NodePatternImpl<>(tClass);
Expand All @@ -40,9 +46,16 @@ static <T extends Node> NodePattern<T> forNodeType(Class<T> tClass) {
* @param <R> the type of the related node
* @param related the related NodePattern
* @param edge an edge to candidates for the related node given a concrete match for this pattern
* @param <C> a C class
*/
<R extends Node, C extends R> void addRelated1ToNNodePattern(NodePattern<C> related, CpgMultiEdge<? super T, R> edge);

/**
* Adds a for-all relation to this pattern
* @param related the pattern to match against all related nodes
* @param edge the edge that points to the related nodes
* @param <R> a R class
*/
<R extends Node> void addForAllRelated(NodePattern<? extends R> related, CpgMultiEdge<? super T, R> edge);

/**
Expand All @@ -51,6 +64,10 @@ static <T extends Node> NodePattern<T> forNodeType(Class<T> tClass) {
*/
void addProperty(Predicate<? super T> property);

/**
* Adds the given {@link MatchProperty} to this {@link NodePattern}.
* @param property the match property
*/
void addMatchProperty(MatchProperty<? super T> property);

/**
Expand Down Expand Up @@ -79,8 +96,12 @@ static <T extends Node> NodePattern<T> forNodeType(Class<T> tClass) {
* Gets the {@link List} of 1:n-related {@link NodePattern}s of this {@link NodePattern}.
* @return the related node pattern
*/
List<Related1ToNNode<? super T, ?>> getRelated1ToNNodes();
List<RelatedOneToNNode<? super T, ?>> getRelated1ToNNodes();

/**
* Gets the related 1-to-N sequences for this note pattern.
* @return the 1-to-N sequences
*/
List<Related1ToNSequence<? super T, ?>> getRelated1ToNSequences();

/**
Expand All @@ -95,10 +116,21 @@ static <T extends Node> NodePattern<T> forNodeType(Class<T> tClass) {
*/
Class<T> getRootClass();

/**
* Set a flag that indicates that no graph operations should be created beyond this node pattern.
*/
void markStopRecursion();

/**
* Determines whether the STOP_RECURSION flag has been set for this node pattern.
* @return true if STOP_RECURSION is set
*/
boolean shouldStopRecursion();

/**
* Gets the list of node classes of possible candidates for this node pattern.
* @return a {@link List} object
*/
List<Class<? extends T>> getCandidateClasses();

/**
Expand Down Expand Up @@ -126,7 +158,7 @@ class NodePatternImpl<T extends Node> implements NodePattern<T> {
/**
* List of related nodes (1:n relation).
*/
private final List<Related1ToNNode<? super T, ?>> related1ToNNodes;
private final List<RelatedOneToNNode<? super T, ?>> related1ToNNodes;
/**
* List of related node sequences.
*/
Expand Down Expand Up @@ -163,7 +195,7 @@ public <R extends Node> void addRelatedNodePattern(NodePattern<? extends R> rela
@Override
public <R extends Node, C extends R> void addRelated1ToNNodePattern(NodePattern<C> related, CpgMultiEdge<? super T, R> edge) {
// Could be refactored to a map by the edge type instead of a list
related1ToNNodes.add(new Related1ToNNode<>(related, edge));
related1ToNNodes.add(new RelatedOneToNNode<>(related, edge));
}

@Override
Expand Down Expand Up @@ -229,7 +261,7 @@ public void recursiveMatch(Node node, List<Match> matches, CpgEdge<?, ?> incomin
Node candidate = candidates.get(i);
var openMatchesCopy = new ArrayList<>(openMatches.stream().map(Match::copy).toList());
int finalI = i;
openMatchesCopy.forEach(match -> match.resolveAny1ofNEdge(this, pair, finalI));
openMatchesCopy.forEach(match -> match.resolveAnyOfNEdge(this, pair, finalI));
pair.getPattern().recursiveMatch(candidate, openMatchesCopy, nthElement(pair.edge, i));
resultMatches.addAll(openMatchesCopy);
}
Expand Down Expand Up @@ -276,7 +308,7 @@ protected boolean localMatch(Node node) {
}

@Override
public List<Related1ToNNode<? super T, ?>> getRelated1ToNNodes() {
public List<RelatedOneToNNode<? super T, ?>> getRelated1ToNNodes() {
return related1ToNNodes;
}

Expand Down Expand Up @@ -393,7 +425,7 @@ public String toString() {
* @param pattern the pattern describing the related node
* @param edge edge from a reference node to the related nodes
*/
record Related1ToNNode<T extends Node, R extends Node>(NodePattern<? extends R> pattern, CpgMultiEdge<T, R> edge) {
record RelatedOneToNNode<T extends Node, R extends Node>(NodePattern<? extends R> pattern, CpgMultiEdge<T, R> edge) {
List<? extends Node> getCandidates(T from) {
return edge.getAllTargets(from);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/
public class SimpleGraphPattern<T extends Node> extends GraphPatternImpl {

private NodePattern<T> root;
private final NodePattern<T> root;

/**
* Creates a new {@link de.jplag.java_cpg.transformation.matching.pattern.SimpleGraphPattern} with the given root
Expand All @@ -41,13 +41,11 @@ public NodePattern<T> getRoot() {
return root;
}

/** {@inheritDoc} */
@Override
public List<NodePattern<?>> getRoots() {
return List.of(root);
}

/** {@inheritDoc} */
@Override
public List<Match> match(Map<NodePattern<?>, List<? extends Node>> rootCandidates) {
return rootCandidates.get(root).stream().map(this::recursiveMatch).flatMap(List::stream).toList();
Expand All @@ -68,15 +66,13 @@ public <C extends Node> List<Match> recursiveMatch(C rootCandidate) {
return matches;
}

/** {@inheritDoc} */
@Override
public boolean validate(Match match) {
Node rootCandidate = match.get(this.root);
List<Match> matches = recursiveMatch(rootCandidate);
return matches.stream().anyMatch(match::equals);
}

/** {@inheritDoc} */
@Override
public void compareTo(GraphPattern targetPattern, BiConsumer<NodePattern<?>, NodePattern<?>> compareFunction) {
if (!(targetPattern instanceof SimpleGraphPattern<?> tTarget && Objects.equals(root.getClass(), tTarget.root.getClass()))) {
Expand All @@ -86,13 +82,4 @@ public void compareTo(GraphPattern targetPattern, BiConsumer<NodePattern<?>, Nod
compareFunction.accept(this.root, tTarget.getRoot());
}

/**
* Sets the root {@link de.jplag.java_cpg.transformation.matching.pattern.NodePattern} of this
* {@link de.jplag.java_cpg.transformation.matching.pattern.SimpleGraphPattern}.
* @param rootPattern the root
*/
protected void setRoot(NodePattern<T> rootPattern) {
this.root = rootPattern;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import de.fraunhofer.aisec.cpg.graph.Node;
import de.fraunhofer.aisec.cpg.graph.edge.Properties;
import de.fraunhofer.aisec.cpg.graph.edge.PropertyEdge;
import de.jplag.java_cpg.transformation.TransformationException;
import de.jplag.java_cpg.transformation.matching.edges.CpgEdge;
import de.jplag.java_cpg.transformation.matching.edges.CpgMultiEdge;
import de.jplag.java_cpg.transformation.matching.edges.CpgNthEdge;
Expand Down Expand Up @@ -50,34 +49,31 @@ public RemoveOperation(NodePattern<? extends S> sourcePattern, CpgEdge<S, T> edg

}

/** {@inheritDoc} */
@Override
public void resolveAndApply(Match match, TranslationContext ctx) throws TransformationException {
public void resolveAndApply(Match match, TranslationContext ctx) {
S parent = match.get(parentPattern);
T element = edge.getter().apply(parent);
apply(element, parent, edge, disconnectEog);
apply(parent, element, edge, disconnectEog);
}

/**
* <p>
* apply.
* </p>
* @param element a T object
* @param parent a S object
* @param edge a {@link de.jplag.java_cpg.transformation.matching.edges.CpgEdge} object
* @param disconnectEog a boolean
* @param <S> a S class
* @param <T> a T class
* Applies a {@link RemoveOperation} to the given nodes.
* @param <S> the source node type
* @param <T> the target node type
* @param source the source node
* @param child the target node
* @param edge the edge
* @param disconnectEog if true, the target node will be disconnected from the EOG graph
*/
public static <S extends Node, T extends Node> void apply(T element, S parent, CpgEdge<S, T> edge, boolean disconnectEog) {
public static <S extends Node, T extends Node> void apply(S source, T child, CpgEdge<S, T> edge, boolean disconnectEog) {

if (!(edge instanceof CpgNthEdge<S, T> nthEdge)) {
logger.debug("Remove " + element.toString());
edge.setter().accept(parent, null);
logger.debug("Remove " + child.toString());
edge.setter().accept(source, null);
} else if (nthEdge.getMultiEdge().isEdgeValued()) {
logger.debug("Remove %s (Element no. %d of %s)".formatted(element.toString(), nthEdge.getIndex(), parent));
logger.debug("Remove %s (Element no. %d of %s)".formatted(child.toString(), nthEdge.getIndex(), source));
// set edge indices of successors
List<PropertyEdge<T>> siblingEdges = nthEdge.getMultiEdge().getAllEdges(parent);
List<PropertyEdge<T>> siblingEdges = nthEdge.getMultiEdge().getAllEdges(source);
int index = nthEdge.getIndex();

// remove edge
Expand All @@ -91,29 +87,27 @@ public static <S extends Node, T extends Node> void apply(T element, S parent, C

} else {
// nthEdge is node-valued
List<T> siblings = nthEdge.getMultiEdge().getAllTargets(parent);
siblings.remove(element);
List<T> siblings = nthEdge.getMultiEdge().getAllTargets(source);
siblings.remove(child);
}

if (!disconnectEog) {
return;
}

List<Node> predExits = TransformationUtil.disconnectFromPredecessor(element);
Node succEntry = TransformationUtil.disconnectFromSuccessor(element);
List<Node> predExits = TransformationUtil.disconnectFromPredecessor(child);
Node succEntry = TransformationUtil.disconnectFromSuccessor(child);

if (!Objects.isNull(succEntry) && succEntry != DummyNeighbor.getInstance()) {
predExits.forEach(exit -> TransformationUtil.connectNewSuccessor(exit, succEntry, false));
}
}

/** {@inheritDoc} */
@Override
public NodePattern<?> getTarget() {
return parentPattern;
}

/** {@inheritDoc} */
@Override
public GraphOperation instantiateWildcard(Match match) {
WildcardGraphPattern.ParentNodePattern<T> wcParent = (WildcardGraphPattern.ParentNodePattern<T>) this.parentPattern;
Expand All @@ -125,7 +119,6 @@ private <S extends Node, T extends Node> RemoveOperation<S, T> fromWildcardMatch
return new RemoveOperation<>(wildcardMatch.parentPattern(), wildcardMatch.edge(), this.disconnectEog);
}

/** {@inheritDoc} */
@Override
public GraphOperation instantiateAnyOfNEdge(Match match) {
CpgMultiEdge<S, T>.AnyOfNEdge anyOfNEdge = (CpgMultiEdge<S, T>.AnyOfNEdge) edge;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,14 @@ private List<RecordDeclaration> getTopLevelRecords(Node node) {
List<Node> declarations = new ArrayList<>(List.of(node));
while (!declarations.isEmpty()) {
Node declaration = declarations.removeFirst();
if (declaration instanceof Component component) {
declarations.addAll(component.getTranslationUnits());
} else if (declaration instanceof TranslationUnitDeclaration tu) {
declarations.addAll(tu.getDeclarations());
} else if (declaration instanceof NamespaceDeclaration namespaceDeclaration) {
declarations.addAll(namespaceDeclaration.getDeclarations());
} else if (declaration instanceof RecordDeclaration recordDeclaration) {
result.add(recordDeclaration);
} else {
// do nothing
switch (declaration) {
case Component component -> declarations.addAll(component.getTranslationUnits());
case TranslationUnitDeclaration tu -> declarations.addAll(tu.getDeclarations());
case NamespaceDeclaration namespaceDeclaration -> declarations.addAll(namespaceDeclaration.getDeclarations());
case RecordDeclaration recordDeclaration -> result.add(recordDeclaration);
case null, default -> {
// do nothing
}
}

}
Expand Down

0 comments on commit fc3d079

Please sign in to comment.