Skip to main content

alux_cli_direct/
interpreter.rs

1use crate::command_line::{Cursor, Read, Skipped, read_word};
2use crate::{DirectRender, ParseError, ParseErrorKind, Parsed, help};
3use alux_cli::{
4    ArgumentInfo, CliArgumentError, CliCommandsAlg, CliContextAlg, CliDecodeSources, CliFailureAlg, CliNestAlg,
5    CliOperationAlg, CliOutcome, CliOutcomeOf, CliProgramAlg, CliSources, CommandDescription, Conventions, SourceInfo,
6    USAGE_STATUS,
7};
8use alux_ext::{ApplyAlg, OperationAlg};
9use core::{fmt::Display, future::Future, marker::PhantomData, pin::Pin};
10use std::{
11    ffi::{OsStr, OsString},
12    io::Write,
13    path::Path,
14    sync::Arc,
15    task::{Context, Poll, Wake, Waker},
16    thread::{self, Thread},
17};
18
19/// What one run of a command line shows: its exit status and what it writes to each stream.
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct Exit {
22    /// The status the process exits with; zero is success.
23    pub status: u8,
24    /// The text written to standard output.
25    pub stdout: String,
26    /// The text written to standard error.
27    pub stderr: String,
28}
29
30impl Exit {
31    fn out(status: u8, stdout: String) -> Self {
32        Self { status, stdout, stderr: String::new() }
33    }
34
35    fn err(status: u8, stderr: String) -> Self {
36        Self { status, stdout: String::new(), stderr }
37    }
38
39    /// Writes both streams and ends the process with the status.
40    pub fn exit(self) -> ! {
41        print!("{}", self.stdout);
42        eprint!("{}", self.stderr);
43        let _ = std::io::stdout().flush();
44        std::process::exit(i32::from(self.status))
45    }
46}
47
48/// A command running on its handle, ending in the exit it renders.
49pub type Running = Pin<Box<dyn Future<Output = Exit> + Send>>;
50
51/// A command whose arguments are decoded, waiting for the handle it is applied to.
52pub type Ready<Handle> = Box<dyn FnOnce(Handle) -> Running + Send>;
53
54/// Decodes one command's arguments, its global ones included, or says which its words do not make.
55///
56/// It reads the arguments the command was described as: the global arguments of the contexts
57/// around it, outermost first, and then its own. A failure it renders is prefixed with the name it
58/// is given.
59type Decode<Handle, Decoder> = Arc<
60    dyn Fn(&Decoder, &[ArgumentInfo], &[ArgumentInfo], &str) -> Result<Ready<Handle>, CliArgumentError<String>>
61        + Send
62        + Sync,
63>;
64
65/// One command of a compiled program: what it is, and how to run it on a handle once its words,
66/// read by a `Decoder`, are decoded.
67pub struct Entry<Handle, Decoder = Parsed> {
68    description: CommandDescription,
69    decode: Decode<Handle, Decoder>,
70}
71
72impl<Handle, Decoder> Clone for Entry<Handle, Decoder> {
73    fn clone(&self) -> Self {
74        Self { description: self.description.clone(), decode: Arc::clone(&self.decode) }
75    }
76}
77
78impl<Handle, Decoder> Entry<Handle, Decoder> {
79    /// Describes the command: its path, documentation, and arguments, global ones included.
80    pub fn description(&self) -> &CommandDescription {
81        &self.description
82    }
83
84    /// Decodes the command's arguments from what `decoder` read, ready to apply to a handle; a
85    /// failure it renders is prefixed with `prefix`.
86    ///
87    /// # Errors
88    ///
89    /// Returns the argument the words do not make.
90    pub fn decode(&self, decoder: &Decoder, prefix: &str) -> Result<Ready<Handle>, CliArgumentError<String>> {
91        (self.decode)(decoder, &self.description.context, &self.description.arguments, prefix)
92    }
93}
94
95/// Compiles a CLI program into the commands run on a `Handle`, their words read by a `Decoder`.
96///
97/// `CliDirect` reads words with `Parsed`; another interpretation that parses its own way compiles
98/// with its own decoder. A context compiles its subtree with the compiler for the handle the
99/// context answers.
100pub struct DirectCompiler<Handle, Decoder = Parsed> {
101    /// The only first-layer name whose commands are compiled, when not every command is.
102    selected: Option<&'static str>,
103    marker: PhantomData<fn() -> (Handle, Decoder)>,
104}
105
106impl<Handle, Decoder> DirectCompiler<Handle, Decoder> {
107    /// Compiles only the commands beneath the first-layer name `name`, so no other command is
108    /// described or decoded.
109    pub fn selecting(name: &'static str) -> Self {
110        Self { selected: Some(name), marker: PhantomData }
111    }
112
113    /// Whether the first-layer name `name` is compiled.
114    fn compiles(&self, name: &str) -> bool {
115        self.selected.is_none_or(|selected| selected == name)
116    }
117}
118
119impl<Handle, Decoder> Default for DirectCompiler<Handle, Decoder> {
120    fn default() -> Self {
121        Self { selected: None, marker: PhantomData }
122    }
123}
124
125/// Interprets a CLI program as a command line, applying its operations to `Handle`.
126///
127/// It parses the words, selects the command by its path, decodes the arguments through their
128/// sources, applies the operation, and renders the outcome. `--help` or `-h` prints help built
129/// from the same program.
130pub struct CliDirect<Handle> {
131    handle: Handle,
132    name: Option<String>,
133    prefix: FailurePrefix,
134    unknown: Option<Unknown>,
135    usage: u8,
136    selected: Option<&'static str>,
137    version: Option<&'static str>,
138}
139
140/// How a command line naming no command ends: its status, and its message for the word.
141type Unknown = (u8, Arc<dyn Fn(&str) -> String + Send + Sync>);
142
143/// The status a program declaring a command path more than once exits with, in a debug build:
144/// `EX_SOFTWARE`, as it is the program's fault, not the command line's.
145pub const DUPLICATE_STATUS: u8 = 70;
146
147/// Names what a failure is written after: `error: reason`, `cat: reason`.
148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
149pub enum FailurePrefix {
150    /// `error`.
151    #[default]
152    Error,
153    /// The name the program is invoked as, the file name of the first word.
154    Invocation,
155    /// The name of the command that failed, or the invocation name when no command was selected.
156    Command,
157}
158
159impl<Handle> CliDirect<Handle> {
160    /// Interprets programs against `handle`, the context every operation is applied to.
161    pub fn new(handle: Handle) -> Self {
162        Self {
163            handle,
164            name: None,
165            prefix: FailurePrefix::Error,
166            unknown: None,
167            usage: USAGE_STATUS.get(),
168            selected: None,
169            version: None,
170        }
171    }
172
173    /// Names the program in help instead of the first word of the command line; an empty name
174    /// shows each command beneath no program name.
175    #[must_use]
176    pub fn named(self, name: impl Into<String>) -> Self {
177        Self { name: Some(name.into()), ..self }
178    }
179
180    /// Writes failures after `prefix` instead of `error`.
181    #[must_use]
182    pub fn failures_after(self, prefix: FailurePrefix) -> Self {
183        Self { prefix, ..self }
184    }
185
186    /// Ends words that do not make a command with `status` instead of `USAGE_STATUS`, as utilities
187    /// that state their own do: `BusyBox` `test` exits 2, most of its others 1.
188    #[must_use]
189    pub fn usage_status(self, status: u8) -> Self {
190        Self { usage: status, ..self }
191    }
192
193    /// Compiles only the commands beneath the first-layer name `name`, as a multicall executable
194    /// invoked by that name runs no other; help then lists only those. `None` compiles every
195    /// command.
196    #[must_use]
197    pub fn selecting(self, name: Option<&'static str>) -> Self {
198        Self { selected: name, ..self }
199    }
200
201    /// Answers `--version` or `-V`, written before any command, with the program's name and
202    /// `version`, and lists it in the program's help.
203    #[must_use]
204    pub fn version(self, version: &'static str) -> Self {
205        Self { version: Some(version), ..self }
206    }
207
208    /// Ends a command line that names no command with `status` and the message `message` writes
209    /// for the word, instead of a usage error with the program's help.
210    #[must_use]
211    pub fn unknown_command(self, status: u8, message: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
212        Self { unknown: Some((status, Arc::new(message))), ..self }
213    }
214
215    /// Compiles `program` and selects the command the words name, decoded and ready for a handle.
216    fn start<Program, Words>(&self, program: Program, words: Words) -> Result<Ready<Handle>, Exit>
217    where
218        Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
219        Words: IntoIterator,
220        Words::Item: Into<OsString>,
221    {
222        let mut words = words.into_iter().map(Into::into);
223        let first = words.next().unwrap_or_default();
224        let invoked = Path::new(&first).file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
225        let words = words.collect::<Vec<_>>();
226        let compiler = DirectCompiler { selected: self.selected, marker: PhantomData };
227        let entries = program.compile_cli(&compiler);
228        let name = self.name.clone().unwrap_or_else(|| invoked.clone());
229        let invocation = Invocation {
230            name: &name,
231            invoked: &invoked,
232            prefix: self.prefix,
233            unknown: self.unknown.as_ref(),
234            usage: self.usage,
235            version: self.version,
236        };
237        select(&invocation, &entries, &words)
238    }
239
240    /// Runs `program` on a full command line, applying the selected command to the handle itself.
241    ///
242    /// It takes the handle, so a handle that owns what it reads, and cannot be cloned, runs too.
243    pub fn run_once<Program, Words>(self, program: Program, words: Words) -> Running
244    where
245        Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
246        Words: IntoIterator,
247        Words::Item: Into<OsString>,
248    {
249        match self.start(program, words) {
250            Ok(ready) => ready(self.handle),
251            Err(exit) => Box::pin(async move { exit }),
252        }
253    }
254
255    /// Runs `program` on a full command line with the handle itself, waiting on the calling thread.
256    pub fn run_once_blocking<Program, Words>(self, program: Program, words: Words) -> Exit
257    where
258        Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
259        Words: IntoIterator,
260        Words::Item: Into<OsString>,
261    {
262        block_on(self.run_once(program, words))
263    }
264
265    /// Runs `program` as the process's command line with the handle itself, writes what it shows,
266    /// and ends the process with its status.
267    pub fn run_main<Program>(self, program: Program) -> !
268    where
269        Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
270    {
271        self.run_once_blocking(program, std::env::args_os()).exit()
272    }
273}
274
275impl<Handle> CliDirect<Handle>
276where
277    Handle: Clone,
278{
279    /// Runs `program` on a full command line, its first word the program's name.
280    pub fn run<Program, Words>(
281        &self,
282        program: Program,
283        words: Words,
284    ) -> impl Future<Output = Exit> + use<Handle, Program, Words>
285    where
286        Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
287        Words: IntoIterator,
288        Words::Item: Into<OsString>,
289    {
290        let selected = self.start(program, words).map(|ready| ready(self.handle.clone()));
291
292        async move {
293            match selected {
294                Ok(running) => running.await,
295                Err(exit) => exit,
296            }
297        }
298    }
299
300    /// Runs `program` on a full command line and waits for its exit, on the calling thread.
301    pub fn run_blocking<Program, Words>(&self, program: Program, words: Words) -> Exit
302    where
303        Program: CliProgramAlg<DirectCompiler<Handle>, Commands = Vec<Entry<Handle>>>,
304        Words: IntoIterator,
305        Words::Item: Into<OsString>,
306    {
307        block_on(self.run(program, words))
308    }
309}
310
311/// How the program was invoked: the name its help shows, the name it was invoked as, what a
312/// failure is written after, how a command line naming no command ends, and the status of a usage
313/// error.
314struct Invocation<'a> {
315    name: &'a str,
316    invoked: &'a str,
317    prefix: FailurePrefix,
318    unknown: Option<&'a Unknown>,
319    usage: u8,
320    version: Option<&'static str>,
321}
322
323impl Invocation<'_> {
324    /// Names what a failure of `command` is written after.
325    fn prefix(&self, command: Option<&CommandDescription>) -> String {
326        match self.prefix {
327            FailurePrefix::Error => "error".to_owned(),
328            FailurePrefix::Invocation => self.invoked.to_owned(),
329            FailurePrefix::Command => command
330                .and_then(|command| command.path.last())
331                .map_or_else(|| self.invoked.to_owned(), |name| (*name).to_owned()),
332        }
333    }
334}
335
336/// Whether `word` is the text `text`.
337fn is(word: &OsStr, text: &str) -> bool {
338    word.to_str() == Some(text)
339}
340
341/// Selects the command the words name, by its longest path, and decodes its arguments.
342fn select<Handle>(
343    invocation: &Invocation<'_>,
344    entries: &[Entry<Handle>],
345    words: &[OsString],
346) -> Result<Ready<Handle>, Exit> {
347    // A program declaring one path more than once runs nothing, whatever the words: it fails on
348    // every start, `--version` and `--help` included. As in `clap`, the check is the program's own,
349    // not the command line's, so a debug build makes it and a release build saves its cost.
350    #[cfg(debug_assertions)]
351    if let Some(duplicated) = duplicated(entries) {
352        return Err(Exit::err(DUPLICATE_STATUS, format!("error: commands declared more than once: {duplicated}\n")));
353    }
354    let name = invocation.name;
355    let descriptions = entries.iter().map(|entry| &entry.description).collect::<Vec<_>>();
356    if let Some(version) = invocation.version
357        && words.first().is_some_and(|word| is(word, "--version") || is(word, "-V"))
358    {
359        return Err(Exit::out(0, format!("{name} {version}\n")));
360    }
361    let selected = entries
362        .iter()
363        .filter_map(|entry| path_words(&entry.description, words).map(|words| (entry, words)))
364        .max_by_key(|(entry, _)| entry.description.path.len());
365    let Some((entry, words)) = selected else {
366        let prefix = invocation.prefix(None);
367        let help = |word: &OsString| is(word, "--help") || is(word, "-h");
368        let first = words.iter().find(|word| !help(word) && word.as_encoded_bytes().starts_with(b"-"));
369        if let Some(option) = first.filter(|_| !words.iter().any(help)) {
370            let option = option.to_string_lossy();
371            let spelled = option.split_once('=').map_or(&*option, |(spelled, _)| spelled);
372            return Err(Exit::err(
373                invocation.usage,
374                format!(
375                    "{prefix}: unknown option `{spelled}`\n\n{}",
376                    help::program(name, &descriptions, invocation.version)
377                ),
378            ));
379        }
380        return Err(match words.first().map(|word| word.to_string_lossy()) {
381            None => Exit::err(invocation.usage, help::program(name, &descriptions, invocation.version)),
382            Some(word) if matches!(&*word, "--help" | "-h" | "help") => {
383                Exit::out(0, help::program(name, &descriptions, invocation.version))
384            }
385            Some(word) => match invocation.unknown {
386                Some((status, message)) => Exit::err(*status, format!("{}\n", message(&word))),
387                None => Exit::err(
388                    invocation.usage,
389                    format!(
390                        "{prefix}: unknown command `{word}`\n\n{}",
391                        help::program(name, &descriptions, invocation.version)
392                    ),
393                ),
394            },
395        });
396    };
397    let description = &entry.description;
398    let conventions = description.conventions;
399    let prefix = invocation.prefix(Some(description));
400    let rest = &words[..];
401    let arguments = description.context.iter().chain(&description.arguments).cloned().collect::<Vec<_>>();
402    let declares_help = arguments.iter().any(|argument| {
403        matches!(&argument.source, SourceInfo::Named { long, short, short_aliases } if long == "help" || *short == Some('h') || short_aliases.contains(&'h'))
404    });
405    // A verbatim command answers no help; another answers it among its options.
406    let options = rest.iter().take_while(|word| !(conventions.double_dash_ends_options && is(word, "--")));
407    if !declares_help && !conventions.verbatim && options.into_iter().any(|word| is(word, "--help") || is(word, "-h")) {
408        // The program's own command, beside named ones, is helped with them.
409        if description.path.is_empty() {
410            return Err(Exit::out(0, help::program(name, &descriptions, invocation.version)));
411        }
412        return Err(Exit::out(0, help::command(name, description)));
413    }
414    let usage =
415        |error: String| Exit::err(invocation.usage, format!("{prefix}: {error}\n\n{}", help::usage(name, description)));
416    let parsed = Parsed::new(&arguments, rest, conventions).map_err(|error| usage(parse_error(&error, rest)))?;
417
418    entry.decode(&parsed, &prefix).map_err(|error| usage(argument_error(&error)))
419}
420
421/// Names each command path declared more than once, in declaration order, or nothing when every path
422/// is declared once.
423#[cfg(debug_assertions)]
424fn duplicated<Handle>(entries: &[Entry<Handle>]) -> Option<String> {
425    let paths = entries.iter().map(|entry| &entry.description.path).collect::<Vec<_>>();
426    let mut duplicated = Vec::new();
427    for (at, path) in paths.iter().enumerate() {
428        if paths[..at].contains(path) && !duplicated.contains(path) {
429            duplicated.push(*path);
430        }
431    }
432    let named = duplicated.iter().map(|path| format!("`{}`", path.join(" "))).collect::<Vec<_>>();
433    (!named.is_empty()).then(|| named.join(", "))
434}
435
436/// Matches a command's path against the words, skipping the global options written before it.
437///
438/// Answers the words that remain for the command's arguments, the skipped global options first, or
439/// nothing when the words do not name this command. A global option before or within the path is
440/// read as after it, with the value word it takes.
441fn path_words(description: &CommandDescription, words: &[OsString]) -> Option<Vec<OsString>> {
442    let mut cursor = Cursor::new(words);
443    let mut global = Vec::new();
444    for segment in &description.path {
445        loop {
446            let start = cursor.at();
447            if is(words.get(start)?, segment) {
448                cursor.bump();
449                break;
450            }
451            // Only global options come before or within the path, so `--` ends options nowhere here.
452            let conventions = Conventions { double_dash_ends_options: false, ..Conventions::default() };
453            let read = read_word(&description.context, conventions, &mut cursor, &mut Skipped).ok()??;
454            if read != Read::Options {
455                return None;
456            }
457            global.extend_from_slice(&words[start..cursor.at()]);
458        }
459    }
460    global.extend_from_slice(&words[cursor.at()..]);
461
462    Some(global)
463}
464
465/// Says what is wrong with `words`, naming the word it is in when that is more than the option.
466fn parse_error(error: &ParseError, words: &[OsString]) -> String {
467    let said = match &error.kind {
468        ParseErrorKind::Unknown(spelling) => format!("unknown option `{spelling}`"),
469        ParseErrorKind::MissingValue(spelling) => format!("`{spelling}` needs a value"),
470        ParseErrorKind::SwitchValue(spelling) => format!("`{spelling}` takes no value"),
471        ParseErrorKind::Unexpected(word) => return format!("unexpected argument `{word}`"),
472    };
473    match words.get(error.at.word).map(|word| word.to_string_lossy()) {
474        // A letter inside a cluster is placed in the word that clusters it.
475        Some(word) if error.at.byte > 1 => format!("{said} in `{word}`"),
476        _ => said,
477    }
478}
479
480fn argument_error(error: &CliArgumentError<String>) -> String {
481    // An argument is named as the command line spells its value.
482    let spelled = |name: &str| name.replace('_', "-");
483    match error {
484        CliArgumentError::Missing(name) => format!("missing <{}>", spelled(name)),
485        CliArgumentError::Repeated(name) => format!("<{}> given more than once", spelled(name)),
486        CliArgumentError::Word(name, reason) => format!("invalid <{}>: {reason}", spelled(name)),
487        CliArgumentError::Conflict(first, second) => {
488            format!("<{}> and <{}> cannot be given together", spelled(first), spelled(second))
489        }
490    }
491}
492
493/// Renders an outcome as the exit it ends with, or answers the value it succeeded with.
494fn outcome<Value, Error>(outcome: CliOutcome<Value, Error>, prefix: &str) -> Result<Value, Exit>
495where
496    Error: Display + CliFailureAlg,
497{
498    let status = outcome.cli_status();
499    match outcome {
500        CliOutcome::Success(value) => Ok(value),
501        // A failure already reported as it happened leaves only its status to the exit.
502        CliOutcome::Failure(error) if error.cli_reported() => Err(Exit::err(status, String::new())),
503        CliOutcome::Failure(error) => Err(Exit::err(status, format!("{prefix}: {error}\n"))),
504    }
505}
506
507impl<Handle, Decoder> CliCommandsAlg for DirectCompiler<Handle, Decoder> {
508    type Commands = Vec<Entry<Handle, Decoder>>;
509
510    fn cli_empty(&self) -> Self::Commands {
511        Vec::new()
512    }
513
514    fn cli_merge(&self, mut left: Self::Commands, right: Self::Commands) -> Self::Commands {
515        left.extend(right);
516        left
517    }
518}
519
520impl<Handle, Decoder> CliNestAlg for DirectCompiler<Handle, Decoder> {
521    type Commands = Vec<Entry<Handle, Decoder>>;
522
523    fn cli_nest(&self, name: &'static str, mut commands: Self::Commands) -> Self::Commands {
524        for entry in &mut commands {
525            entry.description.path.insert(0, name);
526        }
527        commands
528    }
529
530    /// A selected name's subtree compiles in full; any other compiles to nothing.
531    fn cli_nest_with(&self, name: &'static str, compile: impl FnOnce(&Self) -> Self::Commands) -> Self::Commands {
532        if !self.compiles(name) {
533            return Vec::new();
534        }
535        self.cli_nest(name, compile(&Self::default()))
536    }
537}
538
539impl<Handle, Decoder, Operation, Sources, Mode> CliOperationAlg<Operation, Sources, Mode>
540    for DirectCompiler<Handle, Decoder>
541where
542    Handle: Send + 'static,
543    Decoder: 'static,
544    Operation: OperationAlg + ApplyAlg<Handle, Operation::Args> + Send + Sync + 'static,
545    Operation::Args: Send,
546    Sources: CliSources<Operation::Args> + CliDecodeSources<Operation::Args, Decoder, String> + Send + Sync + 'static,
547    Mode: CliOutcomeOf<Operation::Output> + Send + Sync + 'static,
548    Mode::Value: DirectRender,
549    Mode::Error: Display + CliFailureAlg,
550{
551    type Commands = Vec<Entry<Handle, Decoder>>;
552
553    fn cli_operation(
554        &self,
555        name: &'static str,
556        operation: Operation,
557        sources: Sources,
558        mode: Mode,
559        conventions: Conventions,
560    ) -> Self::Commands {
561        if !self.compiles(name) {
562            return Vec::new();
563        }
564        let mut description = CommandDescription::of::<Operation, Sources>(name, &sources);
565        description.conventions = conventions;
566        let (operation, mode) = (Arc::new(operation), Arc::new(mode));
567        let decode: Decode<Handle, Decoder> = Arc::new(move |parsed, _, arguments, prefix| {
568            let args = sources.cli_decode(arguments, parsed)?;
569            let (operation, mode, prefix) = (Arc::clone(&operation), Arc::clone(&mode), prefix.to_owned());
570            Ok(Box::new(move |handle| {
571                Box::pin(async move {
572                    match outcome(mode.cli_outcome(operation.apply(handle, args).await), &prefix) {
573                        Ok(value) => {
574                            let mut out = String::new();
575                            value.render(&mut out);
576                            if !out.is_empty() {
577                                out.push('\n');
578                            }
579                            Exit::out(0, out)
580                        }
581                        Err(exit) => exit,
582                    }
583                }) as Running
584            }) as Ready<Handle>)
585        });
586        vec![Entry { description, decode }]
587    }
588}
589
590/// Applies a subtree's commands to the handle the context operation answers.
591///
592/// The global arguments are decoded with the command's own, so a usage error is reported before
593/// the context is opened; a context that fails ends the run with its status.
594impl<Handle, Decoder, Operation, Sources, Mode> CliContextAlg<Operation, Sources, Mode>
595    for DirectCompiler<Handle, Decoder>
596where
597    Handle: Send + 'static,
598    Decoder: 'static,
599    Operation: OperationAlg + ApplyAlg<Handle, Operation::Args> + Send + Sync + 'static,
600    Operation::Args: Send,
601    Sources: CliSources<Operation::Args> + CliDecodeSources<Operation::Args, Decoder, String> + Send + Sync + 'static,
602    Mode: CliOutcomeOf<Operation::Output> + Send + Sync + 'static,
603    Mode::Value: Send + 'static,
604    Mode::Error: Display + CliFailureAlg,
605{
606    type Inner = DirectCompiler<Mode::Value, Decoder>;
607    type InnerCommands = Vec<Entry<Mode::Value, Decoder>>;
608    type Commands = Vec<Entry<Handle, Decoder>>;
609
610    /// A context adds no path, so its subtree's first layer is this one's, selected alike.
611    fn cli_inner(&self) -> Self::Inner {
612        DirectCompiler { selected: self.selected, marker: PhantomData }
613    }
614
615    fn cli_within(
616        &self,
617        operation: Operation,
618        sources: Sources,
619        mode: Mode,
620        commands: Self::InnerCommands,
621    ) -> Self::Commands {
622        let global = sources.cli_arguments(Operation::ARG_NAMES);
623        let count = global.len();
624        let (operation, sources, mode) = (Arc::new(operation), Arc::new(sources), Arc::new(mode));
625        commands
626            .into_iter()
627            .map(|Entry { mut description, decode: inner }| {
628                description.context.splice(0..0, global.iter().cloned());
629                let (operation, sources, mode) = (Arc::clone(&operation), Arc::clone(&sources), Arc::clone(&mode));
630                let decode: Decode<Handle, Decoder> = Arc::new(move |parsed, context, arguments, prefix| {
631                    // This context's global arguments come first; the rest are the subtree's.
632                    let (global, inner_context) = context.split_at(count);
633                    let args = sources.cli_decode(global, parsed)?;
634                    let command = inner(parsed, inner_context, arguments, prefix)?;
635                    let (operation, mode, prefix) = (Arc::clone(&operation), Arc::clone(&mode), prefix.to_owned());
636                    Ok(Box::new(move |handle| {
637                        Box::pin(async move {
638                            match outcome(mode.cli_outcome(operation.apply(handle, args).await), &prefix) {
639                                Ok(context) => command(context).await,
640                                Err(exit) => exit,
641                            }
642                        }) as Running
643                    }) as Ready<Handle>)
644                });
645                Entry { description, decode }
646            })
647            .collect()
648    }
649}
650
651/// Wakes the thread waiting on a future.
652struct Unpark(Thread);
653
654impl Wake for Unpark {
655    fn wake(self: Arc<Self>) {
656        self.0.unpark();
657    }
658}
659
660/// Waits for `future` on the calling thread.
661fn block_on<Output>(future: impl Future<Output = Output>) -> Output {
662    let mut future = core::pin::pin!(future);
663    let waker = Waker::from(Arc::new(Unpark(thread::current())));
664    let mut context = Context::from_waker(&waker);
665    loop {
666        if let Poll::Ready(output) = future.as_mut().poll(&mut context) {
667            return output;
668        }
669        thread::park();
670    }
671}