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
//! # merge_whitespace
//!
//! This crate contains procedural macros for removing multiple consecutive whitespaces from a
//! given string literal, replacing them with a single space.
//!
//! ## Example
//!
//! ```
//! # use merge_whitespace::merge_whitespace;
//! const QUERY: &str = merge_whitespace!(r#"
//! query {
//! users (limit: 1) {
//! id
//! name
//! todos(order_by: {created_at: desc}, limit: 5) {
//! id
//! title
//! }
//! }
//! }
//! "#);
//!
//! assert_eq!(QUERY, "query { users (limit: 1) { id name todos(order_by: {created_at: desc}, limit: 5) { id title } } }");
//! ```
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, LitStr};
/// This is a procedural macro that removes multiple consecutive whitespaces from a given string
/// literal and replaces them with a single space.
///
/// ## Example
///
/// ```
/// # use merge_whitespace::merge_whitespace;///
/// let output = merge_whitespace!("Hello World!\r\n How are you?");
/// assert_eq!(output, "Hello World! How are you?");
/// ```
///
/// # Return
///
/// The macro expands to the modified string literal.
#[proc_macro]
pub fn merge_whitespace(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(input as LitStr);
// Get the string literal value
let input_str = input.value();
// Replace multiple whitespaces with a single space
let output_str = input_str.split_whitespace().collect::<Vec<_>>().join(" ");
// Generate the output tokens
let output = quote! {
#output_str
};
output.into()
}