-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
132 lines (113 loc) · 2.86 KB
/
main.rs
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
use std::env;
use std::fs::read_to_string;
use std::io::{stdin, stdout, Write};
use drift::lexer::Lexer;
pub const COMPILER_VERSION: &'static str = "Drift 0.0.1 (MADE AT Oct 2021 08, 13:41:48)";
pub const LICENSE: &'static str = "GNU General Public License GPL v3.0";
#[derive(Debug, PartialEq)]
pub enum IResult {
Done,
}
#[derive(Debug, PartialEq)]
enum IMode {
Repl,
Token,
Op,
Tb,
None,
}
#[derive(Debug)]
pub struct Env {
mode: IMode,
path: String,
nfp: bool,
}
fn main() {
let args: Vec<String> = env::args().collect();
let len = args.len();
let parse = |x: String| -> IMode {
match x.as_str() {
"repl" => IMode::Repl,
"token" => IMode::Token,
"op" => IMode::Op,
"tb" => IMode::Tb,
_ => IMode::None,
}
};
match len {
2..=3 => {
let arg = args.get(if len == 2 { 1 } else { 2 }).unwrap();
let mode = parse(arg.clone());
let mut fp: Option<&String> = args.get(1);
if len == 2 && mode != IMode::None {
fp = None;
}
let path = if fp == None {
String::new()
} else {
fp.unwrap().clone()
};
let nfp = path.is_empty();
execute(Env { mode, path, nfp });
}
_ => println!("{}", usage()),
}
}
fn usage() -> String {
format!(
"
Drift Interpreter With Rust!
usage: drift [FILE(.ft)] <option>
command:
repl enter read-eval-print-loop mode
token show lexical token list
op show bytecode
tb after exec, show environment mapping
version: {}
license: {}
@ bingxio - [email protected]",
COMPILER_VERSION, LICENSE
)
}
fn execute(env: Env) {
if env.mode == IMode::Repl {
repl();
} else {
if env.nfp {
panic!("specify a drift program source file");
}
if !env.path.ends_with(".ft") {
panic!("specify a file ending in an `.ft` suffix");
}
match read_to_string(env.path) {
Ok(code) => {
let result = evaluate(code);
println!("{:?}", result);
}
Err(msg) => {
panic!("failed to read file: {}", msg);
}
}
}
}
fn repl() {
let mut p = 1;
loop {
print!("{:03} > ", p);
let mut line = String::new();
stdout().flush().expect("failed to flush the screen!");
stdin().read_line(&mut line).expect("failed to read line!");
if line.trim_end().len() > 0 {
line.pop();
evaluate(line);
}
p += 1;
}
}
pub fn evaluate(code: String) -> IResult {
let tokens = Lexer::new(code).lexical();
for i in &tokens {
println!("{:?}", i);
}
IResult::Done
}