|
| 1 | +// Copyright 2018-2022 Parity Technologies (UK) Ltd. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +use proc_macro2::{ |
| 16 | + Ident, |
| 17 | + TokenStream as TokenStream2, |
| 18 | +}; |
| 19 | +use quote::ToTokens; |
| 20 | +use syn::{ |
| 21 | + ext::IdentExt as _, |
| 22 | + parse::{ |
| 23 | + Parse, |
| 24 | + ParseStream, |
| 25 | + }, |
| 26 | + punctuated::Punctuated, |
| 27 | + spanned::Spanned, |
| 28 | + LitInt, |
| 29 | + Token, |
| 30 | +}; |
| 31 | + |
| 32 | +/// Content of a compile-time structured attribute. |
| 33 | +/// |
| 34 | +/// This is a subset of `syn::Meta` that allows the `value` of a name-value pair |
| 35 | +/// to be a plain identifier or path. |
| 36 | +#[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 37 | +pub enum Meta { |
| 38 | + /// A path, like `message`. |
| 39 | + Path(syn::Path), |
| 40 | + /// A name-value pair, like `feature = "nightly"`. |
| 41 | + NameValue(MetaNameValue), |
| 42 | +} |
| 43 | + |
| 44 | +impl Parse for Meta { |
| 45 | + fn parse(input: ParseStream) -> Result<Self, syn::Error> { |
| 46 | + let path = input.call(parse_meta_path)?; |
| 47 | + if input.peek(Token![=]) { |
| 48 | + MetaNameValue::parse_meta_name_value_after_path(path, input) |
| 49 | + .map(Meta::NameValue) |
| 50 | + } else { |
| 51 | + Ok(Meta::Path(path)) |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl ToTokens for Meta { |
| 57 | + fn to_tokens(&self, tokens: &mut TokenStream2) { |
| 58 | + match self { |
| 59 | + Self::Path(path) => path.to_tokens(tokens), |
| 60 | + Self::NameValue(name_value) => name_value.to_tokens(tokens), |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +/// A name-value pair within an attribute, like `feature = "nightly"`. |
| 66 | +/// |
| 67 | +/// The only difference from `syn::MetaNameValue` is that this additionally |
| 68 | +/// allows the `value` to be a plain identifier or path. |
| 69 | +#[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 70 | +pub struct MetaNameValue { |
| 71 | + pub name: syn::Path, |
| 72 | + pub eq_token: syn::token::Eq, |
| 73 | + pub value: PathOrLit, |
| 74 | +} |
| 75 | + |
| 76 | +impl Parse for MetaNameValue { |
| 77 | + fn parse(input: ParseStream) -> Result<Self, syn::Error> { |
| 78 | + let path = input.call(parse_meta_path)?; |
| 79 | + Self::parse_meta_name_value_after_path(path, input) |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +impl ToTokens for MetaNameValue { |
| 84 | + fn to_tokens(&self, tokens: &mut TokenStream2) { |
| 85 | + self.name.to_tokens(tokens); |
| 86 | + self.eq_token.to_tokens(tokens); |
| 87 | + self.value.to_tokens(tokens); |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +impl MetaNameValue { |
| 92 | + fn parse_meta_name_value_after_path( |
| 93 | + name: syn::Path, |
| 94 | + input: ParseStream, |
| 95 | + ) -> Result<MetaNameValue, syn::Error> { |
| 96 | + let span = name.span(); |
| 97 | + Ok(MetaNameValue { |
| 98 | + name, |
| 99 | + eq_token: input.parse().map_err(|_error| { |
| 100 | + format_err!( |
| 101 | + span, |
| 102 | + "ink! config options require an argument separated by '='", |
| 103 | + ) |
| 104 | + })?, |
| 105 | + value: input.parse()?, |
| 106 | + }) |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +/// Either a path or a literal. |
| 111 | +#[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 112 | +pub enum PathOrLit { |
| 113 | + Path(syn::Path), |
| 114 | + Lit(syn::Lit), |
| 115 | +} |
| 116 | + |
| 117 | +impl Parse for PathOrLit { |
| 118 | + fn parse(input: ParseStream) -> Result<Self, syn::Error> { |
| 119 | + if input.fork().peek(syn::Lit) { |
| 120 | + return input.parse::<syn::Lit>().map(PathOrLit::Lit) |
| 121 | + } |
| 122 | + if input.fork().peek(Ident::peek_any) || input.fork().peek(Token![::]) { |
| 123 | + return input.call(parse_meta_path).map(PathOrLit::Path) |
| 124 | + } |
| 125 | + Err(input.error("cannot parse into either literal or path")) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +impl ToTokens for PathOrLit { |
| 130 | + fn to_tokens(&self, tokens: &mut TokenStream2) { |
| 131 | + match self { |
| 132 | + Self::Lit(lit) => lit.to_tokens(tokens), |
| 133 | + Self::Path(path) => path.to_tokens(tokens), |
| 134 | + } |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +impl PathOrLit { |
| 139 | + /// Returns the value of the literal if it is a boolean literal. |
| 140 | + pub fn as_bool(&self) -> Option<bool> { |
| 141 | + match self { |
| 142 | + Self::Lit(syn::Lit::Bool(lit_bool)) => Some(lit_bool.value), |
| 143 | + _ => None, |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + /// Returns the value of the literal if it is a string literal. |
| 148 | + pub fn as_string(&self) -> Option<String> { |
| 149 | + match self { |
| 150 | + Self::Lit(syn::Lit::Str(lit_str)) => Some(lit_str.value()), |
| 151 | + _ => None, |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + /// Returns the the literal if it is an integer literal. |
| 156 | + pub fn as_lit_int(&self) -> Option<&LitInt> { |
| 157 | + match self { |
| 158 | + Self::Lit(syn::Lit::Int(lit_int)) => Some(lit_int), |
| 159 | + _ => None, |
| 160 | + } |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +/// Like [`syn::Path::parse_mod_style`] but accepts keywords in the path. |
| 165 | +/// |
| 166 | +/// # Note |
| 167 | +/// |
| 168 | +/// This code was taken from the `syn` implementation for a very similar |
| 169 | +/// syntactical pattern. |
| 170 | +fn parse_meta_path(input: ParseStream) -> Result<syn::Path, syn::Error> { |
| 171 | + Ok(syn::Path { |
| 172 | + leading_colon: input.parse()?, |
| 173 | + segments: { |
| 174 | + let mut segments = Punctuated::new(); |
| 175 | + while input.peek(Ident::peek_any) { |
| 176 | + let ident = Ident::parse_any(input)?; |
| 177 | + segments.push_value(syn::PathSegment::from(ident)); |
| 178 | + if !input.peek(syn::Token![::]) { |
| 179 | + break |
| 180 | + } |
| 181 | + let punct = input.parse()?; |
| 182 | + segments.push_punct(punct); |
| 183 | + } |
| 184 | + if segments.is_empty() { |
| 185 | + return Err(input.error("expected path")) |
| 186 | + } else if segments.trailing_punct() { |
| 187 | + return Err(input.error("expected path segment")) |
| 188 | + } |
| 189 | + segments |
| 190 | + }, |
| 191 | + }) |
| 192 | +} |
| 193 | + |
| 194 | +#[cfg(test)] |
| 195 | +mod tests { |
| 196 | + use super::*; |
| 197 | + use crate::ast::PathOrLit; |
| 198 | + use quote::quote; |
| 199 | + |
| 200 | + #[test] |
| 201 | + fn underscore_token_works() { |
| 202 | + assert_eq!( |
| 203 | + syn::parse2::<Meta>(quote! { selector = _ }).unwrap(), |
| 204 | + Meta::NameValue(MetaNameValue { |
| 205 | + name: syn::parse_quote! { selector }, |
| 206 | + eq_token: syn::parse_quote! { = }, |
| 207 | + value: PathOrLit::Path(syn::Path::from(quote::format_ident!("_"))), |
| 208 | + }) |
| 209 | + ) |
| 210 | + } |
| 211 | +} |
0 commit comments