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
use crate::sdk::std::flowcontrol::{end, forin, function, get_line_key};
use crate::utils::state::{get_core_sub_state_for_command, get_list, get_sub_state};
use crate::utils::{condition, instruction_query, pckg};
use duckscript::types::command::{Command, CommandResult, Commands, GoToValue};
use duckscript::types::error::ScriptError;
use duckscript::types::instruction::Instruction;
use duckscript::types::runtime::StateValue;
use std::collections::HashMap;

#[cfg(test)]
#[path = "./mod_test.rs"]
mod mod_test;

static IFELSE_STATE_KEY: &str = "ifelse";
static META_INFO_STATE_KEY: &str = "meta_info";
static CALL_STACK_STATE_KEY: &str = "call_stack";

#[derive(Debug, Clone)]
struct IfElseMetaInfo {
    pub(crate) start: usize,
    pub(crate) end: usize,
    pub(crate) else_lines: Vec<usize>,
}

#[derive(Debug)]
struct CallInfo {
    pub(crate) current: usize,
    pub(crate) passed: bool,
    pub(crate) else_line_index: usize,
    pub(crate) meta_info: IfElseMetaInfo,
}

fn serialize_ifelse_meta_info(
    meta_info: &IfElseMetaInfo,
    sub_state: &mut HashMap<String, StateValue>,
) {
    sub_state.insert(
        "start".to_string(),
        StateValue::UnsignedNumber(meta_info.start),
    );
    sub_state.insert("end".to_string(), StateValue::UnsignedNumber(meta_info.end));

    let mut list = vec![];
    for line in &meta_info.else_lines {
        list.push(StateValue::UnsignedNumber(*line));
    }
    sub_state.insert("else_lines".to_string(), StateValue::List(list));
}

fn deserialize_ifelse_meta_info(
    sub_state: &mut HashMap<String, StateValue>,
) -> Option<IfElseMetaInfo> {
    let start = match sub_state.get("start") {
        Some(state_value) => match state_value {
            StateValue::UnsignedNumber(value) => *value,
            _ => return None,
        },
        None => return None,
    };
    let end = match sub_state.get("end") {
        Some(state_value) => match state_value {
            StateValue::UnsignedNumber(value) => *value,
            _ => return None,
        },
        None => return None,
    };

    let mut else_lines = vec![];
    match sub_state.get("else_lines") {
        Some(state_values_list) => match state_values_list {
            StateValue::List(list) => {
                for state_value_item in list {
                    match state_value_item {
                        StateValue::UnsignedNumber(value) => else_lines.push(*value),
                        _ => return None,
                    }
                }
            }
            _ => return None,
        },
        None => return None,
    };

    Some(IfElseMetaInfo {
        start,
        end,
        else_lines,
    })
}

fn serialize_call_info(call_info: &CallInfo, sub_state: &mut HashMap<String, StateValue>) {
    sub_state.insert(
        "current".to_string(),
        StateValue::UnsignedNumber(call_info.current),
    );
    sub_state.insert("passed".to_string(), StateValue::Boolean(call_info.passed));
    sub_state.insert(
        "else_line_index".to_string(),
        StateValue::UnsignedNumber(call_info.else_line_index),
    );

    let mut meta_info_state = HashMap::new();
    serialize_ifelse_meta_info(&call_info.meta_info, &mut meta_info_state);
    sub_state.insert(
        "meta_info".to_string(),
        StateValue::SubState(meta_info_state),
    );
}

fn deserialize_call_info(sub_state: &mut HashMap<String, StateValue>) -> Option<CallInfo> {
    let current = match sub_state.get("current") {
        Some(state_value) => match state_value {
            StateValue::UnsignedNumber(value) => *value,
            _ => return None,
        },
        None => return None,
    };
    let passed = match sub_state.get("passed") {
        Some(state_value) => match state_value {
            StateValue::Boolean(value) => *value,
            _ => return None,
        },
        None => return None,
    };
    let else_line_index = match sub_state.get("else_line_index") {
        Some(state_value) => match state_value {
            StateValue::UnsignedNumber(value) => *value,
            _ => return None,
        },
        None => return None,
    };
    let meta_info = match sub_state.get("meta_info") {
        Some(state_value) => match state_value.clone() {
            StateValue::SubState(mut value) => match deserialize_ifelse_meta_info(&mut value) {
                Some(meta_info) => meta_info,
                None => return None,
            },
            _ => return None,
        },
        None => return None,
    };

    Some(CallInfo {
        current,
        passed,
        else_line_index,
        meta_info,
    })
}

