SILICON
Loading...
Searching...
No Matches
projectFile.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 <chrono>
21#include <filesystem>
22#include <format>
23#include <fstream>
24#include <memory>
25#include <stdexcept>
26#include <string>
27#include <string_view>
28#include <utility>
29#include <vector>
30
32#include <nlohmann/json.hpp>
33#include <zip.h>
34
35using namespace SILICON::core;
36using namespace SILICON::project;
37
38namespace {
39
40// RAII wrappers for Libzip C-pointers to prevent test leaks on assertion failures
41struct ZipDeleter {
42 void operator()(zip_t* z) const noexcept
43 {
44 if (z)
45 zip_discard(z);
46 }
47};
48struct ZipFileDeleter {
49 void operator()(zip_file_t* f) const noexcept
50 {
51 if (f)
52 zip_fclose(f);
53 }
54};
55struct ZipSourceDeleter {
56 void operator()(zip_source_t* s) const noexcept
57 {
58 if (s)
59 zip_source_free(s);
60 }
61};
62
63using UniqueZip = std::unique_ptr<zip_t, ZipDeleter>;
64using UniqueZipFile = std::unique_ptr<zip_file_t, ZipFileDeleter>;
65using UniqueZipSource = std::unique_ptr<zip_source_t, ZipSourceDeleter>;
66
67struct FileCleanup {
68 std::filesystem::path filename;
69 ~FileCleanup() { std::filesystem::remove(filename); }
70};
71
72std::filesystem::path tempProjectPath(const std::string_view testName)
73{
74 const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
75 return std::filesystem::temp_directory_path()
76 / std::format("silicon_{}_{}.sil", testName, stamp);
77}
78
79nlohmann::ordered_json validMetadata()
80{
81 return nlohmann::ordered_json{{"formatVersion", SILICON::project::FORMAT_VERSION},
82 {"siliconVersion", SILICON_VERSION},
83 {"creationDate", "2026-01-02T03:04:05Z"},
84 {"lastModify", "2026-01-02T03:04:05Z"}};
85}
86
87nlohmann::ordered_json validProject()
88{
89 return nlohmann::ordered_json{{"name", "CPU demo"}, {"description", ""}};
90}
91
92void addZipEntry(zip_t* archive, const std::string& name, const std::string_view contents)
93{
94 // freep=0 implies libzip will not free the buffer. This is safe here because
95 // contents strings outlive zip_close() in the test's scope.
96 UniqueZipSource source(zip_source_buffer(archive, contents.data(), contents.size(), 0));
97 if (!source)
98 throw std::runtime_error("zip_source_buffer failed");
99
100 if (zip_file_add(archive, name.c_str(), source.get(),
101 ZIP_FL_OVERWRITE | ZIP_FL_ENC_UTF_8)
102 < 0) {
103 throw std::runtime_error("zip_file_add failed");
104 }
105
106 // Release source ownership to the archive now that it has been successfully added
107 source.release();
108}
109
110void writeZip(const std::filesystem::path& path,
111 const std::vector<std::pair<std::string, std::string>>& entries)
112{
113 int errorCode = 0;
114 UniqueZip archive(
115 zip_open(path.string().c_str(), ZIP_CREATE | ZIP_TRUNCATE, &errorCode));
116 ASSERT_NE(archive, nullptr);
117
118 for (const auto& [name, contents] : entries) {
119 addZipEntry(archive.get(), name, contents);
120 }
121
122 // zip_close commits and deletes the pointer.
123 // If it fails, RAII will zip_discard. If it passes, we release ownership.
124 ASSERT_EQ(zip_close(archive.get()), 0);
125 archive.release();
126}
127
128std::string readZipEntry(const std::filesystem::path& path, const std::string& entryName)
129{
130 int errorCode = 0;
131 UniqueZip archive(zip_open(path.string().c_str(), ZIP_RDONLY, &errorCode));
132 if (!archive)
133 throw std::runtime_error("zip_open failed");
134
135 const zip_int64_t index =
136 zip_name_locate(archive.get(), entryName.c_str(), ZIP_FL_ENC_UTF_8);
137 if (index < 0)
138 throw std::runtime_error(std::format("zip_name_locate failed for {}", entryName));
139
140 zip_stat_t stat;
141 zip_stat_init(&stat);
142 if (zip_stat_index(archive.get(), static_cast<zip_uint64_t>(index), 0, &stat) != 0)
143 throw std::runtime_error("zip_stat_index failed");
144
145 UniqueZipFile file(zip_fopen_index(archive.get(), static_cast<zip_uint64_t>(index), 0));
146 if (!file)
147 throw std::runtime_error("zip_fopen_index failed");
148
149 std::string contents;
150 // C++23 String creation optimization avoiding double-initialization
151 contents.resize_and_overwrite(stat.size, [&](char* buf, std::size_t) {
152 const auto bytesRead = zip_fread(file.get(), buf, stat.size);
153 return static_cast<std::size_t>(std::max<zip_int64_t>(0, bytesRead));
154 });
155
156 return contents;
157}
158
159void readProjectFileIgnoringResult(const std::filesystem::path& path)
160{
161 [[maybe_unused]] const auto projectFile = SILICON::project::readProjectFile(path);
162}
163
164} // namespace
165
166TEST(ProjectFileTest, WritesAndReadsProjectArchive)
167{
169 const auto path = tempProjectPath("roundtrip");
170 FileCleanup cleanup{path};
171
173 .metadata = {.formatVersion = SILICON::project::FORMAT_VERSION,
174 .siliconVersion = SILICON_VERSION,
175 .creationDate = "2026-01-02T03:04:05Z",
176 .lastModify = "2026-01-02T03:05:06Z"},
177 .project = {.name = "CPU demo", .description = "Demo project"},
178 .documents = {{std::string(SILICON::project::DEFAULT_CIRCUIT_PATH),
179 R"({"circuit":{},"visual":{"components":[],"wires":[]}})"}}};
180
181 SILICON::project::writeProjectFile(path, projectFile);
182
183 EXPECT_EQ(readZipEntry(path, "mimetype"), SILICON::project::MIME_TYPE);
184
185 const auto metadataJson = nlohmann::json::parse(readZipEntry(path, "metadata.json"));
186 EXPECT_EQ(metadataJson["formatVersion"], SILICON::project::FORMAT_VERSION);
187 EXPECT_EQ(metadataJson["siliconVersion"], SILICON_VERSION);
188 EXPECT_EQ(metadataJson["creationDate"], "2026-01-02T03:04:05Z");
189 EXPECT_EQ(metadataJson["lastModify"], "2026-01-02T03:05:06Z");
190
191 const auto projectJson = nlohmann::json::parse(readZipEntry(path, "project.json"));
192 EXPECT_EQ(projectJson["name"], "CPU demo");
193 EXPECT_FALSE(projectJson.contains("mainCircuit"));
194 EXPECT_EQ(projectJson["description"], "Demo project");
195
196 const auto loaded = SILICON::project::readProjectFile(path);
197 EXPECT_EQ(loaded.project.name, "CPU demo");
198 ASSERT_EQ(loaded.documents.size(), 1);
199 EXPECT_EQ(loaded.documents.front().getPath(), SILICON::project::DEFAULT_CIRCUIT_PATH);
200 EXPECT_EQ(loaded.documents.front().getContents(),
201 projectFile.documents.front().getContents());
202}
203
204TEST(ProjectFileTest, RejectsObsoleteProjectFields)
205{
206 const auto path = tempProjectPath("obsolete_project_field");
207 FileCleanup cleanup{path};
208 auto project = validProject();
209 project["codeFiles"] = nlohmann::ordered_json::array();
210 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
211 {"metadata.json", validMetadata().dump(2)},
212 {"project.json", project.dump(2)},
213 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"}});
214
215 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
216}
217
218TEST(ProjectFileTest, WritesAndReadsProjectArchiveWithMultipleCircuits)
219{
220 const auto path = tempProjectPath("multi_circuit_roundtrip");
221 FileCleanup cleanup{path};
222
223 const std::string mainJson =
224 R"({"circuit":{"name":"Main"},"visual":{"components":[],"wires":[]}})";
225 const std::string controllerJson =
226 R"({"circuit":{"name":"Controller"},"visual":{"components":[],"wires":[]}})";
227
229 .metadata = {.formatVersion = SILICON::project::FORMAT_VERSION,
230 .siliconVersion = SILICON_VERSION,
231 .creationDate = "2026-01-02T03:04:05Z",
232 .lastModify = "2026-01-02T03:05:06Z"},
233 .project = {.name = "CPU demo", .description = "Demo project"},
234 .documents = {{std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), mainJson},
235 {"circuits/controller.json", controllerJson}}};
236
237 SILICON::project::writeProjectFile(path, projectFile);
238
239 EXPECT_EQ(readZipEntry(path, SILICON::project::DEFAULT_CIRCUIT_PATH.data()), mainJson);
240 EXPECT_EQ(readZipEntry(path, "circuits/controller.json"), controllerJson);
241
242 const auto loaded = SILICON::project::readProjectFile(path);
243 ASSERT_EQ(loaded.documents.size(), 2);
244 const auto mainIt = std::ranges::find(
245 loaded.documents, std::string(SILICON::project::DEFAULT_CIRCUIT_PATH),
247 const auto controllerIt =
248 std::ranges::find(loaded.documents, std::string("circuits/controller.json"),
250 ASSERT_NE(mainIt, loaded.documents.end());
251 ASSERT_NE(controllerIt, loaded.documents.end());
252 EXPECT_EQ(mainIt->getContents(), mainJson);
253 EXPECT_EQ(controllerIt->getContents(), controllerJson);
254}
255
256TEST(ProjectFileTest, RejectsEntriesCollidingWithCircuitNamespace)
257{
258 const auto path = tempProjectPath("nested_circuit_entry");
259 FileCleanup cleanup{path};
260
261 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
262 {"metadata.json", validMetadata().dump(2)},
263 {"project.json", validProject().dump(2)},
264 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
265 {"circuits/nested/controller.json", "{}"}});
266
267 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
268}
269
270TEST(ProjectFileTest, WritesAndReadsMultipleCircuitDocuments)
271{
272 const auto path = tempProjectPath("mixed_documents");
273 FileCleanup cleanup{path};
274 const std::string mainJson = R"({"circuit":{"name":"Main"}})";
275 const std::string subJson = R"({"circuit":{"name":"Adder"}})";
276
278 .metadata = {.formatVersion = SILICON::project::FORMAT_VERSION,
279 .siliconVersion = SILICON_VERSION,
280 .creationDate = "2026-01-02T03:04:05Z",
281 .lastModify = "2026-01-02T03:05:06Z"},
282 .project = {.name = "Mixed", .description = ""},
283 .documents = {{std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), mainJson},
284 {"circuits/adder.json", subJson}}};
285
286 SILICON::project::writeProjectFile(path, projectFile);
287 EXPECT_EQ(readZipEntry(path, "circuits/adder.json"), subJson);
288
289 const auto loaded = SILICON::project::readProjectFile(path);
290 ASSERT_EQ(loaded.documents.size(), 2);
291 EXPECT_TRUE(std::ranges::all_of(loaded.documents, [](const auto& document) {
292 return document.getType() == SILICON::project::DocumentType::Circuit;
293 }));
294}
295
296TEST(ProjectFileTest, RoundTripsCodeDocuments)
297{
298 const auto path = tempProjectPath("code_files");
299 FileCleanup cleanup{path};
300 const std::string mainJson = R"({"circuit":{"name":"Main"}})";
301 const std::string source = "module adder(input a, output y); assign y = a; endmodule\n";
302 const std::string isaSource = "arch RV32 = { endianness = Little; };\n";
303
306 .project = {.name = "Code", .description = ""},
307 .documents = {{std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), mainJson},
308 {"code/adder.v", source},
309 {"code/control.v", "module control; endmodule\n"},
310 {"isa/rv32/instr_format.sisl", isaSource}}};
311
312 SILICON::project::writeProjectFile(path, projectFile);
313 EXPECT_EQ(readZipEntry(path, "code/adder.v"), source);
314 EXPECT_EQ(readZipEntry(path, "isa/rv32/instr_format.sisl"), isaSource);
315 const auto projectJson = nlohmann::json::parse(readZipEntry(path, "project.json"));
316 EXPECT_FALSE(projectJson.contains("codeFiles"));
317
318 const auto loaded = SILICON::project::readProjectFile(path);
319 ASSERT_EQ(loaded.documents.size(), 4);
320 EXPECT_EQ(loaded.documents[1].getType(), SILICON::project::DocumentType::Verilog);
321 EXPECT_EQ(loaded.documents[1].getContents(), source);
322 EXPECT_EQ(loaded.documents[3].getType(), SILICON::project::DocumentType::Sisl);
323 EXPECT_EQ(loaded.documents[3].getContents(), isaSource);
324}
325
326TEST(ProjectFileTest, RoundTripsRawBinaryDocumentsByteForByte)
327{
328 const auto path = tempProjectPath("binary_files");
329 FileCleanup cleanup{path};
330 const std::string raw("\0\x01\x7f\x80\xff", 5);
333 .project = {.name = "Binary", .description = ""},
334 .documents = {{std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
335 {"bin/firmware", raw}}};
336
337 SILICON::project::writeProjectFile(path, projectFile);
338 EXPECT_EQ(readZipEntry(path, "bin/firmware"), raw);
339 const auto loaded = SILICON::project::readProjectFile(path);
340 ASSERT_EQ(loaded.documents.size(), 2);
341 EXPECT_EQ(loaded.documents[1].getType(), SILICON::project::DocumentType::RawBinary);
342 EXPECT_EQ(loaded.documents[1].getContents(), raw);
343}
344
345TEST(ProjectFileTest, RejectsNonDocumentEntries)
346{
347 const auto assetPath = tempProjectPath("asset_entry");
348 FileCleanup assetCleanup{assetPath};
349 writeZip(assetPath, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
350 {"metadata.json", validMetadata().dump(2)},
351 {"project.json", validProject().dump(2)},
352 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
353 {"notes/readme.txt", "preserved"}});
354 EXPECT_THROW(readProjectFileIgnoringResult(assetPath), std::runtime_error);
355
356 const auto collisionPath = tempProjectPath("asset_namespace_collision");
357 FileCleanup collisionCleanup{collisionPath};
358 writeZip(collisionPath, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
359 {"metadata.json", validMetadata().dump(2)},
360 {"project.json", validProject().dump(2)},
361 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
362 {"code/adder.sv", "unsupported"}});
363 EXPECT_THROW(readProjectFileIgnoringResult(collisionPath), std::runtime_error);
364
365 const auto oldSislPath = tempProjectPath("old_sisl_entry");
366 FileCleanup oldSislCleanup{oldSislPath};
367 writeZip(oldSislPath, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
368 {"metadata.json", validMetadata().dump(2)},
369 {"project.json", validProject().dump(2)},
370 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
371 {"code/rv32.isa", "arch rv32 = {};"}});
372 EXPECT_THROW(readProjectFileIgnoringResult(oldSislPath), std::runtime_error);
373}
374
375TEST(ProjectFileTest, RejectsInvalidEntriesInsideCodeNamespace)
376{
377 for (const auto& entry :
378 {std::string("code/nested/adder.v"), std::string("code/../adder.v")}) {
379 const auto path = tempProjectPath("invalid_code_path");
380 FileCleanup cleanup{path};
381 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
382 {"metadata.json", validMetadata().dump(2)},
383 {"project.json", validProject().dump(2)},
384 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
385 {entry, "module adder; endmodule"}});
386 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
387 }
388}
389
390TEST(ProjectFileTest, RejectsLegacySubcircuitPathBeforeCreatingArchive)
391{
392 const auto path = tempProjectPath("nested_subcircuit");
393 FileCleanup cleanup{path};
396 .project = {.name = "Invalid", .description = ""},
397 .documents = {{std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"}}};
398
399 EXPECT_THROW(projectFile.documents.emplace_back("subcircuits/adder.json", "{}"),
400 std::invalid_argument);
401}
402
403TEST(ProjectFileTest, RejectsLegacySubcircuitArchiveEntries)
404{
405 const auto path = tempProjectPath("nested_subcircuit_entry");
406 FileCleanup cleanup{path};
407
408 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
409 {"metadata.json", validMetadata().dump(2)},
410 {"project.json", validProject().dump(2)},
411 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
412 {"subcircuits/adder.json", "{}"}});
413
414 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
415}
416
417TEST(ProjectFileTest, RejectsDuplicateDocumentPathsBeforeCreatingArchive)
418{
419 const auto path = tempProjectPath("duplicate_document_paths");
420 FileCleanup cleanup{path};
423 .project = {.name = "Invalid", .description = ""},
424 .documents = {{std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
425 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"}}};
426
427 EXPECT_THROW(SILICON::project::writeProjectFile(path, projectFile), std::runtime_error);
428 EXPECT_FALSE(std::filesystem::exists(path));
429}
430
431TEST(ProjectFileTest, RejectsDuplicateCircuitNamesBeforeCreatingArchive)
432{
433 const auto path = tempProjectPath("duplicate_subcircuit_slugs");
434 FileCleanup cleanup{path};
437 .project = {.name = "Invalid", .description = ""},
438 .documents = {{std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"},
439 {"circuits/adder.json", "{}"},
440 {"circuits/adder.json", "{}"}}};
441
442 EXPECT_THROW(SILICON::project::writeProjectFile(path, projectFile), std::runtime_error);
443 EXPECT_FALSE(std::filesystem::exists(path));
444}
445
446TEST(ProjectFileTest, RejectsWrongMimetype)
447{
448 const auto path = tempProjectPath("wrong_mimetype");
449 FileCleanup cleanup{path};
450
451 writeZip(path, {{"mimetype", "application/octet-stream"},
452 {"metadata.json", validMetadata().dump(2)},
453 {"project.json", validProject().dump(2)},
454 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"}});
455
456 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
457}
458
459TEST(ProjectFileTest, RejectsRawJsonFile)
460{
461 const auto path = tempProjectPath("raw_json");
462 FileCleanup cleanup{path};
463
464 std::ofstream file(path);
465 file << R"({"circuit":{},"visual":{}})";
466 file.close();
467
468 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
469}
470
471TEST(ProjectFileTest, RejectsMissingProjectJson)
472{
473 const auto path = tempProjectPath("missing_project");
474 FileCleanup cleanup{path};
475
476 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
477 {"metadata.json", validMetadata().dump(2)},
478 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"}});
479
480 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
481}
482
483TEST(ProjectFileTest, RejectsMissingMetadataJson)
484{
485 const auto path = tempProjectPath("missing_metadata");
486 FileCleanup cleanup{path};
487
488 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
489 {"project.json", validProject().dump(2)},
490 {std::string(SILICON::project::DEFAULT_CIRCUIT_PATH), "{}"}});
491
492 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
493}
494
495TEST(ProjectFileTest, RejectsProjectWithoutCircuits)
496{
497 const auto path = tempProjectPath("missing_circuit");
498 FileCleanup cleanup{path};
499
500 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
501 {"metadata.json", validMetadata().dump(2)},
502 {"project.json", validProject().dump(2)}});
503
504 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
505}
506
507TEST(ProjectFileTest, RejectsObsoleteMainCircuitField)
508{
509 const auto path = tempProjectPath("obsolete_main_circuit");
510 FileCleanup cleanup{path};
511
512 auto project = validProject();
513 project["mainCircuit"] = "circuits/main.json";
514
515 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
516 {"metadata.json", validMetadata().dump(2)},
517 {"project.json", project.dump(2)},
518 {"circuits/main.json", "{}"}});
519
520 EXPECT_THROW(readProjectFileIgnoringResult(path), std::runtime_error);
521}
522
523TEST(ProjectFileTest, AcceptsOrdinaryCircuitNamedMain)
524{
525 const auto path = tempProjectPath("ordinary_main");
526 FileCleanup cleanup{path};
527
528 writeZip(path, {{"mimetype", std::string(SILICON::project::MIME_TYPE)},
529 {"metadata.json", validMetadata().dump(2)},
530 {"project.json", validProject().dump(2)},
531 {"circuits/main.json", "{}"}});
532
533 const auto loaded = readProjectFile(path);
534 ASSERT_EQ(loaded.documents.size(), 1);
535 EXPECT_EQ(loaded.documents.front().getPath(), "circuits/main.json");
536}
const std::string & getPath() const noexcept
constexpr int FORMAT_VERSION
Current version of the Silicon project archive schema.
constexpr std::string_view MIME_TYPE
MIME marker stored in Silicon project archives.
ProjectFile readProjectFile(const std::filesystem::path &path)
Reads and validates a Silicon .sil project archive.
void writeProjectFile(const std::filesystem::path &path, const ProjectFile &projectFile)
Writes a Silicon .sil project archive.
ProjectMetadata metadataForNewFile()
Creates default metadata for a new project file.
const std::string DEFAULT_CIRCUIT_PATH
Default path of the initial circuit JSON file.
std::string filename
In-memory representation of a .sil project archive.
std::vector< Document > documents
Authoritative ordered collection of project documents.
TEST(ProjectFileTest, WritesAndReadsProjectArchive)