aboutsummaryrefslogtreecommitdiff
path: root/mingling_core/src/program/repl_exec.rs
blob: 5246ece5245862c3b73669ffd0d502930bdfebaa (plain) (blame)
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
#![allow(unused_imports)]
#![allow(dead_code)]

use std::io::Write;

mod splitter;

use crate::error::{ProgramInternalExecuteError, ProgramPanic};
use crate::program::repl_exec::splitter::split_input_string;
use crate::{Program, ProgramCollect, RenderResult};

#[cfg(not(feature = "async"))]
impl<C> Program<C>
where
    C: ProgramCollect<Enum = C> + Send + Sync + 'static,
{
    /// Executes the REPL interactive CLI mode.
    ///
    /// This method starts an infinite loop that continuously reads user input, parses commands, executes them,
    /// and displays the execution result or error message. It is suitable for scenarios requiring command-line interaction with the user.
    pub fn exec_repl(self) {
        self.run_hook_repl_on_begin();

        self.exec_wrapper(|p| -> ! {
            loop {
                p.run_hook_repl_pre_readline();
                let readline = readline_or_empty();
                p.run_hook_repl_post_readline(&readline);

                let args = split_input_string(readline.clone());

                match exec_once(p, args) {
                    Ok(r) => {
                        p.run_hook_repl_on_receive_result(&r);
                    }
                    Err(ProgramInternalExecuteError::REPLPanic(panic)) => {
                        p.run_hook_repl_on_panic(&panic);
                    }
                    _ => {}
                }
            }
        });
    }
}

#[cfg(feature = "async")]
impl<C> Program<C>
where
    C: ProgramCollect<Enum = C> + Send + Sync + 'static,
{
    /// Executes the REPL interactive CLI mode.
    ///
    /// This method starts an infinite loop that continuously reads user input, parses commands, executes them,
    /// and displays the execution result or error message. It is suitable for scenarios requiring command-line interaction with the user.
    ///
    /// **Note:** When the `async` feature is enabled, panic unwinding is not supported.
    /// Any panics during command execution will result in an abort rather than being caught and handled gracefully.
    pub async fn exec_repl(self) {
        self.run_hook_repl_on_begin();

        self.exec_wrapper(async |p| -> ! {
            loop {
                p.run_hook_repl_pre_readline();
                let readline = readline_or_empty();
                p.run_hook_repl_post_readline(&readline);

                let args = split_input_string(readline.clone());

                match exec_once(p, args).await {
                    Ok(r) => {
                        p.run_hook_repl_on_receive_result(&r);
                    }
                    _ => {}
                }
            }
        })
        .await;
    }
}

fn readline() -> Result<String, std::io::Error> {
    let mut input = String::new();
    std::io::stdout().flush()?;
    std::io::stdin().read_line(&mut input)?;
    Ok(input.trim().to_string())
}

fn readline_or_empty() -> String {
    readline().unwrap_or("".to_string())
}

#[cfg(not(feature = "async"))]
fn exec_once<C>(
    p: &'static Program<C>,
    args: Vec<String>,
) -> Result<RenderResult, ProgramInternalExecuteError>
where
    C: ProgramCollect<Enum = C> + Send + Sync + 'static,
{
    #[cfg(panic = "abort")]
    let exec_result = super::exec::exec_with_args(p, args);

    #[cfg(not(panic = "abort"))]
    let exec_result = {
        let exec_unwind_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            super::exec::exec_with_args(p, args)
        }));

        match exec_unwind_result {
            Err(panic_info) => {
                let panic_payload = ProgramPanic {
                    payload: panic_info,
                };
                let program = crate::program::THIS_PROGRAM
                    .get()
                    .unwrap()
                    .as_ref()
                    .unwrap()
                    .downcast_ref::<Program<C>>()
                    .unwrap();
                program.run_hook_repl_on_panic(&panic_payload);
                Err(ProgramInternalExecuteError::REPLPanic(panic_payload))
            }
            Ok(r) => r,
        }
    };

    exec_result
}

#[cfg(feature = "async")]
async fn exec_once<C>(
    p: &'static Program<C>,
    args: Vec<String>,
) -> Result<RenderResult, ProgramInternalExecuteError>
where
    C: ProgramCollect<Enum = C> + Send + Sync + 'static,
{
    super::exec::exec_with_args(p, args).await
}