Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raw identifier keywords #1362

Closed
michaelfairley opened this issue Aug 22, 2018 · 2 comments
Closed

Raw identifier keywords #1362

michaelfairley opened this issue Aug 22, 2018 · 2 comments

Comments

@michaelfairley
Copy link

michaelfairley commented Aug 22, 2018

Right now, serde_derive passes through the r# on raw identifiers when the identifier is a keyword.

For example (playground link)

#[derive(Serialize)]
struct Foo {
    r#type: i32,
    r#bar: i32
}

fn main() {
    let foo = Foo{ r#type: 3, r#bar: 12 };
    println!("{}", serde_json::to_string_pretty(&foo).unwrap());
}

prints

{
  "r#type": 3,
  "bar": 12
}

That r# on the r#type seems like it shouldn't be exposed downstream of serde, since the current-list-of-keywords-in-Rust is an implementation detail that serialization probably shouldn't care about. Currently, a bunch of the data format libraries that work with serde (e.g. ron) emit invalid data when provided with these raw identifiers, since they assume that field identifiers have a limited set of characters (that doesn't include #).

Unfortunately, the root of this issue is probably upstream of serde, and even writing a test case for this in this repo is tricky (since the test code has to be Rust 2018).

@michaelfairley michaelfairley changed the title Raw identifier keywrods Raw identifier keywords Aug 22, 2018
@dtolnay
Copy link
Member

dtolnay commented Aug 22, 2018

Interesting! This is a bug. That program should be printing "type": 3 instead of "r#type": 3.

Would you be interested in tracking down where this is going wrong and sending a PR? Otherwise I should be able to take a look later this week.

As a workaround, at least serde(rename = "...") seems to work but this shouldn't be necessary.

#[derive(Serialize)]
struct Foo {
    #[serde(rename = "type")]
    r#type: i32,
    r#bar: i32
}

@dtolnay
Copy link
Member

dtolnay commented Aug 23, 2018

I published 1.0.73 with this fix. Thanks! The code in the playground link will print:

{
  "type": 3,
  "bar": 12
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants