310 lines
10 KiB
Rust
Raw Normal View History

2017-04-13 17:34:42 -07:00
// Copyright 2017 Serde Developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::collections::HashSet;
2017-02-20 13:18:38 -08:00
use syn::{self, visit};
2018-01-08 21:49:09 -08:00
use syn::punctuated::Punctuated;
2018-01-08 21:49:09 -08:00
use internals::ast::{Data, Container};
use internals::attr;
2018-03-31 23:46:25 +02:00
use proc_macro2::Span;
2017-02-20 13:18:38 -08:00
// Remove the default from every type parameter because in the generated impls
// they look like associated types: "error: associated type bindings are not
// allowed here".
2016-09-10 21:53:14 -07:00
pub fn without_defaults(generics: &syn::Generics) -> syn::Generics {
syn::Generics {
2018-01-08 21:49:09 -08:00
params: generics
.params
2017-02-12 21:59:04 -08:00
.iter()
2018-01-08 21:49:09 -08:00
.map(|param| match *param {
syn::GenericParam::Type(ref param) => {
syn::GenericParam::Type(syn::TypeParam {
eq_token: None,
default: None,
..param.clone()
})
}
_ => param.clone(),
2017-12-23 20:13:08 -08:00
})
2017-02-12 21:59:04 -08:00
.collect(),
..generics.clone()
}
}
2017-04-13 12:28:23 -07:00
pub fn with_where_predicates(
generics: &syn::Generics,
predicates: &[syn::WherePredicate],
) -> syn::Generics {
2017-02-20 13:18:38 -08:00
let mut generics = generics.clone();
2018-04-01 16:58:14 +02:00
generics.make_where_clause()
2017-04-13 12:28:23 -07:00
.predicates
2018-01-08 21:49:09 -08:00
.extend(predicates.into_iter().cloned());
2017-02-20 13:18:38 -08:00
generics
}
pub fn with_where_predicates_from_fields<F, W>(
cont: &Container,
2017-04-13 12:28:23 -07:00
generics: &syn::Generics,
trait_bound: &syn::Path,
2017-04-13 12:28:23 -07:00
from_field: F,
2018-04-09 23:43:49 -04:00
gen_bound_where: W,
2017-04-13 12:28:23 -07:00
) -> syn::Generics
where
F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>,
2018-04-09 23:43:49 -04:00
W: for<'a> Fn(&attr::Field) -> bool,
{
2018-01-08 21:49:09 -08:00
let predicates = cont.data
2017-02-20 13:18:38 -08:00
.all_fields()
.flat_map(|field| {
2018-04-10 10:53:37 -04:00
let field_ty = field.ty;
let field_bound: Option<syn::WherePredicate> = match (field_ty, gen_bound_where(&field.attrs)) {
(&syn::Type::Path(ref ty_path), true) => match (ty_path.path.segments.first(), generics.params.first()) {
(Some(syn::punctuated::Pair::Punctuated(ref t, _)), Some(syn::punctuated::Pair::End(&syn::GenericParam::Type(ref generic_ty))))
if generic_ty.ident == t.ident =>
{
let predicate: syn::WherePredicate = parse_quote!(#field_ty: #trait_bound);
Some(predicate)
},
_ => None
2018-04-09 23:43:49 -04:00
},
2018-04-10 10:53:37 -04:00
(_, _) => None
};
field_bound.into_iter().chain(from_field(&field.attrs).into_iter().flat_map(|predicates| predicates.to_vec()))
});
2017-02-20 13:18:38 -08:00
let mut generics = generics.clone();
2018-04-01 16:58:14 +02:00
generics.make_where_clause()
2018-01-08 21:49:09 -08:00
.predicates
.extend(predicates);
2017-02-20 13:18:38 -08:00
generics
}
// Puts the given bound on any generic type parameters that are used in fields
// for which filter returns true.
//
// For example, the following struct needs the bound `A: Serialize, B: Serialize`.
//
// struct S<'b, A, B: 'b, C> {
// a: A,
// b: Option<&'b B>
// #[serde(skip_serializing)]
// c: C,
// }
2017-04-13 12:28:23 -07:00
pub fn with_bound<F>(
cont: &Container,
2017-04-13 12:28:23 -07:00
generics: &syn::Generics,
filter: F,
bound: &syn::Path,
) -> syn::Generics
where
F: Fn(&attr::Field, Option<&attr::Variant>) -> bool,
{
struct FindTyParams {
// Set of all generic type parameters on the current struct (A, B, C in
// the example). Initialized up front.
2016-09-10 21:53:14 -07:00
all_ty_params: HashSet<syn::Ident>,
// Set of generic type parameters used in fields for which filter
// returns true (A and B in the example). Filled in as the visitor sees
// them.
2016-09-10 21:53:14 -07:00
relevant_ty_params: HashSet<syn::Ident>,
}
2018-01-08 21:49:09 -08:00
impl<'ast> visit::Visit<'ast> for FindTyParams {
2016-09-10 21:53:14 -07:00
fn visit_path(&mut self, path: &syn::Path) {
if let Some(seg) = path.segments.last() {
2018-01-08 21:49:09 -08:00
if seg.into_value().ident == "PhantomData" {
// Hardcoded exception, because PhantomData<T> implements
// Serialize and Deserialize whether or not T implements it.
return;
}
}
2018-01-08 21:49:09 -08:00
if path.leading_colon.is_none() && path.segments.len() == 1 {
2018-01-09 19:34:35 -08:00
let id = path.segments[0].ident;
if self.all_ty_params.contains(&id) {
self.relevant_ty_params.insert(id);
}
}
2018-01-08 21:49:09 -08:00
visit::visit_path(self, path);
}
// Type parameter should not be considered used by a macro path.
//
// struct TypeMacro<T> {
// mac: T!(),
// marker: PhantomData<T>,
// }
2018-01-08 21:49:09 -08:00
fn visit_macro(&mut self, _mac: &syn::Macro) {}
}
2017-04-13 12:28:23 -07:00
let all_ty_params: HashSet<_> = generics
2018-01-08 21:49:09 -08:00
.params
2017-02-12 21:59:04 -08:00
.iter()
2018-01-08 21:49:09 -08:00
.filter_map(|param| match *param {
syn::GenericParam::Type(ref param) => Some(param.ident),
_ => None,
})
.collect();
let mut visitor = FindTyParams {
all_ty_params: all_ty_params,
relevant_ty_params: HashSet::new(),
};
2018-01-08 21:49:09 -08:00
match cont.data {
Data::Enum(ref variants) => for variant in variants.iter() {
2017-12-23 20:13:08 -08:00
let relevant_fields = variant
.fields
.iter()
.filter(|field| filter(&field.attrs, Some(&variant.attrs)));
for field in relevant_fields {
2018-01-08 21:49:09 -08:00
visit::visit_type(&mut visitor, field.ty);
}
2017-12-23 20:13:08 -08:00
},
2018-01-08 21:49:09 -08:00
Data::Struct(_, ref fields) => {
for field in fields.iter().filter(|field| filter(&field.attrs, None)) {
2018-01-08 21:49:09 -08:00
visit::visit_type(&mut visitor, field.ty);
}
}
}
2017-04-13 12:28:23 -07:00
let new_predicates = generics
2018-01-08 21:49:09 -08:00
.params
2017-02-20 13:18:38 -08:00
.iter()
2018-01-08 21:49:09 -08:00
.filter_map(|param| match *param {
syn::GenericParam::Type(ref param) => Some(param.ident),
_ => None,
})
2017-02-20 13:18:38 -08:00
.filter(|id| visitor.relevant_ty_params.contains(id))
2017-12-23 20:13:08 -08:00
.map(|id| {
2018-01-08 21:49:09 -08:00
syn::WherePredicate::Type(syn::PredicateType {
lifetimes: None,
2017-12-23 20:13:08 -08:00
// the type parameter that is being bounded e.g. T
2018-01-08 21:49:09 -08:00
bounded_ty: syn::Type::Path(syn::TypePath {
qself: None,
path: id.into(),
}),
colon_token: Default::default(),
2017-12-23 20:13:08 -08:00
// the bound e.g. Serialize
bounds: vec![
2018-01-08 21:49:09 -08:00
syn::TypeParamBound::Trait(syn::TraitBound {
2018-03-31 23:45:30 +02:00
paren_token: None,
2018-01-08 21:49:09 -08:00
modifier: syn::TraitBoundModifier::None,
lifetimes: None,
path: bound.clone(),
}),
].into_iter().collect(),
2017-12-23 20:13:08 -08:00
})
});
2017-02-20 13:18:38 -08:00
let mut generics = generics.clone();
2018-04-01 16:58:14 +02:00
generics.make_where_clause()
2018-01-08 21:49:09 -08:00
.predicates
.extend(new_predicates);
2017-02-20 13:18:38 -08:00
generics
}
2017-02-20 13:18:38 -08:00
2017-04-18 14:23:21 -07:00
pub fn with_self_bound(
cont: &Container,
generics: &syn::Generics,
bound: &syn::Path,
) -> syn::Generics {
let mut generics = generics.clone();
2018-04-01 16:58:14 +02:00
generics.make_where_clause()
2017-04-13 12:28:23 -07:00
.predicates
2018-01-08 21:49:09 -08:00
.push(syn::WherePredicate::Type(syn::PredicateType {
lifetimes: None,
// the type that is being bounded e.g. MyStruct<'a, T>
bounded_ty: type_of_item(cont),
colon_token: Default::default(),
// the bound e.g. Default
bounds: vec![
syn::TypeParamBound::Trait(syn::TraitBound {
2018-03-31 23:45:30 +02:00
paren_token: None,
2018-01-08 21:49:09 -08:00
modifier: syn::TraitBoundModifier::None,
lifetimes: None,
path: bound.clone(),
}),
].into_iter().collect(),
}));
generics
}
2017-04-13 12:28:23 -07:00
pub fn with_lifetime_bound(generics: &syn::Generics, lifetime: &str) -> syn::Generics {
2018-03-31 23:46:25 +02:00
let bound = syn::Lifetime::new(lifetime, Span::call_site());
2018-01-08 21:49:09 -08:00
let def = syn::LifetimeDef {
attrs: Vec::new(),
lifetime: bound,
colon_token: None,
bounds: Punctuated::new(),
};
2017-02-20 13:18:38 -08:00
2018-01-08 21:49:09 -08:00
let params = Some(syn::GenericParam::Lifetime(def))
.into_iter()
.chain(generics.params
.iter()
.cloned()
.map(|mut param| {
match param {
syn::GenericParam::Lifetime(ref mut param) => {
param.bounds.push(bound);
}
syn::GenericParam::Type(ref mut param) => {
param.bounds.push(syn::TypeParamBound::Lifetime(bound));
}
syn::GenericParam::Const(_) => {}
}
param
}))
.collect();
2017-02-20 13:18:38 -08:00
2018-01-08 21:49:09 -08:00
syn::Generics {
params: params,
..generics.clone()
2017-02-20 13:18:38 -08:00
}
}
2018-01-08 21:49:09 -08:00
fn type_of_item(cont: &Container) -> syn::Type {
syn::Type::Path(syn::TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
2017-04-13 12:28:23 -07:00
segments: vec![
syn::PathSegment {
2018-01-09 19:34:35 -08:00
ident: cont.ident,
2018-01-08 21:49:09 -08:00
arguments: syn::PathArguments::AngleBracketed(
syn::AngleBracketedGenericArguments {
colon2_token: None,
lt_token: Default::default(),
args: cont.generics
.params
.iter()
2018-01-08 21:49:09 -08:00
.map(|param| match *param {
syn::GenericParam::Type(ref param) => {
syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
qself: None,
path: param.ident.into(),
}))
}
syn::GenericParam::Lifetime(ref param) => {
syn::GenericArgument::Lifetime(param.lifetime)
}
syn::GenericParam::Const(_) => {
panic!("Serde does not support const generics yet");
}
})
.collect(),
2018-01-08 21:49:09 -08:00
gt_token: Default::default(),
2017-04-13 12:28:23 -07:00
},
),
},
2018-01-08 21:49:09 -08:00
].into_iter().collect(),
2017-04-13 12:28:23 -07:00
},
2018-01-08 21:49:09 -08:00
})
}