summaryrefslogtreecommitdiff
path: root/matrix-bin/src/main.rs
blob: 2b00a6afe42be1583d4a6d76c921dd71a0f07d1b (plain)
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
use std::{cell::RefCell, io::{self, IsTerminal, Read}, path::PathBuf, rc::Rc};
use clap::{Parser as ArgParser, ColorChoice};
use matrix_lang::prelude::*;
use repl::Repl;

mod repl;
mod helper;

#[derive(Debug, ArgParser)]
#[command(version, long_about = None)]
pub struct Args {
    /// A path to a input program. Uses stdin if not specified.
    file: Option<PathBuf>,

    /// Compiles the given program
    #[arg(short, long)]
    compile: bool,

    /// Optional output for compiled output
    #[arg(short, long)]
    output: Option<PathBuf>,

    /// Print out debug information
    #[arg(short, long)]
    debug: bool,

    /// Force repl after running a file
    #[arg(short, long)]
    repl: bool,

    /// Choses color
    #[arg(long)]
    color: Option<ColorChoice>,

    /// Disables optimizations
    #[arg(long)]
    disable_optimizations: bool,
}

pub enum Mode {
    Repl,
    Execute(Vec<u8>),
    Compile(Vec<u8>, PathBuf),
}

pub struct State<'a> {
    parser: Parser,
    compiler: Compiler<'a>,
    vm: Rc<RefCell<Vm>>,
    color: bool,
    repl: bool,
}

pub fn error(err: Exception, state: &State) {
    if state.color {
        println!("\x1b[31mError:\x1b[0m {err}");
    } else {
        println!("Error: {err}");
    }
}

impl<'a> State<'a> {
    pub fn new (args: Args) -> Result<(Self, Mode)> {

        let mut buffer = Vec::new();
        if let Some(path) = &args.file {
            let mut f = File::open(path)?;
            f.read_to_end(&mut buffer)?;
        } else {
            let mut stdin = io::stdin();
            if !stdin.is_terminal() {
                stdin.read_to_end(&mut buffer)?;
            }
        }

        let mode;
        let repl;
        if args.compile {
            let path = match (args.output, args.file) {
                (Some(path), _) => path,
                (None, Some(path)) => {
                    let mut path = path.clone();
                    path.set_extension("matc");
                    path
                },
                (None, None) => {
                    PathBuf::from("matc.out")
                }
            };
            mode = Mode::Compile(buffer, path);
            repl = args.repl;
        } else if buffer.len() > 0 {
            mode = Mode::Execute(buffer);
            repl = args.repl;
        } else {
            mode = Mode::Repl;
            repl = true;
        }

        let mut vm = Vm::new();
        let parser = ParserBuilder::new()
            .optimize(!args.disable_optimizations)
            .build();
        let compiler = CompilerBuilder::new()
            .repl(repl)
            .debug(args.debug)
            .names(vm.names())
            .globals(vm.globals())
            .build();

        matrix_std::load(&mut vm);

        let color = match args.color {
            Some(ColorChoice::Auto) | None => {
                io::stdout().is_terminal()
            },
            Some(ColorChoice::Always) => true,
            Some(ColorChoice::Never) => false,
        };

        Ok((Self {
            parser,
            vm: Rc::new(RefCell::new(vm)),
            compiler,
            color,
            repl,
        }, mode))
    }

    pub fn execute(&mut self, fun: Rc<Function>) -> Result<Value> {
        let val = self.vm.borrow_mut().run(fun)?;
        Ok(val)
    }

    pub fn compile(&mut self, code: String) -> Result<Rc<Function>> {
        let ast = self.parser.parse(code)?;
        let fun = self.compiler.compile(&ast)?;
        Ok(fun)
    }

    pub fn load_program(&mut self, mut buffer: Vec<u8>) -> Result<Rc<Function>> {
        let res = Program::load(buffer.as_mut_slice())?;
        match res {
            Some(fun) => {
                Ok(fun)
            },
            None => {
                let body = buffer_to_string(buffer)?;
                self.compile(body)
            },
        }
    }
}

fn buffer_to_string(buffer: Vec<u8>) -> Result<String> {
    String::from_utf8(buffer)
        .map_err(|e| exception!(IO_EXCEPTION, "{e}"))
}

fn handle_mode(state: &mut State, mode: Mode) -> Result<()> {
    match mode {
        Mode::Repl => {
            let mut repl = Repl::new(state);
            repl.run()?;
            state.repl = false;
        },
        Mode::Execute(buffer) => {
            let fun = state.load_program(buffer)?;
            state.execute(fun)?;
        },
        Mode::Compile(buffer, path) => {
            let body = buffer_to_string(buffer)?;
            let fun = state.compile(body)?;
            let mut file = File::create(path).map_err(|e|
                exception!(IO_EXCEPTION, "{e}")
            )?;
            Program::save(fun, &mut file)?;
        }
    };

    if state.repl {
        let mut repl = Repl::new(state);
        repl.run()?;
    }

    Ok(())
}

fn load() -> Result<()> {
    let args = Args::parse();
    let (mut state, mode) = State::new(args)?;
    if let Err(e) = handle_mode(&mut state, mode) {
        error(e, &state);
    }
    Ok(())
}

fn main() {
    if let Err(e) = load() {
        println!("\x1b[31mFatal:\x1b[0m {e}");
    }
}