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
//! # runner
//!
//! The main entry point which enables running scripts.
//!

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

use crate::expansion::{self, ExpandedValue};
use crate::parser;
use crate::types::command::{CommandResult, Commands, GoToValue};
use crate::types::error::{ErrorInfo, ScriptError};
use crate::types::instruction::{
    Instruction, InstructionMetaInfo, InstructionType, ScriptInstruction,
};
use crate::types::runtime::{Context, Runtime, StateValue};
use std::collections::HashMap;
use std::io::stdin;

#[derive(Debug)]
enum EndReason {
    ExitCalled,
    ReachedEnd,
    Crash(ScriptError),
}

/// Executes the provided script with the given context
pub fn run_script(text: &str, context: Context) -> Result<Context, ScriptError> {
    match parser::parse_text(text) {
        Ok(instructions) => run(instructions, context),
        Err(error) => Err(error),
    }
}

/// Executes the provided script file with the given context
pub fn run_script_file(file: &str, context: Context) -> Result<Context, ScriptError> {
    match parser::parse_file(file) {
        Ok(instructions) => run(instructions, context),
        Err(error) => Err(error),
    }
}

/// Provides the REPL entry point
pub fn repl(mut context: Context) -> Result<Context, ScriptError> {
    let mut text = String::new();
    let mut instructions = vec![];

    loop {
        text.clear();

        match stdin().read_line(&mut text) {
            Ok(_) => {
                match parser::parse_text(&text) {
                    Ok(mut new_instructions) => {
                        // get start line
                        let start = instructions.len();

                        // add new instructions
                        instructions.append(&mut new_instructions);
                        let runtime = create_runtime(instructions.clone(), context);

                        let (updated_context, end_reason) = run_instructions(runtime, start, true)?;

                        context = updated_context;

                        match end_reason {
                            EndReason::ExitCalled => return Ok(context),
                            EndReason::Crash(error) => println!("{}", &error.to_string()),
                            _ => (),
                        };
                    }
                    Err(error) => return Err(error),
                }
            }
            Err(error) => {
                return Err(ScriptError {
                    info: ErrorInfo::Runtime(error.to_string(), Some(InstructionMetaInfo::new())),
                });
            }
        };
    }
}

fn run(instructions: Vec<Instruction>, context: Context) -> Result<Context, ScriptError> {
    let runtime = create_runtime(instructions, context);

    match run_instructions(runtime, 0, false) {
        Ok((context, _)) => Ok(context),
        Err(error) => Err(error),
    }
}

fn create_runtime(instructions: Vec<Instruction>, context: Context) -> Runtime {
    let mut runtime = Runtime::new(context);

    let mut line = 0;
    for instruction in &instructions {
        match &instruction.instruction_type {
            InstructionType::Script(ref value) => {
                match value.label {
                    Some(ref label) => {
                        runtime.label_to_line.insert(label.to_string(), line);
                        ()
                    }
                    None => (),
                };
            }
            _ => (),
        };

        line = line + 1;
    }

    runtime.instructions = Some(instructions);

    runtime
}

fn run_instructions(
    mut runtime: Runtime,
    start_at: usize,
    repl_mode: bool,
) -> Result<(Context, EndReason), ScriptError> {
    let mut line = start_at;
    let mut state = runtime.context.state.clone();

    let instructions = match runtime.instructions {
        Some(ref instructions) => instructions,
        None => return Ok((runtime.context, EndReason::ReachedEnd)),
    };

    let mut end_reason = EndReason::ReachedEnd;
    loop {
        let (instruction, meta_info) = if instructions.len() > line {
            let instruction = instructions[line].clone();
            let meta_info = instruction.meta_info.clone();
            (instruction, meta_info)
        } else {
            break;
        };

        let (command_result, output_variable) = run_instruction(
            &mut runtime.context.commands,
            &mut runtime.context.variables,
            &mut state,
            &instructions,
            instruction,
            line,
        );

        match command_result {
            CommandResult::Exit(output) => {
                update_output(&mut runtime.context.variables, output_variable, output);
                end_reason = EndReason::ExitCalled;

                break;
            }
            CommandResult::Error(error) => {
                update_output(
                    &mut runtime.context.variables,
                    output_variable,
                    Some("false".to_string()),
                );

                let post_error_line = line + 1;

                match run_on_error_instruction(
                    &mut runtime.context.commands,
                    &mut runtime.context.variables,
                    &mut state,
                    &instructions,
                    error,
                    meta_info.clone(),
                ) {
                    Err(error) => {
                        return Err(ScriptError {
                            info: ErrorInfo::Runtime(error, Some(meta_info.clone())),
                        });
                    }
                    _ => (),
                };

                line = post_error_line;

                ()
            }
            CommandResult::Crash(error) => {
                let script_error = ScriptError {
                    info: ErrorInfo::Runtime(error, Some(meta_info)),
                };

                if repl_mode {
                    return Ok((runtime.context, EndReason::Crash(script_error)));
                }

                return Err(script_error);
            }
            CommandResult::Continue(output) => {
                update_output(&mut runtime.context.variables, output_variable, output);

                line = line + 1;

                ()
            }
            CommandResult::GoTo(output, goto_value) => {
                update_output(&mut runtime.context.variables, output_variable, output);

                match goto_value {
                    GoToValue::Label(label) => match runtime.label_to_line.get(&label) {
                        Some(value) => line = *value,
                        None => {
                            return Err(ScriptError {
                                info: ErrorInfo::Runtime(
                                    format!("Label: {} not found.", label),
                                    Some(meta_info),
                                ),
                            });
                        }
                    },
                    GoToValue::Line(line_number) => line = line_number,
                }
            }
        };
    }

    runtime.context.state = state;

    Ok((runtime.context, end_reason))
}

