pmhelp_internal/exts/
mod.rs

1/// Extension traits to existing types.
2use alloc::vec::Vec;
3use syn::{
4    parse::{Parse, ParseBuffer, Peek},
5    GenericArgument, Ident, Path, PathArguments, PathSegment, Type, TypePath,
6};
7
8mod is_exts;
9pub use is_exts::*;
10
11pub trait ParseBufferExt {
12    /// Peeks to see if a token is present. If it is, then it consumes the token and returns true.
13    fn peek_and_consume<T: Peek<Token = P>, P: Parse>(&self, token: T) -> bool;
14}
15
16impl<'a> ParseBufferExt for ParseBuffer<'a> {
17    fn peek_and_consume<T: Peek<Token = P>, P: Parse>(&self, token: T) -> bool {
18        if self.peek(token) {
19            // Since we KNOW it's the next token, we can just unwrap it
20            self.parse::<T::Token>().unwrap();
21            true
22        } else {
23            false
24        }
25    }
26}
27
28pub trait GetBaseTypes {
29    fn get_base_types(&self) -> Vec<&Type>;
30}
31
32impl GetBaseTypes for PathSegment {
33    fn get_base_types(&self) -> Vec<&Type> {
34        if let PathArguments::AngleBracketed(generics) = &self.arguments {
35            generics
36                .args
37                .iter()
38                .filter_map(|arg| {
39                    if let GenericArgument::Type(ty) = arg {
40                        Some(ty)
41                    } else {
42                        None
43                    }
44                })
45                .collect()
46        } else {
47            Vec::new()
48        }
49    }
50}
51
52impl GetBaseTypes for Path {
53    fn get_base_types(&self) -> Vec<&Type> {
54        if let Some(last) = self.segments.last() {
55            last.get_base_types()
56        } else {
57            Vec::new()
58        }
59    }
60}
61
62impl GetBaseTypes for Type {
63    fn get_base_types(&self) -> Vec<&Type> {
64        if let Self::Path(TypePath { path, qself: None }) = &self {
65            path.get_base_types()
66        } else {
67            Vec::new()
68        }
69    }
70}