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
#[macro_use]
mod concat_assert;

#[cfg(feature = "non_basic")]
#[macro_use]
pub(crate) mod concat_macro;

#[cfg(feature = "non_basic")]
#[macro_use]
mod non_basic_macros;

#[cfg(feature = "non_basic")]
#[macro_use]
mod macro_utils;

#[cfg(feature = "non_basic")]
#[macro_use]
mod impl_panicfmt;

#[macro_use]
mod unwrapping;

#[doc(hidden)]
#[macro_export]
macro_rules! __write_array {
    ($array:expr, $len:expr, $value:expr) => {
        $array[$len] = $value;
        $len += 1;
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __write_array_checked {
    ($array:expr, $len:expr, $value:expr) => {
        if $array.len() > $len {
            $array[$len] = $value;
            $len += 1;
        }
    };
}

/// Coerces `$reff` to a type that has a `to_panicvals` method,
/// which is expected to return a `[PanicVal<'_>; LEN]`.
///
/// # Limitations
///
#[doc = crate::doc_macros::limitation_docs!()]
///
/// # Example
///
/// This example uses [`const_panic::ArrayString`](crate::ArrayString)
/// to show what the values format into,
/// which requires the `"non_basic"` crate feature (enabled by default).
///
#[cfg_attr(feature = "non_basic", doc = "```rust")]
#[cfg_attr(not(feature = "non_basic"), doc = "```ignore")]
/// use const_panic::{ArrayString, FmtArg, IsCustomType, PanicFmt, PanicVal, coerce_fmt};
///
/// type AS = ArrayString<100>;
///
/// assert_eq!(
///     AS::from_panicvals(&coerce_fmt!(100u8).to_panicvals(FmtArg::DEBUG)).unwrap(),
///     "100",
/// );
///
/// assert_eq!(
///     AS::from_panicvals(&coerce_fmt!("hello\n").to_panicvals(FmtArg::DEBUG)).unwrap(),
///     r#""hello\n""#,
/// );
///
/// assert_eq!(
///     AS::from_panicvals(&coerce_fmt!(IsReal::No).to_panicvals(FmtArg::DEBUG)).unwrap(),
///     "No",
/// );
///
/// assert_eq!(
///     AS::from_panicvals(&coerce_fmt!(IsReal::Yes).to_panicvals(FmtArg::DEBUG)).unwrap(),
///     "Yes",
/// );
///
///
///
/// enum IsReal{Yes, No}
///
/// // All the code below manually implements panic formatting for a field-less enum.
/// // This can be written concisely with the `PanicFmt` derive or `impl_panicfmt` macro.
/// impl PanicFmt for IsReal {
///     type This = Self;
///     type Kind = IsCustomType;
///     const PV_COUNT: usize = 1;
/// }
///
/// impl IsReal {
///     pub const fn to_panicvals(&self, _f: FmtArg) -> [PanicVal<'_>; IsReal::PV_COUNT] {
///         let x = match self {
///             Self::Yes => "Yes",
///             Self::No => "No",
///         };
///         [PanicVal::write_str(x)]
///     }
/// }
///
/// ```
#[macro_export]
macro_rules! coerce_fmt {
    ($reff:expr) => {
        match &$reff {
            reff => $crate::__::PanicFmt::PROOF.infer(reff).coerce(reff),
        }
    };
}

/// Panics with the concanenation of the arguments.
///
/// [**Examples below**](#examples)
///
/// # Syntax
///
/// This macro uses this syntax:
/// ```text
/// concat_panic!(
///     $($fmtarg:expr;)?
///     $(
///         $( $format_override:tt: )? $arg_to_fmt:expr
///     ),*
///     $(,)?
/// )
/// ```
///
/// `$fmtarg` is an optional [`FmtArg`](crate::FmtArg) argument
/// which defaults to `FmtArg::DEBUG`,
/// determining how non-literal `$arg_to_fmt` arguments are formatted.
///
/// [`$format_override`](#formatting-overrides) overrides the `$fmtarg` argument,
/// changing how that `$arg_to_fmt` argument is formatted.
///
#[doc = formatting_docs!()]
///
/// # Limitations
///
#[doc = crate::doc_macros::limitation_docs!()]
///
/// # Examples
///
/// ### `Odd`-type
///
/// ```rust, compile_fail
/// use const_panic::concat_panic;
///
/// use odd::Odd;
///
/// # fn main(){
/// const _: Odd = match Odd::new(3 * 4) {
///     Ok(x) => x,
///     Err(x) => concat_panic!("\nexpected odd number, got `", x, "`"),
/// };
/// # }
///
/// mod odd {
///     pub struct Odd(u32);
///
///     impl Odd {
///         pub const fn new(n: u32) -> Result<Odd, Even> {
///             if n % 2 == 1 {
///                 Ok(Odd(n))
///             } else {
///                 Err(Even(n))
///             }
///         }
///     }
///
/// #   /*
///     #[derive(const_panic::PanicFmt))]
/// #   */
///     pub struct Even(u32);
/// #
/// #   impl const_panic::PanicFmt for Even {
/// #       type This = Self;
/// #       type Kind = const_panic::IsCustomType;
/// #       const PV_COUNT: usize = 1;
/// #   }
/// #   impl Even {
/// #       pub const fn to_panicvals(
/// #           &self,
/// #           f: const_panic::FmtArg,
/// #       ) -> [const_panic::PanicVal<'static>; 1] {
/// #           const_panic::StdWrapper(&self.0).to_panicvals(f)
/// #       }
/// #   }
/// }
///
/// ```
/// produces this compile-time error:
/// ```text
/// error[E0080]: evaluation of constant value failed
///   --> src/macros.rs:188:15
///    |
/// 10 |     Err(x) => concat_panic!("\nexpected odd number, got `", x, "`"),
///    |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the evaluated program panicked at '
/// expected odd number, got `12`', src/macros.rs:10:15
///    |
///    = note: this error originates in the macro `concat_panic` (in Nightly builds, run with -Z macro-backtrace for more info)
///
/// ```
///
///
/// ### All the syntax
///
/// This example demonstrates using all of the syntax of this macro.
///
/// ```compile_fail
/// use const_panic::{FmtArg, concat_panic, fmt};
///
/// const _: () = concat_panic!{
///     // the optional `$fmtarg` parameter.
///     // If this argument isn't passed, it defaults to `FmtArg::DEBUG`
///     FmtArg::ALT_DEBUG;
///
///     "\n\nshowing off literals:\n",
///     100u8,
///     "hello",
///
///     "\n\nnon-literals with formatting determined by the $fmtarg parameter:\n",
///     // this is considered a non-literal, because it's inside other tokens.
///     ("a non-literal"),
///     [100u8, 200],
///
///     "\n\nexplicitly debug formatted:\n",
///     debug: "foo",
///     // `{?}:` is The same as `debug:`
///     {?}: "bar",
///
///     "\n\nalternate debug formatted:\n",
///     alt_debug: ["foo"],
///     // `{#?}:` is The same as `alt_debug:`
///     {#?}: "bar",
///
///     "\n\ndisplay formatted:\n",
///     display: "baz",
///     // `{}:` is The same as `display:`
///     {}: ["qux", "aaa"],
///
///     "\n\nalternate display formatted:",
///     alt_display: ["bbb", "ccc"],
///     // `{#}:` is The same as `alt_display:`
///     {#}: ["bbb", "ccc"],
///
///     "\n\nbinary formatted:\n",
///     bin: [3u8, 5, 8, 13],
///     // `{b}:` is The same as `bin:`
///     {b}: [3u8, 5, 8, 13],
///
///     "\n\nalternate-binary formatted:\n",
///     alt_bin: [21u8, 34, 55, 89],
///     // `{#b}:` is The same as `alt_bin:`
///     {#b}: [21u8, 34, 55, 89],
///
///     "\n\nhexadecimal formatted:\n",
///     hex: [3u8, 5, 8, 13],
///     // `{X}:` is The same as `hex:`
///     {X}: [3u8, 5, 8, 13],
///
///     "\n\nalternate-hexadecimal formatted:\n",
///     alt_hex: [21u8, 34, 55, 89],
///     // `{#X}:` is The same as `alt_hex:`
///     {#X}: [21u8, 34, 55, 89],
///
///     "\n\n",
/// };
///
/// ```
/// The above code produces this compile-time error:
/// ```text
/// error[E0080]: evaluation of constant value failed
///   --> src/macros.rs:186:15
///    |
/// 6  |   const _: () = concat_panic!{
///    |  _______________^
/// 7  | |     // the optional `$fmtarg` parameter.
/// 8  | |     // If this argument isn't passed, it defaults to `FmtArg::DEBUG`
/// 9  | |     FmtArg::ALT_DEBUG;
/// ...  |
/// 60 | |     "\n\n",
/// 61 | | };
///    | |_^ the evaluated program panicked at '
///
/// showing off literals:
/// 100hello
///
/// non-literals with formatting determined by the $fmtarg parameter:
/// "a non-literal"[
///     100,
///     200,
/// ]
///
/// explicitly debug formatted:
/// "foo""bar"
///
/// alternate debug formatted:
/// [
///     "foo",
/// ]"bar"
///
/// display formatted:
/// baz[qux, aaa]
///
/// alternate display formatted:[
///     bbb,
///     ccc,
/// ][
///     bbb,
///     ccc,
/// ]
///
/// binary formatted:
/// [11, 101, 1000, 1101][11, 101, 1000, 1101]
///
/// alternate-binary formatted:
/// [
///     0b10101,
///     0b100010,
///     0b110111,
///     0b1011001,
/// ][
///     0b10101,
///     0b100010,
///     0b110111,
///     0b1011001,
/// ]
///
/// hexadecimal formatted:
/// [3, 5, 8, D][3, 5, 8, D]
///
/// alternate-hexadecimal formatted:
/// [
///     0x15,
///     0x22,
///     0x37,
///     0x59,
/// ][
///     0x15,
///     0x22,
///     0x37,
///     0x59,
/// ]
///
/// ', src/macros.rs:6:15
///    |
///    = note: this error originates in the macro `concat_panic` (in Nightly builds, run with -Z macro-backtrace for more info)
///
/// error: aborting due to previous error
///
/// ```
///
#[macro_export]
macro_rules! concat_panic {
    ($($args:tt)*) => (
        $crate::__concat_func_setup!{
            (|args| $crate::concat_panic(args))
            []
            [$($args)*,]
        }
    )
}

// This macro takes the optional `$fmt:expr;` argument before everything else.
// But I had to parse the argument manually,
// because `$fmt:expr;` fails compilation instead of trying the following branches
// when the argument isn't valid expression syntax.
#[doc(hidden)]
#[macro_export]
macro_rules! __concat_func_setup {
    ($args:tt $prev:tt [$($fmt:tt).*; $($rem:tt)* ]) => ({
        let mut fmt: $crate::FmtArg = $($fmt).*;
        $crate::__concat_func!{fmt $args $prev [$($rem)*]}
    });
    ($args:tt $prev:tt [$(:: $(@$_dummy:tt@)?)? $($fmt:ident)::* ; $($rem:tt)* ]) => ({
        let mut fmt: $crate::FmtArg = $(:: $($_dummy)?)? $($fmt)::*;
        $crate::__concat_func!{fmt $args $prev [$($rem)*]}
    });
    ($args:tt $prev:tt $rem:tt) => ({
        let mut fmt: $crate::FmtArg = $crate::FmtArg::DEBUG;
        $crate::__concat_func!{fmt $args $prev $rem}
    });
}
#[doc(hidden)]
#[macro_export]
macro_rules! __concat_func {
    ($fmt:ident $args:tt [$($prev:tt)*] [$keyword:tt: $expr:expr, $($rem:tt)* ]) => {
        $crate::__concat_func!{
            $fmt
            $args
            [$($prev)* ($crate::__set_fmt_from_kw!($keyword, $fmt), $expr)]
            [$($rem)*]
        }
    };
    ($fmt:ident $args:tt [$($prev:tt)*] [$expr:literal, $($rem:tt)* ]) => {
        $crate::__concat_func!{
            $fmt
            $args
            [$($prev)* ($crate::__set_fmt_from_kw!(display, $fmt), $expr)]
            [$($rem)*]
        }
    };
    ($fmt:ident $args:tt [$($prev:tt)*] [$expr:expr, $($rem:tt)* ]) => {
        $crate::__concat_func!{
            $fmt
            $args
            [$($prev)* ($fmt, $expr)]
            [$($rem)*]
        }
    };
    ($fmt:ident (|$args:ident| $function_call:expr) [$(($fmt_arg:expr, $reff:expr))*] [$(,)*]) => {
        match &[
            $(
                $crate::StdWrapper(
                    &$crate::coerce_fmt!($reff)
                    .to_panicvals($fmt_arg)
                ).deref_panic_vals(),
            )*
        ] {
            $args => $function_call,
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __set_fmt_from_kw {
    (open, $fmtarg:ident) => {{
        $fmtarg = $fmtarg.indent();
        $fmtarg.set_display()
    }};
    (close, $fmtarg:ident) => {{
        $fmtarg = $fmtarg.unindent();
        $fmtarg.set_display()
    }};
    (display, $fmtarg:ident) => {
        $fmtarg.set_display().set_alternate(false)
    };
    ({}, $fmtarg:ident) => {
        $fmtarg.set_display().set_alternate(false)
    };
    (alt_display, $fmtarg:ident) => {
        $fmtarg.set_display().set_alternate(true)
    };
    ({#}, $fmtarg:ident) => {
        $fmtarg.set_display().set_alternate(true)
    };
    (debug, $fmtarg:ident) => {
        $fmtarg.set_debug().set_alternate(false)
    };
    ({?}, $fmtarg:ident) => {
        $fmtarg.set_debug().set_alternate(false)
    };
    (alt_debug, $fmtarg:ident) => {
        $fmtarg.set_debug().set_alternate(true)
    };
    ({#?}, $fmtarg:ident) => {
        $fmtarg.set_debug().set_alternate(true)
    };
    (hex, $fmtarg:ident) => {
        $fmtarg.set_hex().set_alternate(false)
    };
    ({X}, $fmtarg:ident) => {
        $fmtarg.set_hex().set_alternate(false)
    };
    (alt_hex, $fmtarg:ident) => {
        $fmtarg.set_hex().set_alternate(true)
    };
    ({#X}, $fmtarg:ident) => {
        $fmtarg.set_hex().set_alternate(true)
    };
    (bin, $fmtarg:ident) => {
        $fmtarg.set_bin().set_alternate(false)
    };
    ({b}, $fmtarg:ident) => {
        $fmtarg.set_bin().set_alternate(false)
    };
    (alt_bin, $fmtarg:ident) => {
        $fmtarg.set_bin().set_alternate(true)
    };
    ({#b}, $fmtarg:ident) => {
        $fmtarg.set_bin().set_alternate(true)
    };
    (_, $fmtarg:ident) => {
        $fmtarg
    };
    ($kw:tt, $fmtarg:ident) => {
        compile_error!(concat!(
            "unrecognized formatting specifier: ",
            stringify!($kw),
            "\n",
            "expected one of:\n",
            "- display/{}\n",
            "- alt_display/{#}\n",
            "- debug/{?}\n",
            "- alt_debug/{#?}\n",
            "- hex/{X}\n",
            "- alt_hex/{#X}\n",
            "- bin/{b}\n",
            "- alt_bin/{#b}\n",
        ))
    };
}