fn update_output(
    variables: &mut HashMap<String, String>,
    output_variable: Option<String>,
    output: Option<String>,
) {
    if output_variable.is_some() {
        match output {
            Some(value) => variables.insert(output_variable.unwrap(), value),
            None => variables.remove(&output_variable.unwrap()),
        };
    }
}

fn run_on_error_instruction(
    commands: &mut Commands,
    variables: &mut HashMap<String, String>,
    state: &mut HashMap<String, StateValue>,
    instructions: &Vec<Instruction>,
    error: String,
    meta_info: InstructionMetaInfo,
) -> Result<(), String> {
    if commands.exists("on_error") {
        let mut script_instruction = ScriptInstruction::new();
        script_instruction.command = Some("on_error".to_string());
        script_instruction.arguments = Some(vec![
            error,
            meta_info.line.unwrap_or(0).to_string(),
            meta_info.source.unwrap_or("".to_string()),
        ]);
        let instruction = Instruction {
            meta_info: InstructionMetaInfo::new(),
            instruction_type: InstructionType::Script(script_instruction),
        };

        let (command_result, output_variable) =
            run_instruction(commands, variables, state, instructions, instruction, 0);

        match command_result {
            CommandResult::Exit(output) => {
                update_output(variables, output_variable, output);

                Err("Exiting Script.".to_string())
            }
            CommandResult::Crash(error) => Err(error),
            _ => Ok(()),
        }
    } else {
        Ok(())
    }
}

/// Enables to evaluate a single instruction and return its result.
pub fn run_instruction(
    commands: &mut Commands,
    variables: &mut HashMap<String, String>,
    state: &mut HashMap<String, StateValue>,
    instructions: &Vec<Instruction>,
    instruction: Instruction,
    line: usize,
) -> (CommandResult, Option<String>) {
    let mut output_variable = None;
    let command_result = match instruction.instruction_type {
        InstructionType::Empty => CommandResult::Continue(None),
        InstructionType::PreProcess(_) => CommandResult::Continue(None),
        InstructionType::Script(ref script_instruction) => {
            output_variable = script_instruction.output.clone();

            match script_instruction.command {
                Some(ref command) => match commands.get_for_use(command) {
                    Some(command_instance) => {
                        let command_arguments = bind_command_arguments(
                            &variables,
                            &script_instruction,
                            &instruction.meta_info,
                        );

                        let command_result = if command_instance.requires_context() {
                            command_instance.run_with_context(
                                command_arguments,
                                state,
                                variables,
                                output_variable.clone(),
                                &instructions,
                                commands,
                                line,
                            )
                        } else {
                            command_instance.run(command_arguments)
                        };

                        command_result
                    }
                    None => CommandResult::Crash(format!("Command: {} not found.", &command)),
                },
                None => CommandResult::Continue(None),
            }
        }
    };

    (command_result, output_variable)
}

fn bind_command_arguments(
    variables: &HashMap<String, String>,
    instruction: &ScriptInstruction,
    meta_info: &InstructionMetaInfo,
) -> Vec<String> {
    let mut arguments = vec![];

    match instruction.arguments {
        Some(ref arguments_ref) => {
            for argument in arguments_ref {
                match expansion::expand_by_wrapper(&argument, meta_info, variables) {
                    ExpandedValue::Single(value) => arguments.push(value),
                    ExpandedValue::Multi(values) => {
                        for value in values {
                            arguments.push(value)
                        }
                    }
                    ExpandedValue::None => arguments.push("".to_string()),
                }
            }
        }
        None => (),
    };

    arguments
}