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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
|
#![doc = include_str!("../README.md")]
use proc_macro::TokenStream as PmTokenStream;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{
parse_macro_input, punctuated::Punctuated, spanned::Spanned, Attribute, Data, DeriveInput,
Error, Ident, Meta, MetaNameValue, Token, Variant,
};
struct ApiType {
name: Ident,
cfgs: Vec<Attribute>,
constructor: TokenStream,
}
impl ApiType {
fn feature(&self) -> TokenStream {
let cfgs = &self.cfgs;
quote! { #(#cfgs)* }
}
}
#[proc_macro_derive(ProviderApi, attributes(provider))]
pub fn provider_api_derive(input: PmTokenStream) -> PmTokenStream {
let ast = parse_macro_input!(input as DeriveInput);
match provider_api_derive_error(&ast) {
Ok(ts) => ts.into(),
Err(e) => e.to_compile_error().into(),
}
}
fn provider_api_derive_error(ast: &DeriveInput) -> Result<TokenStream, Error> {
let variants = extract_variants(ast)?;
if variants.is_empty() {
panic!("Provider API needs at least one variant active");
}
let type_list = impl_type_list(&variants);
let type_list_variants = impl_type_list_variants(&variants);
let type_list_from_str = impl_type_list_from_str(&variants);
let type_list_to_str = impl_type_list_to_str(&variants);
let constructor = impl_constructor(&variants);
let provider_impl = impl_provider_impl(&variants);
let result = quote! {
#type_list
#type_list_variants
#type_list_from_str
#type_list_to_str
#constructor
#provider_impl
};
Ok(result)
}
fn extract_variants(ast: &DeriveInput) -> Result<Vec<ApiType>, Error> {
let Data::Enum(data) = &ast.data else {
return Err(Error::new(
ast.span(),
"ProviderApi-macro only applicable to enums",
));
};
data.variants.iter().map(variant_to_api_variant).collect()
}
fn variant_to_api_variant(var: &Variant) -> Result<ApiType, Error> {
let name = var.ident.clone();
let my_attrs = var
.attrs
.iter()
.flat_map(|a| match &a.meta {
Meta::List(l)
if l.path.get_ident().map(|i| i.to_string()) == Some("provider".to_string()) =>
{
l.parse_args_with(Punctuated::<MetaNameValue, Token![,]>::parse_terminated)
.unwrap_or_default()
.into_iter()
.collect()
}
_ => vec![],
})
.collect::<Vec<_>>();
let Some(constructor) = my_attrs
.iter()
.filter(|a| a.path.get_ident().map(|i| i.to_string()) == Some("constructor".to_string()))
.map(|n| n.value.to_token_stream())
.next()
.or_else(|| {
my_attrs
.iter()
.filter(|a| a.path.get_ident().map(|i| i.to_string()) == Some("hafas".to_string()))
.map(|n| &n.value)
.map(|v| quote! { |r| rhafas::client::HafasClient::new(#v, r) })
.next()
})
else {
return Err(Error::new(
var.span(),
"Provider does not have a constructor or hafas",
));
};
let cfg_attrs = var
.attrs
.iter()
.filter(|a| {
matches!(&a.meta,
Meta::List(l)
if l.path.get_ident().map(|i| i.to_string()) == Some("cfg".to_string()))
})
.cloned()
.collect::<Vec<_>>();
Ok(ApiType {
name,
constructor: constructor.clone(),
cfgs: cfg_attrs,
})
}
fn impl_type_list(types: &[ApiType]) -> TokenStream {
let parts = types.iter().map(impl_type_list_single);
quote! {
#[automatically_derived]
#[derive(Debug, Clone, PartialEq, Eq)]
/// An enumeration listing all available [`Provider`s](rcore::Provider) in the [`RailwayProvider`].
pub enum RailwayProviderType {
#(#parts),*
}
}
}
fn impl_type_list_single(t: &ApiType) -> TokenStream {
let name = &t.name;
let feature = t.feature();
quote! {
#feature
#name
}
}
fn impl_type_list_variants(types: &[ApiType]) -> TokenStream {
let parts = types.iter().map(impl_type_list_single_variant);
quote! {
#[automatically_derived]
impl RailwayProviderType {
pub fn variants() -> &'static [Self] {
&[
#(#parts),*
]
}
}
}
}
fn impl_type_list_single_variant(t: &ApiType) -> TokenStream {
let name = &t.name;
let feature = t.feature();
quote! {
#feature
Self::#name
}
}
fn impl_type_list_from_str(types: &[ApiType]) -> TokenStream {
let parts = types.iter().map(impl_type_list_from_str_single);
quote! {
#[automatically_derived]
impl std::str::FromStr for RailwayProviderType {
type Err = ();
fn from_str(input: &str) -> Result<Self, Self::Err> {
let input = input.to_lowercase().replace(&['-', '_'][..], "");
match &input[..] {
#(#parts)*
_ => Err(()),
}
}
}
}
}
fn impl_type_list_from_str_single(t: &ApiType) -> TokenStream {
let name = &t.name;
let string = t.name.to_string().to_lowercase();
let feature = t.feature();
quote! {
#feature
#string => Ok(Self::#name),
}
}
fn impl_type_list_to_str(types: &[ApiType]) -> TokenStream {
let parts = types.iter().map(impl_type_list_to_str_single);
quote! {
#[automatically_derived]
impl std::fmt::Display for RailwayProviderType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let s = match self {
#(#parts)*
};
write!(f, "{}", s)
}
}
}
}
fn impl_type_list_to_str_single(t: &ApiType) -> TokenStream {
use convert_case::{Case, Casing};
let name = &t.name;
let string = t.name.to_string().to_case(Case::Kebab);
let feature = t.feature();
quote! {
#feature
Self::#name => #string,
}
}
fn impl_constructor(types: &[ApiType]) -> TokenStream {
let parts = types.iter().map(impl_constructor_single);
quote! {
#[automatically_derived]
impl RailwayProvider {
pub fn new(r#type: RailwayProviderType, builder: rcore::ReqwestRequesterBuilder) -> Self {
match r#type {
#(#parts),*
}
}
}
}
}
fn impl_constructor_single(t: &ApiType) -> TokenStream {
let name = &t.name;
let constructor = &t.constructor;
let feature = t.feature();
quote! {
#feature
RailwayProviderType::#name => Self::#name((#constructor)(builder))
}
}
fn impl_provider_impl(types: &[ApiType]) -> TokenStream {
let journeys = impl_provider_impl_journeys(types);
let locations = impl_provider_impl_locations(types);
let station_board = impl_provider_impl_station_board(types);
let refresh = impl_provider_impl_refresh(types);
quote! {
#[automatically_derived]
#[cfg_attr(feature = "rt-multi-thread", async_trait::async_trait)]
#[cfg_attr(not(feature = "rt-multi-thread"), async_trait::async_trait(?Send))]
impl rcore::Provider<rcore::ReqwestRequester> for RailwayProvider {
type Error = BoxedError;
#journeys
#locations
#station_board
#refresh
}
}
}
fn impl_provider_impl_journeys(types: &[ApiType]) -> TokenStream {
let parts = types
.iter()
.map(|t| impl_provider_impl_single(t, quote! {journeys(from, to, opts)}));
quote! {
async fn journeys(
&self,
from: rcore::Place,
to: rcore::Place,
opts: rcore::JourneysOptions,
) -> Result<rcore::JourneysResponse, rcore::Error<<R as Requester>::Error, Self::Error>> {
use rcore::Provider;
match self {
#(#parts),*
}
}
}
}
fn impl_provider_impl_locations(types: &[ApiType]) -> TokenStream {
let parts = types
.iter()
.map(|t| impl_provider_impl_single(t, quote! {refresh_journey(journey, opts)}));
quote! {
async fn refresh_journey(
&self,
journey: &rcore::Journey,
opts: rcore::RefreshJourneyOptions,
) -> Result<rcore::RefreshJourneyResponse, rcore::Error<<R as Requester>::Error, Self::Error>>
{
use rcore::Provider;
match self {
#(#parts),*
}
}
}
}
fn impl_provider_impl_station_board(types: &[ApiType]) -> TokenStream {
let parts = types
.iter()
.map(|t| impl_provider_impl_single(t, quote! {station_board(place, kind, opts)}));
quote! {
async fn station_board(
&self,
place: rcore::Place,
kind: rcore::StationBoardKind,
opts: rcore::StationBoardOptions,
) -> Result<rcore::StationBoardResponse, rcore::Error<<R as Requester>::Error, Self::Error>> {
use rcore::Provider;
match self {
#(#parts),*
}
}
}
}
fn impl_provider_impl_refresh(types: &[ApiType]) -> TokenStream {
let parts = types
.iter()
.map(|t| impl_provider_impl_single(t, quote! {locations(opts)}));
quote! {
async fn locations(
&self,
opts: rcore::LocationsOptions,
) -> Result<rcore::LocationsResponse, rcore::Error<<R as Requester>::Error, Self::Error>> {
use rcore::Provider;
match self {
#(#parts),*
}
}
}
}
fn impl_provider_impl_single(t: &ApiType, code: TokenStream) -> TokenStream {
let name = &t.name;
let feature = t.feature();
quote! {
#feature
RailwayProvider::#name(p) => p.#code.await.map_err(transform_error)
}
}
|