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
18#include "tests.hpp"
19
20#include <format>
21#include <stdexcept>
22#include <string>
23#include <vector>
24
27#include <nlohmann/json.hpp>
28
29using namespace SILICON::core;
30using namespace SILICON::project;
31
32namespace {
33
34std::string sceneWithSubcircuits(std::vector<std::string> slugs)
35{
36 nlohmann::ordered_json scene;
37 scene["circuit"] =
38 nlohmann::ordered_json{{"version", SILICON_VERSION},
39 {"name", "Document"},
40 {"components", nlohmann::ordered_json::array()}};
41 scene["visual"]["components"] = nlohmann::ordered_json::array();
42 scene["visual"]["wires"] = nlohmann::ordered_json::array();
43
44 for (const auto& slug : slugs) {
45 scene["circuit"]["components"].push_back(
46 nlohmann::ordered_json{{"id", scene["circuit"]["components"].size()},
47 {"type", "Subcircuit"},
48 {"properties", {{"slug", slug}}},
49 {"inputs", nlohmann::ordered_json::array()},
50 {"outputs", nlohmann::ordered_json::array()}});
51 }
52
53 return scene.dump(2);
54}
55
56std::string emptyScene()
57{
58 return sceneWithSubcircuits({});
59}
60
61SILICON::project::Document circuit(std::string path, std::string sceneJson)
62{
63 return {std::move(path), std::move(sceneJson)};
64}
65
66SILICON::project::Document subcircuit(std::string slug, std::string sceneJson)
67{
68 return {std::format("circuits/{}.json", slug), std::move(sceneJson)};
69}
70
71void expectRuntimeErrorContaining(auto callback, const std::string& expected)
72{
73 try {
74 callback();
75 FAIL() << "Expected std::runtime_error";
76 } catch (const std::runtime_error& e) {
77 EXPECT_NE(std::string(e.what()).find(expected), std::string::npos)
78 << "Actual message: " << e.what();
79 }
80}
81
82} // namespace
83
84TEST(CircuitDependencyGraphTest, ExtractsEdgesFromCircuitsAndSubcircuits)
85{
88 {circuit("circuits/main.json", sceneWithSubcircuits({"adder"})),
89 subcircuit("adder", sceneWithSubcircuits({"half_adder"})),
90 subcircuit("half_adder", emptyScene())});
91
92 EXPECT_EQ(graph.dependentsOf("circuits/adder.json"),
93 std::vector<std::string>({"circuits/main.json"}));
94 EXPECT_EQ(graph.dependentsOf("circuits/half_adder.json"),
95 std::vector<std::string>({"circuits/adder.json"}));
96}
97
98TEST(CircuitDependencyGraphTest, DuplicatePlacementsProduceOneDependency)
99{
101 graph.rebuildFromProject(
102 {circuit("circuits/main.json", sceneWithSubcircuits({"adder", "adder"})),
103 subcircuit("adder", emptyScene())});
104
105 EXPECT_EQ(graph.dependentsOf("circuits/adder.json"),
106 std::vector<std::string>({"circuits/main.json"}));
107}
108
109TEST(CircuitDependencyGraphTest, RejectsMissingSubcircuitTarget)
110{
112
113 EXPECT_THROW(graph.rebuildFromProject(
114 {circuit("circuits/main.json", sceneWithSubcircuits({"missing"}))}),
115 std::runtime_error);
116}
117
118TEST(CircuitDependencyGraphTest, DetectsDirectSelfCycle)
119{
121 graph.addDocument("circuits/adder.json");
122
123 EXPECT_TRUE(
124 graph.wouldIntroduceCycle("circuits/adder.json", sceneWithSubcircuits({"adder"})));
125}
126
127TEST(CircuitDependencyGraphTest, RejectsDirectSelfCycleWithSlugTrace)
128{
130 graph.addDocument("circuits/adder.json");
131
132 expectRuntimeErrorContaining(
133 [&] {
134 graph.replaceDocumentDependencies("circuits/adder.json",
135 sceneWithSubcircuits({"adder"}));
136 },
137 "recursion trace: [adder, adder]");
138
139 EXPECT_TRUE(graph.dependentsOf("circuits/adder.json").empty());
140}
141
142TEST(CircuitDependencyGraphTest, DetectsIndirectCycle)
143{
145 graph.rebuildFromProject({circuit("circuits/main.json", sceneWithSubcircuits({"cpu"})),
146 subcircuit("cpu", sceneWithSubcircuits({"alu"})),
147 subcircuit("alu", emptyScene())});
148
149 EXPECT_TRUE(
150 graph.wouldIntroduceCycle("circuits/alu.json", sceneWithSubcircuits({"cpu"})));
151}
152
153TEST(CircuitDependencyGraphTest, RejectsIndirectCycleWithSlugTrace)
154{
156 graph.rebuildFromProject({circuit("circuits/main.json", sceneWithSubcircuits({"cpu"})),
157 subcircuit("cpu", sceneWithSubcircuits({"alu"})),
158 subcircuit("alu", emptyScene())});
159
160 expectRuntimeErrorContaining(
161 [&] {
162 graph.replaceDocumentDependencies("circuits/alu.json",
163 sceneWithSubcircuits({"cpu"}));
164 },
165 "recursion trace: [cpu, alu, cpu]");
166
167 EXPECT_EQ(graph.dependentsOf("circuits/cpu.json"),
168 std::vector<std::string>({"circuits/main.json"}));
169}
170
171TEST(CircuitDependencyGraphTest, RebuildRejectsCyclicProject)
172{
174
175 EXPECT_THROW(graph.rebuildFromProject(
176 {circuit("circuits/main.json", sceneWithSubcircuits({"cpu"})),
177 subcircuit("cpu", sceneWithSubcircuits({"alu"})),
178 subcircuit("alu", sceneWithSubcircuits({"cpu"}))}),
179 std::runtime_error);
180}
181
182TEST(CircuitDependencyGraphTest, LooksUpDependentsForDeletionBlocking)
183{
185 graph.rebuildFromProject({circuit("circuits/main.json", sceneWithSubcircuits({"alu"})),
186 circuit("circuits/debug.json", sceneWithSubcircuits({"alu"})),
187 subcircuit("alu", sceneWithSubcircuits({"adder"})),
188 subcircuit("adder", emptyScene())});
189
190 EXPECT_EQ(graph.dependentsOf("circuits/alu.json"),
191 (std::vector<std::string>{"circuits/debug.json", "circuits/main.json"}));
192 EXPECT_EQ(graph.dependentsOf("circuits/adder.json"),
193 std::vector<std::string>({"circuits/alu.json"}));
194}
195
196TEST(CircuitDependencyGraphTest, ReplacementRequiresRegisteredDocument)
197{
199
200 EXPECT_THROW(graph.replaceDocumentDependencies("circuits/missing.json", emptyScene()),
201 std::runtime_error);
202 EXPECT_FALSE(graph.containsDocument("circuits/missing.json"));
203}
204
205TEST(CircuitDependencyGraphTest, ReferencedDocumentRemovalIsRejectedAtomically)
206{
208 graph.rebuildFromProject({circuit("circuits/main.json", sceneWithSubcircuits({"alu"})),
209 circuit("circuits/debug.json", sceneWithSubcircuits({"alu"})),
210 subcircuit("alu", emptyScene())});
211
212 try {
213 graph.removeDocument("circuits/alu.json");
214 FAIL() << "Expected referenced removal to fail";
215 } catch (const std::runtime_error& error) {
216 EXPECT_NE(std::string(error.what()).find("circuits/debug.json"), std::string::npos);
217 EXPECT_NE(std::string(error.what()).find("circuits/main.json"), std::string::npos);
218 }
219
220 EXPECT_TRUE(graph.containsDocument("circuits/alu.json"));
221 EXPECT_EQ(graph.dependentsOf("circuits/alu.json"),
222 (std::vector<std::string>{"circuits/debug.json", "circuits/main.json"}));
223
224 graph.removeDocument("circuits/main.json");
225 EXPECT_FALSE(graph.containsDocument("circuits/main.json"));
226 EXPECT_EQ(graph.dependentsOf("circuits/alu.json"),
227 std::vector<std::string>{"circuits/debug.json"});
228}
229
230TEST(CircuitDependencyGraphTest, RejectsMalformedSubcircuitComponentsWithContext)
231{
232 for (const std::string_view malformed :
233 {R"({"components":[{"type":"Subcircuit"}]})",
234 R"({"components":[{"type":"Subcircuit","properties":{}}]})",
235 R"({"components":[{"type":"Subcircuit","properties":{"slug":123}}]})",
236 R"({"components":[{"type":"Subcircuit","properties":{"slug":""}}]})",
237 R"({"components":[{"type":"Subcircuit","properties":{"slug":"a/b"}}]})"}) {
239 graph.addDocument("circuits/main.json");
240 expectRuntimeErrorContaining(
241 [&] { graph.replaceDocumentDependencies("circuits/main.json", malformed); },
242 "circuits/main.json");
243 }
244}
245
246TEST(CircuitDependencyGraphTest, RejectsMalformedComponentsField)
247{
249 graph.addDocument("circuits/main.json");
250 expectRuntimeErrorContaining(
251 [&] {
252 graph.replaceDocumentDependencies("circuits/main.json",
253 R"({"components":"not-an-array"})");
254 },
255 "components must be an array");
256}
257
258TEST(CircuitDependencyGraphTest, SupportsBothEstablishedJsonRootForms)
259{
261 graph.rebuildFromProject(
262 {circuit("circuits/main.json",
263 R"({"components":[{"type":"Subcircuit","properties":{"slug":"alu"}}]})"),
264 subcircuit("alu", emptyScene())});
265 EXPECT_EQ(graph.dependentsOf("circuits/alu.json"),
266 std::vector<std::string>{"circuits/main.json"});
267}
268
269TEST(CircuitDependencyGraphTest, CyclePredicatePropagatesNonCycleFailures)
270{
272 graph.addDocument("circuits/main.json");
273
274 EXPECT_FALSE(graph.wouldIntroduceCycle("circuits/main.json", emptyScene()));
275 EXPECT_THROW(static_cast<void>(graph.wouldIntroduceCycle(
276 "circuits/main.json", sceneWithSubcircuits({"missing"}))),
277 std::runtime_error);
278 EXPECT_THROW(
279 static_cast<void>(graph.wouldIntroduceCycle("circuits/main.json", "not json")),
280 std::runtime_error);
281}
282
283TEST(CircuitDependencyGraphTest, RecursiveErrorMessageIncludesTrace)
284{
286 graph.rebuildFromProject({subcircuit("cpu", sceneWithSubcircuits({"alu"})),
287 subcircuit("alu", emptyScene())});
288 try {
289 graph.validateDocumentDependencies("circuits/alu.json",
290 sceneWithSubcircuits({"cpu"}));
291 FAIL() << "Expected recursion";
292 } catch (const std::runtime_error& error) {
293 EXPECT_NE(std::string(error.what()).find("[cpu, alu, cpu]"), std::string::npos);
294 }
295}
296
297TEST(CircuitDependencyGraphTest, FailedFullRebuildPreservesPreviousGraph)
298{
300 graph.rebuildFromProject({circuit("circuits/main.json", sceneWithSubcircuits({"alu"})),
301 subcircuit("alu", emptyScene())});
302
303 EXPECT_THROW(graph.rebuildFromProject({circuit("circuits/replacement.json",
304 sceneWithSubcircuits({"missing"}))}),
305 std::runtime_error);
306
307 EXPECT_TRUE(graph.containsDocument("circuits/main.json"));
308 EXPECT_TRUE(graph.containsDocument("circuits/alu.json"));
309 EXPECT_FALSE(graph.containsDocument("circuits/replacement.json"));
310 EXPECT_EQ(graph.dependentsOf("circuits/alu.json"),
311 std::vector<std::string>{"circuits/main.json"});
312}
313
314TEST(CircuitDependencyGraphTest, CodeDocumentsAreExcludedFromRebuild)
315{
317 graph.rebuildFromProject({circuit("circuits/main.json", emptyScene()),
318 Document("code/adder.v", "module adder; endmodule")});
319 EXPECT_TRUE(graph.containsDocument("circuits/main.json"));
320 EXPECT_FALSE(graph.containsDocument("code/adder.v"));
321 EXPECT_THROW(graph.addDocument("code/adder.v"), std::invalid_argument);
322}
323
324TEST(CircuitDependencyGraphTest, BinaryDocumentsAreExcludedFromRebuild)
325{
327 graph.rebuildFromProject({circuit("circuits/main.json", emptyScene()),
328 Document("bin/firmware", std::string("\0\xff", 2))});
329 EXPECT_TRUE(graph.containsDocument("circuits/main.json"));
330 EXPECT_FALSE(graph.containsDocument("bin/firmware"));
331 EXPECT_THROW(graph.addDocument("bin/firmware"), std::invalid_argument);
332}
333
334TEST(CircuitDependencyGraphTest, RebuildRejectsDuplicateGraphicalDocuments)
335{
337 EXPECT_THROW(graph.rebuildFromProject({circuit("circuits/main.json", emptyScene()),
338 circuit("circuits/main.json", emptyScene())}),
339 std::runtime_error);
340 EXPECT_FALSE(graph.containsDocument("circuits/main.json"));
341}
342
343TEST(ProjectContextTest, FailedCircuitUpdateLeavesDocumentsAndDependenciesUnchanged)
344{
346 project.setDocuments({circuit("circuits/main.json", sceneWithSubcircuits({"alu"})),
347 subcircuit("alu", emptyScene())});
348
349 EXPECT_THROW(project.upsertDocument(
350 circuit("circuits/main.json", sceneWithSubcircuits({"missing"}))),
351 std::runtime_error);
352
353 ASSERT_NE(project.documents().find("circuits/main.json"), nullptr);
354 EXPECT_EQ(project.documents().find("circuits/main.json")->getContents(),
355 sceneWithSubcircuits({"alu"}));
356 EXPECT_EQ(project.circuitDependencies().dependentsOf("circuits/alu.json"),
357 std::vector<std::string>{"circuits/main.json"});
358}
359
360TEST(ProjectContextTest, ReferencedRemovalLeavesProjectStateUnchanged)
361{
363 project.setDocuments({circuit("circuits/main.json", sceneWithSubcircuits({"alu"})),
364 subcircuit("alu", emptyScene())});
365
366 EXPECT_THROW(project.removeDocument("circuits/alu.json"), std::runtime_error);
367 EXPECT_TRUE(project.documents().contains("circuits/alu.json"));
368 EXPECT_TRUE(project.circuitDependencies().containsDocument("circuits/alu.json"));
369}
370
371TEST(ProjectContextTest, ListenerFailureDoesNotReportACommittedUpdateAsFailed)
372{
374 project.setDocuments(
375 {circuit("circuits/main.json", emptyScene()), subcircuit("alu", emptyScene())});
376
377 bool successfulListenerCalled = false;
378 const auto throwingListener = project.documents().addListener(
379 [](const DocumentChange&) { throw std::runtime_error("listener failed"); });
380 const auto successfulListener = project.documents().addListener(
381 [&](const DocumentChange&) { successfulListenerCalled = true; });
382
383 EXPECT_NO_THROW(project.upsertDocument(
384 circuit("circuits/main.json", sceneWithSubcircuits({"alu"}))));
385
386 EXPECT_TRUE(successfulListenerCalled);
387 ASSERT_NE(project.documents().find("circuits/main.json"), nullptr);
388 EXPECT_EQ(project.documents().find("circuits/main.json")->getContents(),
389 sceneWithSubcircuits({"alu"}));
390 EXPECT_EQ(project.circuitDependencies().dependentsOf("circuits/alu.json"),
391 std::vector<std::string>{"circuits/main.json"});
392
393 project.documents().removeListener(throwingListener);
394 project.documents().removeListener(successfulListener);
395}
Runtime-only graph of Circuit-to-Circuit instantiation dependencies.
bool containsDocument(std::string_view documentPath) const
Checks whether a document vertex is present in the graph.
bool wouldIntroduceCycle(std::string_view documentPath, std::string_view contents) const
Tests whether rewiring a document's dependencies would create a cycle.
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.
void addDocument(std::string_view documentPath)
Ensures a document vertex exists, creating it if necessary.
void rebuildFromProject(const std::vector< Document > &documents)
Rebuilds the graph from a full project description.
TEST(CircuitDependencyGraphTest, ExtractsEdgesFromCircuitsAndSubcircuits)