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 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
//! The `typle` macro generates code for multiple tuple lengths. This code
//!
//! ```rust
//! use typle::typle;
//!
//! struct MyStruct<T> {
//! t: T,
//! }
//!
//! #[typle(Tuple for 0..=3)]
//! impl<T: Tuple> From<T> for MyStruct<T>
//! {
//! fn from(t: T) -> Self {
//! MyStruct { t }
//! }
//! }
//! ```
//!
//! generates implementations of the `From` trait for tuples with 0 to 3 components:
//! ```rust
//! # struct MyStruct<T> {
//! # t: T,
//! # }
//! impl From<()> for MyStruct<()> {
//! fn from(t: ()) -> Self {
//! MyStruct { t }
//! }
//! }
//!
//! impl<T0> From<(T0,)> for MyStruct<(T0,)> {
//! fn from(t: (T0,)) -> Self {
//! MyStruct { t }
//! }
//! }
//!
//! impl<T0, T1> From<(T0, T1)> for MyStruct<(T0, T1)> {
//! fn from(t: (T0, T1)) -> Self {
//! MyStruct { t }
//! }
//! }
//!
//! impl<T0, T1, T2> From<(T0, T1, T2)> for MyStruct<(T0, T1, T2)> {
//! fn from(t: (T0, T1, T2)) -> Self {
//! MyStruct { t }
//! }
//! }
//! ```
//!
//! Inside `typle` code, individual components of a tuple can be selected using
//! `<{i}>` for types and `[[i]]` for values. The value `i` must be a *typle
//! index expression*, an expression that only uses literal `usize` values or
//! *typle indexes* created by one of several macros.
//!
//! The [`typle_for!`] macro creates a new tuple type or value. Inside the macro
//! the typle index can provide access to each component of an existing tuple
//! type or value.
//!
//! ```rust
//! # use typle::typle;
//! // Split off the first component
//! #[typle(Tuple for 1..=12)]
//! fn split<T: Tuple>(
//! t: T // t: (T0, T1, T2,...)
//! ) -> (T<0>, typle_for!(i in 1.. => T<{i}>)) // (T0, (T1, T2,...))
//! {
//! (t[[0]], typle_for!(i in 1.. => t[[i]])) // (t.0, (t.1, t.2,...))
//! }
//!
//! assert_eq!(split(('1', 2, 3.0)), ('1', (2, 3.0)));
//! assert_eq!(split((2, 3.0)), (2, (3.0,)));
//! assert_eq!(split((3.0,)), (3.0, ()));
//! ```
//! Specify constraints on the tuple components using one of the following
//! forms. Except for the first form, these constraints can only appear in the
//! `where` clause.
//! - `T: Tuple<C>` - each component of the tuple has type `C`
//! - `T<_>: Copy` - each component of the tuple implements `Copy`
//! - `T<0>: Copy` - the first component of the tuple implements `Copy`
//! - `T<{1..=2}>: Copy` - the second and third components implement `Copy`
//! - `typle_bound!` - the most general way to bound components,
//! allowing the typle index to be used in the trait bounds, as shown below:
//!
//! ```rust
//! # use typle::typle;
//! use std::{ops::Mul, time::Duration};
//!
//! // Multiply the components of two tuples
//! #[typle(Tuple for 0..=12)]
//! fn multiply<S: Tuple, T: Tuple>(
//! s: S, // s: (S0,...)
//! t: T, // t: (T0,...)
//! ) -> typle_for!(i in .. => <S<{i}> as Mul<T<{i}>>>::Output) // (<S0 as Mul<T0>>::Output,...)
//! where
//! typle_bound!(i in .. => S<{i}>): Mul<T<{i}>>, // S0: Mul<T0>,...
//! {
//! typle_for!(i in .. => s[[i]] * t[[i]]) // (s.0 * t.0,...)
//! }
//!
//! assert_eq!(
//! multiply((Duration::from_secs(5), 2), (4, 3)),
//! (Duration::from_secs(20), 6)
//! )
//! ```
//!
//! The associated constant `LEN` provides the length of the tuple in each
//! generated item. It can be used as a typle index.
//!
//! Use the `typle_index!` macro in a `for` loop to iterate over a range bounded
//! by typle index expressions.
//!
//! ```rust
//! # use typle::typle;
//! # struct MyStruct<T> {
//! # t: T,
//! # }
//! # impl<T0, T1, T2> From<(T0, T1, T2)> for MyStruct<(T0, T1, T2)> {
//! # fn from(t: (T0, T1, T2)) -> Self {
//! # MyStruct { t }
//! # }
//! # }
//! #[typle(Tuple for 1..=3)]
//! impl<T, C> MyStruct<T>
//! where
//! T: Tuple<C>,
//! C: for<'a> std::ops::AddAssign<&'a C> + Default,
//! {
//! // Return the sums of all odd positions and all even positions.
//! fn interleave(&self) -> [C; 2] {
//! let mut odd_even = [C::default(), C::default()];
//! for typle_index!(i) in 0..T::LEN {
//! odd_even[i % 2] += &self.t[[i]];
//! }
//! odd_even
//! }
//! }
//!
//! let m = MyStruct::from((3, 9, 11));
//! assert_eq!(m.interleave(), [14, 9]);
//! ```
//!
//! The next example is simplified from code in the
//! [`hefty`](https://github.com/jongiddy/hefty/blob/main/src/tuple.rs) crate and
//! demonstrates the use of `typle` with `enum`s.
//!
//! The [`typle_variant!`] macro creates multiple enum variants by looping
//! similarly to `typle_for!`.
//!
//! Typled `enum`s and `struct`s require a separate identifier for each tuple
//! length. The `typle` macro adds the tuple length to their original name. For
//! example `enum TupleSequenceState<T>` expands to `enum TupleSequenceState3<T0, T1, T2>`
//! for 3-tuples. When referring to these types from other typled items, use
//! `TupleSequenceState<T<{ .. }>>`.
//!
//! Use the `typle_ident!` macro to concatenate a number to an identifier. For
//! example `S::<typle_ident!(3)>` becomes the identifer `S3`.
//!
//! The `typle_attr_if` attribute allows conditional inclusion of attributes. It works similarly to
//! [`cfg_attr`](https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute)
//! except that the first argument is a boolean typle index expression.
//!
//! The `typle_const!` macro supports const-if on a boolean typle index
//! expression. const-if allows branches that do not compile, as long as they
//! are `false` at compile-time. For example, this code compiles when
//! `i + 1 == T::LEN` even though the identifier `S::<typle_ident!(T::LEN)>`
//! (`S3` for 3-tuples) is not defined.
//!
//! ```rust
//! use typle::typle;
//!
//! #[typle(Tuple for 1..=12)]
//! mod tuple {
//! pub trait Extract {
//! type State;
//! type Output;
//!
//! fn extract(&self, state: Option<Self::State>) -> Self::Output;
//! }
//!
//! pub enum TupleSequenceState<T>
//! where
//! T: Tuple,
//! T<_>: Extract,
//! {
//! S = typle_variant!(i in .. =>
//! typle_for!(j in ..i => T::<{j}>::Output),
//! Option<T<{i}>::State>
//! ),
//! }
//!
//! pub struct TupleSequence<T> {
//! tuple: T,
//! }
//!
//! impl<T> Extract for TupleSequence<T>
//! where
//! T: Tuple,
//! T<_>: Extract,
//! {
//! type State = TupleSequenceState<T<{ .. }>>;
//! type Output = typle_for!(i in .. => T<{i}>::Output);
//!
//! fn extract(&self, state: Option<Self::State>) -> Self::Output {
//! #[typle_attr_if(T::LEN == 1, allow(unused_mut))]
//! let mut state = state.unwrap_or(Self::State::S::<typle_ident!(0)>((), None));
//! for typle_index!(i) in 0..T::LEN {
//! // For LEN = 1 there is only one variant (S0) so `let` is irrefutable
//! #[typle_attr_if(T::LEN == 1, allow(irrefutable_let_patterns, unused_variables))]
//! if let Self::State::S::<typle_ident!(i)>(output, inner_state) = state {
//! let matched = self.tuple[[i]].extract(inner_state);
//! let output = typle_for!(j in ..=i =>
//! if typle_const!(j != i) { output[[j]] } else { matched }
//! );
//! if typle_const!(i + 1 == T::LEN) {
//! return output;
//! } else {
//! state = Self::State::S::<typle_ident!(i + 1)>(output, None);
//! }
//! }
//! }
//! unreachable!();
//! }
//! }
//! }
//! ```
//!
//! Generated implementation for 3-tuples:
//! ```rust
//! # pub trait Extract {
//! # type State;
//! # type Output;
//! # fn extract(&self, state: Option<Self::State>) -> Self::Output;
//! # }
//! # pub struct TupleSequence<T> {
//! # tuple: T,
//! # }
//! pub enum TupleSequenceState3<T0, T1, T2>
//! where
//! T0: Extract,
//! T1: Extract,
//! T2: Extract,
//! {
//! S0((), Option<<T0>::State>),
//! S1((<T0>::Output,), Option<<T1>::State>),
//! S2((<T0>::Output, <T1>::Output), Option<<T2>::State>),
//! }
//!
//! impl<T0, T1, T2> Extract for TupleSequence<(T0, T1, T2)>
//! where
//! T0: Extract,
//! T1: Extract,
//! T2: Extract,
//! {
//! type State = TupleSequenceState3<T0, T1, T2>;
//! type Output = (<T0>::Output, <T1>::Output, <T2>::Output);
//!
//! fn extract(&self, state: Option<Self::State>) -> Self::Output {
//! let mut state = state.unwrap_or(Self::State::S0((), None));
//! {
//! {
//! if let Self::State::S0(output, inner_state) = state {
//! let matched = self.tuple.0.extract(inner_state);
//! let output = ({ matched },);
//! {
//! state = Self::State::S1(output, None);
//! }
//! }
//! }
//! {
//! if let Self::State::S1(output, inner_state) = state {
//! let matched = self.tuple.1.extract(inner_state);
//! let output = ({ output.0 }, { matched });
//! {
//! state = Self::State::S2(output, None);
//! }
//! }
//! }
//! {
//! if let Self::State::S2(output, inner_state) = state {
//! let matched = self.tuple.2.extract(inner_state);
//! let output = ({ output.0 }, { output.1 }, { matched });
//! {
//! return output;
//! }
//! }
//! }
//! ()
//! }
//! unreachable!();
//! }
//! }
//! ```
//!
//! # Limitations
//!
//! - The typle trait (`Tuple` in the examples) cannot be combined with other constraints. To
//! support `?Sized` tuples constrain the last component using `T<{T::LEN - 1}>: ?Sized`.
//! - Standalone `async` and `unsafe` functions are not supported.
//! - Standalone functions require explicit lifetimes on references
//! ```rust
//! # use std::hash::{Hash, Hasher};
//! # use typle::typle;
//! #[typle(Tuple for 1..=3)]
//! pub fn hash<'a, T, S: Hasher>(tuple: &'a T, state: &'a mut S)
//! where
//! T: Tuple,
//! T<_>: Hash,
//! T<{T::LEN - 1}>: ?Sized,
//! {
//! for typle_index!(i) in 0..T::LEN {
//! tuple[[i]].hash(state);
//! }
//! }
//! ```
//! - Shadowing of typle indexes is not supported. For example, in:
//! ```rust ignore
//! for typle_index!(i) in 2..=3 {
//! let i = 1;
//! func(i)
//! }
//! ```
//! `func` will be called with 2 and 3, never with 1. The same is true for other places where typle
//! indexes are introduced. For example in a `typle_for!` macro.
//! - A `continue` referencing a label on a `for` loop using `typle_index!` works but displays an
//! [unsuppressible warning](https://github.com/rust-lang/rust/issues/31745) during compilation.
//! ```rust ignore
//! // warning: label name `'cont` shadows a label name that is already in scope
//! 'cont: for typle_index!(i) in 2..=3 {
//! loop {
//! if typle_const!(i == 2) {
//! continue 'cont;
//! }
//! break;
//! }
//! }
//! ```
mod constant;
mod specific;
use std::collections::HashMap;
use constant::evaluate_usize;
use proc_macro2::{Ident, Span, TokenStream, TokenTree};
use proc_macro_error::{abort, abort_call_site, proc_macro_error};
use quote::{format_ident, ToTokens};
use specific::{ident_to_path, BlockState, SpecificContext};
use syn::punctuated::Punctuated;
use syn::{parse_quote, token, Expr, GenericParam, Generics, Item, ItemImpl, Pat, TypeParam};
#[doc(hidden)]
#[proc_macro]
pub fn typle_identity(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
item
}
#[doc(hidden)]
#[proc_macro_error]
#[proc_macro_attribute]
pub fn typle(
args: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let iteration_trait = parse_args(TokenStream::from(args));
let Ok(item) = syn::parse::<Item>(item) else {
abort_call_site!("unsupported tokens");
};
let mut output = Vec::new();
output.extend(iteration_trait.process_item(item));
output
.into_iter()
.map(Item::into_token_stream)
.collect::<TokenStream>()
.into()
}
#[derive(Clone)]
struct IterationTrait {
ident: Ident,
min_len: usize,
max_len: usize,
}
fn parse_args(args: TokenStream) -> IterationTrait {
// #[typle(Tuple for 2..=12)]
let mut args_iter = args.into_iter();
// Tuple
let Some(TokenTree::Ident(trait_ident)) = args_iter.next() else {
abort_call_site!("expected identifier");
};
// for
match args_iter.next() {
Some(TokenTree::Ident(for_ident)) if for_ident == "for" => {}
_ => {
abort_call_site!("expected for keyword");
}
}
// 2..=12
let rest = args_iter.collect();
let range = syn::parse2::<syn::ExprRange>(rest).unwrap_or_else(|e| abort_call_site!("{}", e));
let min = range
.start
.as_ref()
.map(|expr| evaluate_usize(&expr).unwrap_or_else(|| abort!(expr, "range start invalid")))
.unwrap_or_else(|| abort!(range, "range start must be bounded"));
let end = range
.end
.as_ref()
.unwrap_or_else(|| abort!(range, "range end must be bounded"));
let max = match range.limits {
syn::RangeLimits::HalfOpen(_) => evaluate_usize(&end)
.and_then(|max| max.checked_sub(1))
.unwrap_or_else(|| abort!(end, "range end invalid")),
syn::RangeLimits::Closed(_) => {
evaluate_usize(&end).unwrap_or_else(|| abort!(end, "range end invalid"))
}
};
if max < min {
abort!(range, "range contains no values");
}
IterationTrait {
ident: trait_ident,
min_len: min,
max_len: max,
}
}
impl IterationTrait {
fn process_item(&self, item: Item) -> Vec<Item> {
let mut output = Vec::new();
match item {
Item::Const(syn::ItemConst { ref generics, .. })
| Item::Enum(syn::ItemEnum { ref generics, .. })
| Item::Impl(syn::ItemImpl { ref generics, .. })
| Item::Struct(syn::ItemStruct { ref generics, .. })
| Item::Trait(syn::ItemTrait { ref generics, .. })
| Item::TraitAlias(syn::ItemTraitAlias { ref generics, .. })
| Item::Type(syn::ItemType { ref generics, .. })
| Item::Union(syn::ItemUnion { ref generics, .. }) => {
if self.has_typles(generics) {
for typle_len in self.min_len..=self.max_len {
let context = SpecificContext {
typle_trait: &self.ident,
typle_len,
constants: HashMap::new(),
typles: HashMap::new(),
};
let mut item = item.clone();
let mut state = BlockState::default();
context.replace_item(&mut item, true, &mut state);
output.push(item);
}
} else {
output.push(item);
}
}
Item::Fn(function) => {
let generics = &function.sig.generics;
if self.has_typles(generics) {
let fn_name = &function.sig.ident;
let fn_meta = &function.attrs;
let fn_vis = &function.vis;
let trait_name = format_ident!("_typle_fn_{}", fn_name);
let fn_type_params = &function.sig.generics.params;
let fn_type_params_no_constraints = remove_constraints(fn_type_params);
let fn_input_params = &function.sig.inputs;
let mut type_tuple = syn::TypeTuple {
paren_token: token::Paren::default(),
elems: Punctuated::new(),
};
let mut pat_tuple = syn::PatTuple {
attrs: Vec::new(),
paren_token: token::Paren::default(),
elems: Punctuated::new(),
};
let mut value_tuple = syn::ExprTuple {
attrs: Vec::new(),
paren_token: token::Paren::default(),
elems: Punctuated::new(),
};
for arg in fn_input_params {
match arg {
syn::FnArg::Receiver(_) => abort!(arg, "unexpected self"),
syn::FnArg::Typed(pat_type) => {
type_tuple.elems.push(pat_type.ty.as_ref().clone());
pat_tuple.elems.push(pat_type.pat.as_ref().clone());
value_tuple
.elems
.push(pat_to_tuple(pat_type.pat.as_ref().clone()));
}
}
}
let trait_item = parse_quote!(
#[allow(non_camel_case_types)]
#fn_vis trait #trait_name {
type Return;
fn apply(self) -> Self::Return;
}
);
output.push(trait_item);
let fn_item = parse_quote!(
#(#fn_meta)*
#fn_vis fn #fn_name <#fn_type_params_no_constraints>(#fn_input_params) -> <#type_tuple as #trait_name>::Return
where
#type_tuple: #trait_name,
{
<#type_tuple as #trait_name>::apply(#value_tuple)
}
);
output.push(fn_item);
let return_type = match function.sig.output {
syn::ReturnType::Default => parse_quote!(()),
syn::ReturnType::Type(_, t) => *t,
};
let fn_body = function.block;
let let_stmt: syn::Stmt = if self.min_len == 0 {
parse_quote!(
#[allow(unused_variables)]
let #pat_tuple = self;
)
} else {
parse_quote!(let #pat_tuple = self;)
};
let items = vec![
syn::ImplItem::Type(syn::ImplItemType {
attrs: Vec::new(),
vis: syn::Visibility::Inherited,
defaultness: None,
type_token: token::Type::default(),
ident: Ident::new("Return", Span::call_site()),
generics: Generics::default(),
eq_token: token::Eq::default(),
ty: return_type,
semi_token: token::Semi::default(),
}),
parse_quote!(
fn apply(self) -> Self::Return {
#let_stmt
#fn_body
}
),
];
let item = Item::Impl(ItemImpl {
attrs: Vec::new(),
defaultness: None,
unsafety: None,
impl_token: token::Impl::default(),
generics: function.sig.generics,
trait_: Some((None, ident_to_path(trait_name), token::For::default())),
self_ty: Box::new(syn::Type::Tuple(type_tuple)),
brace_token: token::Brace::default(),
items,
});
for typle_len in self.min_len..=self.max_len {
let context = SpecificContext {
typle_trait: &self.ident,
typle_len,
constants: HashMap::new(),
typles: HashMap::new(),
};
let mut item = item.clone();
let mut state = BlockState::default();
context.replace_item(&mut item, true, &mut state);
output.push(item);
}
} else {
output.push(Item::Fn(function));
}
}
Item::Mod(mut module) => {
if let Some((_, items)) = &mut module.content {
for item in std::mem::take(items) {
items.extend(self.process_item(item));
}
}
output.push(Item::Mod(module));
}
item => {
output.push(item);
}
}
output
}
fn has_typles(&self, generics: &Generics) -> bool {
for param in &generics.params {
if let GenericParam::Type(type_param) = param {
for bound in &type_param.bounds {
if let syn::TypeParamBound::Trait(trait_bound) = bound {
let trait_path = &trait_bound.path;
if trait_path.leading_colon.is_none()
&& trait_path.segments.len() == 1
&& trait_path.segments[0].ident == self.ident
{
return true;
}
}
}
}
}
if let Some(where_clause) = &generics.where_clause {
for predicate in &where_clause.predicates {
if let syn::WherePredicate::Type(predicate_type) = predicate {
for bound in &predicate_type.bounds {
if let syn::TypeParamBound::Trait(trait_bound) = bound {
let trait_path = &trait_bound.path;
if trait_path.leading_colon.is_none()
&& trait_path.segments.len() == 1
&& trait_path.segments[0].ident == self.ident
{
return true;
}
}
}
}
}
}
false
}
}
fn remove_constraints(
fn_type_params: &Punctuated<GenericParam, token::Comma>,
) -> Punctuated<GenericParam, token::Comma> {
let mut output = Punctuated::new();
for param in fn_type_params.into_iter() {
if let GenericParam::Type(ref type_param) = param {
output.push(GenericParam::Type(TypeParam {
bounds: Punctuated::new(),
..type_param.clone()
}));
} else {
output.push(param.clone());
}
}
output
}
fn pat_to_tuple(pat: Pat) -> Expr {
match pat {
Pat::Const(p) => Expr::Const(p),
Pat::Ident(p) => Expr::Path(syn::ExprPath {
attrs: p.attrs,
qself: None,
path: ident_to_path(p.ident),
}),
Pat::Lit(p) => Expr::Lit(p),
Pat::Macro(p) => Expr::Macro(p),
Pat::Or(_) => todo!(),
Pat::Paren(_) => todo!(),
Pat::Path(_) => todo!(),
Pat::Range(_) => todo!(),
Pat::Reference(_) => todo!(),
Pat::Rest(_) => todo!(),
Pat::Slice(_) => todo!(),
Pat::Struct(_) => todo!(),
Pat::Tuple(p) => Expr::Tuple(syn::ExprTuple {
attrs: p.attrs,
paren_token: p.paren_token,
elems: p.elems.into_iter().map(pat_to_tuple).collect(),
}),
Pat::TupleStruct(_) => todo!(),
Pat::Type(_) => todo!(),
Pat::Verbatim(_) => todo!(),
Pat::Wild(_) => todo!(),
_ => todo!(),
}
}
/// Create a tuple or array.
///
/// Loop over the indices of the tuple, performing the expression for each index.
///
/// If the macro uses parentheses, the returned value is a tuple. If the macro uses brackets, the
/// returned value is an array.
///
/// With parentheses, this macro can be used in type or value position.
///
/// Examples:
/// ```ignore
/// #[typle(Tuple for 0..=2)]
/// impl<T> S<T<{ .. }>>
/// where
/// T: Tuple<u32>
/// {
/// fn new(t: typle_for!(i in .. => &T<{i}>)) {
/// // Square brackets create an array
/// let a = typle_for![i in 0..T::LEN => *t[[i]] * 2];
/// // Parentheses create a tuple
/// // The default bounds of the range are 0..Tuple::LEN
/// let b = typle_for!(i in .. => *t[[i]] * 2);
/// // Arbitrary expressions can be used for the indices and
/// // the iterator variable can be left out if not needed
/// let init: [Option<u32>; T::LEN] = typle_for![T::LEN * 2..T::LEN * 3 => None];
/// }
/// }
/// ```
/// generates
/// ```ignore
/// impl S0 {
/// fn new(t: ()) {
/// let a = [];
/// let b = ();
/// let init: [Option<u32>; 0] = [];
/// }
/// }
/// impl S1<u32> {
/// fn new(t: (&u32,)) {
/// let a = [*t.0 * 2];
/// let b = (*t.0 * 2,);
/// let init: [Option<u32>; 1] = [None];
/// }
/// }
/// impl S2<u32, u32> {
/// fn new(t: (&u32, &u32)) {
/// let a = [*t.0 * 2, *t.1 * 2];
/// let b = (*t.0 * 2, *t.1 * 2);
/// let init: [Option<u32>; 2] = [None, None];
/// }
/// }
/// ```
#[proc_macro_error]
#[proc_macro]
pub fn typle_for(_item: proc_macro::TokenStream) -> proc_macro::TokenStream {
abort_call_site!("typle_variant macro only available in item with typle attribute");
}
/// Create variants in an enum.
///
/// In an enum, the `typle_variant` macro allows the creation of variants for each component.
///
/// A variant is created for each index in the range provided. The default range is `0..Tuple::LEN`.
///
/// The variants will start with the variant name given before the `=` character, followed by the
/// index.
///
/// If the macro uses parentheses the variant will use unnamed fields. If the macro uses braces the
/// variant will use named fields. If the macro uses brackets the variant will have no fields.
///
/// Examples:
///
/// ```
/// # use typle::typle;
/// # trait Process {
/// # type State;
/// # }
/// #[typle(Tuple for 2..=2)]
/// pub enum ProcessState<T>
/// where
/// T: Tuple,
/// T<_>: Process,
/// {
/// Q = typle_variant![..],
/// R = typle_variant!{i in 0..T::LEN => r: T<{i}>},
/// S = typle_variant!(i in .. => Option<T<{i}>::State>, [u64; i]),
/// Done([u64; Tuple::LEN])
/// }
/// ```
/// creates
/// ```
/// # trait Process {
/// # type State;
/// # }
/// pub enum ProcessState2<T0, T1>
/// where
/// T0: Process,
/// T1: Process,
/// {
/// Q0,
/// Q1,
/// R0 { r: T0 },
/// R1 { r: T1 },
/// S0(Option<<T0>::State>, [u64; 0]),
/// S1(Option<<T1>::State>, [u64; 1]),
/// Done([u64; 2]),
/// }
/// ```
#[proc_macro_error]
#[proc_macro]
pub fn typle_variant(_item: proc_macro::TokenStream) -> proc_macro::TokenStream {
abort_call_site!("typle_variant macro only available in item with typle attribute");
}