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
//! [![github]](https://github.com/dtolnay/indoc) [![crates-io]](https://crates.io/crates/indoc) [![docs-rs]](https://docs.rs/indoc)
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! <br>
//!
//! This crate provides a procedural macro for indented string literals. The
//! `indoc!()` macro takes a multiline string literal and un-indents it at
//! compile time so the leftmost non-space character is in the first column.
//!
//! ```toml
//! [dependencies]
//! indoc = "2"
//! ```
//!
//! <br>
//!
//! # Using indoc
//!
//! ```
//! use indoc::indoc;
//!
//! fn main() {
//!     let testing = indoc! {"
//!         def hello():
//!             print('Hello, world!')
//!
//!         hello()
//!     "};
//!     let expected = "def hello():\n    print('Hello, world!')\n\nhello()\n";
//!     assert_eq!(testing, expected);
//! }
//! ```
//!
//! Indoc also works with raw string literals:
//!
//! ```
//! use indoc::indoc;
//!
//! fn main() {
//!     let testing = indoc! {r#"
//!         def hello():
//!             print("Hello, world!")
//!
//!         hello()
//!     "#};
//!     let expected = "def hello():\n    print(\"Hello, world!\")\n\nhello()\n";
//!     assert_eq!(testing, expected);
//! }
//! ```
//!
//! And byte string literals:
//!
//! ```
//! use indoc::indoc;
//!
//! fn main() {
//!     let testing = indoc! {b"
//!         def hello():
//!             print('Hello, world!')
//!
//!         hello()
//!     "};
//!     let expected = b"def hello():\n    print('Hello, world!')\n\nhello()\n";
//!     assert_eq!(testing[..], expected[..]);
//! }
//! ```
//!
//! <br><br>
//!
//! # Formatting macros
//!
//! The indoc crate exports five additional macros to substitute conveniently
//! for the standard library's formatting macros:
//!
//! - `formatdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `format!(indoc!($fmt), ...)`
//! - `printdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `print!(indoc!($fmt), ...)`
//! - `eprintdoc!($fmt, ...)`&ensp;&mdash;&ensp;equivalent to `eprint!(indoc!($fmt), ...)`
//! - `writedoc!($dest, $fmt, ...)`&ensp;&mdash;&ensp;equivalent to `write!($dest, indoc!($fmt), ...)`
//! - `concatdoc!(...)`&ensp;&mdash;&ensp;equivalent to `concat!(...)` with each string literal wrapped in `indoc!`
//!
//! ```
//! # macro_rules! env {
//! #     ($var:literal) => {
//! #         "example"
//! #     };
//! # }
//! #
//! use indoc::{concatdoc, printdoc};
//!
//! const HELP: &str = concatdoc! {"
//!     Usage: ", env!("CARGO_BIN_NAME"), " [options]
//!
//!     Options:
//!         -h, --help
//! "};
//!
//! fn main() {
//!     printdoc! {"
//!         GET {url}
//!         Accept: {mime}
//!         ",
//!         url = "http://localhost:8080",
//!         mime = "application/json",
//!     }
//! }
//! ```
//!
//! <br><br>
//!
//! # Explanation
//!
//! The following rules characterize the behavior of the `indoc!()` macro:
//!
//! 1. Count the leading spaces of each line, ignoring the first line and any
//!    lines that are empty or contain spaces only.
//! 2. Take the minimum.
//! 3. If the first line is empty i.e. the string begins with a newline, remove
//!    the first line.
//! 4. Remove the computed number of spaces from the beginning of each line.

#![doc(html_root_url = "https://docs.rs/indoc/2.0.5")]
#![allow(
    clippy::derive_partial_eq_without_eq,
    clippy::from_iter_instead_of_collect,
    clippy::module_name_repetitions,
    clippy::needless_doctest_main,
    clippy::needless_pass_by_value,
    clippy::trivially_copy_pass_by_ref,
    clippy::type_complexity
)]

mod error;
mod expr;
mod unindent;

use crate::error::{Error, Result};
use crate::unindent::do_unindent;
use proc_macro::token_stream::IntoIter as TokenIter;
use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
use std::iter::{self, Peekable};
use std::str::FromStr;

#[derive(Copy, Clone, PartialEq)]
enum Macro {
    Indoc,
    Format,
    Print,
    Eprint,
    Write,
    Concat,
}

