Skip to main content

leanfran_runtime/
fs.rs

1//! Files, directories and the environment of the process: `IO.FS`, `IO.getEnv`, `IO.appPath`,
2//! the current directory, process and thread ids, random bytes and `timeit`.
3
4#[cfg(unix)]
5use crate::array::{lean_alloc_sarray, lean_array_push, lean_mk_empty_array, lean_sarray_cptr};
6#[cfg(unix)]
7use crate::int::lean_int64_to_int;
8#[cfg(not(unix))]
9use crate::io::io_result_unsupported;
10#[cfg(unix)]
11use crate::io::{io_result_of_error, lean_io_result_mk_error, lean_io_result_mk_ok, wrap_file};
12#[cfg(unix)]
13use crate::io_error::{
14    embedded_nul_error, file_not_found_error, lean_mk_io_user_error, of_std, of_std_uv,
15};
16#[cfg(unix)]
17use crate::model::scalar_offset;
18use crate::nat::lean_uint64_to_nat;
19use crate::object::*;
20use crate::string::lean_mk_string;
21#[cfg(unix)]
22use crate::string::{lean_mk_string_from_bytes, lean_string_bytes};
23#[cfg(unix)]
24use std::os::unix::ffi::OsStrExt;
25
26/// The path of a borrowed `FilePath` (a `String`), or the `error` result for a path with a NUL
27/// byte.
28#[cfg(unix)]
29pub(crate) unsafe fn path_of<'a>(p: Obj) -> Result<&'a std::path::Path, Obj> {
30    let b = lean_string_bytes(p);
31    if b.contains(&0) {
32        Err(lean_io_result_mk_error(embedded_nul_error(p)))
33    } else {
34        Ok(std::path::Path::new(std::ffi::OsStr::from_bytes(b)))
35    }
36}
37
38#[cfg(unix)]
39unsafe fn mk_path(p: &std::path::Path) -> Obj {
40    lean_mk_string_from_bytes(p.as_os_str().as_bytes())
41}
42
43#[cfg(unix)]
44unsafe fn unit_or(r: std::io::Result<()>, err: impl FnOnce(&std::io::Error) -> Obj) -> Obj {
45    match r {
46        Ok(()) => lean_io_result_mk_ok(lean_box(0)),
47        Err(e) => lean_io_result_mk_error(err(&e)),
48    }
49}
50
51#[cfg(unix)]
52macro_rules! path_or_return {
53    ($p:expr) => {
54        match path_of($p) {
55            Ok(p) => p,
56            Err(e) => return e,
57        }
58    };
59}
60
61/* Directories and files */
62
63/// `IO.FS.readDir : @& FilePath → IO (Array DirEntry)`: `DirEntry` is `⟨root, fileName⟩`.
64#[cfg(unix)]
65pub unsafe fn lean_io_read_dir(dir: Obj) -> Obj {
66    let path = path_or_return!(dir);
67    let entries = match std::fs::read_dir(path) {
68        Ok(it) => it,
69        Err(e) => return lean_io_result_mk_error(of_std(&e, Some(dir))),
70    };
71    let mut arr = lean_mk_empty_array();
72    for entry in entries.flatten() {
73        let e = lean_alloc_ctor(0, 2, 0);
74        lean_inc(dir);
75        lean_ctor_set(e, 0, dir);
76        lean_ctor_set(
77            e,
78            1,
79            lean_mk_string_from_bytes(entry.file_name().as_bytes()),
80        );
81        arr = lean_array_push(arr, e);
82    }
83    lean_io_result_mk_ok(arr)
84}
85
86#[cfg(unix)]
87unsafe fn system_time(sec: i64, nsec: i64) -> Obj {
88    let o = lean_alloc_ctor(0, 1, 4);
89    lean_ctor_set(o, 0, lean_int64_to_int(sec));
90    lean_ctor_set_uint32(o, scalar_offset(1, 0), nsec as u32);
91    o
92}
93
94/// `IO.FS.Metadata`: `accessed`, `modified`, `byteSize`, `numLinks` and `type` (`dir`, `file`,
95/// `symlink`, `other`).
96#[cfg(unix)]
97unsafe fn metadata_obj(m: &std::fs::Metadata) -> Obj {
98    use std::os::unix::fs::MetadataExt;
99    let o = lean_alloc_ctor(0, 2, 17);
100    lean_ctor_set(o, 0, system_time(m.atime(), m.atime_nsec()));
101    lean_ctor_set(o, 1, system_time(m.mtime(), m.mtime_nsec()));
102    lean_ctor_set_uint64(o, scalar_offset(2, 0), m.size());
103    lean_ctor_set_uint64(o, scalar_offset(2, 8), m.nlink());
104    let t = m.file_type();
105    let ty = if t.is_dir() {
106        0
107    } else if t.is_file() {
108        1
109    } else if t.is_symlink() {
110        2
111    } else {
112        3
113    };
114    lean_ctor_set_uint8(o, scalar_offset(2, 16), ty);
115    o
116}
117
118/// `System.FilePath.metadata : @& FilePath → IO Metadata`.
119#[cfg(unix)]
120pub unsafe fn lean_io_metadata(fname: Obj) -> Obj {
121    let path = path_or_return!(fname);
122    match std::fs::metadata(path) {
123        Ok(m) => lean_io_result_mk_ok(metadata_obj(&m)),
124        Err(e) => lean_io_result_mk_error(of_std_uv(&e, Some(fname))),
125    }
126}
127
128/// `System.FilePath.symlinkMetadata : @& FilePath → IO Metadata`.
129#[cfg(unix)]
130pub unsafe fn lean_io_symlink_metadata(fname: Obj) -> Obj {
131    let path = path_or_return!(fname);
132    match std::fs::symlink_metadata(path) {
133        Ok(m) => lean_io_result_mk_ok(metadata_obj(&m)),
134        Err(e) => lean_io_result_mk_error(of_std_uv(&e, Some(fname))),
135    }
136}
137
138/// `IO.FS.createDir : @& FilePath → IO Unit`.
139#[cfg(unix)]
140pub unsafe fn lean_io_create_dir(p: Obj) -> Obj {
141    let path = path_or_return!(p);
142    unit_or(std::fs::create_dir(path), |e| of_std(e, Some(p)))
143}
144
145/// `IO.FS.removeDir : @& FilePath → IO Unit`.
146#[cfg(unix)]
147pub unsafe fn lean_io_remove_dir(p: Obj) -> Obj {
148    let path = path_or_return!(p);
149    unit_or(std::fs::remove_dir(path), |e| of_std(e, Some(p)))
150}
151
152/// `IO.FS.removeFile : @& FilePath → IO Unit`.
153#[cfg(unix)]
154pub unsafe fn lean_io_remove_file(p: Obj) -> Obj {
155    let path = path_or_return!(p);
156    unit_or(std::fs::remove_file(path), |e| of_std_uv(e, Some(p)))
157}
158
159/// `IO.FS.rename : (old new : @& FilePath) → IO Unit`; the file name of an error is
160/// `"<old> and/or <new>"`.
161#[cfg(unix)]
162pub unsafe fn lean_io_rename(from: Obj, to: Obj) -> Obj {
163    let f = path_or_return!(from);
164    let t = path_or_return!(to);
165    unit_or(std::fs::rename(f, t), |e| {
166        let mut both = lean_string_bytes(from).to_vec();
167        both.extend_from_slice(b" and/or ");
168        both.extend_from_slice(lean_string_bytes(to));
169        let s = lean_mk_string_from_bytes(&both);
170        let r = of_std(e, Some(s));
171        lean_dec(s);
172        r
173    })
174}
175
176/// `IO.FS.hardLink : (orig link : @& FilePath) → IO Unit`.
177#[cfg(unix)]
178pub unsafe fn lean_io_hard_link(orig: Obj, link: Obj) -> Obj {
179    let o = path_or_return!(orig);
180    let l = path_or_return!(link);
181    unit_or(std::fs::hard_link(o, l), |e| of_std_uv(e, Some(orig)))
182}
183
184/// `IO.FS.realPath : FilePath → IO FilePath` (consumes `fname`).
185#[cfg(unix)]
186pub unsafe fn lean_io_realpath(fname: Obj) -> Obj {
187    let r = match path_of(fname) {
188        Ok(p) => match std::fs::canonicalize(p) {
189            Ok(real) => lean_io_result_mk_ok(mk_path(&real)),
190            Err(_) => lean_io_result_mk_error(file_not_found_error(fname)),
191        },
192        Err(e) => e,
193    };
194    lean_dec(fname);
195    r
196}
197
198/// `IO.setAccessRights` through `chmod : (@& FilePath) → UInt32 → IO Unit`.
199#[cfg(unix)]
200pub unsafe fn lean_chmod(fname: Obj, mode: u32) -> Obj {
201    use std::os::unix::fs::PermissionsExt;
202    let path = path_or_return!(fname);
203    unit_or(
204        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)),
205        |e| of_std(e, Some(fname)),
206    )
207}
208
209/// `uv_os_tmpdir`: `TMPDIR`, `TMP`, `TEMP` or `TEMPDIR`, else `/tmp`, without a trailing `/`.
210#[cfg(unix)]
211fn temp_dir() -> Vec<u8> {
212    let mut d = ["TMPDIR", "TMP", "TEMP", "TEMPDIR"]
213        .iter()
214        .find_map(|v| std::env::var_os(v).filter(|s| !s.is_empty()))
215        .map(|s| s.as_bytes().to_vec())
216        .unwrap_or_else(|| b"/tmp".to_vec());
217    if d.len() > 1 && d.ends_with(b"/") {
218        d.pop();
219    }
220    d
221}
222
223/// `<tmpdir>/tmp.XXXXXXXX` as a C string, for `mkstemp` and `mkdtemp`.
224#[cfg(unix)]
225fn temp_template() -> Vec<u8> {
226    let mut t = temp_dir();
227    t.extend_from_slice(b"/tmp.XXXXXXXX\0");
228    t
229}
230
231/// `IO.FS.createTempFile : IO (Handle × FilePath)`.
232#[cfg(unix)]
233pub unsafe fn lean_io_create_tempfile() -> Obj {
234    use std::os::fd::FromRawFd;
235    let mut t = temp_template();
236    let fd = libc::mkstemp(t.as_mut_ptr() as *mut libc::c_char);
237    if fd < 0 {
238        return lean_io_result_mk_error(of_std_uv(&std::io::Error::last_os_error(), None));
239    }
240    let file = std::fs::File::from_raw_fd(fd);
241    let pair = lean_alloc_ctor(0, 2, 0);
242    lean_ctor_set(pair, 0, wrap_file(file));
243    lean_ctor_set(pair, 1, lean_mk_string_from_bytes(&t[..t.len() - 1]));
244    lean_io_result_mk_ok(pair)
245}
246
247/// `IO.FS.createTempDir : IO FilePath`.
248#[cfg(unix)]
249pub unsafe fn lean_io_create_tempdir() -> Obj {
250    let mut t = temp_template();
251    if libc::mkdtemp(t.as_mut_ptr() as *mut libc::c_char).is_null() {
252        return lean_io_result_mk_error(of_std_uv(&std::io::Error::last_os_error(), None));
253    }
254    lean_io_result_mk_ok(lean_mk_string_from_bytes(&t[..t.len() - 1]))
255}
256
257/* The process */
258
259/// `IO.getEnv : @& String → BaseIO (Option String)`.
260#[cfg(unix)]
261pub unsafe fn lean_io_getenv(var: Obj) -> Obj {
262    let name = lean_string_bytes(var);
263    if name.contains(&0) {
264        return lean_box(0);
265    }
266    match std::env::var_os(std::ffi::OsStr::from_bytes(name)) {
267        Some(v) => {
268            let s = lean_alloc_ctor(1, 1, 0);
269            lean_ctor_set(s, 0, lean_mk_string_from_bytes(v.as_bytes()));
270            s
271        }
272        None => lean_box(0),
273    }
274}
275
276/// `IO.appPath : IO FilePath`: the executable, with symbolic links resolved.
277#[cfg(unix)]
278pub unsafe fn lean_io_app_path() -> Obj {
279    match std::env::current_exe() {
280        Ok(p) => lean_io_result_mk_ok(mk_path(&p)),
281        Err(_) => lean_io_result_mk_error(lean_mk_io_user_error(lean_mk_string(
282            "failed to locate application",
283        ))),
284    }
285}
286
287/// `IO.currentDir : IO FilePath`.
288#[cfg(unix)]
289pub unsafe fn lean_io_current_dir() -> Obj {
290    match std::env::current_dir() {
291        Ok(p) => lean_io_result_mk_ok(mk_path(&p)),
292        Err(_) => lean_io_result_mk_error(lean_mk_io_user_error(lean_mk_string(
293            "failed to retrieve current working directory",
294        ))),
295    }
296}
297
298/// `IO.Process.getCurrentDir : IO FilePath`.
299#[cfg(unix)]
300pub unsafe fn lean_io_process_get_current_dir() -> Obj {
301    match std::env::current_dir() {
302        Ok(p) => lean_io_result_mk_ok(mk_path(&p)),
303        Err(e) => io_result_of_error(&e),
304    }
305}
306
307/// `IO.Process.setCurrentDir : @& FilePath → IO Unit`.
308#[cfg(unix)]
309pub unsafe fn lean_io_process_set_current_dir(p: Obj) -> Obj {
310    let path = path_or_return!(p);
311    unit_or(std::env::set_current_dir(path), |e| of_std(e, Some(p)))
312}
313
314/// `IO.Process.getPID : BaseIO UInt32`.
315#[cfg(unix)]
316pub unsafe fn lean_io_process_get_pid() -> u32 {
317    std::process::id()
318}
319
320/// `IO.getTID : BaseIO UInt64`: the id of the OS thread.
321pub unsafe fn lean_io_get_tid() -> u64 {
322    #[cfg(target_os = "linux")]
323    {
324        libc::syscall(libc::SYS_gettid) as u64
325    }
326    #[cfg(target_os = "macos")]
327    {
328        let mut tid = 0u64;
329        libc::pthread_threadid_np(0, &mut tid);
330        tid
331    }
332    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
333    {
334        0
335    }
336}
337
338/// `IO.getRandomBytes : USize → IO ByteArray`, from `/dev/urandom`.
339#[cfg(unix)]
340pub unsafe fn lean_io_get_random_bytes(n: usize) -> Obj {
341    use std::io::Read;
342    if n == 0 {
343        return lean_io_result_mk_ok(lean_alloc_sarray(1, 0, 0));
344    }
345    let mut f = match std::fs::File::open("/dev/urandom") {
346        Ok(f) => f,
347        Err(e) => {
348            let name = lean_mk_string("/dev/urandom");
349            let r = lean_io_result_mk_error(of_std(&e, Some(name)));
350            lean_dec(name);
351            return r;
352        }
353    };
354    let r = lean_alloc_sarray(1, n, n);
355    let buf = core::slice::from_raw_parts_mut(lean_sarray_cptr(r), n);
356    match f.read_exact(buf) {
357        Ok(()) => lean_io_result_mk_ok(r),
358        Err(e) => {
359            lean_dec_ref(r);
360            io_result_of_error(&e)
361        }
362    }
363}
364
365/// `IO.Process.forceExit : UInt8 → IO α`: exits without flushing the standard streams.
366#[cfg(unix)]
367pub unsafe fn lean_io_force_exit(code: u8) -> Obj {
368    libc::_exit(code as i32)
369}
370
371/* Targets without an OS: the file system and the process are unsupported operations */
372
373#[cfg(not(unix))]
374pub unsafe fn lean_io_read_dir(_dir: Obj) -> Obj {
375    io_result_unsupported("the file system")
376}
377
378#[cfg(not(unix))]
379pub unsafe fn lean_io_metadata(_fname: Obj) -> Obj {
380    io_result_unsupported("the file system")
381}
382
383#[cfg(not(unix))]
384pub unsafe fn lean_io_symlink_metadata(_fname: Obj) -> Obj {
385    io_result_unsupported("the file system")
386}
387
388#[cfg(not(unix))]
389pub unsafe fn lean_io_create_dir(_p: Obj) -> Obj {
390    io_result_unsupported("the file system")
391}
392
393#[cfg(not(unix))]
394pub unsafe fn lean_io_remove_dir(_p: Obj) -> Obj {
395    io_result_unsupported("the file system")
396}
397
398#[cfg(not(unix))]
399pub unsafe fn lean_io_remove_file(_p: Obj) -> Obj {
400    io_result_unsupported("the file system")
401}
402
403#[cfg(not(unix))]
404pub unsafe fn lean_io_rename(_from: Obj, _to: Obj) -> Obj {
405    io_result_unsupported("the file system")
406}
407
408#[cfg(not(unix))]
409pub unsafe fn lean_io_hard_link(_orig: Obj, _link: Obj) -> Obj {
410    io_result_unsupported("the file system")
411}
412
413#[cfg(not(unix))]
414pub unsafe fn lean_io_realpath(fname: Obj) -> Obj {
415    lean_dec(fname);
416    io_result_unsupported("the file system")
417}
418
419#[cfg(not(unix))]
420pub unsafe fn lean_chmod(_fname: Obj, _mode: u32) -> Obj {
421    io_result_unsupported("the file system")
422}
423
424#[cfg(not(unix))]
425pub unsafe fn lean_io_create_tempfile() -> Obj {
426    io_result_unsupported("the file system")
427}
428
429#[cfg(not(unix))]
430pub unsafe fn lean_io_create_tempdir() -> Obj {
431    io_result_unsupported("the file system")
432}
433
434/// No variable is set.
435#[cfg(not(unix))]
436pub unsafe fn lean_io_getenv(_var: Obj) -> Obj {
437    lean_box(0)
438}
439
440#[cfg(not(unix))]
441pub unsafe fn lean_io_app_path() -> Obj {
442    io_result_unsupported("the application path")
443}
444
445#[cfg(not(unix))]
446pub unsafe fn lean_io_current_dir() -> Obj {
447    io_result_unsupported("the current directory")
448}
449
450#[cfg(not(unix))]
451pub unsafe fn lean_io_process_get_current_dir() -> Obj {
452    io_result_unsupported("the current directory")
453}
454
455#[cfg(not(unix))]
456pub unsafe fn lean_io_process_set_current_dir(_p: Obj) -> Obj {
457    io_result_unsupported("the current directory")
458}
459
460/// The process id 0.
461#[cfg(not(unix))]
462pub unsafe fn lean_io_process_get_pid() -> u32 {
463    0
464}
465
466#[cfg(not(unix))]
467pub unsafe fn lean_io_get_random_bytes(_n: usize) -> Obj {
468    io_result_unsupported("random bytes")
469}
470
471#[cfg(not(unix))]
472pub unsafe fn lean_io_force_exit(_code: u8) -> Obj {
473    io_result_unsupported("exiting the process")
474}
475
476/* Profiling */
477
478/// `std::setprecision(3)` of a C++ stream: 3 significant digits, `%g`-style.
479fn g3(x: f64) -> String {
480    if x == 0.0 {
481        return "0".to_string();
482    }
483    let s = format!("{:.2e}", x);
484    let (m, e) = s.split_once('e').unwrap();
485    let e: i32 = e.parse().unwrap();
486    let trim = |s: &str| {
487        if s.contains('.') {
488            s.trim_end_matches('0').trim_end_matches('.').to_string()
489        } else {
490            s.to_string()
491        }
492    };
493    if !(-4..3).contains(&e) {
494        let sign = if e < 0 { '-' } else { '+' };
495        return format!("{}e{sign}{:02}", trim(m), e.abs());
496    }
497    trim(&format!("{:.*}", (2 - e) as usize, x))
498}
499
500/// Prints `s` and a newline on the current standard error stream (`IO.eprintln`).
501unsafe fn eprintln_stream(s: &str) {
502    let err = crate::io::lean_get_stderr();
503    let put = lean_ctor_get(err, 4);
504    lean_inc(put);
505    lean_dec(err);
506    let r = crate::closure::lean_apply_2(put, lean_mk_string(&format!("{s}\n")), lean_box(0));
507    lean_dec(r);
508}
509
510/// `timeit : (@& String) → IO α → IO α`: runs the action and prints `<msg> <time>` on the
511/// standard error stream.
512pub unsafe fn lean_io_timeit(msg: Obj, f: Obj) -> Obj {
513    let start = crate::io::mono_elapsed();
514    let r = crate::closure::lean_apply_1(f, lean_box(0));
515    let d = (crate::io::mono_elapsed() - start).as_secs_f64();
516    let m = crate::string::lean_string_to_str(msg);
517    let line = if d < 1.0 {
518        format!("{m} {}ms", g3(d * 1000.0))
519    } else {
520        format!("{m} {}s", g3(d))
521    };
522    eprintln_stream(&line);
523    r
524}
525
526/// `allocprof : (@& String) → IO α → IO α`: runs the action (this runtime keeps no
527/// allocation profile, so it prints an empty line).
528pub unsafe fn lean_io_allocprof(_msg: Obj, f: Obj) -> Obj {
529    let r = crate::closure::lean_apply_1(f, lean_box(0));
530    eprintln_stream("");
531    r
532}
533
534thread_local! {
535    static HEARTBEATS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
536}
537
538/// `IO.getNumHeartbeats : BaseIO Nat`: the value last set by `setNumHeartbeats` (this runtime
539/// counts no heartbeats).
540pub unsafe fn lean_io_get_num_heartbeats() -> Obj {
541    lean_uint64_to_nat(HEARTBEATS.get())
542}
543
544/// `IO.setNumHeartbeats : Nat → BaseIO Unit` (consumes `count`).
545pub unsafe fn lean_io_set_heartbeats(count: Obj) -> Obj {
546    HEARTBEATS.set(crate::uint::lean_uint64_of_nat(count));
547    lean_dec(count);
548    lean_box(0)
549}
550
551#[cfg(test)]
552mod tests {
553    use super::g3;
554
555    #[test]
556    fn three_significant_digits() {
557        assert_eq!(g3(1.23456), "1.23");
558        assert_eq!(g3(12.0), "12");
559        assert_eq!(g3(123.456), "123");
560        assert_eq!(g3(0.0123456), "0.0123");
561        assert_eq!(g3(999.7), "1e+03");
562        assert_eq!(g3(0.0000012345), "1.23e-06");
563    }
564}