oxidecomputer / typify

JSON Schema -> Rust type converter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Panic during `anyOf` usage

spencerwilson opened this issue · comments

Given

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "License",
  "description": "The license(s) under which this package is published.",
  "type": "object",
  "anyOf": [
    {
      "required": [
        "name"
      ]
    },
    {
      "required": [
        "path"
      ]
    }
  ],
  "properties": {
    "name": {
      "type": "string"
    },
    "path": {
      "type": "string"
    },
    "title": {
      "type": "string"
    }
  }
}

cargo-typify 0.0.13 errors:

% cargo typify other.json
The application panicked (crashed).
Message:  not yet implemented: invalid (or unexpected) schema:
...

A (possibly lazy) correct behavior would be to ignore anyOf here, to not use the constraints within any branch of it. In the resulting struct, all three properties name, path, and title would be Options.

To compute actual possible variants (all combinations of possible types) an object could take, given its anyOf and allOf clauses, could get a little hairy, though may be possible.

I've been giving this some consideration (there are other issues in this vein). I think the code I'd like to generate looks like this:

struct License {
    #[serde(flatten)]
    name_or_path: LicenseNameOrPath,
    title: Option<String>,
}

#[serde(untagged)]
enum LicenseNameOrPath {
    Name {
        name: String,
        path: Option<String>,
    },
    Path {
        name: Option<String>,
        path: String,
    }
}

I might also throw in some accessor fns like fn path(&self) -> Option<&String>.

In general, I'd like to make sure that types are restricted to values permitted by the schema.