findGraphRoots.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const NO_MARKER = 0;
  7. const IN_PROGRESS_MARKER = 1;
  8. const DONE_MARKER = 2;
  9. const DONE_MAYBE_ROOT_CYCLE_MARKER = 3;
  10. const DONE_AND_ROOT_MARKER = 4;
  11. /**
  12. * @template T
  13. */
  14. class Node {
  15. /**
  16. * @param {T} item the value of the node
  17. */
  18. constructor(item) {
  19. this.item = item;
  20. /** @type {Set<Node<T>>} */
  21. this.dependencies = new Set();
  22. this.marker = NO_MARKER;
  23. /** @type {Cycle<T> | undefined} */
  24. this.cycle = undefined;
  25. this.incoming = 0;
  26. }
  27. }
  28. /**
  29. * @template T
  30. */
  31. class Cycle {
  32. constructor() {
  33. /** @type {Set<Node<T>>} */
  34. this.nodes = new Set();
  35. }
  36. }
  37. /**
  38. * @template T
  39. * @typedef {Object} StackEntry
  40. * @property {Node<T>} node
  41. * @property {Node<T>[]} openEdges
  42. */
  43. /**
  44. * @template T
  45. * @param {Iterable<T>} items list of items
  46. * @param {function(T): Iterable<T>} getDependencies function to get dependencies of an item (items that are not in list are ignored)
  47. * @returns {Iterable<T>} graph roots of the items
  48. */
  49. module.exports = (items, getDependencies) => {
  50. /** @type {Map<T, Node<T>>} */
  51. const itemToNode = new Map();
  52. for (const item of items) {
  53. const node = new Node(item);
  54. itemToNode.set(item, node);
  55. }
  56. // early exit when there is only a single item
  57. if (itemToNode.size <= 1) return items;
  58. // grab all the dependencies
  59. for (const node of itemToNode.values()) {
  60. for (const dep of getDependencies(node.item)) {
  61. const depNode = itemToNode.get(dep);
  62. if (depNode !== undefined) {
  63. node.dependencies.add(depNode);
  64. }
  65. }
  66. }
  67. // Set of current root modules
  68. // items will be removed if a new reference to it has been found
  69. /** @type {Set<Node<T>>} */
  70. const roots = new Set();
  71. // Set of current cycles without references to it
  72. // cycles will be removed if a new reference to it has been found
  73. // that is not part of the cycle
  74. /** @type {Set<Cycle<T>>} */
  75. const rootCycles = new Set();
  76. // For all non-marked nodes
  77. for (const selectedNode of itemToNode.values()) {
  78. if (selectedNode.marker === NO_MARKER) {
  79. // deep-walk all referenced modules
  80. // in a non-recursive way
  81. // start by entering the selected node
  82. selectedNode.marker = IN_PROGRESS_MARKER;
  83. // keep a stack to avoid recursive walk
  84. /** @type {StackEntry<T>[]} */
  85. const stack = [
  86. {
  87. node: selectedNode,
  88. openEdges: Array.from(selectedNode.dependencies)
  89. }
  90. ];
  91. // process the top item until stack is empty
  92. while (stack.length > 0) {
  93. const topOfStack = stack[stack.length - 1];
  94. // Are there still edges unprocessed in the current node?
  95. if (topOfStack.openEdges.length > 0) {
  96. // Process one dependency
  97. const dependency = topOfStack.openEdges.pop();
  98. switch (dependency.marker) {
  99. case NO_MARKER:
  100. // dependency has not be visited yet
  101. // mark it as in-progress and recurse
  102. stack.push({
  103. node: dependency,
  104. openEdges: Array.from(dependency.dependencies)
  105. });
  106. dependency.marker = IN_PROGRESS_MARKER;
  107. break;
  108. case IN_PROGRESS_MARKER: {
  109. // It's a in-progress cycle
  110. let cycle = dependency.cycle;
  111. if (!cycle) {
  112. cycle = new Cycle();
  113. cycle.nodes.add(dependency);
  114. dependency.cycle = cycle;
  115. }
  116. // set cycle property for each node in the cycle
  117. // if nodes are already part of a cycle
  118. // we merge the cycles to a shared cycle
  119. for (
  120. let i = stack.length - 1;
  121. stack[i].node !== dependency;
  122. i--
  123. ) {
  124. const node = stack[i].node;
  125. if (node.cycle) {
  126. if (node.cycle !== cycle) {
  127. // merge cycles
  128. for (const cycleNode of node.cycle.nodes) {
  129. cycleNode.cycle = cycle;
  130. cycle.nodes.add(cycleNode);
  131. }
  132. }
  133. } else {
  134. node.cycle = cycle;
  135. cycle.nodes.add(node);
  136. }
  137. }
  138. // don't recurse into dependencies
  139. // these are already on the stack
  140. break;
  141. }
  142. case DONE_AND_ROOT_MARKER:
  143. // This node has be visited yet and is currently a root node
  144. // But as this is a new reference to the node
  145. // it's not really a root
  146. // so we have to convert it to a normal node
  147. dependency.marker = DONE_MARKER;
  148. roots.delete(dependency);
  149. break;
  150. case DONE_MAYBE_ROOT_CYCLE_MARKER:
  151. // This node has be visited yet and
  152. // is maybe currently part of a completed root cycle
  153. // we found a new reference to the cycle
  154. // so it's not really a root cycle
  155. // remove the cycle from the root cycles
  156. // and convert it to a normal node
  157. rootCycles.delete(dependency.cycle);
  158. dependency.marker = DONE_MARKER;
  159. break;
  160. // DONE_MARKER: nothing to do, don't recurse into dependencies
  161. }
  162. } else {
  163. // All dependencies of the current node has been visited
  164. // we leave the node
  165. stack.pop();
  166. topOfStack.node.marker = DONE_MARKER;
  167. }
  168. }
  169. const cycle = selectedNode.cycle;
  170. if (cycle) {
  171. for (const node of cycle.nodes) {
  172. node.marker = DONE_MAYBE_ROOT_CYCLE_MARKER;
  173. }
  174. rootCycles.add(cycle);
  175. } else {
  176. selectedNode.marker = DONE_AND_ROOT_MARKER;
  177. roots.add(selectedNode);
  178. }
  179. }
  180. }
  181. // Extract roots from root cycles
  182. // We take the nodes with most incoming edges
  183. // inside of the cycle
  184. for (const cycle of rootCycles) {
  185. let max = 0;
  186. /** @type {Set<Node<T>>} */
  187. const cycleRoots = new Set();
  188. const nodes = cycle.nodes;
  189. for (const node of nodes) {
  190. for (const dep of node.dependencies) {
  191. if (nodes.has(dep)) {
  192. dep.incoming++;
  193. if (dep.incoming < max) continue;
  194. if (dep.incoming > max) {
  195. cycleRoots.clear();
  196. max = dep.incoming;
  197. }
  198. cycleRoots.add(dep);
  199. }
  200. }
  201. }
  202. for (const cycleRoot of cycleRoots) {
  203. roots.add(cycleRoot);
  204. }
  205. }
  206. // When roots were found, return them
  207. if (roots.size > 0) {
  208. return Array.from(roots, r => r.item);
  209. } else {
  210. throw new Error("Implementation of findGraphRoots is broken");
  211. }
  212. };