-
Notifications
You must be signed in to change notification settings - Fork 39
/
refident.rs
86 lines (75 loc) · 2.1 KB
/
refident.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/// Provide `RefIdent` and `MaybeIdent` traits that give a shortcut to extract identity reference
/// (`syn::Ident` struct).
use proc_macro2::Ident;
use syn::{FnArg, Pat, PatType, Type};
pub trait RefIdent {
/// Return the reference to ident if any
fn ident(&self) -> &Ident;
}
pub trait MaybeIdent {
/// Return the reference to ident if any
fn maybe_ident(&self) -> Option<&Ident>;
}
impl<I: RefIdent> MaybeIdent for I {
fn maybe_ident(&self) -> Option<&Ident> {
Some(self.ident())
}
}
impl RefIdent for Ident {
fn ident(&self) -> &Ident {
self
}
}
impl<'a> RefIdent for &'a Ident {
fn ident(&self) -> &Ident {
self
}
}
impl MaybeIdent for FnArg {
fn maybe_ident(&self) -> Option<&Ident> {
match self {
FnArg::Typed(PatType { pat, .. }) => match pat.as_ref() {
Pat::Ident(ident) => Some(&ident.ident),
_ => None,
},
_ => None,
}
}
}
impl MaybeIdent for Type {
fn maybe_ident(&self) -> Option<&Ident> {
match self {
Type::Path(tp) if tp.qself.is_none() => tp.path.get_ident(),
_ => None,
}
}
}
pub trait MaybeType {
/// Return the reference to type if any
fn maybe_type(&self) -> Option<&Type>;
}
impl MaybeType for FnArg {
fn maybe_type(&self) -> Option<&Type> {
match self {
FnArg::Typed(PatType { ty, .. }) => Some(ty.as_ref()),
_ => None,
}
}
}
impl MaybeIdent for syn::GenericParam {
fn maybe_ident(&self) -> Option<&Ident> {
match self {
syn::GenericParam::Type(syn::TypeParam { ident, .. })
| syn::GenericParam::Const(syn::ConstParam { ident, .. }) => Some(ident),
syn::GenericParam::Lifetime(syn::LifetimeParam { lifetime, .. }) => Some(&lifetime.ident),
}
}
}
impl MaybeIdent for crate::parse::Attribute {
fn maybe_ident(&self) -> Option<&Ident> {
use crate::parse::Attribute::*;
match self {
Attr(ident) | Tagged(ident, _) | Type(ident, _) => Some(ident),
}
}
}