SILICON
Loading...
Searching...
No Matches
projectDocument.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
21
22#include <algorithm>
23#include <cstdint>
24#include <string>
25#include <string_view>
26#include <type_traits>
27#include <vector>
28
29#include <gtest/gtest.h>
30#include <nlohmann/json.hpp>
31#include <sisl/sisl.hpp>
32
33using namespace SILICON::core;
34using namespace SILICON::project;
35
39
40static_assert(std::is_class_v<sisl::Isa>);
41
42TEST(ProjectDocumentTest, ClassifiesCanonicalFlatPaths)
43{
44 EXPECT_EQ(SILICON::project::documentTypeForPath("circuits/main.json"),
47 EXPECT_EQ(SILICON::project::documentTypeForPath("isa/rv32/instr_format.sisl"), DocumentType::Sisl);
48 EXPECT_FALSE(SILICON::project::documentTypeForPath("code/rv32.isa"));
49 EXPECT_EQ(SILICON::project::documentTypeForPath("bin/firmware"),
52 EXPECT_FALSE(SILICON::project::documentTypeForPath("circuits/nested/main.json"));
53 EXPECT_FALSE(SILICON::project::documentTypeForPath("circuits/main.txt"));
54 EXPECT_EQ(SILICON::project::documentTypeForPath("circuits/foo..bar.json"),
56 EXPECT_FALSE(SILICON::project::documentTypeForPath("circuits/../main.json"));
57 EXPECT_EQ(SILICON::project::documentSlugForPath("circuits/adder.json"), "adder");
58 EXPECT_EQ(SILICON::project::documentSlugForPath("bin/firmware"), "firmware");
59 EXPECT_FALSE(SILICON::project::documentSlugForPath("bin/nested/firmware"));
60 EXPECT_EQ(SILICON::project::documentSlugForPath("code/adder.v"), "adder");
61}
62
63TEST(ProjectDocumentTest, ClassifiesConcreteTypesByCategory)
64{
69}
70
71TEST(ProjectDocumentTest, ValidatesBinarySlugsAndRoundTripsExactNames)
72{
73 for (const std::string_view invalid : {"", ".", "..", "a/b", "a\\b", "line\nbreak"}) {
74 EXPECT_FALSE(isValidDocumentSlug(invalid));
75 EXPECT_THROW(static_cast<void>(documentPathForSlug(DocumentType::RawBinary, invalid)),
76 std::invalid_argument);
77 }
78 for (const std::string_view valid : {"firmware", "rom.bin", "name with spaces"}) {
79 const auto path = documentPathForSlug(DocumentType::RawBinary, valid);
80 ASSERT_TRUE(documentSlugForPath(path));
81 EXPECT_EQ(*documentSlugForPath(path), valid);
82 }
83}
84
85TEST(ProjectDocumentTest, ValidatesDocumentNamesAndRoundTripsEveryType)
86{
87 for (const std::string_view invalid :
88 {"", ".", "..", "a/b", "a\\b", "../foo", "foo/bar", "line\nbreak"}) {
89 EXPECT_FALSE(isValidDocumentSlug(invalid));
90 EXPECT_THROW(static_cast<void>(documentPathForSlug(DocumentType::Circuit, invalid)),
91 std::invalid_argument);
92 }
93
94 for (const std::string_view valid : {"adder", "foo..bar", "name with spaces"}) {
95 ASSERT_TRUE(isValidDocumentSlug(valid));
96 const auto path = documentPathForSlug(DocumentType::Circuit, valid);
97 ASSERT_TRUE(documentSlugForPath(path));
98 EXPECT_EQ(*documentSlugForPath(path), valid);
99 }
100
101 const auto verilogPath = documentPathForSlug(DocumentType::Verilog, "adder");
102 EXPECT_EQ(verilogPath, "code/adder.v");
103 EXPECT_EQ(documentSlugForPath(verilogPath), "adder");
104 const auto sislPath = documentPathForSlug(DocumentType::Sisl, "rv32");
105 EXPECT_EQ(sislPath, "isa/rv32/instr_format.sisl");
106 EXPECT_EQ(documentSlugForPath(sislPath), "rv32");
107}
108
109TEST(ProjectDocumentTest, ContentReplacementUpdatesOnlyPersistedContents)
110{
111 Document document("circuits/adder.json", "old");
112 document.setContents("new");
113 EXPECT_EQ(document.getContents(), "new");
114}
115
116TEST(ProjectDocumentTest, ImportsDocumentsFromDefinitiveExtensions)
117{
118 const auto verilog = importDocument("/tmp/Adder.V", "not validated by extension");
119 EXPECT_EQ(verilog.getType(), DocumentType::Verilog);
120 EXPECT_EQ(verilog.getPath(), "code/Adder.v");
121 EXPECT_EQ(verilog.getContents(), "not validated by extension");
122
123 const auto sisl = importDocument("/tmp/format.SISL", "arch RV32 = {};\n");
124 EXPECT_EQ(sisl.getType(), DocumentType::Sisl);
125 EXPECT_EQ(sisl.getPath(), "isa/RV32/instr_format.sisl");
126 EXPECT_EQ(sisl.getContents(), "arch RV32 = {};\n");
127
128 const std::string bytes("\0\xfftext", 6);
129 const auto binary = importDocument("firmware.BIN", bytes);
130 EXPECT_EQ(binary.getType(), DocumentType::RawBinary);
131 EXPECT_EQ(binary.getPath(), "bin/firmware.BIN");
132 EXPECT_EQ(binary.getContents(), bytes);
133}
134
135TEST(ProjectDocumentTest, ReadsArchitectureDeclarationWithoutCompilingTheBody)
136{
137 EXPECT_TRUE(isValidArchitectureName("RV32_I"));
138 EXPECT_FALSE(isValidArchitectureName("instr"));
139 EXPECT_FALSE(isValidArchitectureName("bad name"));
140 EXPECT_EQ(declaredArchitectureName("// note\n/* comment */ arch /* gap */ RV32 = {"),
141 "RV32");
142 EXPECT_FALSE(declaredArchitectureName("// arch Wrong\nmodule X;"));
143 EXPECT_NO_THROW(validateArchitectureDeclaration("RV32", "arch RV32 = {};"));
144 EXPECT_THROW(validateArchitectureDeclaration("rv32", "arch RV32 = {};"),
145 std::invalid_argument);
146 EXPECT_EQ(renameArchitectureDeclaration("// note\narch RV32 = {};", "RV32", "RV64"),
147 "// note\narch RV64 = {};");
148 EXPECT_THROW((void)importDocument("broken.sisl", "module X;"),
149 std::invalid_argument);
150}
151
152TEST(ProjectDocumentTest, ImportsDocumentsDetectedFromContents)
153{
154 const auto circuit = importDocument(
155 "Adder.json", R"({"circuit":{"name":"Adder","components":[]},"visual":{}})");
156 EXPECT_EQ(circuit.getType(), DocumentType::Circuit);
157 EXPECT_EQ(circuit.getPath(), "circuits/Adder.json");
158
159 const auto binary = importDocument("assets/rom.dat", std::string("\x89PNG\r\n", 6));
160 EXPECT_EQ(binary.getType(), DocumentType::RawBinary);
161 EXPECT_EQ(binary.getPath(), "bin/rom.dat");
162}
163
164TEST(ProjectDocumentTest, RejectsUnsupportedImportedDocuments)
165{
166 EXPECT_THROW((void)importDocument("notes.txt", "ordinary text"), std::invalid_argument);
167 EXPECT_THROW((void)importDocument("alu.txt", "module alu; endmodule"),
168 std::invalid_argument);
169 EXPECT_THROW((void)importDocument("data.json", R"({"unrelated":true})"),
170 std::invalid_argument);
171 EXPECT_THROW((void)importDocument("", "module top; endmodule"), std::invalid_argument);
172 EXPECT_THROW((void)importDocument(".v", "module top; endmodule"),
173 std::invalid_argument);
174}
175
176TEST(ProjectDocumentTest, ExportsCanonicalDocumentLeafNames)
177{
178 EXPECT_EQ(documentFileName(Document("circuits/adder.json", "{}")), "adder.json");
179 EXPECT_EQ(documentFileName(Document("code/adder.v", "")), "adder.v");
180 EXPECT_EQ(documentFileName(Document("isa/rv32/instr_format.sisl", "")), "instr_format.sisl");
181 EXPECT_EQ(documentFileName(Document("bin/firmware.bin", "")), "firmware.bin");
182}
183
184TEST(ProjectDocumentTest, DescribesRegisteredDocumentTypes)
185{
186 ASSERT_EQ(DOCUMENT_TYPE_INFO.size(), 4);
188 EXPECT_EQ(verilog.category, DocumentCategory::Code);
189 EXPECT_EQ(verilog.root, "code/");
190 EXPECT_EQ(verilog.suffix, ".v");
191 EXPECT_EQ(documentTypeForPath("code/adder.v"), DocumentType::Verilog);
192 EXPECT_EQ(documentTypeForPath("isa/rv32/instr_format.sisl"), DocumentType::Sisl);
193 EXPECT_FALSE(documentTypeForPath("code/adder.sv"));
194 EXPECT_FALSE(documentTypeForPath("isa/rv32/other.sisl"));
195 EXPECT_FALSE(documentTypeForPath("isa/../instr_format.sisl"));
196 EXPECT_FALSE(documentTypeForPath("code/nested/adder.v"));
197 EXPECT_FALSE(documentTypeForPath("code/../adder.v"));
198}
199
200TEST(ProjectDocumentStoreTest, ProjectContextsOwnIndependentDocumentStores)
201{
202 ProjectContext first;
203 ProjectContext second;
204
205 first.upsertDocument({"code/main.v", "first"});
206 second.upsertDocument({"code/main.v", "second"});
207
208 ASSERT_NE(first.documents().find("code/main.v"), nullptr);
209 ASSERT_NE(second.documents().find("code/main.v"), nullptr);
210 EXPECT_EQ(first.documents().find("code/main.v")->getContents(), "first");
211 EXPECT_EQ(second.documents().find("code/main.v")->getContents(), "second");
212}
213
214TEST(ProjectDocumentStoreTest, PreservesOrderAcrossMixedKindsAndUpserts)
215{
217 project.setDocuments({{"circuits/main.json", "{}"},
218 {"circuits/adder.json", "{}"},
219 {"code/adder.v", "module adder; endmodule"},
220 {"bin/firmware", std::string("\0\xff", 2)},
221 {"circuits/control.json", "{}"}});
222
223 project.upsertDocument({"circuits/adder.json", R"({"components":[]})"});
224 const auto& store = project.documents();
225 ASSERT_EQ(store.getDocuments().size(), 5);
226 EXPECT_EQ(store.getDocuments()[1].getPath(), "circuits/adder.json");
227 EXPECT_EQ(store.getDocuments()[1].getContents(), R"({"components":[]})");
228
229 const auto& allDocuments = store.getDocuments();
230 const auto circuitCount = std::ranges::count_if(
231 allDocuments, [](const auto& d) { return d.getType() == DocumentType::Circuit; });
232 ASSERT_EQ(circuitCount, 3);
233 EXPECT_TRUE(store.contains(DocumentType::Circuit));
234
235 const auto codeIt = std::ranges::find_if(
236 allDocuments, [](const auto& d) { return d.getType() == DocumentType::Verilog; });
237 ASSERT_NE(codeIt, allDocuments.end());
238 EXPECT_EQ(codeIt->getContents(), "module adder; endmodule");
239 EXPECT_EQ(documentTypeForPath(codeIt->getPath()), DocumentType::Verilog);
240
241 const auto binaryIt = std::ranges::find_if(
242 allDocuments, [](const auto& d) { return d.getType() == DocumentType::RawBinary; });
243 ASSERT_NE(binaryIt, allDocuments.end());
244 EXPECT_EQ(binaryIt->getContents(), std::string("\0\xff", 2));
245
246 project.removeDocument("circuits/adder.json");
247 EXPECT_FALSE(store.contains("circuits/adder.json"));
248 EXPECT_EQ(store.indexOf("circuits/control.json"), 3);
249}
250
251TEST(ProjectDocumentStoreTest, RejectsDuplicatePaths)
252{
254 EXPECT_THROW(
255 project.setDocuments({{"circuits/main.json", "{}"}, {"circuits/main.json", "{}"}}),
256 std::invalid_argument);
257}
258
259TEST(ProjectDocumentStoreTest, NotificationsUseSnapshotAndCanonicalPaths)
260{
262 const DocumentStore& store = project.documents();
263 std::vector<std::pair<DocumentChangeKind, std::optional<std::string>>> notifications;
264 std::uint64_t selfRemovingId = 0;
265 std::uint64_t addedId = 0;
266
267 selfRemovingId = store.addListener([&](const DocumentChange& change) {
268 notifications.emplace_back(change.kind, change.path);
269 store.removeListener(selfRemovingId);
270 if (addedId == 0) {
271 addedId = store.addListener([&](const DocumentChange& nextChange) {
272 notifications.emplace_back(nextChange.kind, nextChange.path);
273 });
274 }
275 });
276
277 project.upsertDocument({"circuits/main.json", "{}"});
278 EXPECT_EQ(notifications,
279 (decltype(notifications){
280 {DocumentChangeKind::Added, std::string("circuits/main.json")}}));
281
282 project.upsertDocument({"circuits/main.json", R"({"components":[]})"});
283 project.removeDocument("missing.json");
284 project.removeDocument("circuits/main.json");
285
286 project.setDocuments({});
287 EXPECT_EQ(notifications,
288 (decltype(notifications){
289 {DocumentChangeKind::Added, std::string("circuits/main.json")},
290 {DocumentChangeKind::Updated, std::string("circuits/main.json")},
291 {DocumentChangeKind::Removed, std::string("circuits/main.json")},
292 {DocumentChangeKind::Reset, std::nullopt}}));
293 store.removeListener(addedId);
294}
295
296TEST(ProjectDocumentStoreTest, RenamesCircuitAndRewritesSubcircuitReferences)
297{
299 project.setDocuments(
300 {{"circuits/main.json",
301 R"({"circuit":{"name":"main","components":[{"type":"Subcircuit","properties":{"slug":"child"}},{"type":"ROM","properties":{"binaryContents":"child"}}]},"visual":{"components":[],"wires":[]}})"},
302 {"circuits/child.json",
303 R"({"circuit":{"name":"Child title","components":[]},"visual":{"components":[],"wires":[]}})"},
304 {"bin/child", "binary"}});
305
306 project.renameDocument("circuits/child.json", "circuits/renamed child.json");
307
308 const auto& documents = project.documents().getDocuments();
309 ASSERT_EQ(documents.size(), 3);
310 EXPECT_EQ(documents[0].getPath(), "circuits/main.json");
311 EXPECT_EQ(documents[1].getPath(), "circuits/renamed child.json");
312 EXPECT_EQ(documents[2].getPath(), "bin/child");
313
314 const auto main = nlohmann::json::parse(documents[0].getContents());
315 EXPECT_EQ(main["circuit"]["components"][0]["properties"]["slug"], "renamed child");
316 EXPECT_EQ(main["circuit"]["components"][1]["properties"]["binaryContents"], "child");
317
318 const auto renamed = nlohmann::json::parse(documents[1].getContents());
319 EXPECT_EQ(renamed["circuit"]["name"], "renamed child");
320 EXPECT_EQ(project.circuitDependencies().dependentsOf("circuits/renamed child.json"),
321 (CircuitDependencyGraph::DocumentPathList{"circuits/main.json"}));
322}
323
324TEST(ProjectDocumentStoreTest, RenamesBinaryAndRewritesRomReferences)
325{
327 project.setDocuments(
328 {{"circuits/main.json",
329 R"({"circuit":{"name":"main","components":[{"type":"ROM","properties":{"binaryContents":"program"}},{"type":"Subcircuit","properties":{"slug":"program"}}]},"visual":{"components":[],"wires":[]}})"},
330 {"circuits/program.json",
331 R"({"circuit":{"name":"program","components":[]},"visual":{"components":[],"wires":[]}})"},
332 {"bin/program", "binary"}});
333
334 project.renameDocument("bin/program", "bin/firmware");
335
336 const auto& documents = project.documents().getDocuments();
337 ASSERT_EQ(documents.size(), 3);
338 EXPECT_EQ(documents[2].getPath(), "bin/firmware");
339 EXPECT_EQ(documents[2].getContents(), "binary");
340 const auto main = nlohmann::json::parse(documents[0].getContents());
341 EXPECT_EQ(main["circuit"]["components"][0]["properties"]["binaryContents"], "firmware");
342 EXPECT_EQ(main["circuit"]["components"][1]["properties"]["slug"], "program");
343}
344
345TEST(ProjectDocumentStoreTest, RenamesCodeWithoutChangingContents)
346{
348 project.setDocuments({{"code/old.v", "module old; endmodule"},
349 {"isa/old/instr_format.sisl", "arch Old = {};"}});
350
351 project.renameDocument("code/old.v", "code/new.v");
352 project.renameDocument("isa/old/instr_format.sisl", "isa/new/instr_format.sisl");
353
354 ASSERT_EQ(project.documents().getDocuments().size(), 2);
355 EXPECT_EQ(project.documents().getDocuments()[0].getPath(), "code/new.v");
356 EXPECT_EQ(project.documents().getDocuments()[0].getContents(), "module old; endmodule");
357 EXPECT_EQ(project.documents().getDocuments()[1].getPath(), "isa/new/instr_format.sisl");
358 EXPECT_EQ(project.documents().getDocuments()[1].getContents(), "arch Old = {};");
359}
360
361TEST(ProjectDocumentStoreTest, RejectsInvalidDocumentRenames)
362{
364 project.setDocuments({{"circuits/main.json", R"({"name":"main","components":[]})"},
365 {"circuits/other.json", R"({"name":"other","components":[]})"}});
366
367 EXPECT_THROW(project.renameDocument("circuits/missing.json", "circuits/new.json"),
368 std::invalid_argument);
369 EXPECT_THROW(project.renameDocument("circuits/main.json", "circuits/other.json"),
370 std::invalid_argument);
371 EXPECT_THROW(project.renameDocument("circuits/main.json", "code/main.v"),
372 std::invalid_argument);
373 EXPECT_THROW(project.renameDocument("circuits/missing.json", "circuits/missing.json"),
374 std::invalid_argument);
375
376 EXPECT_NO_THROW(project.renameDocument("circuits/main.json", "circuits/main.json"));
377 EXPECT_EQ(project.documents().getDocuments().size(), 2);
378}
std::vector< std::string > DocumentPathList
List of project-relative document paths.
std::uint64_t addListener(Listener listener) const
void removeListener(std::uint64_t id) const
const Document * find(std::string_view documentPath) const noexcept
void setContents(std::string contents)
const std::string & getContents() const noexcept
void upsertDocument(Document document)
const DocumentStore & documents() const noexcept
std::string documentPathForSlug(const DocumentType type, const std::string_view slug)
constexpr const DocumentTypeInfo & documentTypeInfo(const DocumentType type)
constexpr std::array< DocumentTypeInfo, 4 > DOCUMENT_TYPE_INFO
std::string documentFileName(const Document &document)
constexpr DocumentCategory categoryOf(const DocumentType type)
std::optional< std::string > declaredArchitectureName(const std::string_view source)
std::string renameArchitectureDeclaration(const std::string_view source, const std::string_view oldName, const std::string_view newName)
std::optional< std::string > documentSlugForPath(const std::string_view path)
Document importDocument(const std::string_view sourcePath, std::string contents)
bool isValidDocumentSlug(const std::string_view slug)
void validateArchitectureDeclaration(const std::string_view directoryName, const std::string_view source)
std::optional< DocumentType > documentTypeForPath(const std::string_view path)
bool isValidArchitectureName(const std::string_view name)
int main(int argc, char **argv)
std::optional< std::string > path
TEST(ProjectDocumentTest, ClassifiesCanonicalFlatPaths)