oxidecomputer / typify

compiler from JSON Schema into idiomatic Rust types
Apache License 2.0
442 stars 59 forks source link

Sub-types naming conflicts #695

Open jandremarais opened 1 week ago

jandremarais commented 1 week ago

The following definitions will result in both an Enum and a Struct named AaBb:

"Aa": {
  "properties": {
    "bb": {
      "anyOf": [
        {
          "$ref": "#/definitions/AaBb"
        },
        {
          "type": "string"
        }
      ]
    }
  }
},
"AaBb": {
  "enum": [
    "A",
    "B"
  ],
  "type": "string"
}

We might need an alternative way to name types in types. Maybe AaSubBb or AaBbProp, idk.

ahl commented 1 week ago

Yeah. Naming is hard. See #1.

What I'd like to do is defer naming until after we've added all items to a "namespace". Then the namespace would be responsible for choosing names. Previously, I was of the opinion that we should try to use context and heuristics to choose good names. I'm increasingly of the opinion that we will want or need a mechanism that allows users to resolve name conflicts. Consider, for example, this schema we get from a GitHub OpenAPI document:

{
  "type": "string",
  "enum": [
    "+1",       
    "-1",       
    "laugh",    
    "confused", 
    "heart",    
    "hooray",   
    "rocket",   
    "eyes"      
  ]
}

How would we produce variant names for -1 and +1? What if the options were -2, -1, 0, +1, +2? Seems like we might want different names in those cases.

My current (background) focus is to have a more complete handling of references to external files and non-$def JSON paths. I believe that this will allow us to include more useful path information throughout. This will be useful for errors, but also to allow manual intervention in these cases. One could imagine an ancillary file to help resolve names, or one could imagine extensions (and first-class JSON patch support to add them). For example:

{
  "type": "string",
  "enum": [
    "+1",       
    "-1",       
    "laugh",    
    "confused", 
    "heart",    
    "hooray",   
    "rocket",   
    "eyes"      
  ],
  "x-code-rename": {
    "+1": "plusOne",
    "-1": "minusOne"
  }
}

In your particular case, I'd love typify to identify the name conflict, produce a meaningful error:

Sorry, but I don't know what to name the type found at #/definitions/Aa/properties/bb such that it doesn't conflict with the type found at #/definitions/AaBb. Could you please help me out? For example, you could make a JSON patch file that looks like this...