aboutsummaryrefslogtreecommitdiff
path: root/mingling_core/src/program/exec.rs
blob: 72a20b9d61fad270a5fb639f01b045a49dfd49a9 (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
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
#![allow(clippy::borrowed_box)]

use crate::{
    AnyOutput, ChainProcess, Dispatcher, NextProcess, Program, ProgramCollect, RenderResult,
    error::ProgramInternalExecuteError,
};

#[doc(hidden)]
pub mod error;

#[cfg(feature = "async")]
pub async fn exec<C>(
    program: &'static Program<C>,
) -> Result<RenderResult, ProgramInternalExecuteError>
where
    C: ProgramCollect<Enum = C>,
{
    let args = program.args.clone();
    exec_with_args(program, args).await
}

#[cfg(not(feature = "async"))]
pub fn exec<C>(program: &'static Program<C>) -> Result<RenderResult, ProgramInternalExecuteError>
where
    C: ProgramCollect<Enum = C>,
{
    let args = program.args.clone();
    exec_with_args(program, args)
}

#[cfg(feature = "async")]
pub async fn exec_with_args<C>(
    program: &'static Program<C>,
    args: Vec<String>,
) -> Result<RenderResult, ProgramInternalExecuteError>
where
    C: ProgramCollect<Enum = C>,
{
    // Run hooks
    program.run_hook_pre_dispatch(&args);

    #[cfg(not(feature = "dispatch_tree"))]
    let mut current = dispatch_args_dynamic(program, &args)?;

    #[cfg(feature = "dispatch_tree")]
    let mut current = C::dispatch_args_trie(&args)?;

    // Run hook
    program.run_hook_post_dispatch(&current.member_id);

    let mut stop_next = false;

    // If the program has Help enabled, skip actual logic and jump to Help
    if program.user_context.help {
        let mut render_result = render_help::<C>(program, current);

        // Run hook
        render_result.exit_code = program.run_hook_finish();

        return Ok(render_result);
    }

    loop {
        let final_exec = stop_next;

        current = {
            // If a chain exists, execute as a chain
            if C::has_chain(&current) {
                // Run hook
                program.run_hook_pre_chain(&current.member_id, current.inner.as_ref());

                match C::do_chain(current).await {
                    ChainProcess::Ok((any, NextProcess::Renderer)) => {
                        let mut render_result = render::<C>(program, any);

                        // Run hook
                        render_result.exit_code = program.run_hook_finish();

                        return Ok(render_result);
                    }
                    ChainProcess::Ok((any, NextProcess::Chain)) => {
                        // Run hook
                        program.run_hook_post_chain(&any);
                        any
                    }
                    ChainProcess::Err(e) => {
                        // Run hook
                        program.run_hook_finish();
                        return Err(e.into());
                    }
                }
            }
            // If no chain exists, attempt to render
            else if C::has_renderer(&current) {
                // Run hook
                program.run_hook_pre_render(&current.member_id, current.inner.as_ref());

                let mut render_result = render::<C>(program, current);

                // Run hooks
                program.run_hook_post_render(&render_result);
                render_result.exit_code = program.run_hook_finish();

                return Ok(render_result);
            }
            // No renderer exists
            else {
                stop_next = true;
                C::build_renderer_not_found(current.member_id)
            }
        };

        if final_exec && stop_next {
            break;
        }
    }
    let mut render_result = RenderResult::default();

    // Run hook
    render_result.exit_code = program.run_hook_finish();

    Ok(render_result)
}

#[cfg(not(feature = "async"))]
pub fn exec_with_args<C>(
    program: &'static Program<C>,
    args: Vec<String>,
) -> Result<RenderResult, ProgramInternalExecuteError>
where
    C: ProgramCollect<Enum = C>,
{
    // Run hooks
    program.run_hook_pre_dispatch(&args);

    #[cfg(not(feature = "dispatch_tree"))]
    let mut current = dispatch_args_dynamic(program, &args)?;

    #[cfg(feature = "dispatch_tree")]
    let mut current = C::dispatch_args_trie(&args)?;

    // Run hook
    program.run_hook_post_dispatch(&current.member_id);

    let mut stop_next = false;

    // If the program has Help enabled, skip actual logic and jump to Help
    if program.user_context.help {
        let mut render_result = render_help::<C>(program, current);

        // Run hook
        render_result.exit_code = program.run_hook_finish();

        return Ok(render_result);
    }

    loop {
        let final_exec = stop_next;

        current = {
            // If a chain exists, execute as a chain
            if C::has_chain(&current) {
                // Run hook
                program.run_hook_pre_chain(&current.member_id, current.inner.as_ref());

                match C::do_chain(current) {
                    ChainProcess::Ok((any, NextProcess::Renderer)) => {
                        {
                            let mut render_result = render::<C>(program, any);

                            // Run hook
                            render_result.exit_code = program.run_hook_finish();

                            return Ok(render_result);
                        };
                    }
                    ChainProcess::Ok((any, NextProcess::Chain)) => {
                        // Run hook
                        program.run_hook_post_chain(&any);
                        any
                    }
                    ChainProcess::Err(e) => {
                        // Run hook
                        program.run_hook_finish();
                        return Err(e.into());
                    }
                }
            }
            // If no chain exists, attempt to render
            else if C::has_renderer(&current) {
                // Run hook
                program.run_hook_pre_render(&current.member_id, current.inner.as_ref());

                let mut render_result = render::<C>(program, current);

                // Run hooks
                program.run_hook_post_render(&render_result);
                render_result.exit_code = program.run_hook_finish();

                return Ok(render_result);
            }
            // No renderer exists
            else {
                stop_next = true;
                C::build_renderer_not_found(current.member_id)
            }
        };

        if final_exec && stop_next {
            break;
        }
    }
    let mut render_result = RenderResult::default();

    // Run hook
    render_result.exit_code = program.run_hook_finish();

    Ok(render_result)
}

/// Dynamically dispatch input arguments to registered entry types
pub(crate) fn dispatch_args_dynamic<C>(
    program: &'static Program<C>,
    args: &Vec<String>,
) -> Result<AnyOutput<C>, ProgramInternalExecuteError>
where
    C: ProgramCollect<Enum = C>,
{
    let next = match match_user_input(program, args) {
        Ok((dispatcher, args)) => {
            // Entry point
            match dispatcher.begin(args) {
                ChainProcess::Ok((any, _)) => any,
                ChainProcess::Err(e) => return Err(e.into()),
            }
        }
        Err(ProgramInternalExecuteError::DispatcherNotFound) => {
            // No matching Dispatcher is found
            C::build_dispatcher_not_found(args.clone())
        }
        Err(e) => return Err(e),
    };
    Ok(next)
}

/// Match user input against registered dispatchers and return the matched dispatcher and remaining arguments.
#[allow(clippy::type_complexity)]
#[allow(clippy::ptr_arg)]
pub(crate) fn match_user_input<C>(
    program: &'static Program<C>,
    args: &Vec<String>,
) -> Result<(&'static (dyn Dispatcher<C> + Send + Sync), Vec<String>), ProgramInternalExecuteError>
where
    C: ProgramCollect<Enum = C>,
{
    let nodes = program.get_nodes();
    let command = format!("{} ", args.join(" "));

    // Find all nodes that match the command prefix
    let matching_nodes: Vec<&(String, &(dyn Dispatcher<C> + Send + Sync))> = nodes
        .iter()
        // Also add a space to the node string to ensure consistent matching logic
        .filter(|(node_str, _)| command.starts_with(&format!("{} ", node_str)))
        .collect();

    match matching_nodes.len() {
        0 => {
            // No matching node found
            Err(ProgramInternalExecuteError::DispatcherNotFound)
        }
        1 => {
            let matched_prefix = matching_nodes[0];
            let prefix_len = matched_prefix.0.split_whitespace().count();
            let trimmed_args: Vec<String> = args.iter().skip(prefix_len).cloned().collect();
            Ok((matched_prefix.1, trimmed_args))
        }
        _ => {
            // Multiple matching nodes found
            // Find the node with the longest length (most specific match)
            let matched_prefix = matching_nodes
                .iter()
                .max_by_key(|node| node.0.len())
                .unwrap();

            let prefix_len = matched_prefix.0.split_whitespace().count();
            let trimmed_args: Vec<String> = args.iter().skip(prefix_len).cloned().collect();
            Ok((matched_prefix.1, trimmed_args))
        }
    }
}

#[inline(always)]
#[allow(unused_variables)]
fn render<C: ProgramCollect<Enum = C>>(program: &Program<C>, any: AnyOutput<C>) -> RenderResult {
    #[cfg(not(feature = "general_renderer"))]
    {
        let mut render_result = RenderResult::default();
        C::render(any, &mut render_result);
        render_result
    }
    #[cfg(feature = "general_renderer")]
    {
        #[allow(unreachable_patterns)]
        match program.general_renderer_name {
            super::GeneralRendererSetting::Disable => {
                let mut render_result = RenderResult::default();
                C::render(any, &mut render_result);
                render_result
            }
            _ => C::general_render(any, &program.general_renderer_name).unwrap(),
        }
    }
}

#[inline(always)]
#[allow(unused_variables)]
fn render_help<C: ProgramCollect<Enum = C>>(
    program: &Program<C>,
    entry: AnyOutput<C>,
) -> RenderResult {
    #[cfg(not(feature = "general_renderer"))]
    {
        let mut render_result = RenderResult::default();
        C::render_help(entry, &mut render_result);
        render_result
    }
    #[cfg(feature = "general_renderer")]
    {
        #[allow(unreachable_patterns)]
        match program.general_renderer_name {
            super::GeneralRendererSetting::Disable => {
                let mut render_result = RenderResult::default();
                C::render_help(entry, &mut render_result);
                render_result
            }
            _ => RenderResult::default(),
        }
    }
}