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
//! Main library for the Carlo language.

mod binary_operation;
mod cli;
mod environment;
mod error;
mod expression;
mod parser;
mod tokenizer;
mod unit;

use std::{
    fs::OpenOptions,
    io::{
        Read,
        stdin,
        stdout,
        Write,
    },
    path::PathBuf,
};

use colored::*;

pub use binary_operation::BinaryOperation;

pub use cli::{
    CliArgs,
    Flag,
    Subcommand,
};

pub use environment::Environment;

pub use error::Error;

pub use expression::Expression;

pub use tokenizer::{
    Token,
    TokenClass,
    Tokenstream,
};

pub use parser::Parser;

pub use unit::{
    PREFIXES,
    UNITS,
};

/// Converts a source file into a list of expressions.
pub fn parse(inputfile: Option<PathBuf>, debug: bool) -> Vec<Expression> {
    if debug {
        println!("{} running Carlo in debug mode", "(notice)".truecolor(220, 180, 0).bold());
        println!();
    }

    // Read data from input file
    let f = match inputfile {
        Some (i) => i,
        None => return Vec::new(),
    };

    let strf = format!("{}", f.display());

    let option_file = OpenOptions::new()
        .read(true)
        .open(f);

    let mut file = match option_file {
        Ok (f) => f,
        _ => Error::CouldNotFindFile (&strf).throw(),
    };

    let mut contents = String::new();
    
    match file.read_to_string(&mut contents) {
        Ok (_) => (),
        _ => Error::CouldNotReadFile (&strf).throw(),
    };

    // Construct parser
    let parser = Parser::new(debug);

    parser.parse(&contents)
}

/// Displays a prompt and reads user input.
pub fn read(prompt: &str) -> String {
    let mut buffer = String::new();

    print!("{}", prompt);
    
    match stdout().flush() {
        Ok (_) => (),
        Err (_) => Error::CouldNotFlushStdout (prompt).throw(),
    };
    match stdin().read_line(&mut buffer) {
        Ok (_) => (),
        Err (_) => Error::CouldNotReadLine (prompt).throw(),
    };

    buffer.trim().to_owned()
}