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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//! This module contains things adapted from syn 1.x
//! to preserve compatibility.

use quote::ToTokens;
use syn::ext::IdentExt as _;
use syn::parse::{Parse, ParseStream, Parser as _};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::Paren;
use syn::{
    parenthesized, token, Attribute, Ident, Lit, LitBool, MacroDelimiter, Meta,
    MetaNameValue, Path, PathSegment, Result, Token,
};

pub(crate) trait AttributeExt {
    fn parse_meta(&self) -> Result<ParsedMeta>;
}

impl AttributeExt for Attribute {
    fn parse_meta(&self) -> Result<ParsedMeta> {
        parse_nested_meta(self.meta.clone())
    }
}

/// [`Meta`] but more like the version from syn 1.x in two important ways:
/// * The nested metas in a list are already parsed
/// * Paths are allowed to contain keywords.
#[derive(Clone)]
pub(crate) enum ParsedMeta {
    Path(Path),
    List(ParsedMetaList),
    NameValue(MetaNameValue),
}

impl Parse for ParsedMeta {
    fn parse(input: ParseStream) -> Result<Self> {
        let path = input.call(parse_meta_path)?;
        parse_meta_after_path(path, input)
    }
}

impl ParsedMeta {
    pub(crate) fn path(&self) -> &Path {
        match self {
            ParsedMeta::Path(path) => path,
            ParsedMeta::List(meta) => &meta.path,
            ParsedMeta::NameValue(meta) => &meta.path,
        }
    }
}

impl ToTokens for ParsedMeta {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            ParsedMeta::Path(p) => p.to_tokens(tokens),
            ParsedMeta::List(l) => l.to_tokens(tokens),
            ParsedMeta::NameValue(n) => n.to_tokens(tokens),
        }
    }
}

#[derive(Clone)]
pub(crate) struct ParsedMetaList {
    pub path: Path,
    pub paren_token: Paren,
    pub nested: Punctuated<NestedMeta, Token![,]>,
}

impl ToTokens for ParsedMetaList {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        self.path.to_tokens(tokens);
        self.paren_token.surround(tokens, |tokens| {
            self.nested.to_tokens(tokens);
        });
    }
}

#[derive(Clone)]
pub(crate) enum NestedMeta {
    Meta(ParsedMeta),
    Lit(Lit),
}

impl Parse for NestedMeta {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(Lit) && !(input.peek(LitBool) && input.peek2(Token![=])) {
            input.parse().map(NestedMeta::Lit)
        } else if input.peek(Ident::peek_any)
            || input.peek(Token![::]) && input.peek3(Ident::peek_any)
        {
            input.parse().map(NestedMeta::Meta)
        } else {
            Err(input.error("expected identifier or literal"))
        }
    }
}

impl ToTokens for NestedMeta {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            NestedMeta::Meta(meta) => meta.to_tokens(tokens),
            NestedMeta::Lit(lit) => lit.to_tokens(tokens),
        }
    }
}

fn parse_nested_meta(meta: Meta) -> Result<ParsedMeta> {
    match meta {
        Meta::Path(path) => Ok(ParsedMeta::Path(path)),
        Meta::NameValue(name_value) => Ok(ParsedMeta::NameValue(name_value)),
        Meta::List(list) => {
            let MacroDelimiter::Paren(paren_token) = list.delimiter else {
                return Err(syn::Error::new(
                    list.delimiter.span().span(),
                    "Expected paren",
                ));
            };
            Ok(ParsedMeta::List(ParsedMetaList {
                path: list.path,
                paren_token,
                nested: Punctuated::parse_terminated.parse2(list.tokens)?,
            }))
        }
    }
}

// Like Path::parse_mod_style but accepts keywords in the path.
fn parse_meta_path(input: ParseStream) -> Result<Path> {
    Ok(Path {
        leading_colon: input.parse()?,
        segments: {
            let mut segments = Punctuated::new();
            while input.peek(Ident::peek_any) {
                let ident = Ident::parse_any(input)?;
                segments.push_value(PathSegment::from(ident));
                if !input.peek(Token![::]) {
                    break;
                }
                let punct = input.parse()?;
                segments.push_punct(punct);
            }
            if segments.is_empty() {
                return Err(input.error("expected path"));
            } else if segments.trailing_punct() {
                return Err(input.error("expected path segment"));
            }
            segments
        },
    })
}

pub(crate) fn parse_meta_after_path(
    path: Path,
    input: ParseStream,
) -> Result<ParsedMeta> {
    if input.peek(token::Paren) {
        parse_meta_list_after_path(path, input).map(ParsedMeta::List)
    } else if input.peek(Token![=]) {
        parse_meta_name_value_after_path(path, input).map(ParsedMeta::NameValue)
    } else {
        Ok(ParsedMeta::Path(path))
    }
}

fn parse_meta_list_after_path(
    path: Path,
    input: ParseStream,
) -> Result<ParsedMetaList> {
    let content;
    Ok(ParsedMetaList {
        path,
        paren_token: parenthesized!(content in input),
        nested: content.parse_terminated(NestedMeta::parse, Token![,])?,
    })
}

fn parse_meta_name_value_after_path(
    path: Path,
    input: ParseStream,
) -> Result<MetaNameValue> {
    Ok(MetaNameValue {
        path,
        eq_token: input.parse()?,
        value: input.parse()?,
    })
}