Path: blob/master/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/InverseDepsAnalyzer.java
41161 views
/*1* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package com.sun.tools.jdeps;2627import static com.sun.tools.jdeps.JdepsFilter.DEFAULT_FILTER;28import static com.sun.tools.jdeps.Module.trace;29import static com.sun.tools.jdeps.Graph.*;3031import java.lang.module.ModuleDescriptor.Requires;32import java.io.IOException;33import java.util.Collections;34import java.util.Deque;35import java.util.HashMap;36import java.util.HashSet;37import java.util.LinkedList;38import java.util.Map;39import java.util.Optional;40import java.util.Set;41import java.util.stream.Collectors;42import java.util.stream.Stream;4344/**45* Inverse transitive dependency analysis (compile-time view)46*/47public class InverseDepsAnalyzer extends DepsAnalyzer {48// the end points for the resulting paths to be reported49private final Map<Archive, Set<Archive>> endPoints = new HashMap<>();50// target archives for inverse transitive dependence analysis51private final Set<Archive> targets = new HashSet<>();5253public InverseDepsAnalyzer(JdepsConfiguration config,54JdepsFilter filter,55JdepsWriter writer,56Analyzer.Type verbose,57boolean apiOnly) {58super(config, filter, writer, verbose, apiOnly);59}6061public boolean run() throws IOException {62try {63if (apiOnly) {64finder.parseExportedAPIs(rootArchives.stream());65} else {66finder.parse(rootArchives.stream());67}68archives.addAll(rootArchives);6970Set<Archive> archives = archives();7172// If -package or -regex is specified, the archives that reference73// the matching types are used as the targets for inverse74// transitive analysis. If -requires is specified, the75// specified modules are the targets.7677if (filter.requiresFilter().isEmpty()) {78targets.addAll(archives);79} else {80filter.requiresFilter().stream()81.map(configuration::findModule)82.flatMap(Optional::stream)83.forEach(targets::add);84}8586// If -package or -regex is specified, the end points are87// the matching archives. If -requires is specified,88// the end points are the modules specified in -requires.89if (filter.requiresFilter().isEmpty()) {90Map<Archive, Set<Archive>> dependences = finder.dependences();91targets.forEach(source -> endPoints.put(source, dependences.get(source)));92} else {93targets.forEach(t -> endPoints.put(t, Collections.emptySet()));94}9596analyzer.run(archives, finder.locationToArchive());9798// print the first-level of dependencies99if (writer != null) {100writer.generateOutput(archives, analyzer);101}102103} finally {104finder.shutdown();105}106return true;107}108109/**110* Returns the target archives determined from the dependency analysis.111*112* Inverse transitive dependency will find all nodes that depend113* upon the returned set of archives directly and indirectly.114*/115public Set<Archive> targets() {116return Collections.unmodifiableSet(targets);117}118119/**120* Finds all inverse transitive dependencies using the given requires set121* as the targets, if non-empty. If the given requires set is empty,122* use the archives depending the packages specified in -regex or -p options.123*/124public Set<Deque<Archive>> inverseDependences() throws IOException {125// create a new dependency finder to do the analysis126DependencyFinder dependencyFinder = new DependencyFinder(configuration, DEFAULT_FILTER);127try {128// parse all archives in unnamed module to get compile-time dependences129Stream<Archive> archives =130Stream.concat(configuration.initialArchives().stream(),131configuration.classPathArchives().stream());132if (apiOnly) {133dependencyFinder.parseExportedAPIs(archives);134} else {135dependencyFinder.parse(archives);136}137138Graph.Builder<Archive> builder = new Graph.Builder<>();139// include all target nodes140targets().forEach(builder::addNode);141142// transpose the module graph143configuration.getModules().values().stream()144.forEach(m -> {145builder.addNode(m);146m.descriptor().requires().stream()147.map(Requires::name)148.map(configuration::findModule) // must be present149.forEach(v -> builder.addEdge(v.get(), m));150});151152// add the dependences from the analysis153Map<Archive, Set<Archive>> dependences = dependencyFinder.dependences();154dependences.entrySet().stream()155.forEach(e -> {156Archive u = e.getKey();157builder.addNode(u);158e.getValue().forEach(v -> builder.addEdge(v, u));159});160161// transposed dependence graph.162Graph<Archive> graph = builder.build();163trace("targets: %s%n", targets());164165// Traverse from the targets and find all paths166// rebuild a graph with all nodes that depends on targets167// targets directly and indirectly168return targets().stream()169.map(t -> findPaths(graph, t))170.flatMap(Set::stream)171.collect(Collectors.toSet());172} finally {173dependencyFinder.shutdown();174}175}176177/**178* Returns all paths reachable from the given targets.179*/180private Set<Deque<Archive>> findPaths(Graph<Archive> graph, Archive target) {181182// path is in reversed order183Deque<Archive> path = new LinkedList<>();184path.push(target);185186Set<Edge<Archive>> visited = new HashSet<>();187188Deque<Edge<Archive>> deque = new LinkedList<>();189deque.addAll(graph.edgesFrom(target));190if (deque.isEmpty()) {191return makePaths(path).collect(Collectors.toSet());192}193194Set<Deque<Archive>> allPaths = new HashSet<>();195while (!deque.isEmpty()) {196Edge<Archive> edge = deque.pop();197198if (visited.contains(edge))199continue;200201Archive node = edge.v;202path.addLast(node);203visited.add(edge);204205Set<Edge<Archive>> unvisitedDeps = graph.edgesFrom(node)206.stream()207.filter(e -> !visited.contains(e))208.collect(Collectors.toSet());209210trace("visiting %s %s (%s)%n", edge, path, unvisitedDeps);211if (unvisitedDeps.isEmpty()) {212makePaths(path).forEach(allPaths::add);213path.removeLast();214}215216// push unvisited adjacent edges217unvisitedDeps.stream().forEach(deque::push);218219220// when the adjacent edges of a node are visited, pop it from the path221while (!path.isEmpty()) {222if (visited.containsAll(graph.edgesFrom(path.peekLast())))223path.removeLast();224else225break;226}227}228229return allPaths;230}231232/**233* Prepend end point to the path234*/235private Stream<Deque<Archive>> makePaths(Deque<Archive> path) {236Set<Archive> nodes = endPoints.get(path.peekFirst());237if (nodes == null || nodes.isEmpty()) {238return Stream.of(new LinkedList<>(path));239} else {240return nodes.stream().map(n -> {241Deque<Archive> newPath = new LinkedList<>();242newPath.addFirst(n);243newPath.addAll(path);244return newPath;245});246}247}248}249250251