summaryrefslogtreecommitdiff
path: root/src/macro_processor/main.rs
blob: 2435cf335a7f431428ccfe8ceffe01563d266a2a (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
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
use skaldpress::macro_processor::MacroProcessor;
use std::env;
use std::fs;
#[cfg(not(feature = "readline"))]
use std::io;
#[cfg(not(feature = "readline"))]
use std::io::Write;

#[cfg(feature = "readline")]
use std::ffi::{CStr, CString};
#[cfg(feature = "readline")]
use std::os::raw::c_char;

#[cfg(feature = "readline")]
#[link(name = "readline")]
extern "C" {
    fn readline(p: *const c_char) -> *const c_char;
}

#[cfg(feature = "readline")]
fn readline_r(prompt: &str) -> String {
    let c_prompt = CString::new(prompt).expect("Could not convert to c_string");
    unsafe {
        let ret = readline(c_prompt.as_ptr());
        CStr::from_ptr(ret).to_string_lossy().into_owned()
    }
}

fn repl() {
    println!("=Skaldpress Macro Processor (REPL)");
    println!(" type \"quit\" to exit");
    let mut macro_processor = MacroProcessor::new();
    loop {
        let mut input = String::new();
        loop {
            let mut _input = String::new();

            #[cfg(feature = "readline")]
            {
                _input = readline_r("> ")
            }
            #[cfg(not(feature = "readline"))]
            {
                print!("> ");
                let _ = io::stdout().flush();
                io::stdin()
                    .read_line(&mut _input)
                    .expect("error: unable to read user input");
            }

            if _input == "" {
                break;
            }
            if _input == "quit\n" {
                std::process::exit(0);
            }
            input.push_str(&_input);
        }
        println!("\x1b[32m=INPUT\x1b[0m\n{:#?}", input);
        println!("\x1b[32m=PROCESSING\x1b[0m");
        match macro_processor.process_input(&input) {
            Ok(out) => println!("\x1b[32m=OUTPUT\x1b[0m\n{}", out),
            Err(e) => println!("Error {}", e),
        }
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        repl();
        std::process::exit(0);
    }

    let input_file = match fs::read_to_string(&args[1]) {
        Ok(x) => x,
        Err(e) => {
            println!("Could not read input-file \"{}\": {}", args[1], e);
            std::process::exit(1);
        }
    };

    let mut macro_processor = MacroProcessor::new();
    match macro_processor.process_input(&input_file) {
        Ok(out) => println!("{}", out),
        Err(e) => println!("Error {}", e),
    }
}