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
use syn::{Path, PathArguments, Type};
#[macro_export]
macro_rules! path_segments {
($($ty:tt)::*) => {
$crate::path::PathSegments::new(&[$(stringify!($ty)),*])
};
(::$($ty:tt)::*) => {
$crate::path::PathSegments::new(&[$(stringify!($ty)),*])
};
}
#[derive(Debug, Clone)]
pub struct PathSegments<'s>(&'s [&'s str]);
impl<'s> PathSegments<'s> {
pub fn new(segments: &'s [&'s str]) -> Self {
Self(segments)
}
}
pub fn is_type(ty: &Type, segments: &PathSegments) -> bool {
match ty {
Type::Path(p) => is_path(&p.path, segments),
Type::Reference(ty_ref) => {
match &*ty_ref.elem {
Type::Path(p) => is_path(&p.path, segments),
_ => false,
}
}
_ => false,
}
}
pub fn is_path(p: &Path, segments: &PathSegments) -> bool {
if segments.0.len() < p.segments.len() {
return false;
}
let mut ty_segs = p.segments.iter().rev();
for seg in segments.0.iter().rev() {
match ty_segs.next() {
Some(ty_seg) => {
if ty_seg.ident != seg {
return false;
}
}
None => return true,
}
}
true
}
pub fn type_args(ty: &Type) -> Option<&PathArguments> {
match ty {
Type::Path(p) => p.path.segments.last().map(|s| &s.arguments),
Type::Reference(ty_ref) => match &*ty_ref.elem {
Type::Path(p) => p.path.segments.last().map(|s| &s.arguments),
_ => None,
},
_ => None,
}
}
pub fn is_option(ty: &Type) -> bool {
is_type(ty, &path_segments!(::core::option::Option))
|| is_type(ty, &path_segments!(::std::option::Option))
}