24#include <unordered_set>
27#include <boost/graph/topological_sort.hpp>
28#include <nlohmann/json.hpp>
33 [[nodiscard]]
bool isCircuitDocument(
const DocumentType type)
38 [[nodiscard]] std::string slugForDocumentPath(
const std::string_view documentPath)
44 return std::string(documentPath);
47 [[nodiscard]] std::string formatRecursionTrace(
const std::vector<std::string>& trace)
49 std::string result =
"[";
50 for (std::size_t i = 0; i < trace.size(); ++i) {
59 [[nodiscard]] std::vector<std::string>
60 extractSubcircuitDependencies(
const std::string_view documentPath,
61 const std::string_view contents)
63 std::vector<std::string> dependencies;
65 nlohmann::json parsed;
67 parsed = nlohmann::json::parse(contents);
68 }
catch (
const nlohmann::json::parse_error& error) {
69 throw std::runtime_error(
70 std::format(
"{} contains invalid JSON: {}", documentPath, error.what()));
72 if (!parsed.is_object())
73 throw std::runtime_error(
74 std::format(
"{} must contain a JSON object", documentPath));
76 const auto* circuit = &parsed;
77 if (
const auto circuitIt = parsed.find(
"circuit"); circuitIt != parsed.end()) {
78 if (!circuitIt->is_object())
79 throw std::runtime_error(
80 std::format(
"{}.circuit must be an object", documentPath));
81 circuit = &*circuitIt;
84 const auto componentsIt = circuit->find(
"components");
86 if (componentsIt == circuit->end())
88 if (!componentsIt->is_array())
89 throw std::runtime_error(
90 std::format(
"{}.components must be an array", documentPath));
92 std::unordered_set<std::string> seen;
93 for (
const auto& component : *componentsIt) {
94 if (!component.is_object())
96 const auto typeIt = component.find(
"type");
97 if (typeIt == component.end() || !typeIt->is_string()
98 || typeIt->get_ref<
const std::string&>() !=
"Subcircuit")
101 const auto propertiesIt = component.find(
"properties");
102 if (propertiesIt == component.end() || !propertiesIt->is_object())
103 throw std::runtime_error(std::format(
104 "{} contains a Subcircuit component whose 'properties' must be an object",
107 const auto slugIt = propertiesIt->find(
"slug");
108 if (slugIt == propertiesIt->end() || !slugIt->is_string())
109 throw std::runtime_error(std::format(
110 "{} contains a Subcircuit component with no string 'slug' property",
113 const auto slug = slugIt->get<std::string>();
115 throw std::runtime_error(
116 std::format(
"{} contains a Subcircuit component with invalid slug '{}'",
117 documentPath, slug));
120 if (seen.insert(path).second)
121 dependencies.push_back(std::move(path));
124 std::ranges::sort(dependencies);
128 [[nodiscard]] std::string
129 formatReferencedDocumentMessage(
const std::string_view documentPath,
130 const std::vector<std::string>& dependents)
133 std::format(
"Cannot remove {} because it is referenced by:", documentPath);
134 for (
const auto& dependent : dependents)
135 message += std::format(
"\n {}", dependent);
150 if (!type || !isCircuitDocument(*type))
151 throw std::invalid_argument(
152 "Circuit dependency graph entries must be Circuit documents");
156 auto updated = *
this;
157 static_cast<void>(updated.ensureVertex(documentPath));
158 *
this = std::move(updated);
169 auto updated = *
this;
170 const auto removed = updated.findVertex(documentPath);
171 boost::clear_vertex(*removed, updated.graph);
172 boost::remove_vertex(*removed, updated.graph);
173 updated.rebuildPathIndex();
174 *
this = std::move(updated);
178 const std::string_view documentPath)
const
183 if (!dependents.empty()) {
184 auto message = formatReferencedDocumentMessage(documentPath, dependents);
185 throw std::runtime_error(std::move(message));
192 std::unordered_set<std::string_view> registeredPaths;
194 for (
const auto& document : documents) {
195 if (!isCircuitDocument(document.getType()))
197 if (!registeredPaths.insert(document.getPath()).second)
198 throw std::runtime_error(
199 std::format(
"Duplicate dependency graph document {}", document.getPath()));
200 static_cast<void>(rebuilt.
ensureVertex(document.getPath()));
203 for (
const auto& document : documents) {
204 if (isCircuitDocument(document.getType()))
209 *
this = std::move(rebuilt);
213 const std::string_view documentPath,
const std::string_view contents)
216 updated.throwIfCyclic();
217 *
this = std::move(updated);
221 const std::string_view documentPath,
const std::string_view contents)
const
224 candidate.throwIfCyclic();
228 const std::string_view contents)
const
232 candidate.validateAcyclic();
233 }
catch (
const boost::not_a_dag&) {
244 const auto target =
findVertex(subcircuitPath);
248 for (
const auto edge : boost::make_iterator_range(boost::edges(
graph))) {
249 if (boost::target(edge,
graph) == *target)
250 dependents.push_back(
graph[boost::source(edge,
graph)].path);
253 std::ranges::sort(dependents);
262std::optional<CircuitDependencyGraph::Vertex>
274 const std::string_view contents)
const
276 auto updated = *
this;
282 const std::string_view contents)
284 const auto documentVertex =
findVertex(documentPath);
286 throw std::runtime_error(
287 std::format(
"Unknown dependency graph document {}", documentPath));
289 const auto dependencies = extractSubcircuitDependencies(documentPath, contents);
290 std::vector<Vertex> dependencyVertices;
291 dependencyVertices.reserve(dependencies.size());
293 for (
const auto& dependency : dependencies) {
294 if (
const auto vertex =
findVertex(dependency)) {
295 dependencyVertices.push_back(*vertex);
297 throw std::runtime_error(
298 std::format(
"{} references missing subcircuit {}", documentPath, dependency));
302 boost::clear_out_edges(*documentVertex,
graph);
303 for (
const auto dependencyVertex : dependencyVertices)
304 boost::add_edge(*documentVertex, dependencyVertex,
graph);
310 std::vector<Vertex> path;
312 for (
const auto vertex : boost::make_iterator_range(boost::vertices(
graph))) {
324 const Vertex vertex, std::vector<VisitState>& states, std::vector<Vertex>& path)
const
327 path.push_back(vertex);
329 for (
const auto edge : boost::make_iterator_range(boost::out_edges(vertex,
graph))) {
330 const auto dependency = boost::target(edge,
graph);
347std::vector<std::string>
349 const std::vector<Vertex>& path)
const
351 const auto cycleStart = std::ranges::find(path, repeated);
353 std::vector<std::string> trace;
354 trace.reserve(
static_cast<std::size_t
>(std::ranges::distance(cycleStart, path.end()))
357 for (
auto it = cycleStart; it != path.end(); ++it)
358 trace.push_back(slugForDocumentPath(
graph[*it].path));
359 trace.push_back(slugForDocumentPath(
graph[repeated].path));
367 const auto key = std::string(documentPath);
371 const auto vertex = boost::add_vertex(
graph);
372 graph[vertex].path = key;
381 for (
const auto vertex : boost::make_iterator_range(boost::vertices(
graph)))
387 std::vector<Vertex> order;
388 order.reserve(boost::num_vertices(
graph));
389 boost::topological_sort(
graph, std::back_inserter(order));
396 }
catch (
const boost::not_a_dag&) {
398 throw std::runtime_error(std::format(
399 "Project contains recursive subcircuit dependencies; recursion trace: {}",
400 formatRecursionTrace(trace)));
Runtime-only graph of Circuit-to-Circuit instantiation dependencies.
std::vector< std::string > DocumentPathList
List of project-relative document paths.
void throwIfCyclic() const
Throws a runtime error with a recursion trace if the graph is cyclic.
void rebuildPathIndex()
Rebuilds pathToVertex from the current graph.
std::optional< Vertex > findVertex(std::string_view documentPath) const
bool containsDocument(std::string_view documentPath) const
Checks whether a document vertex is present in the graph.
CircuitDependencyGraph()=default
Graph graph
The dependency graph itself.
void replaceDependencyEdges(std::string_view documentPath, std::string_view contents)
std::vector< std::string > findCycleTrace() const
Finds one recursive dependency cycle and returns it as ordered slugs.
bool wouldIntroduceCycle(std::string_view documentPath, std::string_view contents) const
Tests whether rewiring a document's dependencies would create a cycle.
CircuitDependencyGraph withDocumentDependencies(std::string_view documentPath, std::string_view contents) const
void removeDocument(std::string_view documentPath)
Removes an unreferenced document atomically.
void validateDocumentDependencies(std::string_view documentPath, std::string_view contents) const
DocumentPathList dependentsOf(std::string_view subcircuitPath) const
Returns the sorted list of documents that depend on a subcircuit.
void replaceDocumentDependencies(std::string_view documentPath, std::string_view contents)
Replaces the dependency edges of a single document atomically.
PathToVertex pathToVertex
Path-to-vertex index kept in sync with graph.
void addDocument(std::string_view documentPath)
Ensures a document vertex exists, creating it if necessary.
void clear()
Removes every vertex and edge, returning the graph to an empty state.
std::vector< std::string > cycleTraceEndingAt(Vertex repeated, const std::vector< Vertex > &path) const
Builds a slug trace when DFS reaches a vertex already in path.
boost::graph_traits< Graph >::vertex_descriptor Vertex
Boost vertex descriptor (an integer index under vecS).
void rebuildFromProject(const std::vector< Document > &documents)
Rebuilds the graph from a full project description.
Vertex ensureVertex(std::string_view documentPath)
Ensures a document vertex exists in this graph (O(1)).
void validateAcyclic() const
Verifies the graph is acyclic.
void validateDocumentRemoval(std::string_view documentPath) const
std::vector< std::string > findCycleTraceFrom(Vertex vertex, std::vector< VisitState > &states, std::vector< Vertex > &path) const
DFS step used by findCycleTrace.
std::string documentPathForSlug(const DocumentType type, const std::string_view slug)
constexpr DocumentCategory categoryOf(const DocumentType type)
std::optional< std::string > documentSlugForPath(const std::string_view path)
bool isValidDocumentSlug(const std::string_view slug)
std::optional< DocumentType > documentTypeForPath(const std::string_view path)