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

Support setting doc & attribute for each field separately #6

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## Unreleased
* add ability to specify attributes and docs on each field individually by [cyqsimon](https://github.com/cyqsimon)
* add an `append` mode to `doc` argument by [cyqsimon](https://github.com/cyqsimon)

## 0.3.0
* update to syn v2.0, bumping minimum rustc version to 1.56.0
* add feature list and attribute order note to documentation
Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ features = ["full", "extra-traits"]

[dev-dependencies]
paste = "1.0.12"
rstest = "0.12.0"

[dev-dependencies.serde]
version = "1.0.163"
Expand Down
71 changes: 46 additions & 25 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use syn::parse::{Error, Parse, ParseStream, Result};
use syn::token::{Comma, Eq, Pub};
use syn::{parse2, Ident, LitStr, Meta, Visibility};

mod kw {
pub mod kw {
// NOTE: when adding new keywords update ArgList::next_is_kw
syn::custom_keyword!(doc);
syn::custom_keyword!(merge_fn);
Expand All @@ -13,12 +13,16 @@ mod kw {
syn::custom_keyword!(field_attrs);
syn::custom_keyword!(from);

pub mod doc_sub {
syn::custom_keyword!(append);
}

pub mod attrs_sub {
syn::custom_keyword!(add);
}
}

#[cfg_attr(test, derive(PartialEq))]
#[derive(Debug, PartialEq)]
pub struct Args {
pub item: GenItem,
pub merge: Option<MergeFn>,
Expand All @@ -30,6 +34,7 @@ pub struct Args {
pub from: bool,
}

#[derive(Debug)]
enum Arg {
Merge(MergeFn),
Doc(Doc),
Expand All @@ -40,31 +45,35 @@ enum Arg {
From(bool),
}

#[cfg_attr(test, derive(PartialEq))]
#[derive(Debug, PartialEq)]
pub struct GenItem {
pub name: Ident,
pub visibility: Option<Visibility>,
}

#[cfg_attr(test, derive(Clone, Debug, PartialEq))]
#[derive(Clone, Debug, PartialEq)]
pub struct MergeFn {
pub visibility: Visibility,
pub name: MergeFnName,
}

#[cfg_attr(test, derive(Clone, Debug, PartialEq))]
#[derive(Clone, Debug, PartialEq)]
pub enum MergeFnName {
Default,
Custom(Ident),
}

#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Debug, PartialEq)]
pub enum Doc {
Same,
Custom(String),
/// Keep the same documentation.
Keep,
/// Replace with custom documentation.
Replace(String),
/// Append additional documentation.
Append(String),
}

#[cfg_attr(test, derive(Debug, PartialEq))]
#[derive(Debug, PartialEq)]
pub enum Attrs {
/// Keep same attributes.
Keep,
Expand All @@ -78,6 +87,7 @@ pub enum Attrs {
pub struct AttrList(Vec<Meta>);

/// Parser for unordered args.
#[derive(Debug)]
struct ArgList {
item: GenItem,
merge: Option<Span>,
Expand Down Expand Up @@ -327,11 +337,18 @@ impl Parse for Doc {
if input.peek(Eq) {
input.parse::<Eq>()?;

let doc_text: LitStr = input.parse()?;
if input.peek(kw::doc_sub::append) {
input.parse::<kw::doc_sub::append>()?;

Ok(Doc::Custom(doc_text.value()))
let group: Group = input.parse()?;
let doc_text: LitStr = parse2(group.stream())?;
Ok(Doc::Append(doc_text.value()))
} else {
let doc_text: LitStr = input.parse()?;
Ok(Doc::Replace(doc_text.value()))
}
} else {
Ok(Doc::Same)
Ok(Doc::Keep)
}
}
}
Expand Down Expand Up @@ -459,7 +476,7 @@ mod tests {
#[test]
#[should_panic(expected = $expected)]
fn [<duplicate_ $attr _panics>]() {
parse_args(quote! {
parse_struct_args(quote! {
Opt,
$attr,
$dup
Expand All @@ -483,7 +500,7 @@ mod tests {
#[test]
#[should_panic(expected = "first argument must be opt struct name")]
fn [<$attr _first_panics>]() {
parse_args(quote! {
parse_struct_args(quote! {
$attr,
Opt
});
Expand All @@ -503,7 +520,7 @@ mod tests {
#[test]
#[should_panic(expected = "expected opt struct name")]
fn empty_args_panics() {
parse_args(TokenStream::new());
parse_struct_args(TokenStream::new());
}

#[test]
Expand All @@ -524,15 +541,15 @@ mod tests {
];

for case in cases {
let args = parse_args(case);
let args = parse_struct_args(case);

assert_eq!(args.item.name, "OptionalFields");
}
}

#[test]
fn parse_no_optional_args() {
let args = parse_args(quote! {
let args = parse_struct_args(quote! {
Opt
});

Expand Down Expand Up @@ -597,7 +614,7 @@ mod tests {
];

for (args_tokens, fn_name, vis) in cases {
let args = parse_args(args_tokens);
let args = parse_struct_args(args_tokens);

assert_eq!(args.merge.clone().unwrap().name, fn_name);
assert_eq!(args.merge.unwrap().visibility, vis);
Expand All @@ -606,7 +623,7 @@ mod tests {

#[test]
fn parse_rewrap() {
let args = parse_args(quote! {
let args = parse_struct_args(quote! {
Opt,
rewrap
});
Expand All @@ -617,10 +634,14 @@ mod tests {
#[test]
fn parse_doc() {
let cases = vec![
(quote! {Opt, doc}, Doc::Same),
(quote! {Opt, doc}, Doc::Keep),
(
quote! {Opt, doc = "custom docs"},
Doc::Custom("custom docs".to_string()),
Doc::Replace("custom docs".to_string()),
),
(
quote! {Opt, doc = append("append docs")},
Doc::Append("append docs".to_string()),
),
];

Expand Down Expand Up @@ -679,15 +700,15 @@ mod tests {
];

for (args_tokens, attrs) in cases {
let args = parse_args(args_tokens);
let args = parse_struct_args(args_tokens);

assert_eq!(args.attrs, Some(attrs));
}
}

#[test]
fn parse_field_doc() {
let args = parse_args(quote! {
let args = parse_struct_args(quote! {
Opt,
field_doc
});
Expand Down Expand Up @@ -720,15 +741,15 @@ mod tests {
];

for (args_tokens, attrs) in cases {
let args = parse_args(args_tokens);
let args = parse_struct_args(args_tokens);

assert_eq!(args.field_attrs, Some(attrs));
}
}

#[test]
fn parse_from() {
let args = parse_args(quote! {
let args = parse_struct_args(quote! {
Opt,
from
});
Expand Down
75 changes: 13 additions & 62 deletions src/attrs/generator.rs
Original file line number Diff line number Diff line change
@@ -1,80 +1,25 @@
use quote::quote;
use syn::{parse::Parser, Attribute, Meta};

use crate::args::Attrs;
use crate::error;

const DOC: &str = "doc";
const OPT_ATTR: &str = "optfield";
const OPTFIELD_ATTR_NAME: &str = "optfield";

pub trait AttrGenerator {
fn no_docs(&self) -> bool;

fn error_action_text(&self) -> String;

fn original_attrs(&self) -> &[Attribute];

fn attrs_arg(&self) -> &Option<Attrs>;

fn custom_docs(&self) -> Option<Meta> {
None
}

fn keep_original_docs(&self) -> bool {
!self.no_docs()
}

fn compute_capacity(&self) -> usize {
use Attrs::*;
fn new_non_doc_attrs(&self) -> Vec<Meta>;

let orig_len = self.original_attrs().len();

match self.attrs_arg() {
Some(Replace(v)) | Some(Add(v)) => orig_len + v.len(),
_ => orig_len,
}
}
fn new_doc_attrs(&self) -> Vec<Meta>;

fn generate(&self) -> Vec<Attribute> {
use Attrs::*;

let attrs_arg = self.attrs_arg();

// if no attrs and no docs should be set, remove all attrs
if self.no_docs() && attrs_arg.is_none() {
return Vec::new();
}

let mut new_attrs = Vec::with_capacity(self.compute_capacity());

if let Some(d) = self.custom_docs() {
new_attrs.push(d);
}

for attr in self.original_attrs() {
let mut add_attr = self.keep_original_docs() && is_doc_attr(attr);

if let Some(Keep) | Some(Add(_)) = attrs_arg {
if !is_doc_attr(attr) {
add_attr = true;
}
}

if attr.path().is_ident(OPT_ATTR) {
add_attr = false
}

if add_attr {
new_attrs.push(attr.meta.clone());
}
}

if let Some(Replace(v)) | Some(Add(v)) = attrs_arg {
new_attrs.extend(v.clone());
}
let attrs_except_docs = self.new_non_doc_attrs();
let docs = self.new_doc_attrs();

let attrs_tokens = quote! {
#(#[#new_attrs])*
#(#[#attrs_except_docs])*
#(#[#docs])*
};

Attribute::parse_outer
Expand All @@ -83,6 +28,12 @@ pub trait AttrGenerator {
}
}

/// Useful during attribute generation: it can prevent some unwanted recursive
/// behaviour.
pub fn is_optfield_attr(attr: &Attribute) -> bool {
attr.path().is_ident(OPTFIELD_ATTR_NAME)
}

pub fn is_doc_attr(attr: &Attribute) -> bool {
attr.path().is_ident(DOC)
}
Loading