Skip to content

[v1.8.0] flatc prints 0 as default enum value instead of its name #4509

@jvanstraten

Description

@jvanstraten

When converting a flatbuffer to json using flatc -t, non-default enum values are represented as their textual name, and default values are not printed. However, when --defaults-json is enabled to also print the default values, they are represented as their numerical value (i.e., 0). That seems unintentional.

To reproduce:

  • Make test.fbs:
namespace Test;

enum Color: byte { Red, Green, Blue }

table Test {
  r: Color;
  g: Color;
  b: Color;
}

root_type Test;
  • Make test.json:
{
  r: Red,
  g: Green,
  b: Blue
}
  • Run flatc -b test.fbs test.json to serialize to test.bin
  • Run flatc -t --defaults-json --raw-binary test.fbs -- test.bin to regenerate test.json
  • Observe that test.json now contains:
{
  r: 0,
  g: Green,
  b: Blue
}

Note that I'm not expecting flatc to magically remember whether the original json file used names or integers to specify the enum value. I'm just expecting the output format to be consistent.

I'm not familiar with the project sources at all so I have no idea what I'm doing, but the following extremely ugly hack seems to fix this, and doesn't seem to break printing the more complex files I'm working with (Apache Arrow schemas). It doesn't seem worth making a pull request for though, because this certainly cannot be the right way to solve this...

diff --git a/src/idl_gen_text.cpp b/src/idl_gen_text.cpp
index 50d54c5..da2e8c1 100644
--- a/src/idl_gen_text.cpp
+++ b/src/idl_gen_text.cpp
@@ -224,7 +224,7 @@ static bool GenStruct(const StructDef &struct_def, const Table *table,
           (fd.value.type.base_type != BASE_TYPE_STRUCT &&
            fd.value.type.base_type != BASE_TYPE_VECTOR)) text += ":";
       text += " ";
-      if (is_present) {
+      if (is_present || 1) {
         switch (fd.value.type.base_type) {
            #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
              CTYPE, JTYPE, GTYPE, NTYPE, PTYPE) \

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions