fire 0.6.0

Turn functions into command-line applications with one attribute, like Python's fire
Documentation
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
//! Turn a Rust function or module into a command-line application with one
//! attribute.
//!
//! Rust Fire derives the command-line interface from ordinary Rust function
//! signatures. It does not use a global command registry and does not require a
//! separate runner macro.
//!
//! # Quick start
//!
//! Add `#[fire::main]` to a function:
//!
//! ```no_run
//! /// Welcome a person.
//! #[fire::main]
//! fn welcome(
//!     /// Person to welcome.
//!     name: String,
//!     /// Add an exclamation mark.
//!     excited: bool,
//! ) {
//!     let suffix = if excited { "!" } else { "." };
//!     println!("Welcome, {name}{suffix}");
//! }
//! ```
//!
//! The generated executable accepts both `--name Ferris` and
//! `--name=Ferris`. Boolean parameters are flags, so `excited` is enabled with
//! `--excited`.
//!
//! # Subcommands
//!
//! Applying [`main`] to an inline module turns each function in that module
//! into a subcommand:
//!
//! ```no_run
//! /// Account management commands.
//! #[fire::main]
//! mod cli {
//!     /// Create an account.
//!     pub fn create(
//!         /// Account name.
//!         name: String,
//!         /// Assign administrator privileges.
//!         admin: bool,
//!     ) {
//!         println!("creating {name}, admin={admin}");
//!     }
//!
//!     /// Remove an account.
//!     pub fn remove(name: String) {
//!         println!("removing {name}");
//!     }
//! }
//! ```
//!
//! Function and parameter names are converted from `snake_case` to
//! `kebab-case`. The example exposes `create` and `remove` as subcommands.
//! Only `pub` functions become subcommands, so a module can keep private
//! helper functions next to its commands.
//!
//! # Parameter mapping
//!
//! | Rust type | Command-line behavior |
//! |---|---|
//! | `T` | Required `--name <VALUE>` option parsed with [`FromStr`](std::str::FromStr) |
//! | `Option<T>` | Optional `--name <VALUE>` option |
//! | `bool` | Value-less `--name` flag, defaulting to `false` |
//! | `&str` | Borrowed string option |
//!
//! Every non-string value is parsed through [`FromStr`](std::str::FromStr).
//! A parse failure, missing value, repeated option, unknown option, unknown
//! command, or argument that is not valid UTF-8 is reported on stderr together
//! with the relevant usage line. CLI errors exit with status code 2.
//!
//! A value that starts with `-` is never taken from the next argument, so it
//! has to be written as `--name=-1`.
//!
//! # Generated help
//!
//! Rust Fire automatically supports `-h` and `--help`. Function, module, and
//! parameter documentation comments become command descriptions:
//!
//! ```text
//! Welcome a person.
//!
//! Usage: app --name <NAME> [--excited]
//!
//! Options:
//!     --name <NAME>    Person to welcome.
//!     --excited        Add an exclamation mark.
//!     -h, --help       Print help
//! ```
//!
//! Module applications additionally support `app --help` to list commands and
//! `app <COMMAND> --help` to describe one command.
//!
//! # Fallible commands
//!
//! A command returns either `()` or `Result<_, E>` where `E` implements
//! [`Display`](std::fmt::Display). An error is formatted through `Display`,
//! printed to stderr, and causes status code 2:
//!
//! ```no_run
//! #[fire::main]
//! fn deploy(target: String) -> Result<(), &'static str> {
//!     if target == "production" {
//!         return Err("production deployments are disabled");
//!     }
//!     Ok(())
//! }
//! ```
//!
//! The return value is dispatched through a trait rather than by matching on
//! the return type, so type aliases work as well:
//!
//! ```no_run
//! type Fallible<T> = std::result::Result<T, Box<dyn std::error::Error>>;
//!
//! #[fire::main]
//! fn deploy(target: String) -> Fallible<()> {
//!     Ok(())
//! }
//! ```
//!
//! Any other return type is rejected at compile time.
//!
//! # Async commands
//!
//! Passing `tokio` to the attribute lets commands be `async`. Each async
//! command runs on a multi-threaded Tokio runtime, so the application must
//! depend on [`tokio`](https://docs.rs/tokio) with the `rt-multi-thread`
//! feature:
//!
//! ```no_run
//! /// Fetch a URL.
//! #[fire::main(tokio)]
//! async fn fetch(url: String) {
//!     // .await freely here
//! }
//! ```
//!
//! The same argument works on modules; async and synchronous commands can be
//! mixed in one module.
//!
//! # Current limitations
//!
//! - Command modules must be inline modules, and only their `pub` functions
//!   become subcommands.
//! - Methods and generic functions are not supported.
//! - A command returns `()` or `Result<_, E>` where `E: Display`; any other
//!   return type is a compile error.
//! - Async functions require `#[fire::main(tokio)]`.
//! - Parameters are named options; positional arguments and short option names
//!   are not currently supported.
//! - Parameter attributes other than documentation comments are rejected.

