Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support for x-enum-varnames in chaotic #712

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions chaotic/chaotic/back/cpp/templates/type.hpp.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@
{% elif type.get_py_type() == 'CppIntEnum' %}
enum class {{ type.cpp_local_name() }} {
{%- for item in type.enums %}
k{{ item }} = {{ item }},
{%- endfor -%}
k{{ item.cpp_name }} = {{ item.value }}, // {{ item.raw_name }}
{%- endfor %}
};

static constexpr {{ type.cpp_local_name() }} k{{ type.cpp_local_name() }}Values [] = {
{%- for item in type.enums %}
{{ type.cpp_local_name() }}::k{{ item }},
{%- endfor -%}
{{ type.cpp_local_name() }}::k{{ item.cpp_name }},
{%- endfor %}
};
{% elif type.get_py_type() == 'CppStringEnum' %}
enum class {{ type.cpp_local_name() }} {
Expand Down
2 changes: 1 addition & 1 deletion chaotic/chaotic/back/cpp/templates/type_parsers.ipp.jinja
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
[](auto selector) {
return selector().template Type<{{ type.cpp_global_name() }}, int>()
{%- for item in type.enums %}
.Case({{ type.cpp_global_name() }}::k{{ item }}, {{ item }})
.Case({{ type.cpp_global_name() }}::k{{ item.cpp_name }}, {{ item.value }})
{%- endfor -%}
;
};
Expand Down
27 changes: 25 additions & 2 deletions chaotic/chaotic/back/cpp/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ class GeneratorState:


NON_NAME_SYMBOL_RE = re.compile('[^_0-9a-zA-Z]')

SPLIT_RE = re.compile(r'[a-zA-Z0-9]+')
SPLIT_WORDS_RE = re.compile(r'[A-Z]+(?=[A-Z][a-z0-9])|[A-Z][a-z0-9]+|[a-z0-9]+|[A-Z]+')

class FormatChooser:
def __init__(self, types: List[cpp_types.CppType]) -> None:
Expand Down Expand Up @@ -262,13 +263,35 @@ def _gen_integer(
assert schema.format is None
assert user_cpp_type is None

enum_names = []

if 'x-enum-varnames' in schema.x_properties:
enum_names = schema.x_properties['x-enum-varnames']

emum_items: List[cpp_types.CppIntEnumItem] = []

def to_camel_case(text: str) -> str:
words = SPLIT_RE.findall(text)
result = []
for word in words:
result.extend([part.capitalize() for part in SPLIT_WORDS_RE.findall(word)])
return ''.join(result)

for i, val in enumerate(schema.enum):
raw_name = str(val)
if i < len(enum_names):
raw_name = enum_names[i]
segoon marked this conversation as resolved.
Show resolved Hide resolved
emum_items.append(cpp_types.CppIntEnumItem(value=schema.enum[i],
raw_name=raw_name,
cpp_name=to_camel_case(raw_name), ))
segoon marked this conversation as resolved.
Show resolved Hide resolved

return cpp_types.CppIntEnum(
json_schema=schema,
nullable=schema.nullable,
raw_cpp_type=name,
user_cpp_type=None,
name=name.in_global_scope(),
enums=schema.enum,
enums=emum_items,
)

if schema.format is None:
Expand Down
11 changes: 10 additions & 1 deletion chaotic/chaotic/back/cpp/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,11 +513,20 @@ def camel_case(string: str, no_lower_casing: bool = False) -> str:
class EnumItemName(str):
pass

@dataclasses.dataclass
class CppIntEnumItem:
value: int
segoon marked this conversation as resolved.
Show resolved Hide resolved
raw_name: str
segoon marked this conversation as resolved.
Show resolved Hide resolved
cpp_name: str

def definition_includes(self) -> List[str]:
return ['fmt/format.h']


@dataclasses.dataclass
class CppIntEnum(CppType):
name: str
enums: List[int]
enums: List[CppIntEnumItem]

__hash__ = CppType.__hash__

Expand Down
81 changes: 81 additions & 0 deletions chaotic/golden_tests/output/schemas/int_enum/int_enum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#include "int_enum.hpp"

#include <userver/chaotic/type_bundle_cpp.hpp>

#include "int_enum_parsers.ipp"

namespace ns {

bool operator==(const ns::Enum& lhs, const ns::Enum& rhs) {
return lhs.foo == rhs.foo && true;
}

USERVER_NAMESPACE::logging::LogHelper& operator<<(
USERVER_NAMESPACE::logging::LogHelper& lh, const ns::Enum::Foo& value) {
return lh << ToString(USERVER_NAMESPACE::formats::json::ValueBuilder(value)
.ExtractValue());
}

USERVER_NAMESPACE::logging::LogHelper& operator<<(
USERVER_NAMESPACE::logging::LogHelper& lh, const ns::Enum& value) {
return lh << ToString(USERVER_NAMESPACE::formats::json::ValueBuilder(value)
.ExtractValue());
}

Enum::Foo Parse(USERVER_NAMESPACE::formats::json::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum::Foo> to) {
return Parse<USERVER_NAMESPACE::formats::json::Value>(json, to);
}

Enum Parse(USERVER_NAMESPACE::formats::json::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum> to) {
return Parse<USERVER_NAMESPACE::formats::json::Value>(json, to);
}

Enum::Foo Parse(USERVER_NAMESPACE::formats::yaml::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum::Foo> to) {
return Parse<USERVER_NAMESPACE::formats::yaml::Value>(json, to);
}

Enum Parse(USERVER_NAMESPACE::formats::yaml::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum> to) {
return Parse<USERVER_NAMESPACE::formats::yaml::Value>(json, to);
}

Enum::Foo Parse(USERVER_NAMESPACE::yaml_config::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum::Foo> to) {
return Parse<USERVER_NAMESPACE::yaml_config::Value>(json, to);
}

Enum Parse(USERVER_NAMESPACE::yaml_config::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum> to) {
return Parse<USERVER_NAMESPACE::yaml_config::Value>(json, to);
}

USERVER_NAMESPACE::formats::json::Value Serialize(
const ns::Enum::Foo& value, USERVER_NAMESPACE::formats::serialize::To<
USERVER_NAMESPACE::formats::json::Value>
to) {
const auto result = kns__Enum__Foo_Mapping.TryFindByFirst(value);
if (result.has_value()) {
return Serialize(*result, to);
}
throw std::runtime_error("Bad enum value");
}

USERVER_NAMESPACE::formats::json::Value Serialize(
[[maybe_unused]] const ns::Enum& value,
USERVER_NAMESPACE::formats::serialize::To<
USERVER_NAMESPACE::formats::json::Value>) {
USERVER_NAMESPACE::formats::json::ValueBuilder vb =
USERVER_NAMESPACE::formats::common::Type::kObject;

if (value.foo) {
vb["foo"] =
USERVER_NAMESPACE::chaotic::Primitive<ns::Enum::Foo>{*value.foo};
}

return vb.ExtractValue();
}

} // namespace ns
65 changes: 65 additions & 0 deletions chaotic/golden_tests/output/schemas/int_enum/int_enum.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#pragma once

#include "int_enum_fwd.hpp"

#include <optional>

#include <userver/chaotic/type_bundle_hpp.hpp>

namespace ns {

struct Enum {
enum class Foo {
kInner = 0, // Inner
kLeft = 1, // Left
kRight = 2, // Right
kOuter = 3, // Outer
k5 = 5, // 5
};

static constexpr Foo kFooValues[] = {
Foo::kInner,
Foo::kLeft,
Foo::kRight,
Foo::kOuter,
Foo::k5,
};

std::optional<ns::Enum::Foo> foo{};
};

bool operator==(const ns::Enum& lhs, const ns::Enum& rhs);

USERVER_NAMESPACE::logging::LogHelper& operator<<(
USERVER_NAMESPACE::logging::LogHelper& lh, const ns::Enum::Foo& value);

USERVER_NAMESPACE::logging::LogHelper& operator<<(
USERVER_NAMESPACE::logging::LogHelper& lh, const ns::Enum& value);

Enum::Foo Parse(USERVER_NAMESPACE::formats::json::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum::Foo>);

Enum Parse(USERVER_NAMESPACE::formats::json::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum>);

Enum::Foo Parse(USERVER_NAMESPACE::formats::yaml::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum::Foo>);

Enum Parse(USERVER_NAMESPACE::formats::yaml::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum>);

Enum::Foo Parse(USERVER_NAMESPACE::yaml_config::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum::Foo>);

Enum Parse(USERVER_NAMESPACE::yaml_config::Value json,
USERVER_NAMESPACE::formats::parse::To<ns::Enum>);

USERVER_NAMESPACE::formats::json::Value Serialize(
const ns::Enum::Foo& value, USERVER_NAMESPACE::formats::serialize::To<
USERVER_NAMESPACE::formats::json::Value>);

USERVER_NAMESPACE::formats::json::Value Serialize(
const ns::Enum& value, USERVER_NAMESPACE::formats::serialize::To<
USERVER_NAMESPACE::formats::json::Value>);

} // namespace ns
7 changes: 7 additions & 0 deletions chaotic/golden_tests/output/schemas/int_enum/int_enum_fwd.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#pragma once

namespace ns {

struct Enum;

} // namespace ns
63 changes: 63 additions & 0 deletions chaotic/golden_tests/output/schemas/int_enum/int_enum_parsers.ipp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#pragma once

#include "int_enum.hpp"

#include <fmt/format.h>
#include <cstdint>
#include <userver/chaotic/exception.hpp>
#include <userver/chaotic/object.hpp>
#include <userver/chaotic/primitive.hpp>
#include <userver/chaotic/with_type.hpp>
#include <userver/formats/parse/common_containers.hpp>
#include <userver/formats/serialize/common_containers.hpp>
#include <userver/utils/trivial_map.hpp>

namespace ns {

static constexpr USERVER_NAMESPACE::utils::TrivialBiMap kns__Enum__Foo_Mapping =
[](auto selector) {
return selector()
.template Type<ns::Enum::Foo, int>()
.Case(ns::Enum::Foo::kInner, 0)
.Case(ns::Enum::Foo::kLeft, 1)
.Case(ns::Enum::Foo::kRight, 2)
.Case(ns::Enum::Foo::kOuter, 3)
.Case(ns::Enum::Foo::k5, 5);
};

static constexpr USERVER_NAMESPACE::utils::TrivialSet
kns__Enum_PropertiesNames = [](auto selector) {
return selector().template Type<std::string_view>().Case("foo");
};

template <typename Value>
ns::Enum::Foo Parse(Value val,
USERVER_NAMESPACE::formats::parse::To<ns::Enum::Foo>) {
const auto value = val.template As<std::int32_t>();
const auto result = kns__Enum__Foo_Mapping.TryFindBySecond(value);
if (result.has_value()) {
return *result;
}
USERVER_NAMESPACE::chaotic::ThrowForValue(
fmt::format("Invalid enum value ({}) for type ns::Enum::Foo", value),
val);
}

template <typename Value>
ns::Enum Parse(Value value, USERVER_NAMESPACE::formats::parse::To<ns::Enum>) {
value.CheckNotMissing();
value.CheckObjectOrNull();

ns::Enum res;

res.foo = value["foo"]
.template As<std::optional<
USERVER_NAMESPACE::chaotic::Primitive<ns::Enum::Foo>>>();

USERVER_NAMESPACE::chaotic::ValidateNoAdditionalProperties(
value, kns__Enum_PropertiesNames);

return res;
}

} // namespace ns
14 changes: 14 additions & 0 deletions chaotic/golden_tests/schemas/int_enum/int_enum.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
components:
schemas:
Enum:
type: object
additionalProperties: false
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это должен быть не голден тест, а тест на то, что static_cast(kInner) == 0 и т.п.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я про тест совсем не понял. Где это должно проверяться и почему именно static_cast(kInner)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

где - где-то в chaotic/tests/back/cpp
почему - ну ты написал некую функциональность, которая генерит другие имена констант; нужно проверить, что эти константы равны нужным значениям, а не абы каким
голден тесты - это не тесты, а лишь витрина для стороннего наблюдателя

properties:
foo:
type: integer
enum: [ 0, 1, 2, 3, 5]
x-enum-varnames:
- Inner
- Left
- Right
- Outer
Loading