SILICON
Loading...
Searching...
No Matches
circuitDependencyGraph.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
19
20#include <algorithm>
21#include <format>
22#include <ranges>
23#include <stdexcept>
24#include <unordered_set>
25#include <utility>
26
27#include <boost/graph/topological_sort.hpp>
28#include <nlohmann/json.hpp>
29
31namespace {
32
33 [[nodiscard]] bool isCircuitDocument(const DocumentType type)
34 {
36 }
37
38 [[nodiscard]] std::string slugForDocumentPath(const std::string_view documentPath)
39 {
40 if (documentTypeForPath(documentPath) == DocumentType::Circuit) {
41 if (const auto slug = documentSlugForPath(documentPath))
42 return *slug;
43 }
44 return std::string(documentPath);
45 }
46
47 [[nodiscard]] std::string formatRecursionTrace(const std::vector<std::string>& trace)
48 {
49 std::string result = "[";
50 for (std::size_t i = 0; i < trace.size(); ++i) {
51 if (i > 0)
52 result += ", ";
53 result += trace[i];
54 }
55 result += "]";
56 return result;
57 }
58
59 [[nodiscard]] std::vector<std::string>
60 extractSubcircuitDependencies(const std::string_view documentPath,
61 const std::string_view contents)
62 {
63 std::vector<std::string> dependencies;
64
65 nlohmann::json parsed;
66 try {
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()));
71 }
72 if (!parsed.is_object())
73 throw std::runtime_error(
74 std::format("{} must contain a JSON object", documentPath));
75
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;
82 }
83
84 const auto componentsIt = circuit->find("components");
85 // Older project documents without a components member represent an empty circuit.
86 if (componentsIt == circuit->end())
87 return dependencies;
88 if (!componentsIt->is_array())
89 throw std::runtime_error(
90 std::format("{}.components must be an array", documentPath));
91
92 std::unordered_set<std::string> seen;
93 for (const auto& component : *componentsIt) {
94 if (!component.is_object())
95 continue;
96 const auto typeIt = component.find("type");
97 if (typeIt == component.end() || !typeIt->is_string()
98 || typeIt->get_ref<const std::string&>() != "Subcircuit")
99 continue;
100
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",
105 documentPath));
106
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",
111 documentPath));
112
113 const auto slug = slugIt->get<std::string>();
114 if (!isValidDocumentSlug(slug))
115 throw std::runtime_error(
116 std::format("{} contains a Subcircuit component with invalid slug '{}'",
117 documentPath, slug));
118
120 if (seen.insert(path).second)
121 dependencies.push_back(std::move(path));
122 }
123
124 std::ranges::sort(dependencies);
125 return dependencies;
126 }
127
128 [[nodiscard]] std::string
129 formatReferencedDocumentMessage(const std::string_view documentPath,
130 const std::vector<std::string>& dependents)
131 {
132 auto message =
133 std::format("Cannot remove {} because it is referenced by:", documentPath);
134 for (const auto& dependent : dependents)
135 message += std::format("\n {}", dependent);
136 return message;
137 }
138
139} // namespace
140
142{
143 graph.clear();
144 pathToVertex.clear();
145}
146
147void CircuitDependencyGraph::addDocument(const std::string_view documentPath)
148{
149 const auto type = documentTypeForPath(documentPath);
150 if (!type || !isCircuitDocument(*type))
151 throw std::invalid_argument(
152 "Circuit dependency graph entries must be Circuit documents");
153 if (containsDocument(documentPath))
154 return;
155
156 auto updated = *this;
157 static_cast<void>(updated.ensureVertex(documentPath));
158 *this = std::move(updated);
159}
160
161void CircuitDependencyGraph::removeDocument(const std::string_view documentPath)
162{
163 const auto vertex = findVertex(documentPath);
164 if (!vertex)
165 return;
166
167 validateDocumentRemoval(documentPath);
168
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);
175}
176
178 const std::string_view documentPath) const
179{
180 if (!containsDocument(documentPath))
181 return;
182 auto dependents = dependentsOf(documentPath);
183 if (!dependents.empty()) {
184 auto message = formatReferencedDocumentMessage(documentPath, dependents);
185 throw std::runtime_error(std::move(message));
186 }
187}
188
189void CircuitDependencyGraph::rebuildFromProject(const std::vector<Document>& documents)
190{
192 std::unordered_set<std::string_view> registeredPaths;
193
194 for (const auto& document : documents) {
195 if (!isCircuitDocument(document.getType()))
196 continue;
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()));
201 }
202
203 for (const auto& document : documents) {
204 if (isCircuitDocument(document.getType()))
205 rebuilt.replaceDependencyEdges(document.getPath(), document.getContents());
206 }
207
208 rebuilt.throwIfCyclic();
209 *this = std::move(rebuilt);
210}
211
213 const std::string_view documentPath, const std::string_view contents)
214{
215 auto updated = withDocumentDependencies(documentPath, contents);
216 updated.throwIfCyclic();
217 *this = std::move(updated);
218}
219
221 const std::string_view documentPath, const std::string_view contents) const
222{
223 auto candidate = withDocumentDependencies(documentPath, contents);
224 candidate.throwIfCyclic();
225}
226
227bool CircuitDependencyGraph::wouldIntroduceCycle(const std::string_view documentPath,
228 const std::string_view contents) const
229{
230 const auto candidate = withDocumentDependencies(documentPath, contents);
231 try {
232 candidate.validateAcyclic();
233 } catch (const boost::not_a_dag&) {
234 return true;
235 }
236
237 return false;
238}
239
241CircuitDependencyGraph::dependentsOf(const std::string_view subcircuitPath) const
242{
243 DocumentPathList dependents;
244 const auto target = findVertex(subcircuitPath);
245 if (!target)
246 return dependents;
247
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);
251 }
252
253 std::ranges::sort(dependents);
254 return dependents;
255}
256
257bool CircuitDependencyGraph::containsDocument(const std::string_view documentPath) const
258{
259 return findVertex(documentPath).has_value();
260}
261
262std::optional<CircuitDependencyGraph::Vertex>
263CircuitDependencyGraph::findVertex(const std::string_view documentPath) const
264{
265 const auto it = pathToVertex.find(documentPath);
266 if (it == pathToVertex.end())
267 return std::nullopt;
268
269 return it->second;
270}
271
273CircuitDependencyGraph::withDocumentDependencies(const std::string_view documentPath,
274 const std::string_view contents) const
275{
276 auto updated = *this;
277 updated.replaceDependencyEdges(documentPath, contents);
278 return updated;
279}
280
281void CircuitDependencyGraph::replaceDependencyEdges(const std::string_view documentPath,
282 const std::string_view contents)
283{
284 const auto documentVertex = findVertex(documentPath);
285 if (!documentVertex)
286 throw std::runtime_error(
287 std::format("Unknown dependency graph document {}", documentPath));
288
289 const auto dependencies = extractSubcircuitDependencies(documentPath, contents);
290 std::vector<Vertex> dependencyVertices;
291 dependencyVertices.reserve(dependencies.size());
292
293 for (const auto& dependency : dependencies) {
294 if (const auto vertex = findVertex(dependency)) {
295 dependencyVertices.push_back(*vertex);
296 } else {
297 throw std::runtime_error(
298 std::format("{} references missing subcircuit {}", documentPath, dependency));
299 }
300 }
301
302 boost::clear_out_edges(*documentVertex, graph);
303 for (const auto dependencyVertex : dependencyVertices)
304 boost::add_edge(*documentVertex, dependencyVertex, graph);
305}
306
307std::vector<std::string> CircuitDependencyGraph::findCycleTrace() const
308{
309 std::vector<VisitState> states(boost::num_vertices(graph), VisitState::Unvisited);
310 std::vector<Vertex> path;
311
312 for (const auto vertex : boost::make_iterator_range(boost::vertices(graph))) {
313 if (states[vertex] != VisitState::Unvisited)
314 continue;
315
316 if (auto trace = findCycleTraceFrom(vertex, states, path); !trace.empty())
317 return trace;
318 }
319
320 return {};
321}
322
324 const Vertex vertex, std::vector<VisitState>& states, std::vector<Vertex>& path) const
325{
326 states[vertex] = VisitState::Visiting;
327 path.push_back(vertex);
328
329 for (const auto edge : boost::make_iterator_range(boost::out_edges(vertex, graph))) {
330 const auto dependency = boost::target(edge, graph);
331
332 if (states[dependency] == VisitState::Visiting)
333 return cycleTraceEndingAt(dependency, path);
334
335 if (states[dependency] != VisitState::Unvisited)
336 continue;
337
338 if (auto trace = findCycleTraceFrom(dependency, states, path); !trace.empty())
339 return trace;
340 }
341
342 path.pop_back();
343 states[vertex] = VisitState::Visited;
344 return {};
345}
346
347std::vector<std::string>
349 const std::vector<Vertex>& path) const
350{
351 const auto cycleStart = std::ranges::find(path, repeated);
352
353 std::vector<std::string> trace;
354 trace.reserve(static_cast<std::size_t>(std::ranges::distance(cycleStart, path.end()))
355 + 1);
356
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));
360
361 return trace;
362}
363
365CircuitDependencyGraph::ensureVertex(const std::string_view documentPath)
366{
367 const auto key = std::string(documentPath);
368 if (const auto it = pathToVertex.find(key); it != pathToVertex.end())
369 return it->second;
370
371 const auto vertex = boost::add_vertex(graph);
372 graph[vertex].path = key;
373 pathToVertex.emplace(key, vertex);
374 return vertex;
375}
376
378{
379 pathToVertex.clear();
380 pathToVertex.reserve(boost::num_vertices(graph));
381 for (const auto vertex : boost::make_iterator_range(boost::vertices(graph)))
382 pathToVertex.emplace(graph[vertex].path, vertex);
383}
384
386{
387 std::vector<Vertex> order;
388 order.reserve(boost::num_vertices(graph));
389 boost::topological_sort(graph, std::back_inserter(order));
390}
391
393{
394 try {
396 } catch (const boost::not_a_dag&) {
397 const auto trace = findCycleTrace();
398 throw std::runtime_error(std::format(
399 "Project contains recursive subcircuit dependencies; recursion trace: {}",
400 formatRecursionTrace(trace)));
401 }
402}
403
404} // namespace SILICON::project
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.
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)