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
//! Macro to expand byte string and string literals
//!
//!
//! ## Usage
//!
//! ```
//! use expand::expand;
//!
//! // expanding a byte string
//! assert_eq!(
//!     &expand!([@b"Hello,", b' ', @b"world", b'!']),
//!     b"Hello, world!",
//! );
//!
//! // expanding a string
//! assert_eq!(
//!     expand!(vec![@"Hello,", ' ', @"world", '!']),
//!     "Hello, world!".chars().collect::<Vec<char>>(),
//! );
//!
//! // pattern matching
//! if let expand!([@b"patt", x, y, b'n', ..]) = b"pattern matching" {
//!     assert_eq!(x, &b'e');
//!     assert_eq!(y, &b'r');
//! } else {
//!     panic!("pattern matching failed");
//! }
//!
//! // more pattern matching
//! if let expand!([@b"msg = \"", xs @ .., b'"']) = br#"msg = "Hello, world!""# {
//!     assert_eq!(xs, b"Hello, world!");
//! } else {
//!     panic!("pattern matching failed");
//! }
//! ```
//!
//!
//! ## Changelog
//!
//! See [CHANGELOG.md](https://github.com/figsoda/expand/blob/main/CHANGELOG.md)

#![forbid(unsafe_code)]
#![no_std]

use proc_macro::{Group, Literal, Punct, Spacing, TokenStream, TokenTree};
use quote::quote_spanned;
use syn::{parse, LitByteStr, LitStr};

/// Expand byte string literals
///
/// Prefix a byte string or a string literal with a `@` to expand it
///
/// ## Examples
///
/// ### expanding a byte string
/// ```
/// # use expand::expand;
/// assert_eq!(
///     &expand!([@b"Hello,", b' ', @b"world", b'!']),
///     b"Hello, world!",
/// );
/// ```
///
/// ### expanding a string
/// ```
/// # use expand::expand;
/// assert_eq!(
///     expand!(vec![@"Hello,", ' ', @"world", '!']),
///     "Hello, world!".chars().collect::<Vec<char>>(),
/// );
/// ```
///
/// ### pattern matching
/// ```
/// # use expand::expand;
/// if let expand!([@b"patt", x, y, b'n', ..]) = b"pattern matching" {
///     assert_eq!(x, &b'e');
///     assert_eq!(y, &b'r');
/// } else {
///     panic!("pattern matching failed");
/// }
/// ```
///
/// ### more pattern matching
/// ``` rust
/// # use expand::expand;
/// if let expand!([@b"msg = \"", xs @ .., b'"']) = br#"msg = "Hello, world!""# {
///     assert_eq!(xs, b"Hello, world!");
/// } else {
///     panic!("pattern matching failed");
/// }
/// ```
#[proc_macro]
pub fn expand(input: TokenStream) -> TokenStream {
    let mut input = input.into_iter();
    let mut output = TokenStream::new();

    loop {
        match input.next() {
            Some(TokenTree::Group(t)) => {
                output.extend(Some(TokenTree::Group(Group::new(
                    t.delimiter(),
                    expand(t.stream()),
                ))));
            }

            Some(TokenTree::Punct(t)) if t == '@' => {
                let tt = if let Some(tt) = input.next() {
                    tt
                } else {
                    output.extend(Some(TokenTree::Punct(t)));
                    break;
                };

                if let Ok(t) = parse::<LitByteStr>(tt.clone().into()) {
                    let mut xs = t
                        .value()
                        .into_iter()
                        .map(Literal::u8_suffixed)
                        .map(TokenTree::Literal);

                    if let Some(x) = xs.next() {
                        output.extend(Some(x));
                    } else {
                        output.extend::<TokenStream>(
                            quote_spanned! { tt.span().into() =>
                                compile_error!("can't expand an empty byte string")
                            }
                            .into(),
                        );
                        break;
                    }

                    for x in xs {
                        output.extend([TokenTree::Punct(Punct::new(',', Spacing::Alone)), x]);
                    }
                } else if let Ok(t) = parse::<LitStr>(tt.clone().into()) {
                    let xs = t.value();
                    let mut xs = xs.chars().map(Literal::character).map(TokenTree::Literal);

                    if let Some(x) = xs.next() {
                        output.extend(Some(x));
                    } else {
                        output.extend::<TokenStream>(
                            quote_spanned! { tt.span().into() =>
                                compile_error!("can't expand an empty string")
                            }
                            .into(),
                        );
                        break;
                    }

                    for x in xs {
                        output.extend([TokenTree::Punct(Punct::new(',', Spacing::Alone)), x]);
                    }
                } else {
                    output.extend([TokenTree::Punct(t), tt]);
                    continue;
                }
            }

            Some(t) => {
                output.extend(Some(t));
            }

            None => break,
        }
    }

    output
}