proxmox/proxmox-api-macro/src/api/enums.rs
Wolfgang Bumiller 7c6ebbdbf3 api-macro: support renamed struct fields
Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
2020-01-08 10:06:48 +01:00

78 lines
2.5 KiB
Rust

use std::convert::{TryFrom, TryInto};
use failure::Error;
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote_spanned;
use syn::punctuated::Punctuated;
use syn::Token;
use super::Schema;
use crate::serde;
use crate::util::{self, FieldName, JSONObject, JSONValue};
/// Enums, provided they're simple enums, simply get an enum string schema attached to them.
pub fn handle_enum(
mut attribs: JSONObject,
mut enum_ty: syn::ItemEnum,
) -> Result<TokenStream, Error> {
if !attribs.contains_key("type") {
attribs.insert(
FieldName::new("type".to_string(), Span::call_site()),
JSONValue::new_ident(Ident::new("String", enum_ty.enum_token.span)),
);
}
if let Some(fmt) = attribs.get("format") {
bail!(fmt.span(), "illegal key 'format', will be autogenerated");
}
let schema = {
let mut schema: Schema = attribs.try_into()?;
if schema.description.is_none() {
let (comment, span) = util::get_doc_comments(&enum_ty.attrs)?;
schema.description = Some(syn::LitStr::new(comment.trim(), span));
}
let mut ts = TokenStream::new();
schema.to_typed_schema(&mut ts)?;
ts
};
let container_attrs = serde::ContainerAttrib::try_from(&enum_ty.attrs[..])?;
// with_capacity(enum_ty.variants.len());
// doesn't exist O.o
let mut variants = Punctuated::<syn::LitStr, Token![,]>::new();
for variant in &mut enum_ty.variants {
match &variant.fields {
syn::Fields::Unit => (),
_ => bail!(variant => "api macro does not support enums with fields"),
}
let attrs = serde::SerdeAttrib::try_from(&variant.attrs[..])?;
if let Some(renamed) = attrs.rename {
variants.push(renamed.into_lit_str());
} else if let Some(rename_all) = container_attrs.rename_all {
let name = rename_all.apply_to_variant(&variant.ident.to_string());
variants.push(syn::LitStr::new(&name, variant.ident.span()));
} else {
let name = &variant.ident;
variants.push(syn::LitStr::new(&name.to_string(), name.span()));
}
}
let name = &enum_ty.ident;
Ok(quote_spanned! { name.span() =>
#enum_ty
impl #name {
pub const API_SCHEMA: &'static ::proxmox::api::schema::Schema =
& #schema
.format(&::proxmox::api::schema::ApiStringFormat::Enum(&[#variants]))
.schema();
}
})
}