#include "rapidproto/interpret.hpp"
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
#include "rapidproto/ast.hpp"
#include "rapidproto/resolver.hpp"
#include "rapidproto/result.hpp"
#include "rapidproto/scalar.hpp"
namespace rapidproto {
namespace {
const OptionValue* find_option(const std::vector<Option>& options, std::string_view name) {
for (const auto& option : options) {
if (option.name.size() == 1 && !option.name[0].is_extension &&
option.name[0].name == name) {
return &option.value;
}
}
return nullptr;
}
void interpret_field(FieldNode& field) {
if (field.is_repeated && is_packable_scalar(field.type_name)) {
if (const OptionValue* packed = find_option(field.options, "packed")) {
if (const auto* value = std::get_if<Identifier>(&packed->value)) {
if (value->name == "true") {
field.repeated_encoding = RepeatedEncoding::Packed;
} else if (value->name == "false") {
field.repeated_encoding = RepeatedEncoding::Expanded;
}
}
}
}
if (const OptionValue* value = find_option(field.options, "default")) {
field.default_value = *value;
}
}
bool declares_message_set(const MessageNode& message) {
const OptionValue* option = find_option(message.options, "message_set_wire_format");
if (option == nullptr) {
return false;
}
const auto* value = std::get_if<Identifier>(&option->value);
return value != nullptr && value->name == "true";
}
std::optional<Error> interpret_message(MessageNode& message, std::vector<std::string>* warnings) {
if (declares_message_set(message) && warnings != nullptr) {
warnings->push_back(
"warning: " + message.fqn +
" uses the MessageSet wire format; it holds only extensions, which this decoder does"
" not materialize, so the message will decode as unknown fields");
}
for (auto& field : message.fields) {
interpret_field(field);
}
for (auto& oneof : message.oneofs) {
for (auto& field : oneof.fields) {
interpret_field(field);
}
}
for (auto& extend : message.extends) {
for (auto& field : extend.fields) {
interpret_field(field);
}
}
for (auto& nested : message.nested_messages) {
if (auto error = interpret_message(nested, warnings)) {
return error;
}
}
return std::nullopt;
}
}
Result<std::monostate> interpret_options(FileNode& file, std::vector<std::string>* warnings) {
for (auto& message : file.messages) {
if (auto error = interpret_message(message, warnings)) {
return *error;
}
}
for (auto& extend : file.extends) {
for (auto& field : extend.fields) {
interpret_field(field);
}
}
return std::monostate{};
}
Result<std::monostate> interpret_options(ResolvedFileSet& file_set,
std::vector<std::string>* warnings) {
for (auto& file : file_set.files) {
if (auto result = interpret_options(file, warnings); result.is_err()) {
return std::move(result).error();
}
}
return std::monostate{};
}
}