fn create_if_meta_info_for_line(
    line: usize,
    instructions: &Vec<Instruction>,
    package: String,
) -> Result<IfElseMetaInfo, String> {
    // start names
    let if_command = IfCommand {
        package: package.clone(),
    };
    let mut start_names = if_command.aliases();
    start_names.push(if_command.name());

    // middle names
    let else_if_command = ElseIfCommand {
        package: package.clone(),
    };
    let mut middle_names = else_if_command.aliases();
    start_names.push(else_if_command.name());
    let else_command = ElseCommand {
        package: package.clone(),
    };
    middle_names.append(&mut else_command.aliases());
    start_names.push(else_command.name());

    // end names
    let end_if_command = EndIfCommand {
        package: package.clone(),
    };
    let mut end_names = end_if_command.aliases();
    end_names.push(end_if_command.name());
    end_names.push(end::END_COMMAND_NAME.to_string());

    let function_command = function::FunctionCommand::new(&package);
    let mut start_blocks = function_command.aliases();
    start_blocks.push(function_command.name());
    let forin_command = forin::ForInCommand::new(&package);
    start_blocks.append(&mut forin_command.aliases());
    start_blocks.push(forin_command.name());

    let end_forin_command = forin::EndForInCommand::new(&package);
    let mut end_blocks = end_forin_command.aliases();
    end_blocks.push(end_forin_command.name());
    let end_function_command = function::EndFunctionCommand::new(&package);
    end_blocks.append(&mut end_function_command.aliases());
    end_blocks.push(end_function_command.name());
    end_blocks.push(end::END_COMMAND_NAME.to_string());

    let positions_options = instruction_query::find_commands(
        instructions,
        &start_names,
        &middle_names,
        &end_names,
        Some(line + 1),
        None,
        true,
        &start_blocks,
        &end_blocks,
    )?;

    match positions_options {
        Some(positions) => Ok(IfElseMetaInfo {
            start: line,
            end: positions.end,
            else_lines: positions.middle,
        }),
        None => Err("End of if/else block not found.".to_string()),
    }
}

fn get_or_create_if_meta_info_for_line(
    line: usize,
    state: &mut HashMap<String, StateValue>,
    instructions: &Vec<Instruction>,
    package: String,
) -> Result<IfElseMetaInfo, String> {
    let key = get_line_key(line, state);
    let if_state = get_core_sub_state_for_command(state, IFELSE_STATE_KEY.to_string());
    let if_meta_info_state = get_sub_state(META_INFO_STATE_KEY.to_string(), if_state);

    let mut if_state_for_line = get_sub_state(key.clone(), if_meta_info_state);

    let result = match deserialize_ifelse_meta_info(&mut if_state_for_line) {
        Some(if_else_info) => Ok(if_else_info),
        None => match create_if_meta_info_for_line(line, instructions, package.clone()) {
            Ok(if_else_info) => {
                serialize_ifelse_meta_info(&if_else_info, if_state_for_line);
                Ok(if_else_info)
            }
            Err(error) => Err(error),
        },
    };

    match result {
        Ok(ref info) => {
            let end_if_command = EndIfCommand {
                package: package.clone(),
            };
            end::set_command(info.end, state, end_if_command.name());
        }
        _ => (),
    };

    result
}

fn pop_call_info_for_line(
    line: usize,
    state: &mut HashMap<String, StateValue>,
) -> Option<CallInfo> {
    let if_state = get_core_sub_state_for_command(state, IFELSE_STATE_KEY.to_string());
    let call_info_stack = get_list(CALL_STACK_STATE_KEY.to_string(), if_state);

    match call_info_stack.pop() {
        Some(state_value) => match state_value {
            StateValue::SubState(mut call_info_state) => {
                match deserialize_call_info(&mut call_info_state) {
                    Some(call_info) => {
                        if call_info.current == line {
                            Some(call_info)
                        } else {
                            pop_call_info_for_line(line, state)
                        }
                    }
                    None => None,
                }
            }
            _ => pop_call_info_for_line(line, state),
        },
        None => None,
    }
}

