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
#![doc(html_root_url = "https://docs.rs/fast_tuple/0.1.3/")]
#![no_std]

//! This procedural macro crate serves the purporse of construct a tuple thought the array-like [T; N] syntax,where T can be a type
//! for annotate or an expression and N is the number of times T repeats. 
//!
//! This macro is **no_std** with debug assertions disabled.

extern crate alloc;
extern crate proc_macro;

#[cfg(debug_assertions)]
extern crate std;

use alloc::string::{String, ToString};
use proc_macro::TokenStream;

/// A tuple array-like constructor tuple!(T; N).
///
/// See [crate docs](./index.html) for more details.
///
/// # Errors
/// 
/// All the failures of this macro throw crate-defined compiler errors. In addition,when debug assertions are enabled
/// the tuples with N longer than 12 will print a error message warning that the standard library traits will not be auto-implemented.
#[proc_macro]
pub fn tuple(ts: TokenStream) -> TokenStream {
    let ts = ts.to_string();
    let mut expansion = String::new();

    let index = ts.rfind(";").unwrap_or_else(|| {
        expansion.push_str("compile_error!(\"Expression does not hold any `;`\")");
        0
    });

    if expansion != "" {
        return expansion.parse().unwrap();
    }

    if index == 0 {
        return String::from("compile_error!(\"Expected expression or type behind the `;` but there's no one\")").parse().unwrap();
    }

    let (mut value, mut arity) = ts.split_at(index);
    value = value.trim();
    arity = &arity[1..];
    arity = arity.trim();

    let arity: usize = arity.parse().unwrap_or_else(|_| {
        expansion.push_str("compile_error!(\"Invalid numeric constant after `;`\")");
        0
    });

    if expansion != "" {
        return expansion.parse().unwrap();
    }

    if arity == 0 {
        return String::from("compile_error!(\"The length cannot be zero use `()` instead\")").parse().unwrap();
    }

    if cfg!(debug_assertions) && arity > 12 {
        std::eprintln!("tuples of arity of more than 12({}) has no standard traits implemented, this message is only show with debug_assertions enabled.", arity);
    }

    expansion.reserve(value.len()*arity + arity + 1);

    expansion.push_str("(");

    for _ in 0..arity - 1 {
        expansion.push_str(value);
        expansion.push_str(",");
    }

    expansion.push_str(value);
    expansion.push_str(")");

    expansion.parse().unwrap()
}