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
//! # Koto
//!
//! Pulls together the compiler and runtime for the Koto programming language.
//!
//! Programs can be compiled and executed with the [Koto] struct.
//!
//! ## Example
//!
//! ```
//! use koto::{Koto, runtime::Value};
//!
//! let mut koto = Koto::default();
//! match koto.compile("1 + 2") {
//!     Ok(_) => match koto.run() {
//!         Ok(result) => match result {
//!             Value::Number(n) => println!("{}", n), // 3.0
//!             other => panic!("Unexpected result: {}", other),
//!         },
//!         Err(runtime_error) => {
//!             panic!("Runtime error: {}", runtime_error);
//!         }
//!     },
//!     Err(compiler_error) => {
//!         panic!("Compiler error: {}", compiler_error);
//!     }
//! }
//! ```

pub use {koto_bytecode as bytecode, koto_parser as parser, koto_runtime as runtime};

use {
    koto_bytecode::{
        chunk_to_string, chunk_to_string_annotated, Chunk, CompilerError, LoaderError,
    },
    koto_parser::{ParserError, Position},
    koto_runtime::{
        type_as_string, Error, Loader, RuntimeFunction, Value, ValueList, ValueMap, ValueVec, Vm,
    },
    std::{path::PathBuf, sync::Arc},
};

/// Settings used to control the behaviour of the [Koto] runtime
#[derive(Copy, Clone, Debug, Default)]
pub struct KotoSettings {
    pub run_tests: bool,
    pub show_annotated: bool,
    pub show_bytecode: bool,
    pub repl_mode: bool,
}

/// The main interface for the Koto language.
///
/// Example
#[derive(Default)]
pub struct Koto {
    script_path: Option<PathBuf>,
    runtime: Vm,
    pub settings: KotoSettings,
    loader: Loader,
    chunk: Option<Arc<Chunk>>,
}

impl Koto {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_settings(settings: KotoSettings) -> Self {
        let mut result = Self::new();
        result.settings = settings;
        result
    }

    pub fn compile(&mut self, script: &str) -> Result<Arc<Chunk>, LoaderError> {
        let compile_result = if self.settings.repl_mode {
            self.loader.compile_repl(script)
        } else {
            self.loader.compile_script(script, &self.script_path)
        };

        match compile_result {
            Ok(chunk) => {
                self.chunk = Some(chunk.clone());
                if self.settings.show_annotated {
                    println!("Constants\n---------\n{}\n", chunk.constants.to_string());

                    let script_lines = script.lines().collect::<Vec<_>>();
                    println!(
                        "Instructions\n------------\n{}",
                        chunk_to_string_annotated(chunk.clone(), &script_lines)
                    );
                } else if self.settings.show_bytecode {
                    println!("{}", chunk_to_string(chunk.clone()));
                }
                Ok(chunk)
            }
            Err(error) => Err(error),
        }
    }

    pub fn run_with_args(&mut self, args: &[String]) -> Result<Value, String> {
        self.set_args(args);
        self.run()
    }

    pub fn run(&mut self) -> Result<Value, String> {
        let chunk = self.chunk.clone();
        match chunk {
            Some(chunk) => self.run_chunk(chunk),
            None => Err("koto.run: missing compiled chunk".to_string()),
        }
    }

    pub fn run_chunk(&mut self, chunk: Arc<Chunk>) -> Result<Value, String> {
        let result = self.runtime.run(chunk).map_err(|e| self.format_error(e))?;

        if self.settings.repl_mode {
            Ok(result)
        } else {
            if self.settings.run_tests {
                let _test_result = match self.runtime.get_global_value("tests") {
                    Some(Value::Map(tests)) => {
                        if let Err(error) = self.runtime.run_tests(tests) {
                            return Err(self.format_error(error));
                        }
                    }
                    Some(other) => {
                        return Err(format!(
                            "Expected a Map for the exported 'tests', found '{}'",
                            type_as_string(&other)
                        ))
                    }
                    None => {}
                };
            }

            if let Some(main) = self.runtime.get_global_function("main") {
                self.runtime
                    .run_function(&main, &[])
                    .map_err(|e| self.format_error(e))
            } else {
                Ok(result)
            }
        }
    }

    pub fn prelude(&self) -> ValueMap {
        self.runtime.prelude()
    }

    pub fn set_args(&mut self, args: &[String]) {
        use Value::{Map, Str};

        let koto_args = args
            .iter()
            .map(|arg| Str(arg.as_str().into()))
            .collect::<ValueVec>();

        match self
            .runtime
            .prelude()
            .data_mut()
            .get_with_string_mut("koto")
            .unwrap()
        {
            Map(map) => map
                .data_mut()
                .add_list("args", ValueList::with_data(koto_args)),
            _ => unreachable!(),
        }
    }