fn store_call_info(call_info: &CallInfo, state: &mut HashMap<String, StateValue>) {
    let if_state = get_core_sub_state_for_command(state, IFELSE_STATE_KEY.to_string());
    let call_info_stack = get_list(CALL_STACK_STATE_KEY.to_string(), if_state);

    let mut call_info_state = HashMap::new();
    serialize_call_info(call_info, &mut call_info_state);
    call_info_stack.push(StateValue::SubState(call_info_state));
}

#[derive(Clone)]
pub(crate) struct IfCommand {
    package: String,
}

impl IfCommand {
    /// Creates and returns a new instance.
    pub(crate) fn new(package: &str) -> IfCommand {
        IfCommand {
            package: package.to_string(),
        }
    }
}

impl Command for IfCommand {
    fn name(&self) -> String {
        pckg::concat(&self.package, "If")
    }

    fn aliases(&self) -> Vec<String> {
        vec!["if".to_string()]
    }

    fn help(&self) -> String {
        include_str!("help.md").to_string()
    }

    fn clone_and_box(&self) -> Box<dyn Command> {
        Box::new((*self).clone())
    }

    fn requires_context(&self) -> bool {
        true
    }

    fn run_with_context(
        &self,
        arguments: Vec<String>,
        state: &mut HashMap<String, StateValue>,
        variables: &mut HashMap<String, String>,
        _output_variable: Option<String>,
        instructions: &Vec<Instruction>,
        commands: &mut Commands,
        line: usize,
    ) -> CommandResult {
        if arguments.is_empty() {
            CommandResult::Error("Missing condition".to_string())
        } else {
            match get_or_create_if_meta_info_for_line(
                line,
                state,
                instructions,
                self.package.clone(),
            ) {
                Ok(if_else_info) => {
                    match condition::eval_condition(
                        arguments,
                        instructions,
                        state,
                        variables,
                        commands,
                    ) {
                        Ok(passed) => {
                            if passed {
                                let next_line = if if_else_info.else_lines.is_empty() {
                                    if_else_info.end
                                } else {
                                    if_else_info.else_lines[0]
                                };

                                let call_info = CallInfo {
                                    current: next_line,
                                    passed,
                                    else_line_index: 0,
                                    meta_info: if_else_info.clone(),
                                };

                                store_call_info(&call_info, state);

                                CommandResult::Continue(None)
                            } else if if_else_info.else_lines.is_empty() {
                                let next_line = if_else_info.end + 1;
                                CommandResult::GoTo(None, GoToValue::Line(next_line))
                            } else {
                                let next_line = if_else_info.else_lines[0];

                                let call_info = CallInfo {
                                    current: next_line,
                                    passed: false,
                                    else_line_index: 0,
                                    meta_info: if_else_info.clone(),
                                };

                                store_call_info(&call_info, state);

                                CommandResult::GoTo(None, GoToValue::Line(next_line))
                            }
                        }
                        Err(error) => CommandResult::Error(error.to_string()),
                    }
                }
                Err(error) => CommandResult::Crash(error.to_string()),
            }
        }
    }
}

#[derive(Clone)]
struct ElseIfCommand {
    package: String,
}

impl Command for ElseIfCommand {
    fn name(&self) -> String {
        pckg::concat(&self.package, "ElseIf")
    }

    fn aliases(&self) -> Vec<String> {
        vec!["elif".to_string(), "elseif".to_string()]
    }

    fn help(&self) -> String {
        "".to_string()
    }

    fn clone_and_box(&self) -> Box<dyn Command> {
        Box::new((*self).clone())
    }

    fn requires_context(&self) -> bool {
        true
    }