use proc_macro::TokenStream;
use proc_macro2::{Ident, TokenStream as TokenStream2};
use quote::{format_ident, quote, quote_spanned};
use syn::{
    parse_macro_input, spanned::Spanned, Attribute, Expr, File, FnArg, Item, ItemFn, ItemMod, Lit,
    Meta, Pat, ReturnType, Type, Visibility,
};

struct Argument {
    ident: Ident,
    ty: Type,
    cli_name: String,
    description: String,
    kind: ArgumentKind,
}

#[derive(Clone, Copy)]
enum ArgumentKind {
    Required,
    Optional,
    Flag,
}

/// Turns a Rust identifier into its command-line spelling, dropping the `r#`
/// prefix of raw identifiers and replacing underscores with dashes.
fn kebab_case(name: &str) -> String {
    name.strip_prefix("r#").unwrap_or(name).replace('_', "-")
}

fn inner_type<'a>(ty: &'a Type, wrapper: &str) -> Option<&'a Type> {
    let Type::Path(path) = ty else {
        return None;
    };
    let segment = path.path.segments.last()?;
    if segment.ident != wrapper {
        return None;
    }
    let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else {
        return None;
    };
    match arguments.args.first()? {
        syn::GenericArgument::Type(ty) => Some(ty),
        _ => None,
    }
}

fn is_bool(ty: &Type) -> bool {
    matches!(ty, Type::Path(path) if path.path.is_ident("bool"))
}

fn is_str_reference(ty: &Type) -> bool {
    matches!(ty, Type::Reference(reference)
        if matches!(&*reference.elem, Type::Path(path) if path.path.is_ident("str")))
}

