Files
Build-System/src/build.cpp
T
faumaray 3cac890ce9 bootstrap
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-25 01:32:43 +03:00

449 lines
17 KiB
C++

#include <vbs/build.hpp>
#include <algorithm>
#include <type_traits>
namespace vbs {
namespace detail {
struct ProjectState {
ProfileContext context;
std::vector<TargetRecord> targets;
std::vector<DependencyRecord> dependencies;
};
} // namespace detail
namespace {
void require_text(std::string_view text, std::string_view field) {
if (text.empty()) {
throw std::invalid_argument{std::string{field} + " must not be empty"};
}
}
auto owner(const std::weak_ptr<detail::ProjectState> &weak) {
auto state = weak.lock();
if (!state) {
throw std::logic_error{"declaration handle's Project has expired"};
}
return state;
}
std::string_view visibility_name(Visibility visibility) {
switch (visibility) {
case Visibility::private_:
return "private";
case Visibility::public_:
return "public";
case Visibility::interface_:
return "interface";
}
throw std::invalid_argument{"unknown visibility"};
}
void validate_context(const ProfileContext &context) {
require_text(context.name, "profile name");
(void)compiler_name(context.compiler);
require_text(context.os, "target OS");
require_text(context.architecture, "target architecture");
for (const auto &option : context.compile_options) {
require_text(option, "compile option");
}
}
void require_utf8(std::string_view text) {
std::size_t position = 0;
const auto invalid = [] { throw std::invalid_argument{"JSON string contains invalid UTF-8"}; };
while (position < text.size()) {
const auto lead = static_cast<unsigned char>(text[position++]);
if (lead < 0x80) {
continue;
}
std::size_t remaining = 0;
std::uint32_t scalar = 0;
std::uint32_t minimum = 0;
if (lead >= 0xc2 && lead <= 0xdf) {
remaining = 1;
scalar = lead & 0x1f;
minimum = 0x80;
} else if (lead >= 0xe0 && lead <= 0xef) {
remaining = 2;
scalar = lead & 0x0f;
minimum = 0x800;
} else if (lead >= 0xf0 && lead <= 0xf4) {
remaining = 3;
scalar = lead & 0x07;
minimum = 0x10000;
} else {
invalid();
}
if (remaining > text.size() - position) {
invalid();
}
for (std::size_t i = 0; i < remaining; ++i) {
const auto continuation = static_cast<unsigned char>(text[position++]);
if ((continuation & 0xc0) != 0x80) {
invalid();
}
scalar = (scalar << 6) | (continuation & 0x3f);
}
// JSON strings contain Unicode scalar values: no overlong forms or surrogates.
if (scalar < minimum || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff)) {
invalid();
}
}
}
std::string quote(std::string_view text) {
require_utf8(text);
constexpr char hex[] = "0123456789abcdef";
std::string output{"\""};
for (const unsigned char c : text) {
switch (c) {
case '"':
output += "\\\"";
break;
case '\\':
output += "\\\\";
break;
case '\n':
output += "\\n";
break;
case '\r':
output += "\\r";
break;
case '\t':
output += "\\t";
break;
default:
if (c < 0x20) {
output += "\\u00";
output += hex[c >> 4];
output += hex[c & 0x0f];
} else {
output += static_cast<char>(c);
}
}
}
output += '"';
return output;
}
template <typename Range, typename Serialize>
std::string array(const Range &range, Serialize serialize) {
std::string output{"["};
bool first = true;
for (const auto &item : range) {
if (!first)
output += ',';
first = false;
output += serialize(item);
}
return output + ']';
}
std::string options_json(const OptionMap &options) {
std::string output{"{"};
bool first = true;
for (const auto &[name, option] : options) {
if (!first)
output += ',';
first = false;
output += quote(name) + ':';
output += std::visit(
[](const auto &value) -> std::string {
using Type = std::remove_cvref_t<decltype(value)>;
if constexpr (std::same_as<Type, std::string>)
return quote(value);
else if constexpr (std::same_as<Type, bool>)
return value ? "true" : "false";
else
return std::to_string(value);
},
option.value);
}
return output + '}';
}
} // namespace
std::string_view compiler_name(CompilerFamily compiler) {
switch (compiler) {
case CompilerFamily::gcc:
return "gcc";
case CompilerFamily::clang:
return "clang";
}
throw std::invalid_argument{"unknown compiler family"};
}
CompilerFamily parse_compiler(std::string_view name) {
if (name == "gcc")
return CompilerFamily::gcc;
if (name == "clang")
return CompilerFamily::clang;
throw std::invalid_argument{"unknown compiler '" + std::string{name} +
"' (expected gcc or clang)"};
}
void Profiles::add(std::string name, std::vector<std::string> compile_options) {
require_text(name, "profile name");
if (std::ranges::any_of(records_, [&](const auto &record) { return record.name == name; })) {
throw std::invalid_argument{"duplicate profile '" + name + "'"};
}
for (const auto &option : compile_options)
require_text(option, "compile option");
records_.push_back({std::move(name), std::move(compile_options)});
}
const std::vector<ProfileDescription> &Profiles::records() const noexcept { return records_; }
ProfileContext Profiles::resolve(std::string_view name, CompilerFamily compiler, std::string os,
std::string architecture) const {
const auto found = std::ranges::find(records_, name, &ProfileDescription::name);
if (found == records_.end()) {
throw std::invalid_argument{"unknown profile '" + std::string{name} + "'"};
}
ProfileContext context{found->name, compiler, std::move(os), std::move(architecture),
found->compile_options};
validate_context(context);
return context;
}
Profiles default_profiles() {
Profiles result;
result.add("debug", {"-O0", "-g"});
result.add("release", {"-O3", "-DNDEBUG"});
return result;
}
SourceSet::SourceSet(std::initializer_list<std::string_view> files) {
for (const auto path : files) {
require_text(path, "source path");
records_.push_back({SourceKind::file, std::string{path}});
}
}
SourceSet SourceSet::file(std::string path) {
require_text(path, "source path");
SourceSet result;
result.records_.push_back({SourceKind::file, std::move(path)});
return result;
}
SourceSet SourceSet::glob(std::string pattern) {
require_text(pattern, "glob pattern");
SourceSet result;
result.records_.push_back({SourceKind::glob, std::move(pattern)});
return result;
}
const std::vector<SourceRecord> &SourceSet::records() const noexcept { return records_; }
Target::Target(std::weak_ptr<detail::ProjectState> state, std::size_t index)
: owner_{std::move(state)}, index_{index} {}
Target &Target::sources(const SourceSet &sources) {
auto state = owner(owner_);
auto &records = state->targets.at(index_).sources;
records.insert(records.end(), sources.records().begin(), sources.records().end());
return *this;
}
Target &Target::include_directory(std::string path, Visibility visibility) {
require_text(path, "include directory");
(void)visibility_name(visibility);
owner(owner_)->targets.at(index_).include_directories.push_back({std::move(path), visibility});
return *this;
}
Target &Target::compile_option(std::string option) {
require_text(option, "compile option");
owner(owner_)->targets.at(index_).compile_options.push_back(std::move(option));
return *this;
}
Target &Target::link(const Target &target, Visibility visibility) {
auto state = owner(owner_);
if (owner(target.owner_) != state) {
throw std::invalid_argument{"cannot link a target from another Project"};
}
(void)visibility_name(visibility);
state->targets.at(index_).links.push_back(
{LinkKind::local, state->targets.at(target.index_).name, {}, visibility});
return *this;
}
Target &Target::link(const ImportedTarget &target, Visibility visibility) {
auto state = owner(owner_);
if (owner(target.owner_) != state) {
throw std::invalid_argument{"cannot link an imported target from another Project"};
}
(void)visibility_name(visibility);
state->targets.at(index_).links.push_back({LinkKind::imported, target.name_,
state->dependencies.at(target.dependency_).name,
visibility});
return *this;
}
const TargetRecord &Target::record() const { return owner(owner_)->targets.at(index_); }
ImportedTarget::ImportedTarget(std::weak_ptr<detail::ProjectState> state, std::size_t dependency,
std::string name)
: owner_{std::move(state)}, dependency_{dependency}, name_{std::move(name)} {}
Dependency::Dependency(std::weak_ptr<detail::ProjectState> state, std::size_t index)
: owner_{std::move(state)}, index_{index} {}
Dependency &Dependency::git(std::string url, Commit commit) {
require_text(url, "Git URL");
if (commit.sha.size() != 40 || !std::ranges::all_of(commit.sha, [](char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
})) {
throw std::invalid_argument{"Commit must contain an exact 40-digit hexadecimal Git SHA"};
}
auto state = owner(owner_);
auto &record = state->dependencies.at(index_);
if (record.source_kind != DependencySourceKind::unspecified) {
throw std::invalid_argument{"dependency '" + record.name +
"' already has a source provider"};
}
record.source_kind = DependencySourceKind::git;
record.location = std::move(url);
record.revision = std::move(commit.sha);
return *this;
}
Dependency &Dependency::cmake(OptionMap options) {
for (const auto &[key, value] : options) {
(void)value;
require_text(key, "CMake option name");
}
auto state = owner(owner_);
auto &record = state->dependencies.at(index_);
if (record.source_kind == DependencySourceKind::package || !record.builder.empty()) {
throw std::invalid_argument{"contradictory builder for dependency '" + record.name + "'"};
}
record.builder = "cmake";
record.options = std::move(options);
return *this;
}
Dependency &Dependency::package(std::string id, std::string range) {
require_text(id, "package identifier");
require_text(range, "package version range");
auto state = owner(owner_);
auto &record = state->dependencies.at(index_);
if (record.source_kind != DependencySourceKind::unspecified || !record.builder.empty()) {
throw std::invalid_argument{"dependency '" + record.name +
"' already has a source/provider"};
}
record.source_kind = DependencySourceKind::package;
record.package = std::move(id);
record.version = std::move(range);
return *this;
}
ImportedTarget Dependency::target(std::string exported_name) const {
(void)owner(owner_);
require_text(exported_name, "exported target name");
return ImportedTarget{owner_, index_, std::move(exported_name)};
}
const DependencyRecord &Dependency::record() const {
return owner(owner_)->dependencies.at(index_);
}
Project::Project(ProfileContext context) : state_{std::make_shared<detail::ProjectState>()} {
validate_context(context);
state_->context = std::move(context);
}
Project::~Project() = default;
const ProfileContext &Project::context() const noexcept { return state_->context; }
Target Project::add_target(std::string name, TargetKind kind) {
require_text(name, "target name");
if (std::ranges::any_of(state_->targets,
[&](const auto &record) { return record.name == name; })) {
throw std::invalid_argument{"duplicate target '" + name + "'"};
}
state_->targets.push_back({std::move(name), kind, {}, {}, {}, {}});
return Target{state_, state_->targets.size() - 1};
}
Target Project::executable(std::string name) {
return add_target(std::move(name), TargetKind::executable);
}
Target Project::static_library(std::string name) {
return add_target(std::move(name), TargetKind::static_library);
}
Dependency Project::dependency(std::string name) {
require_text(name, "dependency name");
if (std::ranges::any_of(state_->dependencies,
[&](const auto &record) { return record.name == name; })) {
throw std::invalid_argument{"duplicate dependency '" + name + "'"};
}
DependencyRecord record;
record.name = std::move(name);
state_->dependencies.push_back(std::move(record));
return Dependency{state_, state_->dependencies.size() - 1};
}
SourceSet Project::glob(std::string pattern) const { return SourceSet::glob(std::move(pattern)); }
const std::vector<TargetRecord> &Project::targets() const noexcept { return state_->targets; }
const std::vector<DependencyRecord> &Project::dependencies() const noexcept {
return state_->dependencies;
}
std::string Project::to_json() const {
const auto &profile = context();
std::string output =
"{\"schema_version\":" + std::to_string(schema_version) +
",\"profile\":{\"name\":" + quote(profile.name) +
",\"compiler\":" + quote(compiler_name(profile.compiler)) + ",\"os\":" + quote(profile.os) +
",\"architecture\":" + quote(profile.architecture) +
",\"compile_options\":" + array(profile.compile_options, quote) + "},\"targets\":";
output += array(targets(), [](const TargetRecord &target) {
return "{\"name\":" + quote(target.name) + ",\"kind\":" +
quote(target.kind == TargetKind::executable ? "executable" : "static_library") +
",\"sources\":" +
array(target.sources,
[](const SourceRecord &source) {
return "{\"kind\":" +
quote(source.kind == SourceKind::file ? "file" : "glob") +
",\"path\":" + quote(source.path) + '}';
}) +
",\"include_directories\":" +
array(target.include_directories,
[](const IncludeDirectory &directory) {
return "{\"path\":" + quote(directory.path) +
",\"visibility\":" + quote(visibility_name(directory.visibility)) +
'}';
}) +
",\"compile_options\":" + array(target.compile_options, quote) + ",\"links\":" +
array(target.links,
[](const LinkRecord &link) {
return "{\"kind\":" +
quote(link.kind == LinkKind::local ? "local" : "imported") +
",\"target\":" + quote(link.target) +
",\"dependency\":" + quote(link.dependency) +
",\"visibility\":" + quote(visibility_name(link.visibility)) + '}';
}) +
'}';
});
output += ",\"dependencies\":" + array(dependencies(), [](const DependencyRecord &dependency) {
if (dependency.source_kind == DependencySourceKind::unspecified) {
throw std::invalid_argument{"dependency '" + dependency.name +
"' has no source provider"};
}
std::string result =
"{\"name\":" + quote(dependency.name) + ",\"source\":{\"kind\":";
if (dependency.source_kind == DependencySourceKind::git) {
result += "\"git\",\"location\":" + quote(dependency.location) +
",\"revision\":" + quote(dependency.revision);
} else {
result += "\"package\",\"package\":" + quote(dependency.package) +
",\"version\":" + quote(dependency.version);
}
return result + "},\"builder\":" + quote(dependency.builder) +
",\"options\":" + options_json(dependency.options) + '}';
});
return output + '}';
}
} // namespace vbs