glideapps / quicktype

Generate types and converters from JSON, Schema, and GraphQL
https://app.quicktype.io
Apache License 2.0
12.11k stars 1.06k forks source link

Detect and properly handle recursive types #273

Open schani opened 6 years ago

schani commented 6 years ago

Recursive types can result even from JSON input (via merging of similar types - see the recursive.json sample), so every backend either needs to be able to handle them, or signal that it can't. Some languages, like Swift, require an option to handle them, so we'd either have to turn that option on when recursive types are involved, or only allow merging in case the option is on. It would be even better if we had an analysis that could detect not only whether there are recursive types, but which types are involved in the recursion, which would allow us to generate class types only for them in Swift, for example, or emit forward declarations in C++.

schani commented 6 years ago

See #187 for some comments on how to make recursion work in Swift and Elm.

schani commented 6 years ago

At this point only Elm is missing. Unfortunately, the code we need to generate for recursive types is quite different from the non-recursive case.

Denis-Gavrielov commented 3 years ago

@schani it seems like the recursive version for C++ is not working for me.

I have something like this:

    "RecursiveThing": {
      "type": "array",
      "items": {
        "anyOf": [
          {
            "$ref": "#/definitions/RecursiveThing"
          },
          { "type": "string" }
        ]
      }
    },

When I use this in C++ I get the following:

    using RecursiveThing = std::variant<std::vector<RecursiveThing>, std::string>;

This unfortunately doesn't compile. I think we would need some forward declarations and using a struct instead of just using.

Maybe there are some commands to generate this properly. I am using the following commands:

quicktype --lang c++ --code-format with-struct --namespace "schema" --hide-null-optional --const-style east-const --src-lang schema --member-style camel-case --no-boost --out json_schema.h request-schema.json

Is this something that you can fix for the C++ codegen?