/// Unindent and produce `&'static str` or `&'static [u8]`.
///
/// Supports normal strings, raw strings, bytestrings, and raw bytestrings.
///
/// # Example
///
/// ```
/// # use indoc::indoc;
/// #
/// // The type of `program` is &'static str
/// let program = indoc! {"
///     def hello():
///         print('Hello, world!')
///
///     hello()
/// "};
/// print!("{}", program);
/// ```
///
/// ```text
/// def hello():
///     print('Hello, world!')
///
/// hello()
/// ```
#[proc_macro]
pub fn indoc(input: TokenStream) -> TokenStream {
    expand(input, Macro::Indoc)
}

/// Unindent and call `format!`.
///
/// Argument syntax is the same as for [`std::format!`].
///
/// # Example
///
/// ```
/// # use indoc::formatdoc;
/// #
/// let request = formatdoc! {"
///     GET {url}
///     Accept: {mime}
///     ",
///     url = "http://localhost:8080",
///     mime = "application/json",
/// };
/// println!("{}", request);
/// ```
///
/// ```text
/// GET http://localhost:8080
/// Accept: application/json
/// ```
#[proc_macro]
pub fn formatdoc(input: TokenStream) -> TokenStream {
    expand(input, Macro::Format)
}

/// Unindent and call `print!`.
///
/// Argument syntax is the same as for [`std::print!`].
///
/// # Example
///
/// ```
/// # use indoc::printdoc;
/// #
/// printdoc! {"
///     GET {url}
///     Accept: {mime}
///     ",
///     url = "http://localhost:8080",
///     mime = "application/json",
/// }
/// ```
///
/// ```text
/// GET http://localhost:8080
/// Accept: application/json
/// ```
#[proc_macro]
pub fn printdoc(input: TokenStream) -> TokenStream {
    expand(input, Macro::Print)
}

/// Unindent and call `eprint!`.
///
/// Argument syntax is the same as for [`std::eprint!`].
///
/// # Example
///
/// ```
/// # use indoc::eprintdoc;
/// #
/// eprintdoc! {"
///     GET {url}
///     Accept: {mime}
///     ",
///     url = "http://localhost:8080",
///     mime = "application/json",
/// }
/// ```
///
/// ```text
/// GET http://localhost:8080
/// Accept: application/json
/// ```
#[proc_macro]
pub fn eprintdoc(input: TokenStream) -> TokenStream {
    expand(input, Macro::Eprint)
}

/// Unindent and call `write!`.
///
/// Argument syntax is the same as for [`std::write!`].
///
/// # Example
///
/// ```
/// # use indoc::writedoc;
/// # use std::io::Write;
/// #
/// let _ = writedoc!(
///     std::io::stdout(),
///     "
///         GET {url}
///         Accept: {mime}
///     ",
///     url = "http://localhost:8080",
///     mime = "application/json",
/// );
/// ```
///
/// ```text
/// GET http://localhost:8080
/// Accept: application/json
/// ```
#[proc_macro]
pub fn writedoc(input: TokenStream) -> TokenStream {
    expand(input, Macro::Write)
}

/// Unindent and call `concat!`.
///
/// Argument syntax is the same as for [`std::concat!`].
///
/// # Example
///
/// ```
/// # use indoc::concatdoc;
/// #
/// # macro_rules! env {
/// #     ($var:literal) => {
/// #         "example"
/// #     };
/// # }
/// #
/// const HELP: &str = concatdoc! {"
///     Usage: ", env!("CARGO_BIN_NAME"), " [options]
///
///     Options:
///         -h, --help
/// "};
///
/// print!("{}", HELP);
/// ```
///
/// ```text
/// Usage: example [options]
///
/// Options:
///     -h, --help
/// ```
#[proc_macro]
pub fn concatdoc(input: TokenStream) -> TokenStream {
    expand(input, Macro::Concat)
}

fn expand(input: TokenStream, mode: Macro) -> TokenStream {
    match try_expand(input, mode) {
        Ok(tokens) => tokens,
        Err(err) => err.to_compile_error(),
    }
}

