GREsau / schemars

Generate JSON Schema documents from Rust code
https://graham.cool/schemars/
MIT License
820 stars 227 forks source link

Simplify generated enum code #286

Closed GREsau closed 5 months ago

GREsau commented 5 months ago

Mitigates #246

Based on #266, but moves new functions into _private module. They are likely to be moved/changed when the structure of Schema changes, so I really don't want them to be part of the public API.

Description from original PR:

Partial solution for #246

  • replace the manual construction of Schema::Object with a helper method
  • replace metadata setting with a function call per-metadata

Taking the enum from https://github.com/adamchalmers/rust-problems/blob/achalmers/schemars-llvm-lines/src/lib.rs and running cargo rustc -- -Z unpretty=mir | wc -l it goes from 165725 lines of MIR to 4871 (removing the serde derives from the linked code)

The per-variant generate code goes from:

{
    let schema = schemars::schema::Schema::Object(schemars::schema::SchemaObject {
        instance_type: Some(
            schemars::schema::InstanceType::String.into(),
        ),
        enum_values: Some(
            <[_]>::into_vec(
                #[rustc_box]
                ::alloc::boxed::Box::new(["Af".into()]),
            ),
        ),
        ..Default::default()
    });
    schemars::_private::apply_metadata(
        schema,
        schemars::schema::Metadata {
            description: Some("Afghanistan".to_owned()),
            ..Default::default()
        },
    )
},

to:

{
    let schema = schemars::schema::Schema::Object(
        schemars::schema::SchemaObject::new_unit_enum("Af"),
    );
    schema.with_description("Afghanistan")
},

~I still have a crate that takes forever to generate the schema for so there are still plenty of room for improvement.~