    pub fn set_script_path(&mut self, path: Option<PathBuf>) {
        use Value::{Empty, Map, Str};

        let (script_dir, script_path) = match &path {
            Some(path) => {
                let path = path.canonicalize().expect("Invalid script path");

                let script_dir = path
                    .parent()
                    .map(|p| {
                        let s = p.to_string_lossy() + "/";
                        Str(s.into_owned().into())
                    })
                    .or(Some(Empty))
                    .unwrap();
                let script_path = Str(path.display().to_string().into());

                (script_dir, script_path)
            }
            None => (Empty, Empty),
        };

        self.script_path = path;

        match self
            .runtime
            .prelude()
            .data_mut()
            .get_with_string_mut("koto")
            .unwrap()
        {
            Map(map) => {
                let mut map = map.data_mut();
                map.add_value("script_dir", script_dir);
                map.add_value("script_path", script_path);
            }
            _ => unreachable!(),
        }
    }

    pub fn call_function_by_name(
        &mut self,
        function_name: &str,
        args: &[Value],
    ) -> Result<Value, String> {
        match self.runtime.get_global_function(function_name) {
            Some(f) => self.call_function(&f, args),
            None => Err(format!(
                "Runtime error: function '{}' not found",
                function_name
            )),
        }
    }

    pub fn call_function(
        &mut self,
        function: &RuntimeFunction,
        args: &[Value],
    ) -> Result<Value, String> {
        self.runtime
            .run_function(function, args)
            .map_err(|e| self.format_error(e))
    }

    pub fn format_error(&self, error: Error) -> String {
        use Error::*;
        match error {
            VmError {
                message,
                chunk,
                instruction,
                extra_error,
            } => {
                if let Some(extra_error) = extra_error {
                    self.format_vm_error(
                        &format!("{}: {}", message, extra_error),
                        chunk,
                        instruction,
                    )
                } else {
                    self.format_vm_error(&message, chunk, instruction)
                }
            }
            TestError { message, error } => {
                format!("{}: {}", message, self.format_error(error.as_ref().clone()))
            }
            LoaderError(error) => {
                self.format_loader_error(error, &self.runtime.chunk().debug_info.source)
            }
            ErrorWithoutLocation { message } => format!("Error: {}\n", message,),
        }
    }

    fn format_vm_error(&self, message: &str, chunk: Arc<Chunk>, instruction: usize) -> String {
        match chunk.debug_info.get_source_span(instruction) {
            Some(span) => self.format_error_with_excerpt(
                message,
                &chunk.source_path,
                &chunk.debug_info.source,
                span.start,
                span.end,
            ),
            None => format!(
                "Runtime error at instruction {}: {}\n",
                instruction, message
            ),
        }
    }

    pub fn format_loader_error(&self, error: LoaderError, source: &str) -> String {
        match error {
            LoaderError::ParserError(ParserError { error, span }) => self
                .format_error_with_excerpt(
                    &error.to_string(),
                    &self.script_path,
                    source,
                    span.start,
                    span.end,
                ),
            LoaderError::CompilerError(CompilerError { message, span }) => self
                .format_error_with_excerpt(
                    &message,
                    &self.script_path,
                    source,
                    span.start,
                    span.end,
                ),
            LoaderError::IoError(message) => message,
        }
    }

    fn format_error_with_excerpt(
        &self,
        message: &str,
        source_path: &Option<PathBuf>,
        source: &str,
        start_pos: Position,
        end_pos: Position,
    ) -> String {
        if self.settings.repl_mode {
            // Don't show source excerpt in the repl
            return message.to_string();
        }

        let (excerpt, padding) = {
            let excerpt_lines = source
                .lines()
                .skip((start_pos.line - 1) as usize)
                .take((end_pos.line - start_pos.line + 1) as usize)
                .collect::<Vec<_>>();

            let line_numbers = (start_pos.line..=end_pos.line)
                .map(|n| n.to_string())
                .collect::<Vec<_>>();

            let number_width = line_numbers.iter().max_by_key(|n| n.len()).unwrap().len();

            let padding = " ".repeat(number_width + 2);

            if start_pos.line == end_pos.line {
                let mut excerpt = format!(
                    " {:>width$} | {}\n",
                    line_numbers.first().unwrap(),
                    excerpt_lines.first().unwrap(),
                    width = number_width
                );

                excerpt += &format!(
                    "{}|{}",
                    padding,
                    format!(
                        "{}{}",
                        " ".repeat(start_pos.column as usize),
                        "^".repeat((end_pos.column - start_pos.column) as usize)
                    ),
                );

                (excerpt, padding)
            } else {
                let mut excerpt = String::new();

                for (excerpt_line, line_number) in excerpt_lines.iter().zip(line_numbers.iter()) {
                    excerpt += &format!(
                        " {:>width$} | {}\n",
                        line_number,
                        excerpt_line,
                        width = number_width
                    );
                }

                (excerpt, padding)
            }
        };

        let position_info = if let Some(path) = source_path {
            format!(
                "{} - {}:{}",
                path.display(),
                start_pos.line,
                start_pos.column
            )
        } else {
            format!("{}:{}", start_pos.line, start_pos.column)
        };

        format!(
            "{message}\n --> {}\n{padding}|\n{excerpt}",
            position_info,
            padding = padding,
            excerpt = excerpt,
            message = message
        )
    }
}