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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use std::fs::remove_file;
use std::io::{Read, Write};
use std::net::{Ipv4Addr, SocketAddrV4, TcpListener, TcpStream};
use std::process;
use std::thread::sleep;
use std::time::Duration;
use erg_common::config::ErgConfig;
use erg_common::error::MultiErrorDisplay;
use erg_common::python_util::{exec_pyc, spawn_py};
use erg_common::traits::Runnable;
use erg_compiler::hir::Expr;
use erg_compiler::ty::HasType;
use erg_compiler::error::{CompileError, CompileErrors};
use erg_compiler::Compiler;
pub type EvalError = CompileError;
pub type EvalErrors = CompileErrors;
fn find_available_port() -> u16 {
let socket = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0);
TcpListener::bind(socket)
.and_then(|listener| listener.local_addr())
.map(|sock_addr| sock_addr.port())
.expect("No free port found.")
}
#[derive(Debug)]
pub struct DummyVM {
compiler: Compiler,
stream: Option<TcpStream>,
}
impl Default for DummyVM {
fn default() -> Self {
Self::new(ErgConfig::default())
}
}
impl Drop for DummyVM {
fn drop(&mut self) {
self.finish();
}
}
impl Runnable for DummyVM {
type Err = EvalError;
type Errs = EvalErrors;
const NAME: &'static str = "Erg interpreter";
#[inline]
fn cfg(&self) -> &ErgConfig {
&self.compiler.cfg
}
#[inline]
fn cfg_mut(&mut self) -> &mut ErgConfig {
&mut self.compiler.cfg
}
fn new(cfg: ErgConfig) -> Self {
let stream = if cfg.input.is_repl() {
if !cfg.quiet_repl {
println!("Starting the REPL server...");
}
let port = find_available_port();
let code = include_str!("scripts/repl_server.py")
.replace("__PORT__", port.to_string().as_str())
.replace("__MODULE__", &cfg.dump_filename().replace('/', "."));
spawn_py(cfg.py_command, &code);
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port);
if !cfg.quiet_repl {
println!("Connecting to the REPL server...");
}
loop {
match TcpStream::connect(addr) {
Ok(stream) => {
stream
.set_read_timeout(Some(Duration::from_secs(cfg.py_server_timeout)))
.unwrap();
break Some(stream);
}
Err(_) => {
if !cfg.quiet_repl {
println!("Retrying to connect to the REPL server...");
}
sleep(Duration::from_millis(500));
continue;
}
}
}
} else {
None
};
Self {
compiler: Compiler::new(cfg),
stream,
}
}
fn finish(&mut self) {
if let Some(stream) = &mut self.stream {
if let Err(err) = stream.write_all("exit".as_bytes()) {
eprintln!("Write error: {err}");
process::exit(1);
}
let mut buf = [0; 1024];
match stream.read(&mut buf) {
Result::Ok(n) => {
let s = std::str::from_utf8(&buf[..n]).unwrap();
if s.contains("closed") && !self.cfg().quiet_repl {
println!("The REPL server is closed.");
}
}
Result::Err(err) => {
eprintln!("Read error: {err}");
process::exit(1);
}
}
remove_file(self.cfg().dump_pyc_filename()).unwrap_or(());
}
}
fn initialize(&mut self) {
self.compiler.initialize();
}
fn clear(&mut self) {
self.compiler.clear();
}
fn exec(&mut self) -> Result<i32, Self::Errs> {
let filename = self.cfg().dump_pyc_filename();
let src = self.cfg_mut().input.read();
let warns = self
.compiler
.compile_and_dump_as_pyc(&filename, src, "exec")
.map_err(|eart| {
eart.warns.fmt_all_stderr();
eart.errors
})?;
warns.fmt_all_stderr();
let code = exec_pyc(&filename, self.cfg().py_command, &self.cfg().runtime_args);
remove_file(&filename).unwrap();
Ok(code.unwrap_or(1))
}
fn eval(&mut self, src: String) -> Result<String, EvalErrors> {
let path = self.cfg().dump_pyc_filename();
let arti = self
.compiler
.eval_compile_and_dump_as_pyc(path, src, "eval")
.map_err(|eart| eart.errors)?;
let (last, warns) = (arti.object, arti.warns);
let mut res = warns.to_string();
res += &match self.stream.as_mut().unwrap().write("load".as_bytes()) {
Result::Ok(_) => {
let mut buf = [0; 1024];
match self.stream.as_mut().unwrap().read(&mut buf) {
Result::Ok(n) => {
let s = std::str::from_utf8(&buf[..n])
.expect("failed to parse the response, maybe the output is too long");
if s == "[Exception] SystemExit" {
return Err(EvalErrors::from(EvalError::system_exit()));
}
s.to_string()
}
Result::Err(err) => {
self.finish();
eprintln!("Read error: {err}");
process::exit(1);
}
}
}
Result::Err(err) => {
self.finish();
eprintln!("Sending error: {err}");
process::exit(1);
}
};
if res.ends_with("None") {
res.truncate(res.len() - 5);
}
if self.cfg().show_type {
res.push_str(": ");
res.push_str(
&last
.as_ref()
.map(|last| last.t())
.unwrap_or_default()
.to_string(),
);
if let Some(Expr::Def(def)) = last {
res.push_str(&format!(" ({})", def.sig.ident()));
}
}
Ok(res)
}
}
impl DummyVM {
pub fn exec(&mut self) -> Result<i32, EvalErrors> {
Runnable::exec(self)
}
pub fn eval(&mut self, src: String) -> Result<String, EvalErrors> {
Runnable::eval(self, src)
}
}