| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package com.google.javascript.jscomp.graph; |
| 18 |
|
| 19 |
import com.google.common.base.Preconditions; |
| 20 |
import com.google.common.base.Predicate; |
| 21 |
import com.google.javascript.jscomp.graph.FixedPointGraphTraversal.EdgeCallback; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
public class GraphReachability<N, E> implements EdgeCallback<N, E> { |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
private final DiGraph<N, E> graph; |
| 35 |
|
| 36 |
private final Predicate<EdgeTuple<N, E>> edgePredicate; |
| 37 |
|
| 38 |
public GraphReachability(DiGraph<N, E> graph) { |
| 39 |
this(graph, null); |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
public GraphReachability(DiGraph<N, E> graph, |
| 49 |
Predicate<EdgeTuple<N, E>> edgePredicate) { |
| 50 |
this.graph = graph; |
| 51 |
this.edgePredicate = edgePredicate; |
| 52 |
} |
| 53 |
|
| 54 |
public void compute(N entry) { |
| 55 |
graph.clearNodeAnnotations(); |
| 56 |
graph.getNode(entry).setAnnotation(REACHABLE); |
| 57 |
FixedPointGraphTraversal.newTraversal(this) |
| 58 |
.computeFixedPoint(graph, entry); |
| 59 |
} |
| 60 |
|
| 61 |
public void recompute(N reachableNode) { |
| 62 |
GraphNode<N, E> newReachable = graph.getNode(reachableNode); |
| 63 |
Preconditions.checkState(newReachable.getAnnotation() != REACHABLE); |
| 64 |
newReachable.setAnnotation(REACHABLE); |
| 65 |
FixedPointGraphTraversal.newTraversal(this) |
| 66 |
.computeFixedPoint(graph, reachableNode); |
| 67 |
} |
| 68 |
|
| 69 |
@Override |
| 70 |
public boolean traverseEdge(N source, E e, N destination) { |
| 71 |
if (graph.getNode(source).getAnnotation() == REACHABLE && |
| 72 |
(edgePredicate == null || |
| 73 |
edgePredicate.apply(new EdgeTuple<N, E>(source, e, destination)))) { |
| 74 |
GraphNode<N, E> destNode = graph.getNode(destination); |
| 75 |
if (destNode.getAnnotation() != REACHABLE) { |
| 76 |
destNode.setAnnotation(REACHABLE); |
| 77 |
return true; |
| 78 |
} |
| 79 |
} |
| 80 |
return false; |
| 81 |
} |
| 82 |
|
| 83 |
public static final Annotation REACHABLE = new Annotation() {}; |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
public static final class EdgeTuple<N, E> { |
| 89 |
public final N sourceNode; |
| 90 |
public final E edge; |
| 91 |
public final N destNode; |
| 92 |
public EdgeTuple(N sourceNode, E edge, N destNode) { |
| 93 |
this.sourceNode = sourceNode; |
| 94 |
this.edge = edge; |
| 95 |
this.destNode = destNode; |
| 96 |
} |
| 97 |
} |
| 98 |
} |