Skip to content

Commit

Permalink
Merge pull request #40 from NordSecurity/enum_naming_styles
Browse files Browse the repository at this point in the history
Enum variant naming styles
  • Loading branch information
Lipt0nas authored Apr 11, 2024
2 parents f07eb35 + 3a5b586 commit 8b30731
Show file tree
Hide file tree
Showing 26 changed files with 252 additions and 78 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
#### v0.6.0+v0.25.0

----
- Core: Added ability to customize enum variant naming styles
- Core: **BREAKING** Changed default enum variant naming style to `kEnumVariant`

#### v0.5.0+v0.25.0

----
Expand Down
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 2 additions & 10 deletions bindgen/src/bindings/cpp/gen_cpp/enum_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,7 @@ impl CodeType for EnumCodeType {
format!("Type{}", self.id)
}

fn literal(&self, literal: &Literal) -> String {
if let Literal::Enum(v, _) = literal {
format!(
"{}::{}",
self.type_label(),
CppCodeOracle.enum_variant_name(v)
)
} else {
unreachable!();
}
fn literal(&self, _: &Literal) -> String {
unreachable!();
}
}
28 changes: 22 additions & 6 deletions bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use crate::bindings::cpp::gen_cpp::{
callback_interface, compounds, custom, enum_, miscellany, object, primitives, record,
};

use super::EnumStyle;

type Result<T> = std::result::Result<T, askama::Error>;

#[derive(Clone)]
Expand All @@ -25,8 +27,11 @@ impl CppCodeOracle {
nm.to_string().to_upper_camel_case()
}

