1{#---
2  Macro for enum definition, and the declaration of associated functions.
3---#}
4{%- macro enum_decl(enum) %}
5enum class {{enum.name}} : int32_t {
6{%- for field in enum.fields %}
7{%-    if field.value %}
8  {{field.name}} = {{field.value|expression_to_text}},
9{%-    else %}
10  {{field.name}},
11{%-    endif %}
12{%- endfor %}
13};
14{%- endmacro %}
15
16{%- macro enum_data_decl(enum) %}
17struct {{enum.name}}_Data {
18 public:
19  static bool const kIsExtensible = {% if enum.extensible %}true{% else %}false{% endif %};
20
21  static bool IsKnownValue(int32_t value) {
22{%- if enum.fields %}
23    switch (value) {
24{%-   for enum_field in enum.fields|groupby('numeric_value') %}
25      case {{enum_field[0]}}:
26{%-   endfor %}
27        return true;
28    }
29{%- endif %}
30    return false;
31  }
32
33  static bool Validate(int32_t value,
34                       mojo::internal::ValidationContext* validation_context) {
35    if (kIsExtensible || IsKnownValue(value))
36      return true;
37
38    ReportValidationError(validation_context,
39                          mojo::internal::VALIDATION_ERROR_UNKNOWN_ENUM_VALUE);
40    return false;
41  }
42};
43{%- endmacro %}
44
45{#--- macros for enum-associated functions. Namely:
46  * operator<<(): outputs the given enum value.
47  * IsKnownEnumValue(): returns true if the given enum value exists in this
48        generated version of enum.
49---#}
50
51{%- macro enum_stream_operator(enum) %}
52inline std::ostream& operator<<(std::ostream& os, {{enum|get_name_for_kind}} value) {
53  switch(value) {
54{%- for _, values in enum.fields|groupby('numeric_value') %}
55    case {{enum|get_name_for_kind}}::{{values[0].name}}:
56      return os << "{{enum|get_name_for_kind}}::
57{%-   if values|length > 1 -%}
58      {{'{'}}
59{%-   endif -%}
60      {{values|map(attribute='name')|join(', ')}}
61{%-   if values|length > 1 -%}
62      {{'}'}}
63{%-   endif -%}
64      ";
65{%- endfor %}
66    default:
67      return os << "Unknown {{enum|get_name_for_kind}} value: " << static_cast<int32_t>(value);
68  }
69}
70{%- endmacro %}
71
72{%- macro is_known_enum_value(enum) %}
73inline bool IsKnownEnumValue({{enum|get_name_for_kind}} value) {
74  return {{enum|get_qualified_name_for_kind(internal=True)}}::IsKnownValue(
75      static_cast<int32_t>(value));
76}
77{%- endmacro %}
78
79{%- macro enum_hash(enum) %}
80template <>
81struct hash<{{enum|get_qualified_name_for_kind}}>
82    : public mojo::internal::EnumHashImpl<{{enum|get_qualified_name_for_kind}}> {};
83{%- endmacro %}
84