1use crate::model::scalar_offset;
5use crate::object::*;
6use crate::string::{lean_mk_string, lean_string_to_str};
7
8const ALREADY_EXISTS: u32 = 0;
11pub(crate) const OTHER_ERROR: u32 = 1;
12const RESOURCE_BUSY: u32 = 2;
13const RESOURCE_VANISHED: u32 = 3;
14const UNSUPPORTED_OPERATION: u32 = 4;
15const HARDWARE_FAULT: u32 = 5;
16const UNSATISFIED_CONSTRAINTS: u32 = 6;
17const ILLEGAL_OPERATION: u32 = 7;
18const PROTOCOL_ERROR: u32 = 8;
19const TIME_EXPIRED: u32 = 9;
20const INTERRUPTED: u32 = 10;
21const NO_FILE_OR_DIRECTORY: u32 = 11;
22const INVALID_ARGUMENT: u32 = 12;
23const PERMISSION_DENIED: u32 = 13;
24const RESOURCE_EXHAUSTED: u32 = 14;
25const INAPPROPRIATE_TYPE: u32 = 15;
26const NO_SUCH_THING: u32 = 16;
27pub(crate) const UNEXPECTED_EOF: u32 = 17;
28pub(crate) const USER_ERROR: u32 = 18;
29
30fn has_filename(tag: u32) -> bool {
33 tag == ALREADY_EXISTS || (INTERRUPTED..=NO_SUCH_THING).contains(&tag)
34}
35
36unsafe fn mk_error(tag: u32, fname: Option<Obj>, code: u32, details: Obj) -> Obj {
39 if has_filename(tag) {
40 let r = lean_alloc_ctor(tag, 2, 4);
41 let f = match fname {
42 Some(f) if tag == INTERRUPTED || tag == NO_FILE_OR_DIRECTORY => f,
43 Some(f) => {
44 let s = lean_alloc_ctor(1, 1, 0);
45 lean_ctor_set(s, 0, f);
46 s
47 }
48 None => lean_box(0),
49 };
50 lean_ctor_set(r, 0, f);
51 lean_ctor_set(r, 1, details);
52 lean_ctor_set_uint32(r, scalar_offset(2, 0), code);
53 r
54 } else {
55 if let Some(f) = fname {
56 lean_dec(f);
57 }
58 let r = lean_alloc_ctor(tag, 1, 4);
59 lean_ctor_set(r, 0, details);
60 lean_ctor_set_uint32(r, scalar_offset(1, 0), code);
61 r
62 }
63}
64
65pub unsafe fn lean_mk_io_user_error(msg: Obj) -> Obj {
67 let r = lean_alloc_ctor(USER_ERROR, 1, 0);
68 lean_ctor_set(r, 0, msg);
69 r
70}
71
72pub unsafe fn lean_mk_io_error_other_error(code: u32, details: Obj) -> Obj {
74 mk_error(OTHER_ERROR, None, code, details)
75}
76
77pub unsafe fn lean_mk_io_error_eof(_unit: Obj) -> Obj {
79 lean_box(UNEXPECTED_EOF as usize)
80}
81
82#[cfg(unix)]
84pub(crate) use libc::{EBADF, EINVAL, ENOENT, ESPIPE};
85#[cfg(not(unix))]
86pub(crate) const EBADF: i32 = 9;
87#[cfg(not(unix))]
88pub(crate) const EINVAL: i32 = 22;
89#[cfg(not(unix))]
90pub(crate) const ESPIPE: i32 = 29;
91
92#[cfg(not(unix))]
95pub(crate) unsafe fn unsupported_error(what: &str) -> Obj {
96 let msg = format!("{what} is not supported on {}", env!("LEANFRAN_TARGET"));
97 mk_error(UNSUPPORTED_OPERATION, None, 0, lean_mk_string(&msg))
98}
99
100#[cfg(unix)]
102pub(crate) unsafe fn file_not_found_error(fname: Obj) -> Obj {
103 lean_inc(fname);
104 mk_error(
105 NO_FILE_OR_DIRECTORY,
106 Some(fname),
107 ENOENT as u32,
108 lean_mk_string(""),
109 )
110}
111
112#[cfg(unix)]
114pub(crate) unsafe fn embedded_nul_error(s: Obj) -> Obj {
115 lean_inc(s);
116 mk_error(
117 INVALID_ARGUMENT,
118 Some(s),
119 EINVAL as u32,
120 lean_mk_string("string contains NUL bytes"),
121 )
122}
123
124#[cfg(unix)]
129fn uv_of_errno(e: i32, approximate: bool) -> Option<(i32, &'static str)> {
130 use libc as c;
131 let table: &[(i32, &str)] = &[
132 (c::E2BIG, "argument list too long"),
133 (c::EACCES, "permission denied"),
134 (c::EADDRINUSE, "address already in use"),
135 (c::EADDRNOTAVAIL, "address not available"),
136 (c::EAFNOSUPPORT, "address family not supported"),
137 (c::EAGAIN, "resource temporarily unavailable"),
138 (c::EBADF, "bad file descriptor"),
139 (c::EBUSY, "resource busy or locked"),
140 (c::ECONNABORTED, "software caused connection abort"),
141 (c::ECONNREFUSED, "connection refused"),
142 (c::ECONNRESET, "connection reset by peer"),
143 (c::EDESTADDRREQ, "destination address required"),
144 (c::EEXIST, "file already exists"),
145 (c::EFAULT, "bad address in system call argument"),
146 (c::EFBIG, "file too large"),
147 (c::EHOSTUNREACH, "host is unreachable"),
148 (c::EILSEQ, "illegal byte sequence"),
149 (c::EINTR, "interrupted system call"),
150 (c::EINVAL, "invalid argument"),
151 (c::EIO, "i/o error"),
152 (c::EISCONN, "socket is already connected"),
153 (c::EISDIR, "illegal operation on a directory"),
154 (c::ELOOP, "too many symbolic links encountered"),
155 (c::EMFILE, "too many open files"),
156 (c::EMLINK, "too many links"),
157 (c::EMSGSIZE, "message too long"),
158 (c::ENAMETOOLONG, "name too long"),
159 (c::ENETDOWN, "network is down"),
160 (c::ENETUNREACH, "network is unreachable"),
161 (c::ENFILE, "file table overflow"),
162 (c::ENOBUFS, "no buffer space available"),
163 (c::ENODEV, "no such device"),
164 (c::ENOENT, "no such file or directory"),
165 (c::ENOMEM, "not enough memory"),
166 (c::ENOPROTOOPT, "protocol not available"),
167 (c::ENOSPC, "no space left on device"),
168 (c::ENOSYS, "function not implemented"),
169 (c::ENOTCONN, "socket is not connected"),
170 (c::ENOTDIR, "not a directory"),
171 (c::ENOTEMPTY, "directory not empty"),
172 (c::ENOTSOCK, "socket operation on non-socket"),
173 (c::ENOTTY, "inappropriate ioctl for device"),
174 (c::ENXIO, "no such device or address"),
175 (c::EOPNOTSUPP, "operation not supported on socket"),
176 (c::EPERM, "operation not permitted"),
177 (c::EPIPE, "broken pipe"),
178 (c::EPROTO, "protocol error"),
179 (c::EPROTONOSUPPORT, "protocol not supported"),
180 (c::EPROTOTYPE, "protocol wrong type for socket"),
181 (c::ERANGE, "result too large"),
182 (c::EROFS, "read-only file system"),
183 (c::ESPIPE, "invalid seek"),
184 (c::ESRCH, "no such process"),
185 (c::ETIMEDOUT, "connection timed out"),
186 (c::ETXTBSY, "text file is busy"),
187 (c::EXDEV, "cross-device link not permitted"),
188 (c::ENODATA, "no data available"),
189 ];
190 let e = if approximate {
191 match e {
193 _ if e == c::ENOMSG => c::ENODATA,
194 _ if e == c::ENOEXEC || e == c::EDOM || e == c::ENOSTR => c::EINVAL,
195 _ if e == c::EBADMSG => c::EPROTO,
196 _ if e == c::ECHILD => c::ESRCH,
197 _ if e == c::EDEADLK => c::EBUSY,
198 _ if e == c::EIDRM => c::EPIPE,
199 _ if e == c::EINPROGRESS => c::EISCONN,
200 _ if e == c::ENETRESET || e == c::ENOLINK => c::ECONNRESET,
201 _ if e == c::ENOLCK => c::EAGAIN,
202 _ if e == c::ENOSR => c::ENOBUFS,
203 _ if e == c::ETIME => c::ETIMEDOUT,
204 _ => e,
205 }
206 } else {
207 e
208 };
209 table.iter().find(|(n, _)| *n == e).copied()
210}
211
212#[cfg(unix)]
214unsafe fn decode(errnum: i32, approximate: bool, fname: Option<Obj>) -> Obj {
215 use libc as c;
216 let (uv, msg) = match uv_of_errno(errnum, approximate) {
217 Some(p) => (p.0, p.1.to_string()),
218 None => (0, format!("Unknown system error {}", -errnum)),
219 };
220 let details = lean_mk_string(&msg);
221 let code = errnum as u32;
222 let file = |f: Option<Obj>| f.inspect(|&f| lean_inc(f));
223 let tag = match uv {
224 0 => OTHER_ERROR,
225 _ if uv == c::EINTR => INTERRUPTED,
226 _ if [
227 c::ELOOP,
228 c::ENAMETOOLONG,
229 c::EDESTADDRREQ,
230 c::EBADF,
231 c::EINVAL,
232 c::EILSEQ,
233 c::ENOTCONN,
234 c::ENOTSOCK,
235 ]
236 .contains(&uv) =>
237 {
238 INVALID_ARGUMENT
239 }
240 _ if uv == c::ENOENT => NO_FILE_OR_DIRECTORY,
241 _ if [c::EACCES, c::EROFS, c::ECONNABORTED, c::EFBIG, c::EPERM].contains(&uv) => {
242 PERMISSION_DENIED
243 }
244 _ if [
245 c::EMFILE,
246 c::ENFILE,
247 c::ENOSPC,
248 c::E2BIG,
249 c::EAGAIN,
250 c::EMLINK,
251 c::EMSGSIZE,
252 c::ENOBUFS,
253 c::ENOMEM,
254 ]
255 .contains(&uv) =>
256 {
257 RESOURCE_EXHAUSTED
258 }
259 _ if uv == c::EISDIR || uv == c::ENOTDIR => INAPPROPRIATE_TYPE,
260 _ if [
261 c::ENXIO,
262 c::EHOSTUNREACH,
263 c::ENETUNREACH,
264 c::ECONNREFUSED,
265 c::ENODATA,
266 c::ESRCH,
267 ]
268 .contains(&uv) =>
269 {
270 NO_SUCH_THING
271 }
272 _ if uv == c::EEXIST || uv == c::EISCONN => ALREADY_EXISTS,
273 _ if uv == c::EIO => HARDWARE_FAULT,
274 _ if uv == c::ENOTEMPTY => UNSATISFIED_CONSTRAINTS,
275 _ if uv == c::ENOTTY => ILLEGAL_OPERATION,
276 _ if [c::ECONNRESET, c::ENETDOWN, c::EPIPE].contains(&uv) => RESOURCE_VANISHED,
277 _ if [c::EPROTO, c::EPROTONOSUPPORT, c::EPROTOTYPE].contains(&uv) => PROTOCOL_ERROR,
278 _ if uv == c::ETIMEDOUT => TIME_EXPIRED,
279 _ if [c::EBUSY, c::ETXTBSY].contains(&uv) || uv == c::EADDRINUSE => RESOURCE_BUSY,
280 _ if [
281 c::EADDRNOTAVAIL,
282 c::EAFNOSUPPORT,
283 c::ENODEV,
284 c::ENOPROTOOPT,
285 c::ENOSYS,
286 c::EOPNOTSUPP,
287 c::ERANGE,
288 c::ESPIPE,
289 c::EXDEV,
290 ]
291 .contains(&uv) =>
292 {
293 UNSUPPORTED_OPERATION
294 }
295 _ => OTHER_ERROR,
296 };
297 let fname = if tag == INTERRUPTED || tag == NO_FILE_OR_DIRECTORY {
298 Some(file(fname).unwrap_or_else(|| lean_mk_string("")))
299 } else if has_filename(tag) {
300 file(fname)
301 } else {
302 None
303 };
304 mk_error(tag, fname, code, details)
305}
306
307#[cfg(not(unix))]
309unsafe fn decode(errnum: i32, _approximate: bool, _fname: Option<Obj>) -> Obj {
310 let msg = format!("Unknown system error {}", -errnum);
311 mk_error(OTHER_ERROR, None, errnum as u32, lean_mk_string(&msg))
312}
313
314pub unsafe fn lean_decode_io_error(errnum: i32, fname: Obj) -> Obj {
317 decode(errnum, true, (!fname.is_null()).then_some(fname))
318}
319
320pub unsafe fn lean_decode_uv_error(errnum: i32, fname: Obj) -> Obj {
322 decode(-errnum, false, (!fname.is_null()).then_some(fname))
323}
324
325pub(crate) unsafe fn of_std(e: &std::io::Error, fname: Option<Obj>) -> Obj {
328 match e.raw_os_error() {
329 Some(n) => decode(n, true, fname),
330 None => lean_mk_io_error_other_error(0, lean_mk_string(&e.to_string())),
331 }
332}
333
334#[cfg(unix)]
336pub(crate) unsafe fn of_std_uv(e: &std::io::Error, fname: Option<Obj>) -> Obj {
337 match e.raw_os_error() {
338 Some(n) => decode(n, false, fname),
339 None => lean_mk_io_error_other_error(0, lean_mk_string(&e.to_string())),
340 }
341}
342
343fn decapitalize(s: &str) -> String {
346 let mut c = s.chars();
347 match c.next() {
348 Some(f) => f.to_ascii_lowercase().to_string() + c.as_str(),
349 None => String::new(),
350 }
351}
352
353fn fopen_error(gist: &str, fname: &str, code: u32, details: Option<&str>) -> String {
354 match details {
355 Some(d) => format!(
356 "{} (error code: {code}, {})\n file: {fname}",
357 decapitalize(gist),
358 decapitalize(d)
359 ),
360 None => format!(
361 "{} (error code: {code})\n file: {fname}",
362 decapitalize(gist)
363 ),
364 }
365}
366
367fn other_error(gist: &str, code: u32, details: Option<&str>) -> String {
368 match details {
369 Some(d) => format!(
370 "{} (error code: {code}, {})",
371 decapitalize(gist),
372 decapitalize(d)
373 ),
374 None => format!("{} (error code: {code})", decapitalize(gist)),
375 }
376}
377
378pub unsafe fn io_error_to_string(e: Obj) -> String {
380 if lean_is_scalar(e) {
381 return "end of file".to_string();
382 }
383 let tag = lean_ptr_tag(e) as u32;
384 if tag == USER_ERROR {
385 return lean_string_to_str(lean_ctor_get(e, 0)).to_string();
386 }
387 let (fname, details, code) = if has_filename(tag) {
388 let f = lean_ctor_get(e, 0);
389 let f = if tag == INTERRUPTED || tag == NO_FILE_OR_DIRECTORY {
390 Some(lean_string_to_str(f))
391 } else if lean_is_scalar(f) {
392 None
393 } else {
394 Some(lean_string_to_str(lean_ctor_get(f, 0)))
395 };
396 (
397 f,
398 lean_string_to_str(lean_ctor_get(e, 1)),
399 lean_ctor_get_uint32(e, scalar_offset(2, 0)),
400 )
401 } else {
402 (
403 None,
404 lean_string_to_str(lean_ctor_get(e, 0)),
405 lean_ctor_get_uint32(e, scalar_offset(1, 0)),
406 )
407 };
408 let d = Some(details);
409 let with_file = |gist: &str, details: Option<&str>| match fname {
410 Some(f) => fopen_error(gist, f, code, details),
411 None => other_error(gist, code, details),
412 };
413 match tag {
414 INAPPROPRIATE_TYPE => with_file("inappropriate type", d),
415 INTERRUPTED => with_file("interrupted system call", d),
416 INVALID_ARGUMENT => with_file("invalid argument", d),
417 NO_FILE_OR_DIRECTORY => with_file("no such file or directory", None),
418 NO_SUCH_THING => with_file("no such thing", d),
419 PERMISSION_DENIED => with_file(details, None),
420 RESOURCE_EXHAUSTED => with_file("resource exhausted", d),
421 ALREADY_EXISTS => with_file("already exists", d),
422 OTHER_ERROR => other_error(details, code, None),
423 RESOURCE_BUSY => other_error("resource busy", code, d),
424 RESOURCE_VANISHED => other_error("resource vanished", code, d),
425 HARDWARE_FAULT => other_error("hardware fault", code, None),
426 ILLEGAL_OPERATION => other_error("illegal operation", code, d),
427 PROTOCOL_ERROR => other_error("protocol error", code, d),
428 TIME_EXPIRED => other_error("time expired", code, d),
429 UNSATISFIED_CONSTRAINTS => other_error("directory not empty", code, None),
430 UNSUPPORTED_OPERATION => other_error("unsupported operation", code, d),
431 _ => String::new(),
432 }
433}