Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
14bbbe9
Capture docs for types, fields, and enum variants
ascjones Apr 26, 2021
4e696dc
Add docs to derive tests
ascjones Apr 26, 2021
55fc739
Fmt
ascjones Apr 26, 2021
ded2f3f
Fmt
ascjones Apr 27, 2021
3b78d47
Make clippy happy
ascjones Apr 27, 2021
c74422d
Fix struct docs tests
ascjones Apr 27, 2021
329d915
Fix struct docs tests
ascjones Apr 27, 2021
637ab5a
Add missing Vec import
ascjones Apr 27, 2021
efdd3e4
Fix test
ascjones Apr 27, 2021
77fc88a
Clear docs
ascjones Apr 27, 2021
912fbcb
Merge branch 'master' into aj-docs
ascjones May 25, 2021
4151589
Promote build to it's own mod, split fields and variant builders
ascjones May 25, 2021
a0743b0
Refactor variant construction with builder
ascjones May 25, 2021
fd6f893
Fix up derive and unit tests with Variant builder
ascjones May 25, 2021
52f5e83
Fmt
ascjones May 25, 2021
2d2ab5c
Condense build module back to single file
ascjones May 25, 2021
c4bf49d
Fix up doc tests
ascjones May 25, 2021
05d875b
Fix up README
ascjones May 25, 2021
790a6b8
Define initial field builder
ascjones May 26, 2021
0f3b795
Fix up field building
ascjones May 26, 2021
655279a
Fix tests
ascjones May 26, 2021
63b986a
Fully qualify calls to stringify
ascjones May 26, 2021
150ef4e
Default impl for FieldBuilder
ascjones May 26, 2021
43551f4
Fix up default impl
ascjones May 26, 2021
0decd01
Fix spelling errors
ascjones May 26, 2021
e031939
Remove clear_docs
ascjones May 26, 2021
fdd96c3
Fully qualify module_path
ascjones May 26, 2021
585a671
Update derive/src/lib.rs
ascjones May 26, 2021
a7179b5
Merge remote-tracking branch 'origin/aj-docs' into aj-docs
ascjones May 26, 2021
4d73ae4
Use callback for variant builder
ascjones May 26, 2021
59ff44c
Update README
ascjones May 26, 2021
e8ea40b
Remove leading space in doc comments
ascjones May 26, 2021
1c01b94
Satisfy clippy
ascjones May 26, 2021
0edec05
Add test for doc capture
ascjones May 27, 2021
fcc8985
Rename index back to discriminant, changes for this will be in https:…
ascjones May 27, 2021
6fb8042
Rename index back to discriminant, changes for this will be in https:…
ascjones May 27, 2021
882bdb4
Update src/build.rs
ascjones May 27, 2021
ebc3e4b
Update src/build.rs
ascjones May 27, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Capture docs for types, fields, and enum variants
  • Loading branch information
ascjones committed Apr 26, 2021
commit 14bbbe9025d75cc696c53cf3ea933eb007043004
23 changes: 16 additions & 7 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,16 @@ fn generate_type(input: TokenStream2) -> Result<TokenStream2> {
Data::Enum(ref e) => generate_variant_type(e, &scale_info),
Data::Union(_) => return Err(Error::new_spanned(input, "Unions not supported")),
};
let docs = utils::get_doc_literals(&ast.attrs);

