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
/// Re-export of derived functions for [Args].
pub use gumdrop::Options;

use std::fmt::Debug;
use std::path::{Path, PathBuf};
use sylt_common::error::Error;
use sylt_common::prog::Prog;
use sylt_common::RustFunction;

/// Generates the linking for the standard library, and lingon if it's active.
pub fn lib_bindings() -> Vec<(String, RustFunction)> {
    let mut lib = Vec::new();

    lib.append(&mut sylt_std::sylt::_sylt_link());

    #[cfg(feature = "lingon")]
    lib.append(&mut sylt_std::lingon::_sylt_link());

    #[cfg(feature = "network")]
    lib.append(&mut sylt_std::network::_sylt_link());

    lib
}

pub fn compile(args: &Args, functions: Vec<(String, RustFunction)>) -> Result<Prog, Vec<Error>> {
    let tree = sylt_parser::tree(&PathBuf::from(args.args.first().expect("No file to run")))?;
    if args.dump_tree {
        println!("Syntax tree: {:#?}", tree);
    }
    let prog = sylt_compiler::compile(tree, &functions)?;
    Ok(prog)
}

/// Compiles, links and runs the given file. The supplied functions are callable
/// external functions.
pub fn run_file(args: &Args, functions: Vec<(String, RustFunction)>) -> Result<(), Vec<Error>> {
    let prog = compile(args, functions)?;
    if !args.skip_typecheck {
        sylt_typechecker::typecheck(&prog, args.verbosity)?;
    }
    run(&prog, &args)
}

pub fn run(prog: &Prog, args: &Args) -> Result<(), Vec<Error>> {
    let mut vm = sylt_machine::VM::new();
    vm.print_bytecode = args.verbosity >= 1;
    vm.print_exec = args.verbosity >= 2;
    vm.init(&prog, &args.args);
    if let Err(e) = vm.run() {
        Err(vec![e])
    } else {
        Ok(())
    }
}

#[derive(Default, Debug, Options)]
pub struct Args {
    #[options(short = "r", long = "run", help = "Runs a precompiled sylt binary")]
    pub is_binary: bool,

    #[options(long = "skip-typecheck", no_short, help = "Does no type checking what so ever")]
    pub skip_typecheck: bool,

    #[options(long = "dump-tree", no_short, help = "Writes the tree to stdout")]
    pub dump_tree: bool,

    #[options(short = "c", long = "compile", help = "Compile a sylt binary")]
    pub compile_target: Option<PathBuf>,

    #[options(short = "v", no_long, count, help = "Increase verbosity, up to max 2")]
    pub verbosity: u32,

    #[options(help = "Print this help")]
    pub help: bool,

    #[options(free)]
    pub args: Vec<String>,
}

impl Args {
    /// Wraps the function with the same name from [gumdrop] for convenience.
    pub fn parse_args_default_or_exit() -> Args {
        <Args as Options>::parse_args_default_or_exit()
    }
}

pub fn path_to_module(current_file: &Path, module: &str) -> PathBuf {
    let mut res = PathBuf::from(current_file);
    res.pop();
    res.push(format!("{}.sy", module));
    res
}

#[cfg(test)]
mod tests {
    #[macro_export]
    macro_rules! assert_errs {
        ($result:expr, $expect:pat) => {
            let errs = $result.err().unwrap_or(Vec::new());

            #[allow(unused_imports)]
            use ::sylt_common::error::Error;
            #[allow(unused_imports)]
            use ::sylt_tokenizer::Span;
            if !matches!(errs.as_slice(), $expect) {
                eprintln!("===== Got =====");
                for err in errs {
                    eprint!("{}", err);
                }
                eprintln!("===== Expect =====");
                eprint!("{}\n\n", stringify!($expect));
                assert!(false);
            }
        };
    }

    #[macro_export]
    macro_rules! test_file {
        ($fn:ident, $path:literal, $print:expr, $errs:pat) => {
            #[test]
            fn $fn() {
                #[allow(unused_imports)]
                use ::sylt_common::error::RuntimeError;
                #[allow(unused_imports)]
                use ::sylt_common::Type;

                let mut args = $crate::Args::default();
                args.args = vec![format!("../{}", $path)];
                args.verbosity = if $print { 1 } else { 0 };
                let res = $crate::run_file(&args, ::sylt_std::sylt::_sylt_link());
                $crate::assert_errs!(res, $errs);
            }
        };
    }

    sylt_macro::find_tests!();
}