pub(crate) fn enum_variant_name(&self, nm: &str) -> String {
nm.to_string().to_shouty_snake_case()
pub(crate) fn enum_variant_name(&self, nm: &str, style: &EnumStyle) -> String {
match style {
EnumStyle::Capitalized => nm.to_string().to_shouty_snake_case(),
EnumStyle::Google => format!("k{}", nm.to_string().to_upper_camel_case()),
}
}

pub(crate) fn fn_name(&self, nm: &str) -> String {
Expand Down Expand Up @@ -107,8 +112,19 @@ pub(crate) fn var_name(nm: &str) -> Result<String> {
Ok(CppCodeOracle.var_name(nm))
}

pub(crate) fn literal_cpp(literal: &Literal, as_ct: &impl AsCodeType) -> Result<String> {
Ok(as_ct.as_codetype().literal(literal))
pub(crate) fn literal_cpp(
literal: &Literal,
as_ct: &impl AsCodeType,
enum_style: &EnumStyle,
) -> Result<String> {
match literal {
Literal::Enum(name, _) => Ok(format!(
"{}::{}",
as_ct.as_codetype().type_label(),
CppCodeOracle.enum_variant_name(&name, enum_style),
)),
_ => Ok(as_ct.as_codetype().literal(literal)),
}
}

pub(crate) fn lift_fn(as_ct: &impl AsCodeType) -> Result<String> {
Expand Down Expand Up @@ -146,8 +162,8 @@ pub(crate) fn allocation_size_fn(as_ct: &impl AsCodeType) -> Result<String> {
))
}

pub(crate) fn variant_name(v: &Variant) -> Result<String> {
Ok(CppCodeOracle.enum_variant_name(v.name()))
pub(crate) fn variant_name(v: &Variant, enum_style: &EnumStyle) -> Result<String> {
Ok(CppCodeOracle.enum_variant_name(v.name(), enum_style))
}

pub(crate) fn ffi_type_name(ffi_type: &FfiType) -> Result<String> {
Expand Down
16 changes: 16 additions & 0 deletions bindgen/src/bindings/cpp/gen_cpp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ use uniffi_bindgen::{
BindingsConfig, ComponentInterface,
};

#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum EnumStyle {
Capitalized,
Google,
}

impl Default for EnumStyle {
fn default() -> Self {
EnumStyle::Google
}
}

#[derive(Clone, Deserialize, Serialize, Debug, Default)]
struct CustomTypesConfig {
imports: Option<Vec<String>>,
Expand All @@ -36,12 +48,16 @@ struct CustomTypesConfig {
pub(crate) struct Config {
#[serde(default)]
custom_types: HashMap<String, CustomTypesConfig>,
#[serde(default)]
enum_style: EnumStyle,
}

#[derive(Clone, Deserialize, Serialize, Debug, Default)]
pub(crate) struct ScaffoldingConfig {
#[serde(default)]
namespace: Option<String>,
#[serde(default)]
enum_style: EnumStyle,
}

impl BindingsConfig for Config {
Expand Down
14 changes: 7 additions & 7 deletions bindgen/src/bindings/cpp/templates/enum.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
enum class {{ type_name }}: int32_t {
{%- for variant in e.variants() %}
{%- call macros::docstring(variant, 4) %}
{{ variant|variant_name }} = {{ loop.index }}
{{ variant|variant_name(config.enum_style) }} = {{ loop.index }}
{%- if !loop.last %},
{%- endif %}
{%- endfor %}
Expand All @@ -20,19 +20,19 @@ struct {{ type_name }} {

{%- for variant in e.variants() %}
{%- call macros::docstring(variant, 4) %}
struct {{ variant|variant_name }} {
struct {{ variant|variant_name(config.enum_style) }} {
{%- for field in variant.fields() %}
{%- call macros::docstring(field, 8) %}
{{ field|type_name }} {{ field.name()|var_name }}
{%- match field.default_value() %}
{%- when Some with (literal) %} = {{ literal|literal_cpp(field) }};{%- else -%};
{%- when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style) }};{%- else -%};
{%- endmatch %}
{%- endfor %}
};
{%- endfor %}

{%- for variant in e.variants() %}
{{ type_name }}({{ variant|variant_name }} variant): variant(variant) {}
{{ type_name }}({{ variant|variant_name(config.enum_style) }} variant): variant(variant) {}
{%- endfor %}

{{ type_name }}(const {{ type_name }} &other): variant(other.variant) {}
Expand All @@ -51,13 +51,13 @@ struct {{ type_name }} {
/**
* Returns the variant of this enum
*/
const std::variant<{% for variant in e.variants() %}{{ variant|variant_name }}{% if !loop.last %}, {% endif %}{% endfor %}> &get_variant() const {
const std::variant<{% for variant in e.variants() %}{{ variant|variant_name(config.enum_style) }}{% if !loop.last %}, {% endif %}{% endfor %}> &get_variant() const {
return variant;
}

private:
std::variant<{% for variant in e.variants() %}{{ variant|variant_name }}{% if !loop.last %}, {% endif %}{% endfor %}> variant;
std::variant<{% for variant in e.variants() %}{{ variant|variant_name(config.enum_style) }}{% if !loop.last %}, {% endif %}{% endfor %}> variant;

{{ type_name }}();
};
{%- endif %}
{%- endif %}
10 changes: 5 additions & 5 deletions bindgen/src/bindings/cpp/templates/enum_tmpl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) {
switch (variant) {
{% for variant in e.variants() %}
case {{ loop.index }}:
return {{ type_name }}::{{ variant|variant_name }};
return {{ type_name }}::{{ variant|variant_name(config.enum_style) }};
{% endfor %}
default:
throw std::runtime_error("No matching {{ type_name }} variant");
Expand All @@ -34,7 +34,7 @@ RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) {
void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &val) {
switch (val) {
{% for variant in e.variants() %}
case {{ type_name }}::{{ variant|variant_name }}:
case {{ type_name }}::{{ variant|variant_name(config.enum_style) }}:
stream << static_cast<int32_t>({{ loop.index }});
break;
{% endfor %}
Expand Down Expand Up @@ -72,7 +72,7 @@ RustBuffer {{ ffi_converter_name }}::lower(const {{ type_name }} &val) {
switch (variant_id) {
{% for variant in e.variants() %}
case {{ loop.index }}:
return {{ type_name }}::{{ variant|variant_name }} {
return {{ type_name }}::{{ variant|variant_name(config.enum_style) }} {
{%- for field in variant.fields() %}
.{{field.name()|var_name}} = {{ field|read_fn }}(stream),
{%- endfor %}
Expand All @@ -91,7 +91,7 @@ void {{ ffi_converter_name }}::write(RustStream &stream, const {{ type_name }} &
std::visit([&](auto &&arg) {
using T = std::decay_t<decltype(arg)>;
{%- for variant in e.variants() %}
{% if !loop.first %}else {% endif %}if constexpr (std::is_same_v<T, {{ type_name }}::{{ variant|variant_name }}>) {
{% if !loop.first %}else {% endif %}if constexpr (std::is_same_v<T, {{ type_name }}::{{ variant|variant_name(config.enum_style) }}>) {
{%- for field in variant.fields() %}
{{ field|write_fn }}(stream, arg.{{ field.name()|var_name }});
{%- endfor %}
Expand All @@ -111,7 +111,7 @@ int32_t {{ ffi_converter_name }}::allocation_size(const {{ type_name|class_name
size += std::visit([&](auto &&arg) {
using T = std::decay_t<decltype(arg)>;
{%- for variant in e.variants() %}
{% if !loop.first %}else {% endif %}if constexpr (std::is_same_v<T, {{ type_name }}::{{ variant|variant_name }}>) {
{% if !loop.first %}else {% endif %}if constexpr (std::is_same_v<T, {{ type_name }}::{{ variant|variant_name(config.enum_style) }}>) {
int32_t size = 0;
{%- for field in variant.fields() %}
size += {{ field|allocation_size_fn }}(arg.{{ field.name()|var_name }});
Expand Down
4 changes: 2 additions & 2 deletions bindgen/src/bindings/cpp/templates/err.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ struct {{ variant.name()|class_name }}: {{ class_name }} {
{%- for field in variant.fields() %}
{{ field|type_name }} {{ field.name()|var_name }}
{%- match field.default_value() %}
{% when Some with (literal) %} = {{ literal|literal_cpp(field) }};{% else %};
{% when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style) }};{% else %};
{%- endmatch %}
{%- endfor %}

Expand All @@ -48,4 +48,4 @@ struct {{ variant.name()|class_name }}: {{ class_name }} {
};
{%- endfor %}
} // namespace {{ class_name|to_lower_snake_case }}
{%- endif %}
{%- endif %}
4 changes: 2 additions & 2 deletions bindgen/src/bindings/cpp/templates/rec.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ struct {{ type_name }} {
{%- call macros::docstring(field, 4) %}
{{ field|type_name }} {{ field.name()|var_name }}
{%- match field.default_value() %}
{%- when Some with (literal) %} = {{ literal|literal_cpp(field) }};{%- else -%};
{%- when Some with (literal) %} = {{ literal|literal_cpp(field, config.enum_style) }};{%- else -%};
{%- endmatch %}
{%- endfor %}
};
};
2 changes: 2 additions & 0 deletions cpp-tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ test_case(coverall)
test_case(uniffi_docstring)
test_case(trait_methods)
test_case(custom_types_builtin)
test_case(enum_style_test)

scaffolding_test_case(arithmetic)
scaffolding_test_case(callbacks)
Expand All @@ -99,6 +100,7 @@ scaffolding_test_case(todolist)
scaffolding_test_case(traits)
scaffolding_test_case(coverall)
scaffolding_test_case(custom_types_builtin)
scaffolding_test_case(enum_style_test)

add_library(uniffi_fixtures SHARED
${SCAFFOLDING_LIB_FILES})
Expand Down
8 changes: 4 additions & 4 deletions cpp-tests/scaffolding_tests/coverall/lib_coverall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -227,21 +227,21 @@ std::vector<std::shared_ptr<coverall::TestTrait>> coverall::get_traits() {

coverall::MaybeSimpleDict coverall::get_maybe_simple_dict(int8_t index) {
if (index == 0) {
return { coverall::MaybeSimpleDict::YEAH {} };
return { coverall::MaybeSimpleDict::kYeah {} };
}
else if (index == 1) {
return { coverall::MaybeSimpleDict::NAH {} };
return { coverall::MaybeSimpleDict::kNah {} };
}

throw std::runtime_error("invalid index");
}

coverall::SimpleFlatMacroEnum coverall::get_simple_flat_macro_enum(int8_t index) {
if (index == 0) {
return { coverall::SimpleFlatMacroEnum::FIRST { "the first" } };
return { coverall::SimpleFlatMacroEnum::kFirst { "the first" } };
}
else if (index == 1) {
return { coverall::SimpleFlatMacroEnum::SECOND { 2 } };
return { coverall::SimpleFlatMacroEnum::kSecond { 2 } };
}

throw std::runtime_error("invalid index");
Expand Down
36 changes: 18 additions & 18 deletions cpp-tests/scaffolding_tests/coverall/lib_coverall.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ namespace {
};

enum class Color {
RED,
BLUE,
GREEN
kRed,
kBlue,
kGreen
};

class Patch {
Expand Down Expand Up @@ -150,48 +150,48 @@ namespace {

class MaybeSimpleDict {
public:
struct YEAH {
struct kYeah {
SimpleDict d;
};

struct NAH {};
struct kNah {};

MaybeSimpleDict(MaybeSimpleDict::YEAH value) { this->variant = value; }
MaybeSimpleDict(MaybeSimpleDict::NAH value) { this->variant = value; }
MaybeSimpleDict(MaybeSimpleDict::kYeah value) { this->variant = value; }
MaybeSimpleDict(MaybeSimpleDict::kNah value) { this->variant = value; }

std::variant<YEAH, NAH> variant;
std::variant<kYeah, kNah> variant;
};

class SimpleFlatEnum {
public:
struct FIRST {
struct kFirst {
std::string val;
};

struct SECOND {
struct kSecond {
uint16_t num;
};

SimpleFlatEnum(SimpleFlatEnum::FIRST value) { this->variant = value; }
SimpleFlatEnum(SimpleFlatEnum::SECOND value) { this->variant = value; }
SimpleFlatEnum(SimpleFlatEnum::kFirst value) { this->variant = value; }
SimpleFlatEnum(SimpleFlatEnum::kSecond value) { this->variant = value; }

std::variant<FIRST, SECOND> variant;
std::variant<kFirst, kSecond> variant;
};

class SimpleFlatMacroEnum {
public:
struct FIRST {
struct kFirst {
std::string val;
};

struct SECOND {
struct kSecond {
uint16_t num;
};

SimpleFlatMacroEnum(SimpleFlatMacroEnum::FIRST value) { this->variant = value; }
SimpleFlatMacroEnum(SimpleFlatMacroEnum::SECOND value) { this->variant = value; }
SimpleFlatMacroEnum(SimpleFlatMacroEnum::kFirst value) { this->variant = value; }
SimpleFlatMacroEnum(SimpleFlatMacroEnum::kSecond value) { this->variant = value; }

std::variant<FIRST, SECOND> variant;
std::variant<kFirst, kSecond> variant;
};

namespace coverall_error {
Expand Down
Loading

0 comments on commit 8b30731

Please sign in to comment.