fn documentation(attributes: &[Attribute]) -> String {
    attributes
        .iter()
        .filter_map(|attribute| {
            if !attribute.path().is_ident("doc") {
                return None;
            }
            let Meta::NameValue(meta) = &attribute.meta else {
                return None;
            };
            let Expr::Lit(expression) = &meta.value else {
                return None;
            };
            let Lit::Str(text) = &expression.lit else {
                return None;
            };
            Some(text.value().trim().to_string())
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn arguments(function: &mut ItemFn) -> syn::Result<Vec<Argument>> {
    function
        .sig
        .inputs
        .iter_mut()
        .map(|input| {
            let FnArg::Typed(input) = input else {
                return Err(syn::Error::new_spanned(
                    input,
                    "methods cannot be CLI commands",
                ));
            };
            let Pat::Ident(pattern) = &*input.pat else {
                return Err(syn::Error::new_spanned(
                    &input.pat,
                    "command parameters must be identifiers",
                ));
            };
            if let Some(attribute) = input
                .attrs
                .iter()
                .find(|attribute| !attribute.path().is_ident("doc"))
            {
                return Err(syn::Error::new_spanned(
                    attribute,
                    "only documentation comments are supported on parameters",
                ));
            }

            let kind = if is_bool(&input.ty) {
                ArgumentKind::Flag
            } else if inner_type(&input.ty, "Option").is_some() {
                ArgumentKind::Optional
            } else {
                ArgumentKind::Required
            };

            let description = documentation(&input.attrs);
            input.attrs.clear();

            Ok(Argument {
                ident: pattern.ident.clone(),
                ty: (*input.ty).clone(),
                cli_name: kebab_case(&pattern.ident.to_string()),
                description,
                kind,
            })
        })
        .collect()
}

/// Renders an indented two column list, padding the left column so that every
/// description starts at the same offset. Entries without a description are
/// left unpadded to avoid trailing whitespace.
fn aligned_list(entries: &[(String, String)]) -> String {
    let width = entries
        .iter()
        .filter(|(_, description)| !description.is_empty())
        .map(|(term, _)| term.chars().count())
        .max()
        .unwrap_or(0);
    let mut list = String::new();
    for (term, description) in entries {
        list.push_str("    ");
        if description.is_empty() {
            list.push_str(term);
        } else {
            let padding = width.saturating_sub(term.chars().count());
            list.push_str(term);
            list.push_str(&" ".repeat(padding));
            list.push_str("    ");
            list.push_str(description);
        }
        list.push('\n');
    }
    list
}

fn command_help(function: &ItemFn, arguments: &[Argument], command_name: &str) -> String {
    let mut help = String::new();
    let description = documentation(&function.attrs);
    if !description.is_empty() {
        help.push_str(&description);
        help.push_str("\n\n");
    }

    help.push_str("Usage: {program}");
    if !command_name.is_empty() {
        help.push(' ');
        help.push_str(command_name);
    }
    for argument in arguments {
        let option = match argument.kind {
            ArgumentKind::Required => format!(
                " --{} <{}>",
                argument.cli_name,
                argument.cli_name.replace('-', "_").to_uppercase()
            ),
            ArgumentKind::Optional => format!(
                " [--{} <{}>]",
                argument.cli_name,
                argument.cli_name.replace('-', "_").to_uppercase()
            ),
            ArgumentKind::Flag => format!(" [--{}]", argument.cli_name),
        };
        help.push_str(&option);
    }
    help.push_str("\n\nOptions:\n");
    let mut options: Vec<(String, String)> = arguments
        .iter()
        .map(|argument| {
            let term = match argument.kind {
                ArgumentKind::Flag => format!("--{}", argument.cli_name),
                _ => format!(
                    "--{} <{}>",
                    argument.cli_name,
                    argument.cli_name.replace('-', "_").to_uppercase()
                ),
            };
            (term, argument.description.replace('\n', " "))
        })
        .collect();
    options.push(("-h, --help".to_string(), "Print help".to_string()));
    help.push_str(aligned_list(&options).trim_end_matches('\n'));
    help
}

fn program_name() -> TokenStream2 {
    quote! {
        std::env::args_os()
            .next()
            .and_then(|path| {
                std::path::Path::new(&path)
                    .file_name()
                    .map(|name| name.to_string_lossy().into_owned())
            })
            .unwrap_or_else(|| "app".to_string())
    }
}

fn parsed_value(value: TokenStream2, ty: &Type, cli_name: &str) -> TokenStream2 {
    if is_str_reference(ty) {
        quote! { #value.as_str() }
    } else {
        quote! {
            #value.parse::<#ty>().map_err(|_| {
                __fire_error(format!("invalid value for '--{}': '{}'", #cli_name, #value))
            })?
        }
    }
}

/// A command's return value is reported through a generated trait rather than
/// by inspecting the return type syntactically, so that type aliases such as
/// `anyhow::Result<()>` or a local `type Fallible<T>` are handled correctly.
fn output_trait() -> TokenStream2 {
    quote! {
        #[doc(hidden)]
        #[diagnostic::on_unimplemented(
            message = "`{Self}` cannot be returned from a #[fire::main] command",
            label = "a command must return `()` or `Result<_, E>` where `E: Display`"
        )]
        trait __FireOutput {
            fn __fire_report(self) -> Result<(), String>;
        }

        impl __FireOutput for () {
            fn __fire_report(self) -> Result<(), String> {
                Ok(())
            }
        }

        impl<T, E> __FireOutput for Result<T, E>
        where
            E: std::fmt::Display,
        {
            fn __fire_report(self) -> Result<(), String> {
                self.map(|_| ()).map_err(|error| error.to_string())
            }
        }
    }
}

/// Whether a command's return value has to be reported through
/// [`output_trait`]. Diverging commands never return, so they need no report.
fn reports_output(function: &ItemFn) -> bool {
    match &function.sig.output {
        ReturnType::Default => false,
        ReturnType::Type(_, ty) => !matches!(**ty, Type::Never(_)),
    }
}

fn command_runner(
    function: &mut ItemFn,
    runner_name: &Ident,
    visibility: TokenStream2,
    command_name: &str,
    tokio: bool,
) -> syn::Result<TokenStream2> {
    if function.sig.asyncness.is_some() && !tokio {
        return Err(syn::Error::new_spanned(
            function.sig.asyncness,
            "async commands require a runtime; use #[fire::main(tokio)]",
        ));
    }
    if !function.sig.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &function.sig.generics,
            "generic commands are not supported",
        ));
    }

    let arguments = arguments(function)?;
    if let Some(argument) = arguments
        .iter()
        .find(|argument| argument.cli_name == "help")
    {
        return Err(syn::Error::new(
            argument.ident.span(),
            "parameter `help` collides with the generated `--help` option",
        ));
    }
    let function_name = &function.sig.ident;
    let help = command_help(function, &arguments, command_name);
    let usage = help
        .lines()
        .find(|line| line.starts_with("Usage:"))
        .expect("command help always contains usage")
        .to_string();
    let program_name = program_name();

    let storage = arguments.iter().map(|argument| {
        let storage_name = format_ident!("__fire_value_{}", argument.ident);
        quote! { let mut #storage_name: Option<String> = None; }
    });

    let option_matches = arguments.iter().map(|argument| {
        let storage_name = format_ident!("__fire_value_{}", argument.ident);
        let cli_name = &argument.cli_name;
        match argument.kind {
            ArgumentKind::Flag => quote! {
                if __fire_key == concat!("--", #cli_name) {
                    if __fire_inline_value.is_some() {
                        return Err(__fire_error(format!("flag '--{}' does not take a value", #cli_name)));
                    }
                    if #storage_name.is_some() {
                        return Err(__fire_error(format!(
                            "flag '--{}' is given more than once",
                            #cli_name
                        )));
                    }
                    #storage_name = Some("true".to_string());
                    __fire_matched = true;
                }
            },
            ArgumentKind::Required | ArgumentKind::Optional => quote! {
                if __fire_key == concat!("--", #cli_name) {
                    if #storage_name.is_some() {
                        return Err(__fire_error(format!(
                            "option '--{}' is given more than once",
                            #cli_name
                        )));
                    }
                    let value = match __fire_inline_value {
                        Some(value) => value.to_string(),
                        None => {
                            __fire_index += 1;
                            let value = __fire_args.get(__fire_index).cloned().ok_or_else(|| {
                                __fire_error(format!("option '--{}' requires a value", #cli_name))
                            })?;
                            if value.starts_with("--") || value == "-h" {
                                return Err(__fire_error(format!(
                                    "option '--{}' requires a value, found '{}'; write '--{}={}' to use it as the value",
                                    #cli_name, value, #cli_name, value
                                )));
                            }
                            value
                        }
                    };
                    #storage_name = Some(value);
                    __fire_matched = true;
                }
            },
        }
    });

    let conversions = arguments.iter().map(|argument| {
        let ident = &argument.ident;
        let ty = &argument.ty;
        let storage_name = format_ident!("__fire_value_{}", ident);
        let cli_name = &argument.cli_name;
        match argument.kind {
            ArgumentKind::Flag => quote! {
                let #ident: bool = #storage_name.is_some();
            },
            ArgumentKind::Optional => {
                let inner = inner_type(ty, "Option").expect("optional type checked above");
                if is_str_reference(inner) {
                    quote! { let #ident: #ty = #storage_name.as_deref(); }
                } else {
                    let parsed = parsed_value(quote! { value }, inner, cli_name);
                    quote! {
                        let #ident: #ty = match #storage_name.as_ref() {
                            Some(value) => Some(#parsed),
                            None => None,
                        };
                    }
                }
            }
            ArgumentKind::Required => {
                if is_str_reference(ty) {
                    quote! {
                        let #ident: #ty = #storage_name.as_deref().ok_or_else(|| {
                            __fire_error(format!("missing required option '--{}'", #cli_name))
                        })?;
                    }
                } else {
                    let parsed = parsed_value(quote! { value }, ty, cli_name);
                    quote! {
                        let #ident: #ty = {
                            let value = #storage_name.as_ref().ok_or_else(|| {
                                __fire_error(format!("missing required option '--{}'", #cli_name))
                            })?;
                            #parsed
                        };
                    }
                }
            }
        }
    });

    let call_arguments = arguments.iter().map(|argument| &argument.ident);
    let mut invocation = quote! { #function_name(#(#call_arguments),*) };
    if function.sig.asyncness.is_some() {
        invocation = quote! {
            ::tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()
                .expect("failed to build tokio runtime")
                .block_on(#invocation)
        };
    }
    let call = match &function.sig.output {
        // A diverging command never returns, so `!` coerces to the runner's
        // own return type.
        ReturnType::Type(_, ty) if matches!(**ty, Type::Never(_)) => quote! { #invocation },
        ReturnType::Type(_, ty) => {
            let report = quote_spanned! { ty.span() =>
                __FireOutput::__fire_report(#invocation)
            };
            quote! { #report.map(|_| None) }
        }
        ReturnType::Default => quote! {
            #invocation;
            Ok(None)
        },
    };

    Ok(quote! {
        #[doc(hidden)]
        #visibility fn #runner_name<I, S>(input: I) -> Result<Option<String>, String>
        where
            I: IntoIterator<Item = S>,
            S: Into<std::ffi::OsString>,
        {
            let program = #program_name;
            let __fire_help = #help.replace("{program}", &program);
            let __fire_usage = #usage.replace("{program}", &program);
            let __fire_error = |message: String| {
                format!(
                    "{}\n\n{}\n\nFor more information, try '--help'.",
                    message, __fire_usage
                )
            };
            let mut __fire_args: Vec<String> = Vec::new();
            for __fire_argument in input {
                let __fire_argument: std::ffi::OsString = __fire_argument.into();
                match __fire_argument.into_string() {
                    Ok(__fire_argument) => __fire_args.push(__fire_argument),
                    Err(__fire_argument) => {
                        return Err(__fire_error(format!(
                            "argument '{}' is not valid UTF-8",
                            __fire_argument.to_string_lossy()
                        )));
                    }
                }
            }
            #(#storage)*

            let mut __fire_index = 0usize;
            while __fire_index < __fire_args.len() {
                let __fire_raw = &__fire_args[__fire_index];
                let (__fire_key, __fire_inline_value) = match __fire_raw.split_once('=') {
                    Some((key, value)) => (key, Some(value)),
                    None => (__fire_raw.as_str(), None),
                };
                if __fire_key == "--help" || __fire_key == "-h" {
                    return Ok(Some(__fire_help));
                }
                let mut __fire_matched = false;
                #(#option_matches)*
                if !__fire_matched {
                    return Err(__fire_error(format!("unexpected argument '{}'", __fire_raw)));
                }
                __fire_index += 1;
            }

            #(#conversions)*
            #call
        }
    })
}

fn entrypoint(call: TokenStream2) -> TokenStream2 {
    quote! {
        fn main() {
            match #call {
                Ok(Some(help)) => println!("{}", help),
                Ok(None) => {}
                Err(error) => {
                    eprintln!("error: {}", error);
                    std::process::exit(2);
                }
            }
        }
    }
}

fn expand_function(mut function: ItemFn, tokio: bool) -> syn::Result<TokenStream2> {
    if function.sig.ident == "main" {
        return Err(syn::Error::new_spanned(
            &function.sig.ident,
            "put #[fire::main] on the command function, not on a function named `main`",
        ));
    }
    let runner_name = format_ident!("__fire_run_{}", function.sig.ident);
    let output = if reports_output(&function) {
        output_trait()
    } else {
        TokenStream2::new()
    };
    let runner = command_runner(&mut function, &runner_name, quote! { pub(crate) }, "", tokio)?;
    let main = entrypoint(quote! { #runner_name(std::env::args_os().skip(1)) });
    Ok(quote! { #function #output #runner #main })
}

fn expand_module(mut module: ItemMod, tokio: bool) -> syn::Result<TokenStream2> {
    let module_name = module.ident.clone();
    let module_description = documentation(&module.attrs);
    let Some((_, items)) = &mut module.content else {
        return Err(syn::Error::new_spanned(
            &module,
            "#[fire::main] requires an inline module",
        ));
    };

    let mut commands = Vec::new();
    let mut runners = Vec::new();
    let mut reports_any_output = false;
    for item in items.iter_mut() {
        let Item::Fn(function) = item else {
            continue;
        };
        if !matches!(function.vis, Visibility::Public(_)) {
            continue;
        }
        let command_name = kebab_case(&function.sig.ident.to_string());
        let runner_name = format_ident!("__fire_run_{}", function.sig.ident);
        let description = documentation(&function.attrs).replace('\n', " ");
        reports_any_output |= reports_output(function);
        runners.push(command_runner(
            function,
            &runner_name,
            quote! {},
            &command_name,
            tokio,
        )?);
        commands.push((command_name, runner_name, description));
    }

    if reports_any_output {
        let output: File = syn::parse2(output_trait()).expect("generated output trait");
        items.extend(output.items);
    }
    for runner in runners {
        items.push(syn::parse2(runner).expect("generated command runner"));
    }
    let dispatch = commands.iter().map(|(command_name, runner_name, _)| {
        quote! { #command_name => #runner_name(arguments), }
    });
    let mut root_help = String::new();
    if !module_description.is_empty() {
        root_help.push_str(&module_description);
        root_help.push_str("\n\n");
    }
    root_help.push_str("Usage: {program} <COMMAND>\n\nCommands:\n");
    let command_list: Vec<(String, String)> = commands
        .iter()
        .map(|(command_name, _, description)| (command_name.clone(), description.clone()))
        .collect();
    root_help.push_str(&aligned_list(&command_list));
    root_help.push_str("\nOptions:\n");
    let root_options = [("-h, --help".to_string(), "Print help".to_string())];
    root_help.push_str(aligned_list(&root_options).trim_end_matches('\n'));
    let root_usage = root_help
        .lines()
        .find(|line| line.starts_with("Usage:"))
        .expect("root help always contains usage")
        .to_string();
    let program_name = program_name();
    items.push(
        syn::parse2(quote! {
            #[doc(hidden)]
            pub(crate) fn __fire_run<I, S>(input: I) -> Result<Option<String>, String>
            where
                I: IntoIterator<Item = S>,
            S: Into<std::ffi::OsString>,
            {
                let mut input = input
                    .into_iter()
                    .map(|argument| -> std::ffi::OsString { argument.into() });
                let program = #program_name;
                let __fire_help = #root_help.replace("{program}", &program);
                let __fire_usage = #root_usage.replace("{program}", &program);
                let __fire_error = |message: String| {
                    format!(
                        "{}\n\n{}\n\nFor more information, try '--help'.",
                        message, __fire_usage
                    )
                };
                let command = input
                    .next()
                    .ok_or_else(|| __fire_error("missing command".to_string()))?;
                let command = command.into_string().map_err(|command| {
                    __fire_error(format!(
                        "command '{}' is not valid UTF-8",
                        command.to_string_lossy()
                    ))
                })?;
                if command == "--help" || command == "-h" {
                    return Ok(Some(__fire_help));
                }
                let arguments: Vec<std::ffi::OsString> = input.collect();
                match command.as_str() {
                    #(#dispatch)*
                    _ => Err(__fire_error(format!("unknown command '{}'", command))),
                }
            }
        })
        .expect("generated command dispatcher"),
    );

    let main = entrypoint(quote! { #module_name::__fire_run(std::env::args_os().skip(1)) });
    Ok(quote! { #module #main })
}

/// Turns a function or inline module into a complete command-line application.
///
/// On a function, this attribute generates a CLI parser and the crate's
/// `fn main()`. On an inline module, it also generates a subcommand dispatcher
/// whose commands are the `pub` functions declared directly inside that
/// module.
///
/// Command behavior is inferred from parameter types:
///
/// - `T` is a required named option;
/// - `Option<T>` is an optional named option;
/// - `bool` is a value-less flag;
/// - `&str` borrows its value for the duration of the command call.
///
/// A command returns `()` or `Result<_, E>` where `E` implements
/// [`Display`](std::fmt::Display); any other return type is rejected at
/// compile time.
///
/// Documentation comments on the target and its parameters are included in
/// the generated `-h`/`--help` output. See the [crate-level documentation](crate)
/// for complete examples, error behavior, and current limitations.
///
/// # Function
///
/// ```no_run
/// /// Print a greeting.
/// #[fire::main]
/// fn greet(name: String, loud: bool) {
///     if loud {
///         println!("HELLO, {}!", name.to_uppercase());
///     } else {
///         println!("Hello, {name}!");
///     }
/// }
/// ```
///
/// # Module
///
/// ```no_run
/// #[fire::main]
/// mod cli {
///     /// Start a service.
///     pub fn start(name: String) {}
///
///     /// Stop a service.
///     pub fn stop(name: String) {}
/// }
/// ```
///
/// # Async
///
/// `#[fire::main(tokio)]` additionally accepts `async` commands and runs each
/// one on a multi-threaded Tokio runtime. The application must depend on
/// `tokio` with the `rt-multi-thread` feature.
///
/// ```no_run
/// /// Fetch a URL.
/// #[fire::main(tokio)]
/// async fn fetch(url: String) {}
/// ```
#[proc_macro_attribute]
pub fn main(metadata: TokenStream, input: TokenStream) -> TokenStream {
    let tokio = if metadata.is_empty() {
        false
    } else {
        let runtime = parse_macro_input!(metadata as Ident);
        if runtime != "tokio" {
            return syn::Error::new_spanned(
                &runtime,
                format!("unsupported runtime `{runtime}`; only `tokio` is supported"),
            )
            .into_compile_error()
            .into();
        }
        true
    };
    let item = parse_macro_input!(input as Item);
    let expanded = match item {
        Item::Fn(function) => expand_function(function, tokio),
        Item::Mod(module) => expand_module(module, tokio),
        other => Err(syn::Error::new_spanned(
            other,
            "#[fire::main] only supports functions and inline modules",
        )),
    };
    expanded
        .unwrap_or_else(syn::Error::into_compile_error)
        .into()
}