summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 8d6e18631b300908ad79c8763c445784e3375f51 (plain) (blame)
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
use std::io::{Read, Write};
use bedrock_asm::*;

fn main() {
    // Read source code from standard input
    let mut source_code = String::new();
    let mut stdin = std::io::stdin().lock();
    if let Err(err) = stdin.read_to_string(&mut source_code) {
        eprintln!("Could not read from standard input, quitting.");
        eprintln!("({err:?})");
        std::process::exit(1);
    };

    let (bytecode, tokens) = assemble(&source_code);
    let mut is_error = false;
    for token in &tokens {
        if token.print_error(&source_code) { is_error = true };
    }
    eprintln!("Assembled program in {} bytes.", bytecode.len());
    let bytecode_len = bytecode.len();

    if is_error {
        std::process::exit(1)
    }

    // Write bytecode to standard output
    let mut stdout = std::io::stdout().lock();
    match stdout.write(&bytecode) {
        Ok(len) => if len != bytecode_len {
            eprintln!("Only wrote {len} of {bytecode_len} bytes")
        }
        Err(err) => {
            eprintln!("Could not write to standard output, quitting.");
            eprintln!("({err:?})");
            std::process::exit(1);
        }
    }
}