Skip to content

Commit

Permalink
style(clap_macros): rustfmt run
Browse files Browse the repository at this point in the history
  • Loading branch information
kbknapp authored and Nemo157 committed Jan 31, 2017
1 parent 59bcbe5 commit a41c8fd
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 77 deletions.
64 changes: 36 additions & 28 deletions clap-macros/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,47 +8,50 @@ pub struct Attribute {

impl Attribute {
pub fn new(key: String) -> Attribute {
Attribute { key: key, values: vec![] }
Attribute {
key: key,
values: vec![],
}
}

pub fn push(&mut self, value: syn::Lit) {
self.values.push(value)
}
pub fn push(&mut self, value: syn::Lit) { self.values.push(value) }

pub fn values(&self) -> Vec<String> {
self.values.iter().map(|s| match *s {
syn::Lit::Str(ref s, _) => s.clone(),
_ => panic!("clap-macros: multi-valued attributes must be strings"),
}).collect()
self.values
.iter()
.map(|s| match *s {
syn::Lit::Str(ref s, _) => s.clone(),
_ => panic!("clap-macros: multi-valued attributes must be strings"),
})
.collect()
}

fn only_value(&self) -> &syn::Lit {
if self.values.len() == 1 {
&self.values[0]
} else {
panic!("clap-macros: expected a single value for attribute '{}' but had multiple", self.key);
panic!("clap-macros: expected a single value for attribute '{}' but had multiple",
self.key);
}
}
}

impl<'a> Into<syn::Lit> for &'a Attribute {
fn into(self) -> syn::Lit {
self.only_value().clone()
}
fn into(self) -> syn::Lit { self.only_value().clone() }
}

impl<'a> Into<&'a syn::Lit> for &'a Attribute {
fn into(self) -> &'a syn::Lit {
self.only_value()
}
fn into(self) -> &'a syn::Lit { self.only_value() }
}

impl<'a> Into<&'a str> for &'a Attribute {
fn into(self) -> &'a str {
if let &syn::Lit::Str(ref value, _) = self.only_value() {
value
} else {
panic!("Expected string value for attribute {} but got a {:?}", self.key, self.only_value());
panic!("Expected string value for attribute {} but got a {:?}",
self.key,
self.only_value());
}
}
}
Expand All @@ -60,7 +63,9 @@ impl<'a> Into<&'a [u8]> for &'a Attribute {
} else if let &syn::Lit::Str(ref value, _) = self.only_value() {
value.as_bytes()
} else {
panic!("Expected bytestring value for attribute {} but got a {:?}", self.key, self.only_value());
panic!("Expected bytestring value for attribute {} but got a {:?}",
self.key,
self.only_value());
}
}
}
Expand All @@ -72,7 +77,9 @@ impl<'a> Into<u8> for &'a Attribute {
} else if let &syn::Lit::Str(ref value, _) = self.only_value() {
value.parse().unwrap()
} else {
panic!("Expected byte value for attribute {} but got a {:?}", self.key, self.only_value());
panic!("Expected byte value for attribute {} but got a {:?}",
self.key,
self.only_value());
}
}
}
Expand All @@ -85,7 +92,9 @@ impl<'a> Into<char> for &'a Attribute {
assert!(value.len() == 1);
value.chars().next().unwrap()
} else {
panic!("Expected char value for attribute {} but got a {:?}", self.key, self.only_value());
panic!("Expected char value for attribute {} but got a {:?}",
self.key,
self.only_value());
}
}
}
Expand All @@ -97,7 +106,9 @@ impl<'a> Into<u64> for &'a Attribute {
} else if let &syn::Lit::Str(ref value, _) = self.only_value() {
value.parse().unwrap()
} else {
panic!("Expected int value for attribute {} but got a {:?}", self.key, self.only_value());
panic!("Expected int value for attribute {} but got a {:?}",
self.key,
self.only_value());
}
}
}
Expand All @@ -109,20 +120,17 @@ impl<'a> Into<bool> for &'a Attribute {
} else if let &syn::Lit::Str(ref value, _) = self.only_value() {
value.parse().unwrap()
} else {
panic!("Expected bool value for attribute {} but got a {:?}", self.key, self.only_value());
panic!("Expected bool value for attribute {} but got a {:?}",
self.key,
self.only_value());
}
}
}