    fn run_with_context(
        &self,
        arguments: Vec<String>,
        state: &mut HashMap<String, StateValue>,
        variables: &mut HashMap<String, String>,
        _output_variable: Option<String>,
        instructions: &Vec<Instruction>,
        commands: &mut Commands,
        line: usize,
    ) -> CommandResult {
        if arguments.is_empty() {
            CommandResult::Error("Missing condition".to_string())
        } else {
            match pop_call_info_for_line(line, state) {
            Some(call_info) => {
                if call_info.passed {
                    let next_line = call_info.meta_info.end + 1;
                    CommandResult::GoTo(None, GoToValue::Line(next_line))
                } else {
                    let if_else_info = call_info.meta_info.clone();
                    match condition::eval_condition(arguments, instructions, state, variables, commands) {
                        Ok(passed) => {
                            if passed {
                                let next_line = if call_info.else_line_index + 1 < if_else_info.else_lines.len() {
                                    if_else_info.else_lines[call_info.else_line_index + 1]
                                } else {
                                    if_else_info.else_lines[0]
                                };

                                let else_call_info = CallInfo {
                                    current: next_line,
                                    passed,
                                    else_line_index: call_info.else_line_index,
                                    meta_info: if_else_info,
                                };

                                store_call_info(&else_call_info, state);

                                CommandResult::Continue(None)
                            } else if call_info.else_line_index + 1 < if_else_info.else_lines.len() {
                                let next_index = call_info.else_line_index + 1;
                                let next_line = if_else_info.else_lines[next_index];

                                let call_info = CallInfo {
                                    current: next_line,
                                    passed: false,
                                    else_line_index: next_index,
                                    meta_info: if_else_info,
                                };

                                store_call_info(&call_info, state);

                                CommandResult::GoTo(None, GoToValue::Line(next_line))
                            } else {
                                let next_line = if_else_info.end + 1;

                                CommandResult::GoTo(None, GoToValue::Line(next_line))
                            }
                        }
                        Err(error) => CommandResult::Error(error.to_string()),
                    }
                }
            },
            None => CommandResult::Error("Found an else-if block but not currently running part of an if/else invocation flow.".to_string())
        }
        }
    }
}

#[derive(Clone)]
struct ElseCommand {
    package: String,
}

impl Command for ElseCommand {
    fn name(&self) -> String {
        pckg::concat(&self.package, "Else")
    }

    fn aliases(&self) -> Vec<String> {
        vec!["else".to_string()]
    }

    fn help(&self) -> String {
        "".to_string()
    }

    fn clone_and_box(&self) -> Box<dyn Command> {
        Box::new((*self).clone())
    }

    fn requires_context(&self) -> bool {
        true
    }

    fn run_with_context(
        &self,
        _arguments: Vec<String>,
        state: &mut HashMap<String, StateValue>,
        _variables: &mut HashMap<String, String>,
        _output_variable: Option<String>,
        _instructions: &Vec<Instruction>,
        _commands: &mut Commands,
        line: usize,
    ) -> CommandResult {
        match pop_call_info_for_line(line, state) {
            Some(call_info) => {
                if call_info.passed {
                    let next_line = call_info.meta_info.end + 1;
                    CommandResult::GoTo(None, GoToValue::Line(next_line))
                } else {
                    CommandResult::Continue(None)
                }
            }
            None => CommandResult::Error(
                "Found an else block but not currently running part of an if/else invocation flow."
                    .to_string(),
            ),
        }
    }
}

#[derive(Clone)]
pub(crate) struct EndIfCommand {
    package: String,
}

impl EndIfCommand {
    /// Creates and returns a new instance.
    pub(crate) fn new(package: &str) -> EndIfCommand {
        EndIfCommand {
            package: package.to_string(),
        }
    }
}

impl Command for EndIfCommand {
    fn name(&self) -> String {
        pckg::concat(&self.package, "EndIf")
    }

    fn aliases(&self) -> Vec<String> {
        vec!["end_if".to_string(), "endif".to_string(), "fi".to_string()]
    }

    fn help(&self) -> String {
        "".to_string()
    }

    fn clone_and_box(&self) -> Box<dyn Command> {
        Box::new((*self).clone())
    }

    fn run(&self, _arguments: Vec<String>) -> CommandResult {
        CommandResult::Continue(None)
    }
}

pub(crate) fn create(package: &str) -> Vec<Box<dyn Command>> {
    vec![
        Box::new(IfCommand {
            package: package.to_string(),
        }),
        Box::new(ElseIfCommand {
            package: package.to_string(),
        }),
        Box::new(ElseCommand {
            package: package.to_string(),
        }),
        Box::new(EndIfCommand {
            package: package.to_string(),
        }),
    ]
}

pub(crate) fn load(commands: &mut Commands, package: &str) -> Result<(), ScriptError> {
    let multi_commands = create(package);

    for command in multi_commands {
        commands.set(command)?;
    }

    Ok(())
}