aboutsummaryrefslogtreecommitdiffstats
path: root/components/style_derive/parse.rs
blob: 76d2c8a82fc666212addfb6e3d4e84c02a65ffe2 (plain) (blame)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use cg;
use quote::Tokens;
use syn::{DeriveInput, Path};
use synstructure;
use to_css::CssVariantAttrs;

#[darling(attributes(parse), default)]
#[derive(Default, FromVariant)]
pub struct ParseVariantAttrs {
    pub aliases: Option<String>,
    pub condition: Option<Path>,
}

pub fn derive(input: DeriveInput) -> Tokens {
    let name = &input.ident;
    let s = synstructure::Structure::new(&input);

    let mut saw_condition = false;
    let match_body = s.variants().iter().fold(quote!(), |match_body, variant| {
        let bindings = variant.bindings();
        assert!(
            bindings.is_empty(),
            "Parse is only supported for single-variant enums for now"
        );

        let css_variant_attrs = cg::parse_variant_attrs_from_ast::<CssVariantAttrs>(&variant.ast());
        let parse_attrs = cg::parse_variant_attrs_from_ast::<ParseVariantAttrs>(&variant.ast());
        if css_variant_attrs.skip {
            return match_body;
        }

        let identifier = cg::to_css_identifier(
            &css_variant_attrs
                .keyword
                .unwrap_or(variant.ast().ident.as_ref().into()),
        );
        let ident = &variant.ast().ident;

        saw_condition |= parse_attrs.condition.is_some();
        let condition = match parse_attrs.condition {
            Some(ref p) => quote! { if #p(context) },
            None => quote!{},
        };

        let mut body = quote! {
            #match_body
            #identifier #condition => Ok(#name::#ident),
        };

        let aliases = match parse_attrs.aliases {
            Some(aliases) => aliases,
            None => return body,
        };

        for alias in aliases.split(",") {
            body = quote! {
                #body
                #alias #condition => Ok(#name::#ident),
            };
        }

        body
    });

    let context_ident = if saw_condition {
        quote! { context }
    } else {
        quote! { _ }
    };

    let parse_body = if saw_condition {
        quote! {
            let location = input.current_source_location();
            let ident = input.expect_ident()?;
            match_ignore_ascii_case! { &ident,
                #match_body
                _ => Err(location.new_unexpected_token_error(
                    ::cssparser::Token::Ident(ident.clone())
                ))
            }
        }
    } else {
        quote! { Self::parse(input) }
    };

    let parse_trait_impl = quote! {
        impl ::parser::Parse for #name {
            #[inline]
            fn parse<'i, 't>(
                #context_ident: &::parser::ParserContext,
                input: &mut ::cssparser::Parser<'i, 't>,
            ) -> Result<Self, ::style_traits::ParseError<'i>> {
                #parse_body
            }
        }
    };

    if saw_condition {
        return parse_trait_impl;
    }

    // TODO(emilio): It'd be nice to get rid of these, but that makes the
    // conversion harder...
    let methods_impl = quote! {
        impl #name {
            /// Parse this keyword.
            #[inline]
            pub fn parse<'i, 't>(
                input: &mut ::cssparser::Parser<'i, 't>,
            ) -> Result<Self, ::style_traits::ParseError<'i>> {
                let location = input.current_source_location();
                let ident = input.expect_ident()?;
                Self::from_ident(ident.as_ref()).map_err(|()| {
                    location.new_unexpected_token_error(
                        ::cssparser::Token::Ident(ident.clone())
                    )
                })
            }

            /// Parse this keyword from a string slice.
            #[inline]
            pub fn from_ident(ident: &str) -> Result<Self, ()> {
                match_ignore_ascii_case! { ident,
                    #match_body
                    _ => Err(()),
                }
            }
        }
    };

    quote! {
        #parse_trait_impl
        #methods_impl
    }
}