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
use rustyline::config::Configurer;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::process::exit;

use rustyline::error::ReadlineError;
use rustyline::DefaultEditor;

use crate::chunk::OpCode::OpReturn;
use crate::chunk::{Instr, ModuleChunk};
use crate::compiler::{CompilationResult, Compiler};
use crate::vm::{ExecutionMode, Global, VMState, VM};
use crate::InterpretResult::InterpretOK;

pub mod chunk;
pub mod compiler;
pub mod debug;
pub mod gc;
pub mod io;
pub mod log;
pub mod native;
pub mod precedence;
pub mod resolver;
pub mod run;
pub mod scanner;
pub mod utils;
pub mod value;
pub mod vm;

#[derive(Debug, PartialEq)]
pub enum InterpretResult {
    InterpretOK(VMState, Vec<ModuleChunk>),
    InterpretCompileError,
    InterpretRuntimeError,
}

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

pub fn fly(file: String, source: String, debug: bool, quiet: bool, wait: bool) -> InterpretResult {
    let mut compiler = Compiler::new_file(file, source, quiet, 0, DEBUG, wait);
    let result = compiler.compile(debug);
    if result.is_none() {
        return InterpretResult::InterpretCompileError;
    }

    let result = result.unwrap();
    let mut vm = if debug {
        VM::new(ExecutionMode::Trace, result, quiet)
    } else {
        VM::new(ExecutionMode::Default, result, quiet)
    };
    vm.run()
}

pub fn repl() -> Result<(), ReadlineError> {
    let mut rl = DefaultEditor::new()?;
    if rl.load_history("history.txt").is_err() {
        println!("No previous history.");
    }
    let s = &String::new();
    let file_name = "script.phx".to_string();
    let mut vm = VM::new(
        if DEBUG {
            ExecutionMode::Trace
        } else {
            ExecutionMode::Default
        },
        CompilationResult::default(),
        false,
    );
    let mut state: Option<VMState> = None;
    let mut modules = Vec::new();
    let mut compiler = Compiler::new_file(file_name, s.clone(), false, 0, DEBUG, false);
    let mut last_state;
    let mut last_compiler;
    let mut current_prompt = ">>";
    let default_prompt = ">>";
    let mut current_line = "".to_string();
    // tracks how many blocks deep we are (and thus how many spaces to indent)
    let mut block_offset = 0;
    loop {
        // let readline = rl.readline(" \x1b[32m>>\x1b[0m");
        let readline = rl.readline_with_initial(current_prompt, (&*"  ".repeat(block_offset), ""));
        match readline {
            Ok(mut line) => {
                rl.set_max_history_size(10000)
                    .expect("failed to set max history size");
                rl.add_history_entry(line.as_str())
                    .expect("failed to add history");
                line.push('\n');
                current_line.push_str(&line);
                // check if there are any open blocks/parens (check for: {, (, [)
                let mut open_blocks = 0;
                let mut open_parens = 0;
                let mut open_brackets = 0;
                for c in current_line.chars() {
                    match c {
                        '{' => open_blocks += 1,
                        '}' => open_blocks -= 1,
                        '(' => open_parens += 1,
                        ')' => open_parens -= 1,
                        '[' => open_brackets += 1,
                        ']' => open_brackets -= 1,
                        _ => (),
                    }
                }
                if open_blocks > 0 || open_parens > 0 || open_brackets > 0 {
                    block_offset = open_blocks;
                    current_prompt = "..";
                    continue;
                }
                current_prompt = default_prompt;
                last_state = state.clone();
                last_compiler = compiler.clone();
                // let _result = fly(file_name.clone(), line, DEBUG, false);
                // dbg!(&compiler.current_module().scanner.code);

                compiler
                    .current_module()
                    .scanner
                    .code
                    .push_str(&current_line);
                current_line = "".to_string();
                block_offset = 0;
                // dbg!(&compiler.current_module().scanner.code);
                let result = compiler.compile(DEBUG);
                if result.is_none() {
                    compiler = last_compiler;
                    continue;
                }

                let mut result = result.unwrap();
                // pop the return instructions
                result.modules[0].functions[0]
                    .chunk
                    .code
                    .retain(|x| x.op_code != OpReturn);
                let line_num = result.modules[0].functions[0]
                    .chunk
                    .code
                    .last()
                    .unwrap()
                    .line_num;
                result.modules[0].functions[0].chunk.code.push(Instr {
                    op_code: OpReturn,
                    line_num,
                });
                state = if let Some(mut s) = state {
                    while s.globals[0].len() < result.modules[0].identifiers.len() {
                        s.globals[0].push(Global::Uninit);
                    }
                    Some(s)
                } else {
                    state
                };
                vm.modules_cache = result.modules;
                let s = vm.run_state(state.clone(), modules.clone());
                if let InterpretOK(mut s, m) = s {
                    s.current_frame.ip -= 1;
                    state = Some(s);
                    modules = m;
                    if DEBUG {
                        // println!("state: {:#?}, modules: {:#?}", state, modules);
                    }
                } else {
                    state = last_state;
                    compiler = last_compiler;
                }
            }
            Err(ReadlineError::Interrupted) => {
                // println!("CTRL-C");
                break;
            }
            Err(ReadlineError::Eof) => {
                // println!("CTRL-D");
                break;
            }
            Err(err) => {
                phoenix_error!("Error: {:?}", err);
            }
        }
    }
    rl.save_history("history.txt")?;
    println!("Saved history. Goodbye!");
    Ok(())
}

pub fn run_file(filename: String, debug: bool, wait: bool) -> InterpretResult {
    let path = Path::new(&filename);
    let path_display = path.display();

    let mut file = match File::open(path) {
        Ok(file) => file,
        Err(why) => {
            eprintln!("Failed to open {}: {}", path_display, why);
            exit(1);
        }
    };

    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Ok(_) => fly(filename, s, debug, false, wait),
        Err(why) => {
            eprintln!("Failed to read {}: {}", path_display, why);
            exit(1);
        }
    }
}

#[cfg(feature = "debug")]
pub const DEBUG: bool = true;

#[cfg(not(feature = "debug"))]
pub const DEBUG: bool = false;