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 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
//! The `syllogism` crate defines the traits `IsNot` and `Specialize` that can be used in a
//! work-around to have some specialization in Rust.
//! These traits require a large amount of boilerplate.
//! The [`impl_specialization`] macro can be used to generate this boilerplate.
//!
//! [`impl_specialization`]: ./macro.impl_specialization.html
#![recursion_limit = "128"]
extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;
extern crate syn;
use proc_macro::TokenStream;
use proc_macro2::{Punct, Spacing};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input,
punctuated::Punctuated,
token::{Colon2, Comma},
Ident, Lifetime, Result, Token,
};
trait AppendCommaSeparated {
fn append_comma_separated<O: ToTokens>(&mut self, other: O);
}
impl AppendCommaSeparated for proc_macro2::TokenStream {
fn append_comma_separated<O: ToTokens>(&mut self, other: O) {
if self.is_empty() {
other.to_tokens(self);
} else {
let mut other_stream = proc_macro2::TokenStream::new();
other.to_tokens(&mut other_stream);
if !other_stream.is_empty() {
self.append(Punct::new(',', Spacing::Alone));
}
self.append_all(other_stream);
}
}
}
struct Type {
typename: Punctuated<Ident, Colon2>,
lifetimes: Punctuated<Lifetime, Comma>,
type_params: Punctuated<Ident, Comma>,
}
impl Type {
/// Return a comma-separated list of all parameters, including lifetimes.
fn get_params(&self) -> proc_macro2::TokenStream {
let mut result = proc_macro2::TokenStream::new();
result.append_all(&self.lifetimes);
result.append_comma_separated(&self.type_params);
result
}
}
impl Parse for Type {
fn parse(input: ParseStream) -> Result<Self> {
let _ = input.parse::<syn::token::Type>()?;
let typename = Punctuated::parse_separated_nonempty(input)?;
let mut lifetimes = Punctuated::new();
let mut type_params = Punctuated::new();
if input.parse::<Token![<]>().is_ok() {
let mut is_parsing_lifetimes = true;
loop {
if input.parse::<Token![>]>().is_ok() {
break;
}
if is_parsing_lifetimes {
if let Ok(lifetime) = input.parse() {
lifetimes.push(lifetime);
} else {
is_parsing_lifetimes = false;
}
}
if !is_parsing_lifetimes {
let type_param = input.parse()?;
type_params.push(type_param);
}
if input.parse::<Token![>]>().is_ok() {
break;
}
let lookahead = input.lookahead1();
if lookahead.peek(Comma) {
let _: Comma = input.parse()?;
} else {
return Err(lookahead.error());
}
}
}
if input.peek(Token![where]) {
panic!("where clauses are not (yet) supported.");
}
Ok(Type {
typename,
lifetimes,
type_params,
})
}
}
struct Macro {
macro_name: Ident,
}
impl Parse for Macro {
fn parse(input: ParseStream) -> Result<Self> {
let _ = input.parse::<syn::token::Macro>()?;
let macro_name = input.parse()?;
Ok(Macro { macro_name })
}
}
struct Trait {
trait_name: Punctuated<Ident, Colon2>,
}
impl Parse for Trait {
fn parse(input: ParseStream) -> Result<Self> {
let _ = input.parse::<syn::token::Trait>()?;
let trait_name = Punctuated::parse_separated_nonempty(input)?;
Ok(Trait { trait_name })
}
}
struct TypeList {
types: Vec<Type>,
macros: Vec<Macro>,
traits: Vec<Trait>,
}
impl Parse for TypeList {
fn parse(input: ParseStream) -> Result<Self> {
let mut types = Vec::new();
let mut macros = Vec::new();
let mut traits = Vec::new();
loop {
if let Ok(mcr) = input.parse() {
macros.push(mcr);
} else if let Ok(trt) = input.parse() {
traits.push(trt);
} else if let Ok(ty) = input.parse() {
types.push(ty);
} else if input.is_empty() {
break;
} else {
panic!(
"Expected `type`, `macro` or `trait`, found {:?}.",
input.cursor().token_stream()
);
}
if input.parse::<Token![;]>().is_ok() {
// Continue
} else {
break;
}
}
Ok(TypeList {
types,
macros,
traits,
})
}
}
fn get_impl_parameters(ty1: &Type, ty2: &Type) -> proc_macro2::TokenStream {
let mut impl_parameters = proc_macro2::TokenStream::new();
impl_parameters.append_comma_separated(&ty1.lifetimes);
impl_parameters.append_comma_separated(&ty2.lifetimes);
impl_parameters.append_comma_separated(&ty1.type_params);
impl_parameters.append_comma_separated(&ty2.type_params);
impl_parameters
}
fn impl_isnot_block(ty1: &Type, ty2: &Type) -> proc_macro2::TokenStream {
let typename1 = &ty1.typename;
let typename2 = &ty2.typename;
let impl_parameters = get_impl_parameters(ty1, ty2);
let ty1_params = ty1.get_params();
let ty2_params = ty2.get_params();
quote! {
impl<#impl_parameters> syllogism::IsNot<#typename2<#ty2_params>> for #typename1<#ty1_params> {}
}
}
fn impl_specialize_self(ty: &Type) -> proc_macro2::TokenStream {
if !ty.type_params.is_empty() {
return proc_macro2::TokenStream::new();
}
let typename = &ty.typename;
let lifetimes = &ty.lifetimes;
quote! {
impl<#lifetimes> syllogism::Specialize<#typename<#lifetimes>> for #typename<#lifetimes> {
fn specialize(self) -> syllogism::Distinction<#typename<#lifetimes>, Self> {
syllogism::Distinction::Special(self)
}
}
}
}
fn impl_specialize_block_generic(ty1: &Type, ty2: &Type) -> proc_macro2::TokenStream {
let typename1 = &ty1.typename;
let typename2 = &ty2.typename;
let impl_parameters = get_impl_parameters(ty1, ty2);
let ty1_params = ty1.get_params();
let ty2_params = ty2.get_params();
quote! {
impl<#impl_parameters> syllogism::Specialize<#typename2<#ty2_params>>
for #typename1<#ty1_params> {
fn specialize(self) -> syllogism::Distinction<#typename2<#ty2_params>, Self> {
syllogism::Distinction::Generic(self)
}
}
}
}
fn call_macro(ty: &Type, mcro: &Macro) -> proc_macro2::TokenStream {
let typename = &ty.typename;
let ty_params = ty.get_params();
let macro_name = &mcro.macro_name;
if ty_params.is_empty() {
quote! {
#macro_name!(impl trait for #typename<#ty_params> {});
}
} else {
quote! {
#macro_name!(impl<#ty_params> trait for #typename<#ty_params> {});
}
}
}
fn impl_isnot_trait(ty: &Type, trt: &Trait) -> proc_macro2::TokenStream {
let typename = &ty.typename;
let ty_params = ty.get_params();
let unique_identifier = Ident::new(
"Type_parameter_used_internally_in_impl_isnot_trait_macro",
proc_macro2::Span::call_site(),
);
let mut impl_params = ty_params.clone();
impl_params.append_comma_separated(&unique_identifier);
let trait_name = &trt.trait_name;
quote! {
impl<#impl_params>
syllogism::IsNot<#unique_identifier>
for #typename<#ty_params>
where #unique_identifier : #trait_name {
}
}
}
fn impl_specialize_trait(ty: &Type, trt: &Trait) -> proc_macro2::TokenStream {
let typename = &ty.typename;
let ty_params = ty.get_params();
let unique_identifier = Ident::new(
"Type_parameter_used_internally_in_impl_isnot_trait_macro",
proc_macro2::Span::call_site(),
);
let mut impl_params = ty_params.clone();
impl_params.append_comma_separated(&unique_identifier);
let trait_name = &trt.trait_name;
quote! {
impl<#impl_params> syllogism::Specialize<#unique_identifier>
for #typename<#ty_params>
where #unique_identifier : #trait_name {
fn specialize(self) -> syllogism::Distinction<#unique_identifier, Self> {
syllogism::Distinction::Generic(self)
}
}
}
}
/// Procedural macro to allow `IsNot`-based and `Specialize`-based specialisation for a number of
/// data-types, allowing handling each other data-type in the generic way.
///
/// It expects a number of items, separated by semicolons (`;`):
/// * a number of data types, possibly with type parameters and lifetimes, each preceded with the
/// `type` keyword (e.g. `impl_specialization!(type MyType; type OtherType<T>);`),
/// * optionally a number of traits without type parameters (usually only one trait),
/// preceded by the `trait` keyword,
/// (e.g. `impl_specialization!(trait MyTrait; type MyType; type OtherType<T>);`),
/// * optionally a number of macro names (usually one macro), preceded by the `macro` keyword.
/// These macros are supposed to be macros as defined by the `define_compatibility` macro
/// in the `syllogism` crate.
///
/// This gives you all you need to use `IsNot`-based and `Specialize`-based implementation, with
/// the exception of the implementation of `Specialize<Self>` for types with type parameters.
/// In other words, the expansion of the macro contains the following:
///
/// * For each pair of distinct data-types `D1`, `D2` in the list of data-types supplied,
/// the expansion contains
///
/// ```ignore
/// impl IsNot<D2> for D1 {} // For each pair of distinct data types `D1`, `D2`
///
/// impl<P> IsNot<P> for D1
/// where P: T1 {/* ... */ } // For each data type `D1` and each treat `T1`
///
/// impl Specialize<D2> for D1 {
/// // Return Distinction::Generic
/// } // For each pair of distinct data types `D1`, `D2`
/// impl Specialize<D1> for D1 {
/// // Return Distinction::Special
/// } // For each data type `D1` that has no type parameters
///
/// impl<P> Specialize<P> for D1
/// where P: T1 {
/// // Return Distinction::Generic
// } // For each data type `D1` and each treat `T1`
///
/// m1!(impl trait for D1 {}); // For each data type `D1` and each macro `m1`
/// ```
///
/// # Warning
/// When using types with type parameters, please note that
/// * The type parameters must have distinct names. E.g.
/// `impl_specialization(type MyType<T>; type OtherType<U>);` is ok, but
/// `impl_specialization(type MyType<T>; type OtherType<T>);` is not ok.
/// * For the types with type parameters, the macro does not generate an implementation of
/// `Specialize<Self>`. E.g. when you write `impl_specialization(type MyType<T>; type OtherType);`,
/// you should manually write an impl block for
/// `impl<T> Specialize<MyType<T>> for MyType<T> { /* ... / }`.
///
/// # Example
///
/// ```
/// # } // HACK! Close the main function.
/// # // Let me know if there is a more elegant solution.
/// # mod hack { // Run the tests outside the main function.
/// use syllogism_macro::impl_specialization;
/// struct S1 {}
/// struct S2<'a, T> {
/// // ...
/// # _t: &'a T
/// }
///
/// mod m {
/// pub struct S3<U> {
/// // ...
/// # _u: U
/// }
/// }
///
/// # trait OtherTrait {}
/// macro_rules! my_macro {
/// // ...
/// # (
/// # $(
/// # impl $(<>)?
/// # trait for $typ:ty {}
/// # )*
/// # ) => {
/// # $(
/// # impl OtherTrait for $typ {}
/// # )*
/// # };
/// # (
/// # $(
/// # impl$(
/// # <$param_header:tt $(,$param_tail:tt)*>
/// # )?
/// # trait for $typ:ty {}
/// # )*
/// # ) => {
/// # $(
/// # impl$(
/// # <$param_header $(,$param_tail)*>
/// # )?
/// # OtherTrait for $typ {}
/// # )*
/// # }
/// }
/// trait MyTrait {}
///
/// impl_specialization!(
/// macro my_macro;
/// trait MyTrait;
/// type S1;
/// type S2<'a, T>;
/// type m::S3<U>
/// );
/// ```
/// In this example, the macro invocation expands to something similar to the following
/// (the difference is that in reality, the expansion contains `syllogism::IsNot` and
/// `syllogism::Specialize`, I have simplified this somewhat).
///
/// ```
/// # struct S1 {}
/// # struct S2<'a, T> { t: &'a T }
/// # mod m {
/// # pub struct S3<U> { u: U }
/// # }
/// # trait OtherTrait {}
/// # macro_rules! my_macro {
/// # (
/// # $(
/// # impl$(
/// # <$($param_header:tt)? $(,$param_tail:tt)*>
/// # )?
/// # trait for $typ:ty {}
/// # )*
/// # ) => {
/// # $(
/// # impl$(
/// # <$($param_header)? $(,$param_tail)*>
/// # )?
/// # OtherTrait for $typ {}
/// # )*
/// # }
/// # }
/// # trait MyTrait {}
/// use syllogism::{IsNot, Specialize, Distinction};
///
/// impl<'a, T> IsNot<S2<'a, T>> for S1 {}
/// impl<U> IsNot<m::S3<U>> for S1 {}
///
/// impl<P> IsNot<P> for S1 where P: MyTrait {}
///
/// impl<'a, T> Specialize<S2<'a, T>> for S1 {
/// fn specialize(self) -> Distinction<S2<'a, T>, S1> {
/// Distinction::Generic(self)
/// }
/// }
/// impl<U> Specialize<m::S3<U>> for S1 {
/// fn specialize(self) -> Distinction<m::S3<U>, S1> {
/// Distinction::Generic(self)
/// }
/// }
/// impl Specialize<S1> for S1 {
/// fn specialize(self) -> Distinction<S1, S1> {
/// Distinction::Special(self)
/// }
/// }
///
/// impl<P> Specialize<P> for S1 where P: MyTrait {
/// fn specialize(self) -> Distinction<P, S1> {
/// Distinction::Generic(self)
/// }
/// }
///
/// my_macro!(impl trait for S1 {});
///
/// impl<'a, T> IsNot<S1> for S2<'a, T> {}
/// impl<'a, T, U> IsNot<m::S3<U>> for S2<'a, T> {}
///
/// impl<'a, T, P> IsNot<P> for S2<'a, T> where P: MyTrait {}
///
/// impl<'a, T> Specialize<S1> for S2<'a, T> {
/// fn specialize(self) -> Distinction<S1, S2<'a, T>> {
/// Distinction::Generic(self)
/// }
/// }
/// impl<'a, T, U> Specialize<m::S3<U>> for S2<'a, T> {
/// fn specialize(self) -> Distinction<m::S3<U>, S2<'a, T>> {
/// Distinction::Generic(self)
/// }
/// }
/// // Note: no `impl<'a, T> Specialize<S2<'a, T>> for S2<'a, T> { /* ... */ }`.
///
/// impl<'a, P, T> Specialize<P> for S2<'a, T> where P: MyTrait {
/// fn specialize(self) -> Distinction<P, S2<'a, T>> {
/// Distinction::Generic(self)
/// }
/// }
///
/// my_macro!(impl<'a, T> trait for S2<'a, T> {});
///
/// impl<U> IsNot<S1> for m::S3<U> {}
/// impl<'a, U, T> IsNot<S2<'a, T>> for m::S3<U> {}
///
/// impl<'a, U, P> IsNot<P> for m::S3<U> where P: MyTrait {}
///
/// impl<U> Specialize<S1> for m::S3<U> {
/// fn specialize(self) -> Distinction<S1, m::S3<U>> {
/// Distinction::Generic(self)
/// }
/// }
/// impl<'a, T, U> Specialize<S2<'a, T>> for m::S3<U> {
/// fn specialize(self) -> Distinction<S2<'a, T>, m::S3<U>> {
/// Distinction::Generic(self)
/// }
/// }
/// // Note: no `impl<U> Specialize<m::S3<U>> for m::S3<U> { /* ... */ }`.
///
/// impl<'a, P, U> Specialize<P> for m::S3<U> where P: MyTrait {
/// fn specialize(self) -> Distinction<P, m::S3<U>> {
/// Distinction::Generic(self)
/// }
/// }
///
/// my_macro!(impl<U> trait for m::S3<U> {});
///
/// ```
///
/// In this way, these types can be used e.g. in the following way:
/// ```
/// # } // HACK! Close the main function.
/// # // Let me know if there is a more elegant solution.
/// # mod hack { // Run the tests outside the main function.
/// # use syllogism_macro::impl_specialization;
/// # trait MyTrait {}
/// # struct S1 {}
/// # struct S2<'a, T> { _t: &'a T }
/// # mod m { pub struct S3<U> {_u: U} }
/// # impl_specialization!(trait MyTrait; type S1; type S2<'a, T>; type m::S3<U>);
/// use syllogism::{IsNot, Specialize, Distinction};
/// trait GenericTrait<T> {
/// fn generic_method(&mut self, by_value: T);
/// // ...
/// }
///
/// struct MyStruct {
/// // ...
/// }
///
/// impl GenericTrait<S1> for MyStruct {
/// // The implementation special for `S1`.
/// # fn generic_method(&mut self, by_value: S1) {
/// # }
/// }
///
/// impl<T> GenericTrait<T> for MyStruct
/// where T: syllogism::IsNot<S1> {
/// // The generic implementation.
/// // This can be used for `S2` and `S3` and types defined in other crates
/// // that implement `MyTrait`.
/// # fn generic_method(&mut self, by_value: T) {
/// # }
/// }
///
/// struct MyGenericStruct<T> {
/// // ...
/// # t: T
/// }
///
/// impl<T> GenericTrait<T> for MyGenericStruct<T>
/// where T: Specialize<S1> {
/// fn generic_method(&mut self, by_value: T) {
/// match by_value.specialize() {
/// Distinction::Special(s) => {
/// // `s` has type `S1` and can have a special treatment
/// },
/// Distinction::Generic(g) => {
/// // The generic implementation.
/// }
/// }
/// }
/// }
/// ```
#[proc_macro]
pub fn impl_specialization(token_stream: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(token_stream as TypeList);
let mut result = proc_macro2::TokenStream::new();
for type1_index in 0..parsed.types.len() {
let ty1 = &parsed.types[type1_index];
let impl_specialize_self_block = impl_specialize_self(&ty1);
result.append_all(impl_specialize_self_block);
for mcro in parsed.macros.iter() {
let macro_call = call_macro(ty1, mcro);
result.append_all(macro_call);
}
for trt in parsed.traits.iter() {
let impl_block = impl_isnot_trait(ty1, trt);
result.append_all(impl_block);
let impl_block = impl_specialize_trait(ty1, trt);
result.append_all(impl_block);
}
for type2_index in 0..parsed.types.len() {
if type1_index != type2_index {
let ty2 = &parsed.types[type2_index];
let isnot_block = impl_isnot_block(ty1, ty2);
result.append_all(isnot_block);
let specialize_block = impl_specialize_block_generic(ty1, ty2);
result.append_all(specialize_block);
}
}
}
result.into()
}