impl<'a> quote::ToTokens for &'a mut Attribute {
fn to_tokens(&self, tokens: &mut quote::Tokens) {
self.only_value().to_tokens(tokens)
}
fn to_tokens(&self, tokens: &mut quote::Tokens) { self.only_value().to_tokens(tokens) }
}

impl quote::ToTokens for Attribute {
fn to_tokens(&self, tokens: &mut quote::Tokens) {
self.only_value().to_tokens(tokens)
}
fn to_tokens(&self, tokens: &mut quote::Tokens) { self.only_value().to_tokens(tokens) }
}

22 changes: 11 additions & 11 deletions clap-macros/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ impl Attributes {
pub fn new() -> Self { Default::default() }

pub fn from_attrs(attrs: &[syn::Attribute]) -> Self {
use syn::NestedMetaItem::*;
use syn::MetaItem::*;
use syn::NestedMetaItem as N;
use syn::MetaItem as M;
let mut claps = BTreeMap::new();
for attr in attrs {
if let syn::MetaItem::List(ref ident, ref values) = attr.value {
Expand All @@ -41,25 +41,25 @@ impl Attributes {
for value in values {
match *value {
// #[foo = "bar"]
MetaItem(NameValue(ref name, ref value)) => {
N::MetaItem(M::NameValue(ref name, ref value)) => {
let &mut (_, ref mut attr) = claps.entry(name.to_string())
.or_insert((RefCell::new(0), Attribute::new(name.to_string())));
attr.push(value.clone());
}
// #[foo]
MetaItem(Word(ref name)) => {
N::MetaItem(M::Word(ref name)) => {
let &mut (_, ref mut attr) = claps.entry(name.to_string())
.or_insert((RefCell::new(0), Attribute::new(name.to_string())));
attr.push(syn::Lit::Bool(true));
}
// #[derive(..)]
MetaItem(List(ref ident, ref values)) => {
N::MetaItem(M::List(ref ident, ref values)) => {
let &mut (_, ref mut attr) = claps.entry(ident.as_ref().to_string())
.or_insert((RefCell::new(0),
Attribute::new(ident.as_ref().to_string())));
for value in values {
match *value {
MetaItem(Word(ref name)) => attr.push(name.as_ref().into()),
N::MetaItem(M::Word(ref name)) => attr.push(name.as_ref().into()),
_ => {
panic!("Invalid clap attribute {} literal value not supported",
quote!(#attr).to_string().replace(" ", ""))
Expand Down Expand Up @@ -157,21 +157,21 @@ impl FieldAttributes {

/// Extracts all clap attributes of the form #[clap(i = V)]
pub fn extract_attrs(ast: &syn::MacroInput) -> (Attributes, FieldAttributes) {
use syn::Body::*;
use syn::VariantData::*;
use syn::Body as B;
use syn::VariantData as V;
let empty = Attributes::new();
let root_attrs = Attributes::from_attrs(&ast.attrs);
let field_attrs = match ast.body {
Struct(Struct(ref fields)) => {
B::Struct(V::Struct(ref fields)) => {
fields.iter()
.map(|field| {
(field.ident.clone().unwrap(),
(RefCell::new(0), Attributes::from_attrs(&field.attrs)))
})
.collect()
}
Struct(Tuple(_)) => panic!("TODO: tuple struct unsupported msg"),
Struct(Unit) | Enum(_) => HashMap::new(),
B::Struct(V::Tuple(_)) => panic!("TODO: tuple struct unsupported msg"),
B::Struct(V::Unit) | B::Enum(_) => HashMap::new(),
};
(root_attrs,
FieldAttributes {
Expand Down
34 changes: 18 additions & 16 deletions clap-macros/src/define_app.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use syn;
use quote;

use attrs::{ Attributes, FieldAttributes };
use field::{ Arg, Field, Subcommand };
use attrs::{Attributes, FieldAttributes};
use field::{Arg, Field, Subcommand};

fn expand_arg(arg: &Arg) -> quote::Tokens {
let name = arg.name;
Expand Down Expand Up @@ -47,7 +47,9 @@ fn expand_arg(arg: &Arg) -> quote::Tokens {
}
}

fn expand_args<'a, 'b: 'a, I>(args: I) -> quote::Tokens where I: Iterator<Item=&'a Arg<'b>> {
fn expand_args<'a, 'b: 'a, I>(args: I) -> quote::Tokens
where I: Iterator<Item = &'a Arg<'b>>
{
let args = args.map(expand_arg);
quote! { .args(&[#(#args),*]) }
}
Expand All @@ -67,8 +69,9 @@ fn expand_subcommand(subcommand: &Subcommand) -> quote::Tokens {
}

fn expand_app(ast: &syn::MacroInput, attrs: &Attributes, fields: &[Field]) -> quote::Tokens {
let name = attrs.get("name").map(|a| a.into())
.unwrap_or_else(|| syn::Lit::from(ast.ident.as_ref().to_lowercase()));
let name = attrs.get("name")
.map(|a| a.into())
.unwrap_or_else(|| syn::Lit::from(ast.ident.as_ref().to_lowercase()));

let version = if attrs.get_bool("crate_version") {
Some(quote! { .version(crate_version!()) })
Expand Down Expand Up @@ -109,22 +112,21 @@ fn expand_app(ast: &syn::MacroInput, attrs: &Attributes, fields: &[Field]) -> qu
}
}

pub fn expand(ast: &syn::MacroInput, attrs: &Attributes, field_attrs: &FieldAttributes) -> quote::Tokens {
pub fn expand(ast: &syn::MacroInput,
attrs: &Attributes,
field_attrs: &FieldAttributes)
-> quote::Tokens {
use syn::Body as B;
use syn::VariantData as V;
let fields = match ast.body {
syn::Body::Struct(syn::VariantData::Unit) => {
Vec::new()
}
syn::Body::Struct(syn::VariantData::Struct(ref fields)) => {
B::Struct(V::Unit) => Vec::new(),
B::Struct(V::Struct(ref fields)) => {
fields.iter()
.map(|field| Field::from((field, field_attrs.get(field))))
.collect()
}
syn::Body::Struct(syn::VariantData::Tuple(_)) => {
panic!("#[derive(DefineApp)] is not supported on tuple structs")
}
syn::Body::Enum(_) => {
panic!("#[derive(DefineApp)] is not supported on enums")
}
B::Struct(V::Tuple(_)) => panic!("#[derive(DefineApp)] is not supported on tuple structs"),
B::Enum(_) => panic!("#[derive(DefineApp)] is not supported on enums"),
};

let ident = &ast.ident;
Expand Down
4 changes: 1 addition & 3 deletions clap-macros/src/define_sub_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ pub fn expand(ast: &syn::MacroInput) -> quote::Tokens {
})
.collect()
}
syn::Body::Struct(_) => {
panic!("#[derive(DefineSubCommands)] is not supported on structs")
}
syn::Body::Struct(_) => panic!("#[derive(DefineSubCommands)] is not supported on structs"),
};

let subcommands = expand_subcommands(&cmds);
Expand Down
14 changes: 9 additions & 5 deletions clap-macros/src/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,16 +63,18 @@ impl<'a> From<(&'a syn::Field, &'a Attributes)> for Field<'a> {

impl<'a> From<(&'a syn::Field, &'a Attributes)> for Arg<'a> {
fn from((field, attrs): (&'a syn::Field, &'a Attributes)) -> Arg<'a> {
let name = attrs.get("name").map(|a| a.into())
.unwrap_or_else(|| field.ident.as_ref().unwrap().as_ref());
let name = attrs.get("name")
.map(|a| a.into())
.unwrap_or_else(|| field.ident.as_ref().unwrap().as_ref());

let index = attrs.get("index").map(|a| a.into());

// Unlike clap we default to a flag option unless there's a attribute given
// telling us to not do so
let is_flag = !index.is_some() && !attrs.get_bool("arg");

let long = attrs.get("long").map(|a| a.into())
let long = attrs.get("long")
.map(|a| a.into())
.or_else(|| if is_flag { Some(name) } else { None });

let short = attrs.get("short").map(|s| Into::<char>::into(s).to_string());
Expand All @@ -87,7 +89,8 @@ impl<'a> From<(&'a syn::Field, &'a Attributes)> for Arg<'a> {
is_optional = path.segments[0].ident == "Option";
is_vec = path.segments[0].ident == "Vec";
if is_optional || is_vec {
if let syn::PathParameters::AngleBracketed(ref params) = path.segments[0].parameters {
if let syn::PathParameters::AngleBracketed(ref params) =
path.segments[0].parameters {
ty = &params.types[0];
} else {
panic!();
Expand Down Expand Up @@ -135,7 +138,8 @@ impl<'a> From<&'a syn::Field> for Subcommand<'a> {
syn::Ty::Path(None, ref path) => {
is_optional = path.segments[0].ident == "Option";
if is_optional {
if let syn::PathParameters::AngleBracketed(ref params) = path.segments[0].parameters {
if let syn::PathParameters::AngleBracketed(ref params) =
path.segments[0].parameters {
ty = &params.types[0];
} else {
panic!();
Expand Down
14 changes: 4 additions & 10 deletions clap-macros/src/from_arg_matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use syn;
use quote;

use attrs::FieldAttributes;
use field::{ Arg, Field, Subcommand };
use field::{Arg, Field, Subcommand};

fn expand_parse_arg(arg: &Arg, matches: &syn::Ident) -> quote::Tokens {
let ident = arg.ident;
Expand Down Expand Up @@ -83,20 +83,14 @@ fn expand_parse(ast: &syn::MacroInput, fields: &[Field], matches: &syn::Ident) -

pub fn expand(ast: &syn::MacroInput, field_attrs: &FieldAttributes) -> quote::Tokens {
let fields = match ast.body {
syn::Body::Struct(syn::VariantData::Unit) => {
Vec::new()
}
syn::Body::Struct(syn::VariantData::Unit) => Vec::new(),
syn::Body::Struct(syn::VariantData::Struct(ref fields)) => {
fields.iter()
.map(|field| Field::from((field, field_attrs.get(field))))
.collect()
}
syn::Body::Struct(syn::VariantData::Tuple(_)) => {
panic!("#[derive(FromArgMatches)] is not supported on tuple structs")
}
syn::Body::Enum(_) => {
panic!("#[derive(FromArgMatches)] is not supported on enums")
}
syn::Body::Struct(syn::VariantData::Tuple(_)) => panic!("#[derive(FromArgMatches)] is not supported on tuple structs"),
syn::Body::Enum(_) => panic!("#[derive(FromArgMatches)] is not supported on enums"),
};

let ident = &ast.ident;
Expand Down
10 changes: 6 additions & 4 deletions clap-macros/src/sub_command_from_arg_matches.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use syn;
use quote;

fn expand_parse(me: &syn::Ident, cmds: &[(&syn::Ident, &syn::Ty)], name: &syn::Ident, matches: &syn::Ident) -> quote::Tokens {
fn expand_parse(me: &syn::Ident,
cmds: &[(&syn::Ident, &syn::Ty)],
name: &syn::Ident,
matches: &syn::Ident)
-> quote::Tokens {
let variants = cmds.iter().map(|&(ident, ty)| {
let name = ident.as_ref().to_lowercase();
quote! { #name => #me::#ident(<#ty as ::std::convert::From<&::clap::ArgMatches>>::from(#matches)) }
Expand Down Expand Up @@ -39,9 +43,7 @@ pub fn expand(ast: &syn::MacroInput) -> quote::Tokens {
})
.collect()
}
syn::Body::Struct(_) => {
panic!("#[derive(SubCommandFromArgMatches)] is not supported on structs")
}
syn::Body::Struct(_) => panic!("#[derive(SubCommandFromArgMatches)] is not supported on structs"),
};

let from = expand_parse(ident, &cmds, &name, &matches);
Expand Down

0 comments on commit a41c8fd

Please sign in to comment.