abi_stable_derive/
parse_utils.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
//! Functions for parsing many `syn` types.

use as_derive_utils::ret_err_on_peek;

use syn::{parse, punctuated::Punctuated, token::Add, TypeParamBound};

use proc_macro2::Span;

//use crate::utils::SynResultExt;

pub(crate) fn parse_str_as_ident(lit: &str) -> syn::Ident {
    syn::Ident::new(lit, Span::call_site())
}

pub(crate) fn parse_str_as_path(lit: &str) -> Result<syn::Path, syn::Error> {
    syn::parse_str(lit)
}

pub(crate) fn parse_str_as_trait_bound(lit: &str) -> Result<syn::TraitBound, syn::Error> {
    syn::parse_str(lit)
}

pub(crate) fn parse_str_as_type(lit: &str) -> Result<syn::Type, syn::Error> {
    syn::parse_str(lit)
}

#[allow(dead_code)]
pub(crate) fn parse_lit_as_type_bound(lit: &syn::LitStr) -> Result<TypeParamBound, syn::Error> {
    lit.parse()
}

pub struct ParseBounds {
    pub list: Punctuated<TypeParamBound, Add>,
}

impl parse::Parse for ParseBounds {
    fn parse(input: parse::ParseStream) -> parse::Result<Self> {
        ret_err_on_peek! {input, syn::Lit, "bound", "literal"}

        let list = Punctuated::<TypeParamBound, Add>::parse_terminated(input).map_err(|e| {
            let msg = format!("while parsing bounds: {}", e);
            syn::Error::new(e.span(), msg)
        })?;

        if list.is_empty() {
            Err(input.error("type bounds can't be empty"))
        } else {
            Ok(Self { list })
        }
    }
}

pub struct ParsePunctuated<T, P> {
    pub list: Punctuated<T, P>,
}

impl<T, P> parse::Parse for ParsePunctuated<T, P>
where
    T: parse::Parse,
    P: parse::Parse,
{
    fn parse(input: parse::ParseStream) -> parse::Result<Self> {
        Ok(Self {
            list: Punctuated::parse_terminated(input)?,
        })
    }
}