let type_info_impl = quote! {
impl #impl_generics :: #scale_info ::TypeInfo for #ident #ty_generics #where_clause {
type Identity = Self;
fn type_info() -> :: #scale_info ::Type {
:: #scale_info ::Type::builder()
.path(:: #scale_info ::Path::new(stringify!(#ident), module_path!()))
.type_params(:: #scale_info ::prelude::vec![ #( #generic_type_ids ),* ])
.docs(&[ #( #docs ),* ])
.#build_type
}
}
Expand Down Expand Up @@ -149,15 +152,16 @@ fn generate_fields(fields: &FieldsList) -> Vec<TokenStream2> {
StaticLifetimesReplace.visit_type_mut(&mut ty);

let type_name = clean_type_string(&quote!(#ty).to_string());
let docs = utils::get_doc_literals(&f.attrs);
let method_call = if utils::is_compact(f) {
quote!(.compact_of::<#ty>)
} else {
quote!(.field_of::<#ty>)
};
if let Some(ident) = ident {
quote!(#method_call(stringify!(#ident), #type_name))
quote!(#method_call(stringify!(#ident), #type_name, &[ #( #docs ),* ]))
} else {
quote!(#method_call(#type_name))
quote!(#method_call(#type_name, &[ #( #docs ),* ]))
}
})
.collect()
Expand Down Expand Up @@ -214,8 +218,9 @@ fn generate_c_like_enum_def(variants: &VariantList, scale_info: &Ident) -> Token
.map(|(i, v)| {
let name = &v.ident;
let discriminant = utils::variant_index(v, i);
let docs = utils::get_doc_literals(&v.attrs);
quote! {
.variant(stringify!(#name), #discriminant as u64)
.variant(stringify!(#name), #discriminant as u64, &[ #( #docs ),* ])
}
});
quote! {
Expand Down Expand Up @@ -246,14 +251,17 @@ fn generate_variant_type(data_enum: &DataEnum, scale_info: &Ident) -> TokenStrea
.map(|v| {
let ident = &v.ident;
let v_name = quote! {stringify!(#ident) };
let docs = utils::get_doc_literals(&v.attrs);

match v.fields {
Fields::Named(ref fs) => {
let fields = generate_fields(&fs.named);
quote! {
.variant(
#v_name,
:: #scale_info::build::Fields::named()
#( #fields)*
#( #fields )*,
&[ #( #docs ),* ]
)
}
}
Expand All @@ -263,21 +271,22 @@ fn generate_variant_type(data_enum: &DataEnum, scale_info: &Ident) -> TokenStrea
.variant(
#v_name,
:: #scale_info::build::Fields::unnamed()
#( #fields)*
#( #fields )*,
&[ #( #docs ),* ]
)
}
}
Fields::Unit => {
quote! {
.variant_unit(#v_name)
.variant_unit(#v_name, &[ #( #docs ),* ])
}
}
}
});
quote! {
variant(
:: #scale_info ::build::Variants::with_fields()
#( #variants)*
#( #variants )*
)
}
}
20 changes: 20 additions & 0 deletions derive/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
//!
//! NOTE: The code here is copied verbatim from `parity-scale-codec-derive`.

use alloc::vec::Vec;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
Expand All @@ -28,6 +29,23 @@ use syn::{
Variant,
};

/// Return all doc attributes literals found.
pub fn get_doc_literals(attrs: &Vec<syn::Attribute>) -> Vec<syn::Lit> {
attrs.iter()
.filter_map(|attr| {
if let Ok(syn::Meta::NameValue(meta)) = attr.parse_meta() {
if meta.path.get_ident().map_or(false, |ident| ident == "doc") {
Some(meta.lit)
} else {
None
}
} else {
None
}
})
.collect()
}

/// Look for a `#[codec(index = $int)]` attribute on a variant. If no attribute
/// is found, fall back to the discriminant or just the variant index.
pub fn variant_index(v: &Variant, i: usize) -> TokenStream {
Expand Down Expand Up @@ -107,3 +125,5 @@ where
})
.next()
}


59 changes: 34 additions & 25 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@
//! .path(Path::new("Foo", module_path!()))
//! .type_params(vec![MetaType::new::<T>()])
//! .composite(Fields::named()
//! .field_of::<T>("bar", "T")
//! .field_of::<u64>("data", "u64")
//! .field_of::<T>("bar", "T", &[])
//! .field_of::<u64>("data", "u64", &[])
//! )
//! }
//! }
Expand All @@ -57,8 +57,8 @@
//! Type::builder()
//! .path(Path::new("Foo", module_path!()))
//! .composite(Fields::unnamed()
//! .field_of::<u32>("u32")
//! .field_of::<bool>("bool")
//! .field_of::<u32>("u32", &[])
//! .field_of::<bool>("bool", &[])
//! )
//! }
//! }
Expand All @@ -84,9 +84,9 @@
//! .type_params(vec![MetaType::new::<T>()])
//! .variant(
//! Variants::with_fields()
//! .variant("A", Fields::unnamed().field_of::<T>("T"))
//! .variant("B", Fields::named().field_of::<u32>("f", "u32"))
//! .variant("C", Fields::unit())
//! .variant("A", Fields::unnamed().field_of::<T>("T", &[]), &[])
//! .variant("B", Fields::named().field_of::<u32>("f", "u32", &[]), &[])
//! .variant("C", Fields::unit(), &[]),
//! )
//! }
//! }
Expand All @@ -108,9 +108,9 @@
//! .path(Path::new("Foo", module_path!()))
//! .variant(
//! Variants::fieldless()
//! .variant("A", 1)
//! .variant("B", 2)
//! .variant("C", 33)
//! .variant("A", 1, &[])
//! .variant("B", 2, &[])
//! .variant("C", 33, &[])
//! )
//! }
//! }
Expand Down Expand Up @@ -146,6 +146,7 @@ pub mod state {
pub struct TypeBuilder<S = state::PathNotAssigned> {
path: Option<Path>,
type_params: Vec<MetaType>,
docs: Vec<&'static str>,
marker: PhantomData<fn() -> S>,
}

Expand All @@ -154,6 +155,7 @@ impl<S> Default for TypeBuilder<S> {
TypeBuilder {
path: Default::default(),
type_params: Default::default(),
docs: Default::default(),
marker: Default::default(),
}
}
Expand All @@ -165,6 +167,7 @@ impl TypeBuilder<state::PathNotAssigned> {
TypeBuilder {
path: Some(path),
type_params: self.type_params,
docs: self.docs,
marker: Default::default(),
}
}
Expand All @@ -176,7 +179,7 @@ impl TypeBuilder<state::PathAssigned> {
D: Into<TypeDef>,
{
let path = self.path.expect("Path not assigned");
Type::new(path, self.type_params, type_def)
Type::new(path, self.type_params, type_def, self.docs)
}

/// Construct a "variant" type i.e an `enum`
Expand All @@ -199,6 +202,12 @@ impl<S> TypeBuilder<S> {
self.type_params = type_params.into_iter().collect();
self
}

/// Set the type documentation
pub fn docs(mut self, docs: &[&'static str]) -> Self {
self.docs = docs.to_vec();
self
}
}

/// A fields builder has no fields (e.g. a unit struct)
Expand Down Expand Up @@ -252,43 +261,43 @@ impl<T> FieldsBuilder<T> {

impl FieldsBuilder<NamedFields> {
/// Add a named field with the type of the type parameter `T`
pub fn field_of<T>(mut self, name: &'static str, type_name: &'static str) -> Self
pub fn field_of<T>(mut self, name: &'static str, type_name: &'static str, docs: &[&'static str]) -> Self
where
T: TypeInfo + ?Sized + 'static,
{
self.fields.push(Field::named_of::<T>(name, type_name));
self.fields.push(Field::named_of::<T>(name, type_name, docs));
self
}

/// Add a named, [`Compact`] field of type `T`.
pub fn compact_of<T>(mut self, name: &'static str, type_name: &'static str) -> Self
pub fn compact_of<T>(mut self, name: &'static str, type_name: &'static str, docs: &[&'static str]) -> Self
where
T: scale::HasCompact,
<T as scale::HasCompact>::Type: TypeInfo + 'static,
{
self.fields
.push(Field::compact_of::<T>(Some(name), type_name));
.push(Field::compact_of::<T>(Some(name), type_name, docs));
self
}
}

impl FieldsBuilder<UnnamedFields> {
/// Add an unnamed field with the type of the type parameter `T`
pub fn field_of<T>(mut self, type_name: &'static str) -> Self
pub fn field_of<T>(mut self, type_name: &'static str, docs: &[&'static str]) -> Self
where
T: TypeInfo + ?Sized + 'static,
{
self.fields.push(Field::unnamed_of::<T>(type_name));
self.fields.push(Field::unnamed_of::<T>(type_name, docs));
self
}

/// Add an unnamed, [`Compact`] field of type `T`.
pub fn compact_of<T>(mut self, type_name: &'static str) -> Self
pub fn compact_of<T>(mut self, type_name: &'static str, docs: &[&'static str]) -> Self
where
T: scale::HasCompact,
<T as scale::HasCompact>::Type: TypeInfo + 'static,
{
self.fields.push(Field::compact_of::<T>(None, type_name));
self.fields.push(Field::compact_of::<T>(None, type_name, docs));
self
}
}
Expand Down Expand Up @@ -326,22 +335,22 @@ pub struct VariantsBuilder<T> {

impl VariantsBuilder<VariantFields> {
/// Add a variant with fields constructed by the supplied [`FieldsBuilder`](`crate::build::FieldsBuilder`)
pub fn variant<F>(mut self, name: &'static str, fields: FieldsBuilder<F>) -> Self {
self.variants.push(Variant::with_fields(name, fields));
pub fn variant<F>(mut self, name: &'static str, fields: FieldsBuilder<F>, docs: &[&'static str]) -> Self {
self.variants.push(Variant::with_fields(name, fields, docs.to_vec()));
self
}

/// Add a variant with no fields i.e. a unit variant
pub fn variant_unit(self, name: &'static str) -> Self {
self.variant::<NoFields>(name, Fields::unit())
pub fn variant_unit(self, name: &'static str, docs: &[&'static str]) -> Self {
self.variant::<NoFields>(name, Fields::unit(), docs)
}
}

impl VariantsBuilder<Fieldless> {
/// Add a fieldless variant, explicitly setting the discriminant
pub fn variant(mut self, name: &'static str, discriminant: u64) -> Self {
pub fn variant(mut self, name: &'static str, discriminant: u64, docs: &[&'static str]) -> Self {
self.variants
.push(Variant::with_discriminant(name, discriminant));
.push(Variant::with_discriminant(name, discriminant, docs));
self
}
}
Expand Down
14 changes: 7 additions & 7 deletions src/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ where
.type_params(tuple_meta_type![T])
.variant(
Variants::with_fields()
.variant_unit("None")
.variant("Some", Fields::unnamed().field_of::<T>("T")),
.variant_unit("None", &[])
.variant("Some", Fields::unnamed().field_of::<T>("T", &[]), &[]),
)
}
}
Expand All @@ -153,8 +153,8 @@ where
.type_params(tuple_meta_type!(T, E))
.variant(
Variants::with_fields()
.variant("Ok", Fields::unnamed().field_of::<T>("T"))
.variant("Err", Fields::unnamed().field_of::<E>("E")),
.variant("Ok", Fields::unnamed().field_of::<T>("T", &[]), &[])
.variant("Err", Fields::unnamed().field_of::<E>("E", &[]), &[]),
)
}
}
Expand All @@ -169,7 +169,7 @@ where
Type::builder()
.path(Path::prelude("Cow"))
.type_params(tuple_meta_type!(T))
.composite(Fields::unnamed().field_of::<T>("T"))
.composite(Fields::unnamed().field_of::<T>("T", &[]))
}
}

Expand All @@ -184,7 +184,7 @@ where
Type::builder()
.path(Path::prelude("BTreeMap"))
.type_params(tuple_meta_type![(K, V)])
.composite(Fields::unnamed().field_of::<[(K, V)]>("[(K, V)]"))
.composite(Fields::unnamed().field_of::<[(K, V)]>("[(K, V)]", &[]))
}
}

Expand All @@ -198,7 +198,7 @@ where
Type::builder()
.path(Path::prelude("BTreeSet"))
.type_params(tuple_meta_type![T])
.composite(Fields::unnamed().field_of::<[T]>("[T]"))
.composite(Fields::unnamed().field_of::<[T]>("[T]", &[]))
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,14 +240,17 @@ mod tests {
.field_of::<Box<RecursiveRefs>>(
"boxed",
"Box < RecursiveRefs >",
&[],
)
.field_of::<&'static RecursiveRefs<'static>>(
"reference",
"&RecursiveRefs",
&[],
)
.field_of::<&'static mut RecursiveRefs<'static>>(
"mutable_reference",
"&mut RecursiveRefs",
&[],
),
)
}
Expand Down
Loading