1use crate::array::{lean_alloc_sarray, lean_sarray_cptr, lean_sarray_set_size, sarray_bytes};
9use crate::closure::lean_alloc_closure;
10use crate::io_error::{io_error_to_string, of_std, EBADF, EINVAL, ESPIPE};
11use crate::nat::lean_uint64_to_nat;
12use crate::object::*;
13use crate::string::{lean_mk_string_from_bytes, lean_string_bytes};
14use core::ffi::c_void;
15use std::cell::{Cell, RefCell};
16use std::io::{BufRead, Read, Seek, SeekFrom, Write};
17
18#[inline]
21pub unsafe fn lean_io_mk_world() -> Obj {
22 lean_box(0)
23}
24
25#[inline]
26pub unsafe fn lean_io_result_mk_ok(a: Obj) -> Obj {
27 let r = lean_alloc_ctor(0, 1, 0);
28 lean_ctor_set(r, 0, a);
29 r
30}
31
32#[inline]
33pub unsafe fn lean_io_result_mk_error(e: Obj) -> Obj {
34 let r = lean_alloc_ctor(1, 1, 0);
35 lean_ctor_set(r, 0, e);
36 r
37}
38
39#[inline]
40pub unsafe fn lean_io_result_is_ok(r: Obj) -> bool {
41 lean_ptr_tag(r) == 0
42}
43
44#[inline]
45pub unsafe fn lean_io_result_is_error(r: Obj) -> bool {
46 lean_ptr_tag(r) == 1
47}
48
49#[inline]
50pub unsafe fn lean_io_result_get_value(r: Obj) -> Obj {
51 lean_ctor_get(r, 0)
52}
53
54#[inline]
55pub unsafe fn lean_io_result_get_error(r: Obj) -> Obj {
56 lean_ctor_get(r, 0)
57}
58
59#[inline]
61pub unsafe fn lean_io_result_take_value(r: Obj) -> Obj {
62 let v = lean_ctor_get(r, 0);
63 lean_inc(v);
64 lean_dec(r);
65 v
66}
67
68pub(crate) unsafe fn io_result_of_error(e: &std::io::Error) -> Obj {
70 lean_io_result_mk_error(of_std(e, None))
71}
72
73#[cfg(not(unix))]
75pub(crate) unsafe fn io_result_unsupported(what: &str) -> Obj {
76 lean_io_result_mk_error(crate::io_error::unsupported_error(what))
77}
78
79pub(crate) unsafe fn io_unit(r: std::io::Result<()>) -> Obj {
81 match r {
82 Ok(()) => lean_io_result_mk_ok(lean_box(0)),
83 Err(e) => io_result_of_error(&e),
84 }
85}
86
87pub unsafe fn lean_io_result_show_error(r: Obj) {
89 let text = io_error_to_string(lean_io_result_get_error(r));
90 let _ = std::io::stdout().flush();
91 eprintln!("uncaught exception: {text}");
92}
93
94pub enum HandleFile {
98 Stdin,
99 Stdout,
100 Stderr,
101 File(RefCell<FileState>),
103}
104
105pub struct FileState {
107 file: std::fs::File,
108 buf: Vec<u8>,
109 pos: usize,
110}
111
112const READ_CHUNK: usize = 8192;
113
114impl FileState {
115 pub fn new(file: std::fs::File) -> Self {
116 FileState {
117 file,
118 buf: Vec::new(),
119 pos: 0,
120 }
121 }
122
123 pub fn file(&self) -> &std::fs::File {
124 &self.file
125 }
126
127 fn fill(&mut self) -> std::io::Result<bool> {
129 if self.pos < self.buf.len() {
130 return Ok(true);
131 }
132 self.buf.resize(READ_CHUNK, 0);
133 self.pos = 0;
134 loop {
135 match self.file.read(&mut self.buf) {
136 Ok(n) => {
137 self.buf.truncate(n);
138 return Ok(n > 0);
139 }
140 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
141 Err(e) => {
142 self.buf.clear();
143 return Err(e);
144 }
145 }
146 }
147 }
148
149 fn read(&mut self, n: usize, out: &mut [u8]) -> std::io::Result<usize> {
151 let mut got = 0;
152 while got < n {
153 if !self.fill()? {
154 break;
155 }
156 let k = (self.buf.len() - self.pos).min(n - got);
157 out[got..got + k].copy_from_slice(&self.buf[self.pos..self.pos + k]);
158 self.pos += k;
159 got += k;
160 }
161 Ok(got)
162 }
163
164 fn get_line(&mut self) -> std::io::Result<Vec<u8>> {
166 let mut line = Vec::new();
167 while self.fill()? {
168 let rest = &self.buf[self.pos..];
169 match rest.iter().position(|&b| b == b'\n') {
170 Some(i) => {
171 line.extend_from_slice(&rest[..=i]);
172 self.pos += i + 1;
173 break;
174 }
175 None => {
176 line.extend_from_slice(rest);
177 self.pos = self.buf.len();
178 }
179 }
180 }
181 Ok(line)
182 }
183
184 fn unread(&mut self) -> std::io::Result<()> {
187 let ahead = self.buf.len() - self.pos;
188 self.buf.clear();
189 self.pos = 0;
190 if ahead > 0 {
191 self.file.seek(SeekFrom::Current(-(ahead as i64)))?;
192 }
193 Ok(())
194 }
195
196 fn write(&mut self, bytes: &[u8]) -> std::io::Result<()> {
197 self.unread()?;
198 self.file.write_all(bytes)
199 }
200
201 fn rewind(&mut self) -> std::io::Result<()> {
202 self.buf.clear();
203 self.pos = 0;
204 self.file.seek(SeekFrom::Start(0)).map(|_| ())
205 }
206
207 fn truncate(&mut self) -> std::io::Result<()> {
208 self.unread()?;
209 let at = self.file.stream_position()?;
210 self.file.set_len(at)
211 }
212}
213
214unsafe fn handle_finalize(p: *mut c_void) {
215 drop(Box::from_raw(p as *mut HandleFile));
216}
217
218unsafe fn handle_foreach(_p: *mut c_void, _f: Obj) {}
219
220static HANDLE_CLASS: ExternalClass = ExternalClass {
221 m_finalize: handle_finalize,
222 m_foreach: handle_foreach,
223};
224
225pub unsafe fn lean_io_wrap_handle(f: HandleFile) -> Obj {
227 lean_alloc_external(&HANDLE_CLASS, Box::into_raw(Box::new(f)) as *mut c_void)
228}
229
230#[cfg(unix)]
232pub(crate) unsafe fn wrap_file(f: std::fs::File) -> Obj {
233 lean_io_wrap_handle(HandleFile::File(RefCell::new(FileState::new(f))))
234}
235
236pub(crate) unsafe fn handle_file<'a>(h: Obj) -> &'a HandleFile {
237 &*(lean_get_external_data(h) as *const HandleFile)
238}
239
240fn write_to(f: &HandleFile, bytes: &[u8]) -> std::io::Result<()> {
241 match f {
242 HandleFile::Stdout => std::io::stdout().write_all(bytes),
243 HandleFile::Stderr => std::io::stderr().write_all(bytes),
244 HandleFile::Stdin => Err(std::io::Error::from_raw_os_error(EBADF)),
245 HandleFile::File(s) => s.borrow_mut().write(bytes),
246 }
247}
248
249#[cfg(unix)]
252pub unsafe fn lean_io_prim_handle_mk(fname: Obj, mode: u8) -> Obj {
253 let path = match crate::fs::path_of(fname) {
254 Ok(p) => p,
255 Err(e) => return e,
256 };
257 let mut o = std::fs::OpenOptions::new();
258 match mode {
259 0 => o.read(true),
260 1 => o.write(true).create(true).truncate(true),
261 2 => o.write(true).create_new(true),
262 3 => o.read(true).write(true),
263 _ => o.append(true).create(true),
264 };
265 match o.open(path) {
266 Ok(f) => lean_io_result_mk_ok(wrap_file(f)),
267 Err(e) => lean_io_result_mk_error(of_std(&e, Some(fname))),
268 }
269}
270
271#[cfg(not(unix))]
272pub unsafe fn lean_io_prim_handle_mk(_fname: Obj, _mode: u8) -> Obj {
273 io_result_unsupported("opening a file")
274}
275
276pub unsafe fn lean_io_prim_handle_flush(h: Obj) -> Obj {
278 io_unit(match handle_file(h) {
279 HandleFile::Stdout => std::io::stdout().flush(),
280 HandleFile::Stderr => std::io::stderr().flush(),
281 HandleFile::Stdin => Ok(()),
282 HandleFile::File(s) => s.borrow_mut().file.flush(),
283 })
284}
285
286pub unsafe fn lean_io_prim_handle_put_str(h: Obj, s: Obj) -> Obj {
288 io_unit(write_to(handle_file(h), lean_string_bytes(s)))
289}
290
291pub unsafe fn lean_io_prim_handle_write(h: Obj, buf: Obj) -> Obj {
293 io_unit(write_to(handle_file(h), sarray_bytes(buf)))
294}
295
296pub unsafe fn lean_io_prim_handle_get_line(h: Obj) -> Obj {
298 let r = match handle_file(h) {
299 HandleFile::Stdin => {
300 let mut line = Vec::new();
301 std::io::stdin()
302 .lock()
303 .read_until(b'\n', &mut line)
304 .map(|_| line)
305 }
306 HandleFile::File(s) => s.borrow_mut().get_line(),
307 _ => Err(std::io::Error::from_raw_os_error(EBADF)),
308 };
309 match r {
310 Ok(line) => lean_io_result_mk_ok(lean_mk_string_from_bytes(&line)),
311 Err(e) => io_result_of_error(&e),
312 }
313}
314
315pub unsafe fn lean_io_prim_handle_read(h: Obj, nbytes: usize) -> Obj {
317 let f = handle_file(h);
318 if matches!(f, HandleFile::Stdout | HandleFile::Stderr) {
319 return io_result_of_error(&std::io::Error::from_raw_os_error(EBADF));
320 }
321 let r = lean_alloc_sarray(1, 0, nbytes);
322 let buf = core::slice::from_raw_parts_mut(lean_sarray_cptr(r), nbytes);
323 let n = match f {
324 HandleFile::File(s) => s.borrow_mut().read(nbytes, buf),
325 _ => std::io::stdin().lock().read(buf),
326 };
327 match n {
328 Ok(n) => {
329 lean_sarray_set_size(r, n);
330 lean_io_result_mk_ok(r)
331 }
332 Err(e) => {
333 lean_dec_ref(r);
334 io_result_of_error(&e)
335 }
336 }
337}
338
339pub unsafe fn lean_io_prim_handle_is_tty(h: Obj) -> u8 {
341 use std::io::IsTerminal;
342 (match handle_file(h) {
343 HandleFile::Stdin => std::io::stdin().is_terminal(),
344 HandleFile::Stdout => std::io::stdout().is_terminal(),
345 HandleFile::Stderr => std::io::stderr().is_terminal(),
346 HandleFile::File(s) => s.borrow().file.is_terminal(),
347 }) as u8
348}
349
350pub unsafe fn lean_io_prim_handle_rewind(h: Obj) -> Obj {
352 io_unit(match handle_file(h) {
353 HandleFile::File(s) => s.borrow_mut().rewind(),
354 _ => Err(std::io::Error::from_raw_os_error(ESPIPE)),
355 })
356}
357
358pub unsafe fn lean_io_prim_handle_truncate(h: Obj) -> Obj {
360 io_unit(match handle_file(h) {
361 HandleFile::File(s) => s.borrow_mut().truncate(),
362 _ => Err(std::io::Error::from_raw_os_error(EINVAL)),
363 })
364}
365
366#[cfg(unix)]
367fn raw_fd(f: &HandleFile) -> i32 {
368 use std::os::fd::AsRawFd;
369 match f {
370 HandleFile::Stdin => 0,
371 HandleFile::Stdout => 1,
372 HandleFile::Stderr => 2,
373 HandleFile::File(s) => s.borrow().file.as_raw_fd(),
374 }
375}
376
377#[cfg(unix)]
378fn flock(f: &HandleFile, op: i32) -> std::io::Result<()> {
379 if unsafe { libc::flock(raw_fd(f), op) } == 0 {
380 Ok(())
381 } else {
382 Err(std::io::Error::last_os_error())
383 }
384}
385
386#[cfg(unix)]
388pub unsafe fn lean_io_prim_handle_lock(h: Obj, exclusive: u8) -> Obj {
389 let op = if exclusive != 0 {
390 libc::LOCK_EX
391 } else {
392 libc::LOCK_SH
393 };
394 io_unit(flock(handle_file(h), op))
395}
396
397#[cfg(unix)]
399pub unsafe fn lean_io_prim_handle_try_lock(h: Obj, exclusive: u8) -> Obj {
400 let op = if exclusive != 0 {
401 libc::LOCK_EX
402 } else {
403 libc::LOCK_SH
404 };
405 match flock(handle_file(h), op | libc::LOCK_NB) {
406 Ok(()) => lean_io_result_mk_ok(lean_box(1)),
407 Err(e) if e.raw_os_error() == Some(libc::EWOULDBLOCK) => lean_io_result_mk_ok(lean_box(0)),
408 Err(e) => io_result_of_error(&e),
409 }
410}
411
412#[cfg(unix)]
414pub unsafe fn lean_io_prim_handle_unlock(h: Obj) -> Obj {
415 io_unit(flock(handle_file(h), libc::LOCK_UN))
416}
417
418#[cfg(not(unix))]
419pub unsafe fn lean_io_prim_handle_lock(_h: Obj, _exclusive: u8) -> Obj {
420 io_result_unsupported("locking a file")
421}
422
423#[cfg(not(unix))]
424pub unsafe fn lean_io_prim_handle_try_lock(_h: Obj, _exclusive: u8) -> Obj {
425 io_result_unsupported("locking a file")
426}
427
428#[cfg(not(unix))]
429pub unsafe fn lean_io_prim_handle_unlock(_h: Obj) -> Obj {
430 io_result_unsupported("locking a file")
431}
432
433unsafe fn stream_flush(h: Obj, _w: Obj) -> Obj {
436 let r = lean_io_prim_handle_flush(h);
437 lean_dec(h);
438 r
439}
440
441unsafe fn stream_read(h: Obj, n: Obj, _w: Obj) -> Obj {
442 let r = lean_io_prim_handle_read(h, lean_unbox_usize(n));
443 lean_dec(n);
444 lean_dec(h);
445 r
446}
447
448unsafe fn stream_write(h: Obj, b: Obj, _w: Obj) -> Obj {
449 let r = lean_io_prim_handle_write(h, b);
450 lean_dec(b);
451 lean_dec(h);
452 r
453}
454
455unsafe fn stream_get_line(h: Obj, _w: Obj) -> Obj {
456 let r = lean_io_prim_handle_get_line(h);
457 lean_dec(h);
458 r
459}
460
461unsafe fn stream_put_str(h: Obj, s: Obj, _w: Obj) -> Obj {
462 let r = lean_io_prim_handle_put_str(h, s);
463 lean_dec(s);
464 lean_dec(h);
465 r
466}
467
468unsafe fn stream_is_tty(h: Obj, _w: Obj) -> Obj {
469 let r = lean_io_prim_handle_is_tty(h);
470 lean_dec(h);
471 lean_box(r as usize)
472}
473
474unsafe fn handle_closure(f: *const (), arity: u32, h: Obj) -> Obj {
475 let c = lean_alloc_closure(f, arity, 1);
476 lean_inc(h);
477 crate::closure::lean_closure_set(c, 0, h);
478 c
479}
480
481pub unsafe fn lean_stream_of_handle(h: Obj) -> Obj {
483 let s = lean_alloc_ctor(0, 6, 0);
484 lean_ctor_set(s, 0, handle_closure(stream_flush as *const (), 2, h));
485 lean_ctor_set(s, 1, handle_closure(stream_read as *const (), 3, h));
486 lean_ctor_set(s, 2, handle_closure(stream_write as *const (), 3, h));
487 lean_ctor_set(s, 3, handle_closure(stream_get_line as *const (), 2, h));
488 lean_ctor_set(s, 4, handle_closure(stream_put_str as *const (), 3, h));
489 lean_ctor_set(s, 5, handle_closure(stream_is_tty as *const (), 2, h));
490 lean_dec(h);
491 s
492}
493
494thread_local! {
495 static STDIN: Cell<Obj> = const { Cell::new(core::ptr::null_mut()) };
496 static STDOUT: Cell<Obj> = const { Cell::new(core::ptr::null_mut()) };
497 static STDERR: Cell<Obj> = const { Cell::new(core::ptr::null_mut()) };
498}
499
500unsafe fn current_stream(
501 slot: &'static std::thread::LocalKey<Cell<Obj>>,
502 f: fn() -> HandleFile,
503) -> Obj {
504 let mut s = slot.get();
505 if s.is_null() {
506 s = lean_stream_of_handle(lean_io_wrap_handle(f()));
507 lean_mark_persistent(s);
508 slot.set(s);
509 }
510 lean_inc(s);
511 s
512}
513
514unsafe fn swap_stream(
515 slot: &'static std::thread::LocalKey<Cell<Obj>>,
516 f: fn() -> HandleFile,
517 h: Obj,
518) -> Obj {
519 let old = current_stream(slot, f);
520 lean_dec(slot.get());
521 slot.set(h);
522 old
523}
524
525pub unsafe fn lean_get_stdin() -> Obj {
527 current_stream(&STDIN, || HandleFile::Stdin)
528}
529
530pub unsafe fn lean_get_stdout() -> Obj {
532 current_stream(&STDOUT, || HandleFile::Stdout)
533}
534
535pub unsafe fn lean_get_stderr() -> Obj {
537 current_stream(&STDERR, || HandleFile::Stderr)
538}
539
540pub unsafe fn lean_get_set_stdin(h: Obj) -> Obj {
542 swap_stream(&STDIN, || HandleFile::Stdin, h)
543}
544
545pub unsafe fn lean_get_set_stdout(h: Obj) -> Obj {
547 swap_stream(&STDOUT, || HandleFile::Stdout, h)
548}
549
550pub unsafe fn lean_get_set_stderr(h: Obj) -> Obj {
552 swap_stream(&STDERR, || HandleFile::Stderr, h)
553}
554
555pub unsafe fn lean_st_mk_ref(a: Obj) -> Obj {
559 lean_alloc_ref(a)
560}
561
562#[inline]
563unsafe fn to_ref(r: Obj) -> *mut RefObject {
564 r as *mut RefObject
565}
566
567pub unsafe fn lean_st_ref_get(r: Obj) -> Obj {
569 let v = (*to_ref(r)).m_value;
570 if v.is_null() {
571 crate::panic::lean_internal_panic("null reference read");
572 }
573 lean_inc(v);
574 v
575}
576
577pub unsafe fn lean_st_ref_take(r: Obj) -> Obj {
579 let v = (*to_ref(r)).m_value;
580 if v.is_null() {
581 crate::panic::lean_internal_panic("null reference read");
582 }
583 (*to_ref(r)).m_value = core::ptr::null_mut();
584 v
585}
586
587pub unsafe fn lean_st_ref_put(r: Obj, a: Obj) -> Obj {
589 let old = (*to_ref(r)).m_value;
590 if !old.is_null() {
591 lean_dec(old);
592 }
593 (*to_ref(r)).m_value = a;
594 lean_box(0)
595}
596
597pub unsafe fn lean_st_ref_swap(r: Obj, a: Obj) -> Obj {
599 let old = (*to_ref(r)).m_value;
600 if old.is_null() {
601 crate::panic::lean_internal_panic("null reference read");
602 }
603 (*to_ref(r)).m_value = a;
604 old
605}
606
607pub unsafe fn lean_st_ref_ptr_eq(r1: Obj, r2: Obj) -> u8 {
609 (r1 == r2) as u8
610}
611
612#[cfg(unix)]
615fn mono_base() -> std::time::Instant {
616 static BASE: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
617 *BASE.get_or_init(std::time::Instant::now)
618}
619
620pub(crate) fn mono_elapsed() -> std::time::Duration {
622 #[cfg(unix)]
623 {
624 mono_base().elapsed()
625 }
626 #[cfg(not(unix))]
627 {
628 std::time::Duration::ZERO
629 }
630}
631
632pub unsafe fn lean_io_mono_ms_now() -> Obj {
634 lean_uint64_to_nat(mono_elapsed().as_millis() as u64 + 1)
635}
636
637pub unsafe fn lean_io_mono_nanos_now() -> Obj {
639 lean_uint64_to_nat(mono_elapsed().as_nanos() as u64 + 1)
640}
641
642#[cfg(unix)]
644pub unsafe fn lean_io_exit(code: u8) -> Obj {
645 let _ = std::io::stdout().flush();
646 std::process::exit(code as i32)
647}
648
649#[cfg(not(unix))]
650pub unsafe fn lean_io_exit(_code: u8) -> Obj {
651 io_result_unsupported("exiting the process")
652}
653
654pub unsafe fn lean_runtime_mark_persistent(a: Obj) -> Obj {
656 lean_mark_persistent(a);
657 a
658}
659
660pub unsafe fn lean_runtime_mark_multi_threaded(a: Obj) -> Obj {
662 a
663}