fn try_expand(input: TokenStream, mode: Macro) -> Result<TokenStream> {
    let mut input = input.into_iter().peekable();

    let prefix = match mode {
        Macro::Indoc | Macro::Format | Macro::Print | Macro::Eprint => None,
        Macro::Write => {
            let require_comma = true;
            let mut expr = expr::parse(&mut input, require_comma)?;
            expr.extend(iter::once(input.next().unwrap())); // add comma
            Some(expr)
        }
        Macro::Concat => return do_concat(input),
    };

    let first = input.next().ok_or_else(|| {
        Error::new(
            Span::call_site(),
            "unexpected end of macro invocation, expected format string",
        )
    })?;

    let preserve_empty_first_line = false;
    let unindented_lit = lit_indoc(first, mode, preserve_empty_first_line)?;

    let macro_name = match mode {
        Macro::Indoc => {
            require_empty_or_trailing_comma(&mut input)?;
            return Ok(TokenStream::from(TokenTree::Literal(unindented_lit)));
        }
        Macro::Format => "format",
        Macro::Print => "print",
        Macro::Eprint => "eprint",
        Macro::Write => "write",
        Macro::Concat => unreachable!(),
    };

    // #macro_name! { #unindented_lit #args }
    Ok(TokenStream::from_iter(vec![
        TokenTree::Ident(Ident::new(macro_name, Span::call_site())),
        TokenTree::Punct(Punct::new('!', Spacing::Alone)),
        TokenTree::Group(Group::new(
            Delimiter::Brace,
            prefix
                .unwrap_or_else(TokenStream::new)
                .into_iter()
                .chain(iter::once(TokenTree::Literal(unindented_lit)))
                .chain(input)
                .collect(),
        )),
    ]))
}

fn do_concat(mut input: Peekable<TokenIter>) -> Result<TokenStream> {
    let mut result = TokenStream::new();
    let mut first = true;

    while input.peek().is_some() {
        let require_comma = false;
        let mut expr = expr::parse(&mut input, require_comma)?;
        let mut expr_tokens = expr.clone().into_iter();
        if let Some(token) = expr_tokens.next() {
            if expr_tokens.next().is_none() {
                let preserve_empty_first_line = !first;
                if let Ok(literal) = lit_indoc(token, Macro::Concat, preserve_empty_first_line) {
                    result.extend(iter::once(TokenTree::Literal(literal)));
                    expr = TokenStream::new();
                }
            }
        }
        result.extend(expr);
        if let Some(comma) = input.next() {
            result.extend(iter::once(comma));
        } else {
            break;
        }
        first = false;
    }

    // concat! { #result }
    Ok(TokenStream::from_iter(vec![
        TokenTree::Ident(Ident::new("concat", Span::call_site())),
        TokenTree::Punct(Punct::new('!', Spacing::Alone)),
        TokenTree::Group(Group::new(Delimiter::Brace, result)),
    ]))
}

fn lit_indoc(token: TokenTree, mode: Macro, preserve_empty_first_line: bool) -> Result<Literal> {
    let span = token.span();
    let mut single_token = Some(token);

    while let Some(TokenTree::Group(group)) = single_token {
        single_token = if group.delimiter() == Delimiter::None {
            let mut token_iter = group.stream().into_iter();
            token_iter.next().xor(token_iter.next())
        } else {
            None
        };
    }

    let single_token =
        single_token.ok_or_else(|| Error::new(span, "argument must be a single string literal"))?;

    let repr = single_token.to_string();
    let is_string = repr.starts_with('"') || repr.starts_with('r');
    let is_byte_string = repr.starts_with("b\"") || repr.starts_with("br");

    if !is_string && !is_byte_string {
        return Err(Error::new(span, "argument must be a single string literal"));
    }

    if is_byte_string {
        match mode {
            Macro::Indoc => {}
            Macro::Format | Macro::Print | Macro::Eprint | Macro::Write => {
                return Err(Error::new(
                    span,
                    "byte strings are not supported in formatting macros",
                ));
            }
            Macro::Concat => {
                return Err(Error::new(
                    span,
                    "byte strings are not supported in concat macro",
                ));
            }
        }
    }

    let begin = repr.find('"').unwrap() + 1;
    let end = repr.rfind('"').unwrap();
    let repr = format!(
        "{open}{content}{close}",
        open = &repr[..begin],
        content = do_unindent(&repr[begin..end], preserve_empty_first_line),
        close = &repr[end..],
    );

    let mut lit = Literal::from_str(&repr).unwrap();
    lit.set_span(span);
    Ok(lit)
}

fn require_empty_or_trailing_comma(input: &mut Peekable<TokenIter>) -> Result<()> {
    let first = match input.next() {
        Some(TokenTree::Punct(punct)) if punct.as_char() == ',' => match input.next() {
            Some(second) => second,
            None => return Ok(()),
        },
        Some(first) => first,
        None => return Ok(()),
    };
    let last = input.last();

    let begin_span = first.span();
    let end_span = last.as_ref().map_or(begin_span, TokenTree::span);
    let msg = format!(
        "unexpected {token} in macro invocation; indoc argument must be a single string literal",
        token = if last.is_some() { "tokens" } else { "token" }
    );
    Err(Error::new2(begin_span, end_span, &msg))
}