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::{ffi::OsStr, fs::write, io::{Result, Write}, path::Path, process::Command};
use std::process::exit;
use c_emit::{CArg, Code};
use tempfile::NamedTempFile;
use crate::ir::parser::Expr;
pub(crate) mod access;
pub(crate) mod compile;
pub(crate) mod lexer;
pub(crate) mod parser;
pub fn run_ir(ir: String) {
for line in ir.lines() {
let ast = parser::parse(line.to_string());
match ast {
Expr::Args(expr) => {
for expr in expr {
match expr {
Expr::Func(f, args) => match f.f {
compile::IRFunc::Void(f) => match f(*args) {
Ok(_) => {},
Err(e) => {
eprintln!("{e}");
exit(1);
}
},
},
_ => todo!(),
}
}
}
_ => todo!(),
}
}
}
pub fn return_ir_code(ir: String) -> String {
let mut c = Code::new();
let mut requires = vec![];
for line in ir.lines() {
let ast = parser::parse(line.to_string());
match ast {
Expr::Args(expr) => {
for expr in expr {
match expr {
Expr::Func(f, args_) => {
for req in f.requires {
if !requires.contains(&req) {
requires.push(req.clone());
c.include(&req);
}
}
let mut args = vec![];
match *args_ {
Expr::_Integer(_) => {}
Expr::_Add(_, _) => {}
Expr::_Subtract(_, _) => {}
Expr::_Multiply(_, _) => {}
Expr::_Divide(_, _) => {}
Expr::Func(_, _) => {}
Expr::Args(args_2) => {
for arg in args_2 {
match arg {
Expr::_Integer(_) => {}
Expr::_Add(_, _) => {}
Expr::_Subtract(_, _) => {}
Expr::_Multiply(_, _) => {}
Expr::_Divide(_, _) => {}
Expr::Func(_, _) => {}
Expr::String(s) => {
args.push(CArg::String(s));
}
Expr::Args(_) => {}
}
}
}
Expr::String(_) => {}
}
c.call_func_with_args(&f.c_func, args);
}
_ => todo!(),
}
}
}
_ => todo!(),
}
}
println!("{c}");
c.to_string()
}
pub fn emit_ir(ir: String, path: &str) -> Result<()> {
let c = return_ir_code(ir);
let path = Path::new(path);
write(path, c)
}
fn compile_c<S: AsRef<OsStr>>(c_path: S, out_path: &str) -> Result<()> {
Command::new("gcc").arg(c_path).args(["-o", out_path]).output()?;
Ok(())
}
pub fn compile_ir(ir: String, path: &str) -> Result<()> {
let c = return_ir_code(ir);
let mut file = NamedTempFile::new()?;
writeln!(file, "{c}")?;
compile_c(file.path(), path)?;
Ok(())
}
pub fn emit_and_compile_ir(ir: String, c_path: &str, out_path: &str) -> Result<()> {
let c = return_ir_code(ir);
let path = Path::new(c_path);
write(path, c)?;
compile_c(path, out_path)
}