oxidecomputer / typify

compiler from JSON Schema into idiomatic Rust types
Apache License 2.0
423 stars 58 forks source link

sanitize keys to raw identifiers instead of postfixing with `_` #541

Closed nyarthan closed 6 months ago

nyarthan commented 6 months ago

With a schema like this, that has a property key type:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$ref": "#/definitions/obj",
  "definitions": {
    "obj": {
      "type": "object",
      "properties": {
        "type": { "type": "string" }
      },
      "required": ["type"],
      "additionalProperties": false
    }
  }
}

The resulting struct would be:

pub struct Obj {
    #[serde(rename = "type")]
    pub type_: String,
}

I think a better way would be to use Raw identifiers instead of a postfix to ensure the key is not a rust ident.

This is a more idiomatic approach to use keywords as properties and also allows getting rid of the serde(rename = "...") attribute since serde handles Raw identifiers out of the box.

pub struct Obj {
    pub r#type: String,
}
nyarthan commented 6 months ago

While playing around with this, I came to the realization that this will not work for the keys super, self, Self, extern and crate (https://internals.rust-lang.org/t/raw-identifiers-dont-work-for-all-identifiers/9094/2). So this approach might not be desirable as it would be inconsistent for these specific keys.

ahl commented 6 months ago

Yeah I've thought about using that after I discovered that syntax... but as you say it's not without its own complexity.

ahl commented 6 months ago

I'm going to close this. I'm amenable to reconsidering if you think the inconsistency is worth it. Suffice to say: I don't love any of the options.