UbiNodeBreadthFirst.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2. * This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef js_UbiNodeBreadthFirst_h
  6. #define js_UbiNodeBreadthFirst_h
  7. #include "js/UbiNode.h"
  8. #include "js/Utility.h"
  9. #include "js/Vector.h"
  10. namespace JS {
  11. namespace ubi {
  12. // A breadth-first traversal template for graphs of ubi::Nodes.
  13. //
  14. // No GC may occur while an instance of this template is live.
  15. //
  16. // The provided Handler type should have two members:
  17. //
  18. // typename NodeData;
  19. //
  20. // The value type of |BreadthFirst<Handler>::visited|, the HashMap of
  21. // ubi::Nodes that have been visited so far. Since the algorithm needs a
  22. // hash table like this for its own use anyway, it is simple to let
  23. // Handler store its own metadata about each node in the same table.
  24. //
  25. // For example, if you want to find a shortest path to each node from any
  26. // traversal starting point, your |NodeData| type could record the first
  27. // edge to reach each node, and the node from which it originates. Then,
  28. // when the traversal is complete, you can walk backwards from any node
  29. // to some starting point, and the path recorded will be a shortest path.
  30. //
  31. // This type must have a default constructor. If this type owns any other
  32. // resources, move constructors and assignment operators are probably a
  33. // good idea, too.
  34. //
  35. // bool operator() (BreadthFirst& traversal,
  36. // Node origin, const Edge& edge,
  37. // Handler::NodeData* referentData, bool first);
  38. //
  39. // The visitor function, called to report that we have traversed
  40. // |edge| from |origin|. This is called once for each edge we traverse.
  41. // As this is a breadth-first search, any prior calls to the visitor function
  42. // were for origin nodes not further from the start nodes than |origin|.
  43. //
  44. // |traversal| is this traversal object, passed along for convenience.
  45. //
  46. // |referentData| is a pointer to the value of the entry in
  47. // |traversal.visited| for |edge.referent|; the visitor function can
  48. // store whatever metadata it likes about |edge.referent| there.
  49. //
  50. // |first| is true if this is the first time we have visited an edge
  51. // leading to |edge.referent|. This could be stored in NodeData, but
  52. // the algorithm knows whether it has just created the entry in
  53. // |traversal.visited|, so it passes it along for convenience.
  54. //
  55. // The visitor function may call |traversal.abandonReferent()| if it
  56. // doesn't want to traverse the outgoing edges of |edge.referent|. You can
  57. // use this to limit the traversal to a given portion of the graph: it will
  58. // never visit nodes reachable only through nodes that you have abandoned.
  59. // Note that |abandonReferent| must be called the first time the given node
  60. // is reached; that is, |first| must be true.
  61. //
  62. // The visitor function may call |traversal.stop()| if it doesn't want
  63. // to visit any more nodes at all.
  64. //
  65. // The visitor function may consult |traversal.visited| for information
  66. // about other nodes, but it should not add or remove entries.
  67. //
  68. // The visitor function should return true on success, or false if an
  69. // error occurs. A false return value terminates the traversal
  70. // immediately, and causes BreadthFirst<Handler>::traverse to return
  71. // false.
  72. template<typename Handler>
  73. struct BreadthFirst {
  74. // Construct a breadth-first traversal object that reports the nodes it
  75. // reaches to |handler|. The traversal asserts that no GC happens in its
  76. // runtime during its lifetime.
  77. //
  78. // We do nothing with noGC, other than require it to exist, with a lifetime
  79. // that encloses our own.
  80. BreadthFirst(JSContext* cx, Handler& handler, const JS::AutoCheckCannotGC& noGC)
  81. : wantNames(true), cx(cx), visited(), handler(handler), pending(),
  82. traversalBegun(false), stopRequested(false), abandonRequested(false)
  83. { }
  84. // Initialize this traversal object. Return false on OOM.
  85. bool init() { return visited.init(); }
  86. // Add |node| as a starting point for the traversal. You may add
  87. // as many starting points as you like. Return false on OOM.
  88. bool addStart(Node node) { return pending.append(node); }
  89. // Add |node| as a starting point for the traversal (see addStart) and also
  90. // add it to the |visited| set. Return false on OOM.
  91. bool addStartVisited(Node node) {
  92. typename NodeMap::AddPtr ptr = visited.lookupForAdd(node);
  93. if (!ptr && !visited.add(ptr, node, typename Handler::NodeData()))
  94. return false;
  95. return addStart(node);
  96. }
  97. // True if the handler wants us to compute edge names; doing so can be
  98. // expensive in time and memory. True by default.
  99. bool wantNames;
  100. // Traverse the graph in breadth-first order, starting at the given
  101. // start nodes, applying |handler::operator()| for each edge traversed
  102. // as described above.
  103. //
  104. // This should be called only once per instance of this class.
  105. //
  106. // Return false on OOM or error return from |handler::operator()|.
  107. bool traverse()
  108. {
  109. MOZ_ASSERT(!traversalBegun);
  110. traversalBegun = true;
  111. // While there are pending nodes, visit them.
  112. while (!pending.empty()) {
  113. Node origin = pending.front();
  114. pending.popFront();
  115. // Get a range containing all origin's outgoing edges.
  116. auto range = origin.edges(cx, wantNames);
  117. if (!range)
  118. return false;
  119. // Traverse each edge.
  120. for (; !range->empty(); range->popFront()) {
  121. MOZ_ASSERT(!stopRequested);
  122. Edge& edge = range->front();
  123. typename NodeMap::AddPtr a = visited.lookupForAdd(edge.referent);
  124. bool first = !a;
  125. if (first) {
  126. // This is the first time we've reached |edge.referent|.
  127. // Mark it as visited.
  128. if (!visited.add(a, edge.referent, typename Handler::NodeData()))
  129. return false;
  130. }
  131. MOZ_ASSERT(a);
  132. // Report this edge to the visitor function.
  133. if (!handler(*this, origin, edge, &a->value(), first))
  134. return false;
  135. if (stopRequested)
  136. return true;
  137. // Arrange to traverse this edge's referent's outgoing edges
  138. // later --- unless |handler| asked us not to.
  139. if (abandonRequested) {
  140. // Skip the enqueue; reset flag for future iterations.
  141. abandonRequested = false;
  142. } else if (first) {
  143. if (!pending.append(edge.referent))
  144. return false;
  145. }
  146. }
  147. }
  148. return true;
  149. }
  150. // Stop traversal, and return true from |traverse| without visiting any
  151. // more nodes. Only |handler::operator()| should call this function; it
  152. // may do so to stop the traversal early, without returning false and
  153. // then making |traverse|'s caller disambiguate that result from a real
  154. // error.
  155. void stop() { stopRequested = true; }
  156. // Request that the current edge's referent's outgoing edges not be
  157. // traversed. This must be called the first time that referent is reached.
  158. // Other edges *to* that referent will still be traversed.
  159. void abandonReferent() { abandonRequested = true; }
  160. // The context with which we were constructed.
  161. JSContext* cx;
  162. // A map associating each node N that we have reached with a
  163. // Handler::NodeData, for |handler|'s use. This is public, so that
  164. // |handler| can access it to see the traversal thus far.
  165. using NodeMap = js::HashMap<Node, typename Handler::NodeData, js::DefaultHasher<Node>,
  166. js::SystemAllocPolicy>;
  167. NodeMap visited;
  168. private:
  169. // Our handler object.
  170. Handler& handler;
  171. // A queue template. Appending and popping the front are constant time.
  172. // Wasted space is never more than some recent actual population plus the
  173. // current population.
  174. template <typename T>
  175. class Queue {
  176. js::Vector<T, 0, js::SystemAllocPolicy> head, tail;
  177. size_t frontIndex;
  178. public:
  179. Queue() : head(), tail(), frontIndex(0) { }
  180. bool empty() { return frontIndex >= head.length(); }
  181. T& front() {
  182. MOZ_ASSERT(!empty());
  183. return head[frontIndex];
  184. }
  185. void popFront() {
  186. MOZ_ASSERT(!empty());
  187. frontIndex++;
  188. if (frontIndex >= head.length()) {
  189. head.clearAndFree();
  190. head.swap(tail);
  191. frontIndex = 0;
  192. }
  193. }
  194. bool append(const T& elt) {
  195. return frontIndex == 0 ? head.append(elt) : tail.append(elt);
  196. }
  197. };
  198. // A queue of nodes that we have reached, but whose outgoing edges we
  199. // have not yet traversed. Nodes reachable in fewer edges are enqueued
  200. // earlier.
  201. Queue<Node> pending;
  202. // True if our traverse function has been called.
  203. bool traversalBegun;
  204. // True if we've been asked to stop the traversal.
  205. bool stopRequested;
  206. // True if we've been asked to abandon the current edge's referent.
  207. bool abandonRequested;
  208. };
  209. } // namespace ubi
  210. } // namespace JS
  211. #endif // js_UbiNodeBreadthFirst_h