Skip to main content

hexicon_vm/
file.rs

1//! The File, FileName, and TemporaryFile built-in classes.
2//!
3//! A file name is text in one syntax on every host: parts separated by
4//! `/`, with `.` for a folder itself and `..` for the one above it. The
5//! reference VM calls this the universal syntax and keeps names in the
6//! local system's; here the two are the same, and the host translates when
7//! it touches a real file system.
8//!
9//! An open file is held in memory whole. Opening one reads it from the
10//! host, and closing one writes it back if it changed. That keeps the
11//! host's part small enough for a browser to supply.
12
13use std::rc::Rc;
14
15use hexicon_host::{FileError, Sandbox, file_type};
16
17/// How the system ends a line in a text file.
18const NEWLINE: &str = if cfg!(windows) { "\r\n" } else { "\n" };
19
20use crate::error::{ErrParam, VmError, VmResult, code};
21use crate::hash;
22use crate::object::Object;
23use crate::pack::Stream;
24use crate::value::{INVALID_PROP, NativeDesc, ObjId, Value};
25use crate::vm::{NativeCall, Vm};
26
27// How a file is read and written.
28pub(crate) const MODE_TEXT: u8 = 1;
29pub(crate) const MODE_DATA: u8 = 2;
30pub(crate) const MODE_RAW: u8 = 3;
31
32/// What a program wants to do with a file.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub(crate) enum Access {
35    Read,
36    Write,
37    ReadWriteKeep,
38    ReadWriteTruncate,
39    Delete,
40    GetInfo,
41    MakeDir,
42    RemoveDir,
43    ReadDir,
44    RenameFrom,
45    RenameTo,
46}
47
48impl Access {
49    /// The access a program asks for by number when it opens a file.
50    fn from_code(code: i32) -> Option<Self> {
51        Some(match code {
52            1 => Self::Read,
53            2 => Self::Write,
54            3 => Self::ReadWriteKeep,
55            4 => Self::ReadWriteTruncate,
56            _ => return None,
57        })
58    }
59
60    fn code(self) -> u8 {
61        match self {
62            Self::Read => 1,
63            Self::Write => 2,
64            Self::ReadWriteKeep => 3,
65            _ => 4,
66        }
67    }
68}
69
70// The values a data file marks its contents with.
71const TAG_INT: u8 = 0x01;
72const TAG_STRING: u8 = 0x03;
73const TAG_TRUE: u8 = 0x08;
74const TAG_ENUM: u8 = 0x20;
75const TAG_BIGNUM: u8 = 0x21;
76const TAG_BYTEARRAY: u8 = 0x22;
77
78/// A file name.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub(crate) struct FileNameObj {
81    /// The name. For a special file, where the host keeps it, if it said.
82    pub path: String,
83    /// The number of a special file, or zero.
84    pub special: i32,
85    /// How the player chose the name in a file dialog: 1 to open a file,
86    /// 2 to save one, or zero if the name came from the program. A file
87    /// the player chose can be used wherever it is.
88    pub from_ui: u8,
89}
90
91/// The contents of an open file.
92#[derive(Debug, Clone)]
93pub(crate) struct OpenFile {
94    /// The name to write the file back under. A resource has none.
95    pub name: Option<String>,
96    pub data: Vec<u8>,
97    pub pos: usize,
98    /// The contents differ from what the host has.
99    pub dirty: bool,
100}
101
102impl OpenFile {
103    /// The bytes from the position on, at most `len` of them, moving
104    /// past them.
105    fn read(&mut self, len: usize) -> &[u8] {
106        let start = self.pos.min(self.data.len());
107        let end = start.saturating_add(len).min(self.data.len());
108        if end > start {
109            self.pos = end;
110        }
111        &self.data[start..end]
112    }
113
114    /// Exactly `len` bytes, or nothing if there are not that many.
115    fn read_exact(&mut self, len: usize) -> Option<Vec<u8>> {
116        let start = self.pos.min(self.data.len());
117        let bytes = self.data.get(start..start.checked_add(len)?)?.to_vec();
118        self.pos = start + len;
119        Some(bytes)
120    }
121
122    fn write(&mut self, bytes: &[u8]) {
123        // Writing past the end leaves zeros in between.
124        if self.pos > self.data.len() {
125            self.data.resize(self.pos, 0);
126        }
127        let end = self.pos + bytes.len();
128        if end > self.data.len() {
129            self.data.resize(end, 0);
130        }
131        self.data[self.pos..end].copy_from_slice(bytes);
132        self.pos = end;
133        self.dirty = true;
134    }
135}
136
137/// A file object.
138#[derive(Debug, Clone)]
139pub(crate) struct FileObj {
140    /// The character set of a text file, or the invalid ID.
141    pub charset: ObjId,
142    pub mode: u8,
143    pub access: u8,
144    /// The object came from an image or a saved state, so it has no file.
145    pub out_of_sync: bool,
146    /// What the program gave to say which file to open.
147    pub spec: Value,
148    /// The contents, while the file is open.
149    pub open: Option<OpenFile>,
150}
151
152/// Which file a program means, once its file specification is worked out.
153#[derive(Debug, Clone)]
154pub(crate) struct FileTarget {
155    /// The name to give the host. `None` for a special file the host has
156    /// no place for.
157    pub name: Option<String>,
158    special: bool,
159    temporary: bool,
160    from_ui: u8,
161    spec: Value,
162}
163
164/// The exceptions the file classes throw. A program that does not define
165/// the class gets a run-time error with the message instead.
166#[derive(Debug, Clone, Copy)]
167enum FileExc {
168    NotFound,
169    Creation,
170    Open,
171    OpenDir,
172    Io,
173    Sync,
174    Closed,
175    Mode,
176    Safety,
177}
178
179// ---- names ----
180
181/// Whether a name starts at a root: with `/`, or with a drive letter on a
182/// system that has them.
183pub(crate) fn is_absolute(path: &str) -> bool {
184    let bytes = path.as_bytes();
185    path.starts_with('/')
186        || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
187}
188
189/// The last part of a name.
190pub(crate) fn root_name(path: &str) -> &str {
191    path.rsplit('/').next().unwrap_or(path)
192}
193
194/// A name without its last part, or nothing if it has only one.
195fn path_name(path: &str) -> &str {
196    match path.rfind('/') {
197        None => "",
198        Some(at) => {
199            let before = path[..at].trim_end_matches('/');
200            if before.is_empty() { "/" } else { before }
201        }
202    }
203}
204
205/// Take `.` and empty parts out of a name, and each `..` with the part
206/// before it.
207fn canonicalize(path: &str) -> String {
208    let mut parts: Vec<&str> = Vec::new();
209    for part in path.split('/') {
210        match part {
211            "" | "." => {}
212            ".." if parts.last().is_some_and(|&last| last != "..") => {
213                parts.pop();
214            }
215            _ => parts.push(part),
216        }
217    }
218    let mut out = String::new();
219    if path.starts_with('/') {
220        out.push('/');
221    }
222    out.push_str(&parts.join("/"));
223    if out.is_empty() {
224        out.push('.');
225    }
226    out
227}
228
229/// A name in a folder. A name that starts at a root stays as it is. A
230/// literal combination keeps `.` and `..` parts as they are.
231pub(crate) fn combine(dir: &str, name: &str, literal: bool) -> String {
232    let joined = if is_absolute(name) || dir.is_empty() {
233        name.to_owned()
234    } else if dir.ends_with('/') {
235        format!("{dir}{name}")
236    } else {
237        format!("{dir}/{name}")
238    };
239    if literal {
240        joined
241    } else {
242        canonicalize(&joined)
243    }
244}
245
246/// The type flags that say a name is a folder's entry for itself or for
247/// its parent.
248fn special_link_flags(path: &str) -> i32 {
249    match root_name(path) {
250        "." => 0x80,
251        ".." => 0x100,
252        _ => 0,
253    }
254}
255
256const FILE_METHODS: [NativeDesc; 25] = [
257    NativeDesc::fixed(0),
258    NativeDesc::optional(2, 1), // openTextFile
259    NativeDesc::fixed(2),       // openDataFile
260    NativeDesc::fixed(2),       // openRawFile
261    NativeDesc::fixed(0),       // getCharacterSet
262    NativeDesc::fixed(1),       // setCharacterSet
263    NativeDesc::fixed(0),       // closeFile
264    NativeDesc::fixed(0),       // readFile
265    NativeDesc::fixed(1),       // writeFile
266    NativeDesc::optional(1, 2), // readBytes
267    NativeDesc::optional(1, 2), // writeBytes
268    NativeDesc::fixed(0),       // getPos
269    NativeDesc::fixed(1),       // setPos
270    NativeDesc::fixed(0),       // setPosEnd
271    NativeDesc::optional(1, 1), // openTextResource
272    NativeDesc::fixed(1),       // openRawResource
273    NativeDesc::fixed(0),       // getFileSize
274    NativeDesc::fixed(0),       // getFileMode
275    NativeDesc::fixed(1),       // getRootName
276    NativeDesc::fixed(1),       // deleteFile
277    NativeDesc::optional(1, 1), // setFileMode
278    NativeDesc::variable(1),    // packBytes
279    NativeDesc::fixed(1),       // unpackBytes
280    NativeDesc::optional(0, 1), // sha256
281    NativeDesc::optional(0, 1), // digestMD5
282];
283
284const FILE_NAME_METHODS: [NativeDesc; 18] = [
285    NativeDesc::fixed(0),
286    NativeDesc::fixed(0),       // getName
287    NativeDesc::fixed(0),       // getBaseName
288    NativeDesc::fixed(0),       // getPath
289    NativeDesc::fixed(1),       // fromUniversal
290    NativeDesc::fixed(0),       // toUniversal
291    NativeDesc::fixed(1),       // addToPath
292    NativeDesc::fixed(0),       // isAbsolute
293    NativeDesc::fixed(0),       // getAbsolutePath
294    NativeDesc::fixed(0),       // getRootDirs
295    NativeDesc::fixed(0),       // getFileType
296    NativeDesc::fixed(0),       // getFileInfo
297    NativeDesc::fixed(0),       // deleteFile
298    NativeDesc::fixed(1),       // renameFile
299    NativeDesc::fixed(0),       // listDir
300    NativeDesc::optional(1, 1), // forEachFile
301    NativeDesc::optional(0, 1), // createDirectory
302    NativeDesc::optional(0, 1), // removeDirectory
303];
304
305impl Vm {
306    // ---- exceptions ----
307
308    /// The error for throwing a new instance of an exception class, or a
309    /// run-time error with the message if the program has no such class.
310    pub(crate) fn throw_class(&mut self, class: ObjId, message: &str) -> VmError {
311        if class.is_valid() {
312            return match self.create_instance(class, 0) {
313                Err(error) => error,
314                Ok(()) => match self.r0 {
315                    Value::Obj(exception) => VmError::Thrown(exception),
316                    _ => VmError::new(code::EXCEPTION_OBJ_REQD),
317                },
318            };
319        }
320        VmError::with(
321            code::INTCLS_GENERAL_ERROR,
322            vec![ErrParam::Str(message.to_owned())],
323        )
324    }
325
326    /// A resource that is not in the image is looked for as a file beside
327    /// it, which is how a game under development gets at resources that
328    /// have not been bundled yet, and how some games read back files they
329    /// wrote. Only a file in the image's folder or below it will do,
330    /// whatever the safety level, unless that allows no reading at all.
331    pub(crate) fn resource_file(&mut self, name: Option<&str>) -> Option<Vec<u8>> {
332        let name = name?;
333        if self.io.safety_read > 3
334            || name.is_empty()
335            || is_absolute(name)
336            || name.split('/').any(|part| part == "..")
337        {
338            return None;
339        }
340        self.host.read_file(name).ok()
341    }
342
343    fn file_exc(&mut self, which: FileExc) -> VmError {
344        let predef = &self.predef;
345        let (class, message) = match which {
346            FileExc::NotFound => (predef.file_not_found_exc, "file not found"),
347            FileExc::Creation => (predef.file_creation_exc, "error creating file"),
348            FileExc::Open => (predef.file_open_exc, "error opening file"),
349            FileExc::OpenDir => (predef.file_open_exc, "error reading directory"),
350            FileExc::Io => (predef.file_io_exc, "file I/O error"),
351            FileExc::Sync => (predef.file_sync_exc, "file out of sync"),
352            FileExc::Closed => (predef.file_closed_exc, "operation attempted on closed file"),
353            FileExc::Mode => (predef.file_mode_exc, "wrong file mode"),
354            FileExc::Safety => (predef.file_safety_exc, "prohibited file access"),
355        };
356        self.throw_class(class, message)
357    }
358
359    // ---- which file ----
360
361    /// A FileName object for a name.
362    pub(crate) fn new_file_name(&mut self, path: &str) -> ObjId {
363        self.alloc_obj(Object::FileName(Box::new(FileNameObj {
364            path: path.to_owned(),
365            special: 0,
366            from_ui: 0,
367        })))
368    }
369
370    /// Note that the player chose a file name in a dialog.
371    pub(crate) fn set_file_name_from_ui(&mut self, id: ObjId, dialog: u8) {
372        if let Some(Object::FileName(name)) = self.objects.get_mut(id) {
373            name.from_ui = dialog;
374        }
375    }
376
377    fn file_name(&self, id: ObjId) -> Option<&FileNameObj> {
378        match self.objects.get(id) {
379            Some(Object::FileName(name)) => Some(name),
380            _ => None,
381        }
382    }
383
384    /// The name a value gives: a FileName's, or the text of a string.
385    pub(crate) fn path_of(&self, value: Value) -> Option<String> {
386        if let Value::Obj(id) = value
387            && let Some(name) = self.file_name(id)
388        {
389            return Some(name.path.clone());
390        }
391        self.as_str(value)
392            .map(|text| String::from_utf8_lossy(&text).into_owned())
393    }
394
395    /// Where the host keeps a special file. Only two numbers mean
396    /// anything.
397    fn special_file_path(&mut self, special: i32) -> VmResult<Option<String>> {
398        match special {
399            1 | 2 => Ok(self.host.special_file(special)),
400            _ => Err(VmError::new(code::BAD_VAL_BIF)),
401        }
402    }
403
404    /// Work out which file a value refers to: a name, a FileName, a
405    /// TemporaryFile, the number of a special file, or an object of the
406    /// program's own that supplies one of those.
407    pub(crate) fn file_target(&mut self, value: Value) -> VmResult<FileTarget> {
408        let mut spec = value;
409        if let Value::Obj(id) = value {
410            let get_filename = self.predef.filespec_get_filename;
411            if get_filename != INVALID_PROP
412                && matches!(self.objects.get(id), Some(Object::Program(_)))
413            {
414                let native = NativeCall::named("FileSpec.getFilename");
415                spec = self.call_prop(value, get_filename, 0, Some(native))?;
416            }
417        }
418        let keep = match value {
419            Value::Obj(_) => value,
420            _ => Value::Nil,
421        };
422        let mut target = FileTarget {
423            name: None,
424            special: false,
425            temporary: false,
426            from_ui: 0,
427            spec: keep,
428        };
429        match spec {
430            Value::Obj(id) => match self.objects.get(id) {
431                Some(Object::TempFile(name)) => {
432                    if name.is_empty() {
433                        return Err(VmError::new(code::CREATE_FILE));
434                    }
435                    target.name = Some(name.clone());
436                    target.temporary = true;
437                    return Ok(target);
438                }
439                Some(Object::FileName(name)) => {
440                    if name.special != 0 {
441                        let special = name.special;
442                        target.name = self.special_file_path(special)?;
443                        target.special = true;
444                    } else {
445                        target.name = Some(name.path.clone());
446                        target.from_ui = name.from_ui;
447                    }
448                    return Ok(target);
449                }
450                Some(Object::Decimal(_)) => {
451                    let special = self.cast_to_int(spec)?;
452                    target.name = self.special_file_path(special)?;
453                    target.special = true;
454                    return Ok(target);
455                }
456                _ => {}
457            },
458            Value::Int(special) => {
459                target.name = self.special_file_path(special)?;
460                target.special = true;
461                return Ok(target);
462            }
463            _ => {}
464        }
465        match self.as_str(spec) {
466            Some(text) => {
467                target.name = Some(String::from_utf8_lossy(&text).into_owned());
468                Ok(target)
469            }
470            None => Err(VmError::new(code::BAD_TYPE_BIF)),
471        }
472    }
473
474    /// Whether the safety levels let the program do something with a
475    /// file. Level 0 allows anything, 1 reading anything but writing only
476    /// in the sandbox folder, 2 reading and writing only there, 3 only
477    /// reading there, and 4 nothing.
478    fn safety_allows(&mut self, name: &str, access: Access) -> bool {
479        let reading = matches!(access, Access::Read | Access::GetInfo | Access::ReadDir);
480        if reading {
481            if self.io.safety_read <= 1 {
482                return true;
483            }
484            if self.io.safety_read >= 4 {
485                return false;
486            }
487        } else {
488            if self.io.safety_write == 0 {
489                return true;
490            }
491            if self.io.safety_write >= 3 {
492                return false;
493            }
494        }
495        match self.host.sandbox(name) {
496            Sandbox::Inside => true,
497            // The folder itself can be looked at and listed, and so much
498            // can be learned about the folders it is in.
499            Sandbox::Itself => matches!(access, Access::GetInfo | Access::ReadDir),
500            Sandbox::Contains => access == Access::GetInfo,
501            Sandbox::Outside => false,
502        }
503    }
504
505    /// Stop the program from doing what the safety levels do not allow.
506    pub(crate) fn check_safety(&mut self, target: &FileTarget, access: Access) -> VmResult<()> {
507        let opening = matches!(
508            access,
509            Access::Read | Access::Write | Access::ReadWriteKeep | Access::ReadWriteTruncate
510        );
511        let looking = matches!(access, Access::GetInfo | Access::ReadDir);
512        // The special files and temporary files are the program's to use.
513        if target.special && (opening || looking) {
514            return Ok(());
515        }
516        if target.temporary && (opening || looking || access == Access::Delete) {
517            return Ok(());
518        }
519        // So is a file the player picked, for what it was picked for.
520        if (target.from_ui == 1 && access == Access::Read)
521            || (target.from_ui == 2 && access == Access::Write)
522        {
523            return Ok(());
524        }
525        let allowed = match &target.name {
526            Some(name) => {
527                let name = name.clone();
528                self.safety_allows(&name, access)
529            }
530            None => true,
531        };
532        if allowed {
533            Ok(())
534        } else {
535            Err(self.file_exc(FileExc::Safety))
536        }
537    }
538
539    /// The name of the file a value refers to, for a function that reads
540    /// or writes a whole file, checked against the safety levels.
541    pub(crate) fn file_name_arg(&mut self, value: Value, access: Access) -> VmResult<String> {
542        let target = self.file_target(value)?;
543        self.check_safety(&target, access)?;
544        target
545            .name
546            .ok_or_else(|| VmError::new(code::FILE_NOT_FOUND))
547    }
548
549    /// Set how much of the file system the program may read and write.
550    pub fn set_file_safety(&mut self, read: u8, write: u8) {
551        self.io.safety_read = read;
552        self.io.safety_write = write;
553    }
554
555    /// Supply a resource for the program to open by name.
556    pub fn add_resource(&mut self, name: &str, data: &[u8]) {
557        self.io.resources.insert(name.to_owned(), data.into());
558    }
559
560    pub(crate) fn resource_exists(&self, name: &str) -> bool {
561        self.io.resources.contains_key(name)
562    }
563
564    // ---- open files ----
565
566    /// Write every open file that has changed back to the host, so that
567    /// whatever looks at the files next sees what the program wrote.
568    pub(crate) fn sync_files(&mut self) {
569        let ids = std::mem::take(&mut self.io.open_files);
570        let mut still_open = Vec::with_capacity(ids.len());
571        for id in ids {
572            if still_open.contains(&id) {
573                continue;
574            }
575            let Some(Object::File(file)) = self.objects.get_mut(id) else {
576                continue;
577            };
578            let Some(open) = &mut file.open else {
579                continue;
580            };
581            still_open.push(id);
582            if open.dirty
583                && let Some(name) = &open.name
584                && self.host.write_file(name, &open.data).is_ok()
585            {
586                open.dirty = false;
587            }
588        }
589        self.io.open_files = still_open;
590    }
591
592    /// Finish with the files of objects the collector freed: write out
593    /// what open files had not written, and delete temporary files.
594    pub(crate) fn release_files(&mut self) {
595        for released in self.objects.take_released() {
596            match released {
597                Object::File(file) => {
598                    if let Some(OpenFile {
599                        name: Some(name),
600                        data,
601                        dirty: true,
602                        ..
603                    }) = file.open
604                    {
605                        let _ = self.host.write_file(&name, &data);
606                    }
607                }
608                Object::TempFile(name) if !name.is_empty() => {
609                    let _ = self.host.delete_file(&name);
610                }
611                _ => {}
612            }
613        }
614    }
615
616    /// Finish with every file at the end of the run.
617    pub fn close_files(&mut self) {
618        self.sync_files();
619        self.objects.release_all_files();
620        self.release_files();
621    }
622
623    fn file(&self, id: ObjId) -> Option<&FileObj> {
624        match self.objects.get(id) {
625            Some(Object::File(file)) => Some(file),
626            _ => None,
627        }
628    }
629
630    /// An open file's contents, to read or change. A file object is
631    /// never saved or undone, so changing one records nothing.
632    fn open_file(&mut self, id: ObjId) -> VmResult<&mut OpenFile> {
633        match self.objects.get_mut(id) {
634            Some(Object::File(file)) => match &mut file.open {
635                Some(open) => Ok(open),
636                None => Err(VmError::new(code::BAD_TYPE_BIF)),
637            },
638            _ => Err(VmError::new(code::BAD_TYPE_BIF)),
639        }
640    }
641
642    /// The file's access and mode, once it is known to be usable.
643    fn check_valid_file(&mut self, id: ObjId) -> VmResult<(u8, u8)> {
644        let Some(file) = self.file(id) else {
645            return Err(VmError::new(code::BAD_TYPE_BIF));
646        };
647        let (out_of_sync, open, access, mode) = (
648            file.out_of_sync,
649            file.open.is_some(),
650            file.access,
651            file.mode,
652        );
653        if out_of_sync {
654            return Err(self.file_exc(FileExc::Sync));
655        }
656        if !open {
657            return Err(self.file_exc(FileExc::Closed));
658        }
659        Ok((access, mode))
660    }
661
662    fn check_raw(&mut self, id: ObjId, writing: bool) -> VmResult<()> {
663        let (access, mode) = self.check_valid_file(id)?;
664        let wrong_access = if writing {
665            access == Access::Read.code()
666        } else {
667            access == Access::Write.code()
668        };
669        if wrong_access || mode != MODE_RAW {
670            return Err(self.file_exc(FileExc::Mode));
671        }
672        Ok(())
673    }
674
675    /// The character set object an argument names, or the default one.
676    fn file_charset_arg(&mut self, index: usize, argc: u32) -> VmResult<ObjId> {
677        if (index as u32) < argc {
678            let arg = self.arg(index);
679            match arg {
680                Value::Nil => {}
681                Value::Obj(id) if matches!(self.objects.get(id), Some(Object::CharSet { .. })) => {
682                    return Ok(id);
683                }
684                _ => match self.as_str(arg) {
685                    Some(name) => {
686                        let name = name.to_vec();
687                        return Ok(self.new_charset(&name));
688                    }
689                    None => return Err(VmError::new(code::BAD_TYPE_BIF)),
690                },
691            }
692        }
693        // Text outside the VM is UTF-8 unless the program says otherwise.
694        Ok(self.new_charset(b"utf8"))
695    }
696
697    /// Open a file: `File.openTextFile` and the rest.
698    fn file_open(&mut self, mode: u8, resource: bool, argc: u32) -> VmResult<Value> {
699        let access = if resource {
700            Access::Read
701        } else {
702            let code = self.cast_to_int(self.arg(1))?;
703            Access::from_code(code).ok_or_else(|| VmError::new(code::BAD_VAL_BIF))?
704        };
705        let target = if resource {
706            let name = self.require_str(self.arg(0))?;
707            FileTarget {
708                name: Some(String::from_utf8_lossy(&name).into_owned()),
709                special: false,
710                temporary: false,
711                from_ui: 0,
712                spec: Value::Nil,
713            }
714        } else {
715            let target = self.file_target(self.arg(0))?;
716            self.check_safety(&target, access)?;
717            target
718        };
719        let charset = if mode == MODE_TEXT {
720            self.file_charset_arg(if resource { 1 } else { 2 }, argc)?
721        } else {
722            ObjId::INVALID
723        };
724
725        self.sync_files();
726        let name = target.name.clone();
727        let data = if resource {
728            let found = name
729                .as_ref()
730                .and_then(|name| self.io.resources.get(name))
731                .cloned();
732            match found {
733                Some(data) => data.to_vec(),
734                None => match self.resource_file(name.as_deref()) {
735                    Some(data) => data,
736                    None => return Err(self.file_exc(FileExc::NotFound)),
737                },
738            }
739        } else {
740            let Some(name) = &name else {
741                // A special file the host has nowhere to keep.
742                return Err(self.file_exc(match access {
743                    Access::Read => FileExc::NotFound,
744                    Access::Write => FileExc::Creation,
745                    _ => FileExc::Open,
746                }));
747            };
748            match access {
749                Access::Read => match self.host.read_file(name) {
750                    Ok(data) => data,
751                    Err(_) => return Err(self.file_exc(FileExc::NotFound)),
752                },
753                Access::Write => match self.host.write_file(name, b"") {
754                    Ok(()) => Vec::new(),
755                    Err(_) => return Err(self.file_exc(FileExc::Creation)),
756                },
757                Access::ReadWriteKeep => match self.host.read_file(name) {
758                    Ok(data) => data,
759                    Err(FileError::NotFound) if self.host.write_file(name, b"").is_ok() => {
760                        Vec::new()
761                    }
762                    Err(_) => return Err(self.file_exc(FileExc::Open)),
763                },
764                _ => match self.host.write_file(name, b"") {
765                    Ok(()) => Vec::new(),
766                    Err(_) => return Err(self.file_exc(FileExc::Open)),
767                },
768            }
769        };
770        let file = FileObj {
771            charset,
772            mode,
773            access: access.code(),
774            out_of_sync: false,
775            spec: target.spec,
776            open: Some(OpenFile {
777                name: if resource { None } else { name },
778                data,
779                pos: 0,
780                dirty: false,
781            }),
782        };
783        let id = self.alloc_obj(Object::File(Box::new(file)));
784        self.objects.set_transient(id);
785        self.io.open_files.push(id);
786        Ok(Value::Obj(id))
787    }
788
789    /// Read a line of a text file, with its line ending as a newline, or
790    /// nil at the end of the file.
791    fn file_read_line(&mut self, id: ObjId) -> VmResult<Value> {
792        let charset = self.file(id).map_or(ObjId::INVALID, |file| file.charset);
793        let map = self.charset_map(charset)?;
794        let wide = matches!(*map, crate::charset::CharMap::Utf16 { .. });
795        let big_endian = matches!(*map, crate::charset::CharMap::Utf16 { big_endian: true });
796        let open = self.open_file(id)?;
797        let data = &open.data;
798        let start = open.pos.min(data.len());
799        let step = if wide { 2 } else { 1 };
800        if data.len() - start < step {
801            return Ok(Value::Nil);
802        }
803        // The character at a position, as far as line endings go.
804        let unit = |at: usize| -> Option<(u32, usize)> {
805            if wide {
806                let pair = data.get(at..at + 2)?;
807                let unit = if big_endian {
808                    u16::from_be_bytes([pair[0], pair[1]])
809                } else {
810                    u16::from_le_bytes([pair[0], pair[1]])
811                };
812                Some((unit.into(), 2))
813            } else if data.get(at..at + 3) == Some(&[0xe2, 0x80, 0xa8]) && !wide {
814                Some((0x2028, 3))
815            } else {
816                data.get(at).map(|&byte| (byte.into(), 1))
817            }
818        };
819        let line_separator_possible = matches!(*map, crate::charset::CharMap::Utf8) || wide;
820        let mut at = start;
821        let mut end = None;
822        while let Some((c, len)) = unit(at) {
823            let is_end =
824                c == 0x0a || c == 0x0d || (c == 0x2028 && (line_separator_possible || wide));
825            if is_end {
826                let mut next = at + len;
827                // A line feed and carriage return together, in either
828                // order, are one line ending.
829                let partner = match c {
830                    0x0a => Some(0x0d),
831                    0x0d => Some(0x0a),
832                    _ => None,
833                };
834                if let (Some(partner), Some((following, following_len))) = (partner, unit(next))
835                    && following == partner
836                {
837                    next += following_len;
838                }
839                end = Some((at, next));
840                break;
841            }
842            at += len;
843        }
844        let (line_end, next) = end.unwrap_or((at, at));
845        let mut text = map.decode(&data[start..line_end]);
846        if end.is_some() {
847            text.push('\n');
848        }
849        open.pos = next;
850        self.try_new_str(&text)
851    }
852
853    /// Read a value from a data file, or nil at the end of the file.
854    fn file_read_data(&mut self, id: ObjId) -> VmResult<Value> {
855        let open = self.open_file(id)?;
856        let Some(tag) = open.read_exact(1) else {
857            return Ok(Value::Nil);
858        };
859        let int = |bytes: Vec<u8>| u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
860        let value = match tag[0] {
861            TAG_INT => open
862                .read_exact(4)
863                .map(|bytes| Value::Int(int(bytes) as i32)),
864            TAG_ENUM => open.read_exact(4).map(|bytes| Value::Enum(int(bytes))),
865            TAG_TRUE => Some(Value::True),
866            TAG_STRING => {
867                let text = open
868                    .read_exact(2)
869                    .map(|len| usize::from(u16::from_le_bytes([len[0], len[1]])))
870                    .and_then(|len| len.checked_sub(2))
871                    .and_then(|len| open.read_exact(len));
872                text.map(|text| self.new_string(text))
873            }
874            TAG_BIGNUM => {
875                // The precision, then the number as it is stored, which
876                // starts with the precision again.
877                let number = open
878                    .read_exact(2)
879                    .map(|prec| usize::from(u16::from_le_bytes([prec[0], prec[1]])))
880                    .and_then(|prec| open.read_exact(5 + prec.div_ceil(2)))
881                    .and_then(|data| crate::decimal::Big::from_bytes(&data));
882                number.map(|number| self.new_big(number))
883            }
884            TAG_BYTEARRAY => {
885                let bytes = open
886                    .read_exact(4)
887                    .map(|len| int(len) as usize)
888                    .and_then(|len| open.read_exact(len));
889                bytes.map(|bytes| self.new_bytes(bytes))
890            }
891            _ => None,
892        };
893        match value {
894            Some(value) => Ok(value),
895            None => Err(self.file_exc(FileExc::Io)),
896        }
897    }
898
899    /// Write a value to a text file: its text, in the file's character
900    /// set, with each newline written as the system writes the end of a
901    /// line, as the reference does.
902    fn file_write_text(&mut self, id: ObjId, value: Value) -> VmResult<()> {
903        let charset = self.file(id).map_or(ObjId::INVALID, |file| file.charset);
904        let map = self.charset_map(charset)?;
905        let (_, text) = self.text_cast(value)?;
906        let text = String::from_utf8_lossy(&text);
907        let text = if NEWLINE == "\n" {
908            text
909        } else {
910            text.replace('\n', NEWLINE).into()
911        };
912        let bytes = map.encode(&text);
913        self.open_file(id)?.write(&bytes);
914        Ok(())
915    }
916
917    /// Write a value to a data file, marked with its type.
918    fn file_write_data(&mut self, id: ObjId, value: Value) -> VmResult<()> {
919        let mut out = Vec::new();
920        let string = |out: &mut Vec<u8>, text: &[u8]| {
921            out.push(TAG_STRING);
922            out.extend_from_slice(&((text.len() + 2) as u16).to_le_bytes());
923            out.extend_from_slice(text);
924        };
925        match value {
926            Value::Int(n) => {
927                out.push(TAG_INT);
928                out.extend_from_slice(&n.to_le_bytes());
929            }
930            Value::Enum(n) => {
931                out.push(TAG_ENUM);
932                out.extend_from_slice(&n.to_le_bytes());
933            }
934            Value::True => out.push(TAG_TRUE),
935            Value::SString(_) => {
936                let text = self.require_str(value)?;
937                string(&mut out, &text);
938            }
939            Value::Obj(object) => match self.objects.get(object) {
940                Some(Object::Decimal(big)) => {
941                    out.push(TAG_BIGNUM);
942                    out.extend_from_slice(&(big.prec() as u16).to_le_bytes());
943                    out.extend_from_slice(&big.to_bytes());
944                }
945                Some(Object::ByteArray(bytes)) => {
946                    out.push(TAG_BYTEARRAY);
947                    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
948                    out.extend_from_slice(bytes);
949                }
950                _ => {
951                    let (_, text) = self.text_cast(value)?;
952                    string(&mut out, &text);
953                }
954            },
955            _ => return Err(VmError::new(code::BAD_TYPE_BIF)),
956        }
957        self.open_file(id)?.write(&out);
958        Ok(())
959    }
960
961    /// The optional length argument of the hash methods: nil or nothing
962    /// is the size of the file.
963    fn file_hash_input(&mut self, id: ObjId, argc: u32) -> VmResult<Vec<u8>> {
964        self.check_raw(id, false)?;
965        let len = if argc >= 1 && self.arg(0) != Value::Nil {
966            Some(self.cast_to_int(self.arg(0))?.max(0) as usize)
967        } else {
968            None
969        };
970        let open = self.open_file(id)?;
971        let len = len.unwrap_or(open.data.len());
972        Ok(open.read(len).to_vec())
973    }
974
975    /// Call a method of File on a file object, or with no object on the
976    /// class itself.
977    pub(crate) fn file_method(
978        &mut self,
979        id: Option<ObjId>,
980        index: u16,
981        argc: Option<&mut u32>,
982    ) -> VmResult<Option<Value>> {
983        let Some(&desc) = FILE_METHODS.get(index as usize).filter(|_| index != 0) else {
984            return Ok(None);
985        };
986        // Only the methods that make or name a file work on the class.
987        let class_method = matches!(index, 1 | 2 | 3 | 14 | 15 | 18 | 19);
988        if id.is_none() && !class_method {
989            return Ok(None);
990        }
991        self.native_method(argc, desc, |vm, argc| match id {
992            Some(id) if !class_method => vm.file_call(id, index, argc),
993            _ => vm.file_class_call(index, argc),
994        })
995        .map(Some)
996    }
997
998    fn file_class_call(&mut self, index: u16, argc: u32) -> VmResult<Value> {
999        match index {
1000            1 => self.file_open(MODE_TEXT, false, argc),
1001            2 => self.file_open(MODE_DATA, false, argc),
1002            3 => self.file_open(MODE_RAW, false, argc),
1003            14 => self.file_open(MODE_TEXT, true, argc),
1004            15 => self.file_open(MODE_RAW, true, argc),
1005            // getRootName(name)
1006            18 => {
1007                let name = self
1008                    .path_of(self.arg(0))
1009                    .ok_or_else(|| VmError::new(code::BAD_TYPE_BIF))?;
1010                Ok(self.try_new_str(root_name(&name))?)
1011            }
1012            // deleteFile(name)
1013            _ => {
1014                let target = self.file_target(self.arg(0))?;
1015                self.check_safety(&target, Access::Delete)?;
1016                self.delete_target(&target)?;
1017                Ok(Value::Nil)
1018            }
1019        }
1020    }
1021
1022    fn delete_target(&mut self, target: &FileTarget) -> VmResult<()> {
1023        self.sync_files();
1024        let deleted = match &target.name {
1025            Some(name) => self.host.delete_file(name).is_ok(),
1026            None => false,
1027        };
1028        if deleted {
1029            Ok(())
1030        } else {
1031            Err(VmError::new(code::DELETE_FILE))
1032        }
1033    }
1034
1035    fn file_call(&mut self, id: ObjId, index: u16, argc: u32) -> VmResult<Value> {
1036        let (access, mode) = self.check_valid_file(id)?;
1037        let read_only = access == Access::Read.code();
1038        let write_only = access == Access::Write.code();
1039        Ok(match index {
1040            // getCharacterSet()
1041            4 => match self.file(id).map(|file| file.charset) {
1042                Some(charset) if charset.is_valid() => Value::Obj(charset),
1043                _ => Value::Nil,
1044            },
1045            // setCharacterSet(charset)
1046            5 => {
1047                let charset = self.file_charset_arg(0, 1)?;
1048                if let Some(Object::File(file)) = self.objects.get_mut(id) {
1049                    file.charset = charset;
1050                }
1051                Value::Nil
1052            }
1053            // closeFile()
1054            6 => {
1055                let (open, spec) = match self.objects.get_mut(id) {
1056                    Some(Object::File(file)) => (file.open.take(), file.spec),
1057                    _ => (None, Value::Nil),
1058                };
1059                self.io.open_files.retain(|&open_id| open_id != id);
1060                if let Some(OpenFile {
1061                    name: Some(name),
1062                    data,
1063                    dirty: true,
1064                    ..
1065                }) = open
1066                    && self.host.write_file(&name, &data).is_err()
1067                {
1068                    return Err(self.file_exc(FileExc::Io));
1069                }
1070                // An object of the program's that stood for the file gets
1071                // to know that the file is finished with.
1072                if let Value::Obj(spec_id) = spec {
1073                    let close_file = self.predef.filespec_close_file;
1074                    if close_file != INVALID_PROP
1075                        && matches!(self.objects.get(spec_id), Some(Object::Program(_)))
1076                    {
1077                        let native = NativeCall::named("System.closeFile");
1078                        self.call_prop(spec, close_file, 0, Some(native))?;
1079                    }
1080                }
1081                Value::Nil
1082            }
1083            // readFile()
1084            7 => {
1085                if write_only || mode == MODE_RAW {
1086                    return Err(self.file_exc(FileExc::Mode));
1087                }
1088                if mode == MODE_TEXT {
1089                    self.file_read_line(id)?
1090                } else {
1091                    self.file_read_data(id)?
1092                }
1093            }
1094            // writeFile(val)
1095            8 => {
1096                if read_only || mode == MODE_RAW {
1097                    return Err(self.file_exc(FileExc::Mode));
1098                }
1099                if mode == MODE_TEXT {
1100                    self.file_write_text(id, self.arg(0))?;
1101                } else {
1102                    self.file_write_data(id, self.arg(0))?;
1103                }
1104                Value::Nil
1105            }
1106            // readBytes(byteArr, start?, cnt?): how many bytes were read.
1107            9 => {
1108                if write_only || mode != MODE_RAW {
1109                    return Err(self.file_exc(FileExc::Mode));
1110                }
1111                let array = self.arg(0);
1112                let Some(count) = self.as_bytes(array).map(Vec::len) else {
1113                    return Err(VmError::new(code::BAD_TYPE_BIF));
1114                };
1115                let index = if argc >= 2 {
1116                    self.int_arg(self.arg(1))?
1117                } else {
1118                    1
1119                };
1120                let len = if argc >= 3 {
1121                    self.int_arg(self.arg(2))? as u32 as usize
1122                } else {
1123                    count
1124                };
1125                if index < 1 {
1126                    return Err(VmError::new(code::INDEX_OUT_OF_RANGE));
1127                }
1128                let index = index as usize;
1129                if index > count || len == 0 {
1130                    return Ok(Value::Int(0));
1131                }
1132                let len = len.min(count - index + 1);
1133                let bytes = self.open_file(id)?.read(len).to_vec();
1134                let target = self.bytes_mut(array.obj_id())?;
1135                target[index - 1..index - 1 + bytes.len()].copy_from_slice(&bytes);
1136                Value::Int(bytes.len() as i32)
1137            }
1138            // writeBytes(source, start?, cnt?)
1139            10 => {
1140                if read_only || mode != MODE_RAW {
1141                    return Err(self.file_exc(FileExc::Mode));
1142                }
1143                self.file_write_bytes(id, argc)?;
1144                Value::Nil
1145            }
1146            // getPos()
1147            11 => Value::Int(self.open_file(id)?.pos as i32),
1148            // setPos(pos)
1149            12 => {
1150                let pos = self.cast_to_int(self.arg(0))?;
1151                self.open_file(id)?.pos = pos.max(0) as usize;
1152                Value::Nil
1153            }
1154            // setPosEnd()
1155            13 => {
1156                let open = self.open_file(id)?;
1157                open.pos = open.data.len();
1158                Value::Nil
1159            }
1160            // getFileSize()
1161            16 => Value::Int(self.open_file(id)?.data.len() as i32),
1162            // getFileMode()
1163            17 => Value::Int(mode.into()),
1164            // setFileMode(mode, charset?)
1165            20 => {
1166                let new_mode = self.int_arg(self.arg(0))?;
1167                let charset = match new_mode {
1168                    1 => self.file_charset_arg(1, argc)?,
1169                    2 | 3 => ObjId::INVALID,
1170                    _ => return Err(VmError::new(code::BAD_VAL_BIF)),
1171                };
1172                if let Some(Object::File(file)) = self.objects.get_mut(id) {
1173                    file.mode = new_mode as u8;
1174                    file.charset = charset;
1175                }
1176                Value::Nil
1177            }
1178            // packBytes(format, ...): how many bytes were written.
1179            21 => {
1180                self.check_raw(id, true)?;
1181                let open = self.open_file(id)?;
1182                if open.pos > open.data.len() {
1183                    let pos = open.pos;
1184                    open.data.resize(pos, 0);
1185                }
1186                let start = open.pos;
1187                let stream = Stream::growing(std::mem::take(&mut open.data), start);
1188                let (stream, result) = self.pack_stream(0, argc as usize, stream);
1189                let open = self.open_file(id)?;
1190                open.pos = stream.pos;
1191                open.data = stream.data;
1192                open.dirty = true;
1193                result?;
1194                Value::Int((self.open_file(id)?.pos - start) as i32)
1195            }
1196            // unpackBytes(format)
1197            22 => {
1198                self.check_raw(id, false)?;
1199                let format = self.arg(0);
1200                if self.as_str(format).is_none() {
1201                    return Err(VmError::new(code::BAD_TYPE_BIF));
1202                }
1203                let open = self.open_file(id)?;
1204                let stream = Stream::fixed(std::mem::take(&mut open.data), open.pos);
1205                let (stream, result) = self.unpack_stream(format, stream);
1206                let open = self.open_file(id)?;
1207                open.pos = open.pos.max(stream.pos);
1208                open.data = stream.data;
1209                result?
1210            }
1211            // sha256(length?)
1212            23 => {
1213                let input = self.file_hash_input(id, argc)?;
1214                self.try_new_str(&hash::hex(&hash::sha256(&input)))?
1215            }
1216            // digestMD5(length?)
1217            24 => {
1218                let input = self.file_hash_input(id, argc)?;
1219                self.try_new_str(&hash::hex(&hash::md5(&input)))?
1220            }
1221            _ => Value::Nil,
1222        })
1223    }
1224
1225    /// `writeBytes(source, start?, cnt?)`: write from a byte array, or
1226    /// copy from another file.
1227    fn file_write_bytes(&mut self, id: ObjId, argc: u32) -> VmResult<()> {
1228        let source = self.arg(0);
1229        let Value::Obj(source_id) = source else {
1230            return Err(VmError::new(code::OBJ_VAL_REQD));
1231        };
1232        let optional = |vm: &Self, index: usize| -> VmResult<Option<i32>> {
1233            if (index as u32) < argc && vm.arg(index) != Value::Nil {
1234                vm.int_arg(vm.arg(index)).map(Some)
1235            } else {
1236                Ok(None)
1237            }
1238        };
1239        if let Some(count) = self.as_bytes(source).map(Vec::len) {
1240            let index = optional(self, 1)?.unwrap_or(1);
1241            let len = optional(self, 2)?.map_or(count, |len| len as u32 as usize);
1242            if index < 1 {
1243                return Err(VmError::new(code::INDEX_OUT_OF_RANGE));
1244            }
1245            let index = index as usize;
1246            if index > count {
1247                return Ok(());
1248            }
1249            let len = len.min(count - index + 1);
1250            let bytes = self
1251                .as_bytes(source)
1252                .map_or_else(Vec::new, |bytes| bytes[index - 1..index - 1 + len].to_vec());
1253            self.open_file(id)?.write(&bytes);
1254            return Ok(());
1255        }
1256        let Some(other) = self.file(source_id) else {
1257            return Err(VmError::new(code::BAD_TYPE_BIF));
1258        };
1259        let usable = !other.out_of_sync && other.open.is_some();
1260        if other.mode != MODE_RAW {
1261            return Err(self.file_exc(FileExc::Mode));
1262        }
1263        let start = optional(self, 1)?;
1264        let len = optional(self, 2)?;
1265        if !usable {
1266            // The reference VM takes the size of an unusable file to be
1267            // -1, a very large count, and then fails to read from it.
1268            return Err(self.file_exc(FileExc::Io));
1269        }
1270        let other = self.open_file(source_id)?;
1271        if let Some(start) = start {
1272            other.pos = start.max(0) as usize;
1273        }
1274        let len = len.map_or(other.data.len(), |len| len as u32 as usize);
1275        let bytes = other.read(len).to_vec();
1276        // A file copied onto itself has moved on by what was read.
1277        self.open_file(id)?.write(&bytes);
1278        Ok(())
1279    }
1280
1281    // ---- FileName ----
1282
1283    /// `new FileName(...)`.
1284    pub(crate) fn create_file_name(&mut self, argc: u32) -> VmResult<ObjId> {
1285        match argc {
1286            0 => Ok(self.new_file_name(".")),
1287            1 => {
1288                let arg = self.arg(0);
1289                if let Some(text) = self.as_str(arg) {
1290                    let path = String::from_utf8_lossy(&text).into_owned();
1291                    return Ok(self.new_file_name(&path));
1292                }
1293                if matches!(arg, Value::Int(_)) || self.as_big(arg).is_some() {
1294                    let special = self.cast_to_int(arg)?;
1295                    let path = self.special_file_path(special)?.unwrap_or_default();
1296                    return Ok(self.alloc_obj(Object::FileName(Box::new(FileNameObj {
1297                        path,
1298                        special,
1299                        from_ui: 0,
1300                    }))));
1301                }
1302                Err(VmError::new(code::BAD_TYPE_BIF))
1303            }
1304            2 => match (self.path_of(self.arg(0)), self.path_of(self.arg(1))) {
1305                (Some(dir), Some(name)) => Ok(self.new_file_name(&combine(&dir, &name, false))),
1306                _ => Err(VmError::new(code::BAD_TYPE_BIF)),
1307            },
1308            _ => Err(VmError::new(code::WRONG_NUM_OF_ARGS)),
1309        }
1310    }
1311
1312    /// A file name with another name added to it, for `+`.
1313    pub(crate) fn file_name_add(&mut self, id: ObjId, other: Value) -> VmResult<Value> {
1314        let Some(name) = self.path_of(other) else {
1315            return Err(VmError::new(code::BAD_TYPE_ADD));
1316        };
1317        let dir = self
1318            .file_name(id)
1319            .map_or_else(String::new, |n| n.path.clone());
1320        Ok(Value::Obj(self.new_file_name(&combine(&dir, &name, false))))
1321    }
1322
1323    /// Whether a file name is the same name as another, or as a string.
1324    pub(crate) fn file_name_equals(&self, id: ObjId, other: Value) -> bool {
1325        match (self.file_name(id), self.path_of(other)) {
1326            (Some(name), Some(other)) => name.path == other,
1327            _ => false,
1328        }
1329    }
1330
1331    /// Call a method of FileName on a file name, or with no object on the
1332    /// class itself.
1333    pub(crate) fn file_name_method(
1334        &mut self,
1335        id: Option<ObjId>,
1336        index: u16,
1337        argc: Option<&mut u32>,
1338    ) -> VmResult<Option<Value>> {
1339        let Some(&desc) = FILE_NAME_METHODS.get(index as usize).filter(|_| index != 0) else {
1340            return Ok(None);
1341        };
1342        let class_method = matches!(index, 4 | 9);
1343        match id {
1344            None if !class_method => return Ok(None),
1345            _ => {}
1346        }
1347        self.native_method(argc, desc, |vm, argc| match (id, class_method) {
1348            (Some(id), false) => vm.file_name_call(id, index, argc),
1349            _ => vm.file_name_class_call(index),
1350        })
1351        .map(Some)
1352    }
1353
1354    fn file_name_class_call(&mut self, index: u16) -> VmResult<Value> {
1355        if index == 4 {
1356            // fromUniversal(path)
1357            let Some(text) = self.as_str(self.arg(0)) else {
1358                return Err(VmError::new(code::BAD_VAL_BIF));
1359            };
1360            let path = String::from_utf8_lossy(&text).into_owned();
1361            return Ok(Value::Obj(self.new_file_name(&path)));
1362        }
1363        // getRootDirs(): the ones the program is allowed to look at.
1364        let mut roots = Vec::new();
1365        for root in self.host.root_dirs() {
1366            if self.safety_allows(&root, Access::GetInfo) {
1367                roots.push(root);
1368            }
1369        }
1370        let list = self.new_list(vec![Value::Nil; roots.len()]);
1371        let names: Vec<Value> = roots
1372            .iter()
1373            .map(|root| Value::Obj(self.new_file_name(root)))
1374            .collect();
1375        self.fill_list(list, names);
1376        Ok(list)
1377    }
1378
1379    /// Put the elements into a list created ahead of them, as the
1380    /// reference VM creates it.
1381    fn fill_list(&mut self, list: Value, items: Vec<Value>) {
1382        if let Some(Object::List(stored)) = self.objects.get_mut(list.obj_id()) {
1383            *stored = items.into();
1384        }
1385    }
1386
1387    /// The file a FileName refers to, checked against the safety levels.
1388    fn file_name_target(&mut self, id: ObjId, access: Access) -> VmResult<FileTarget> {
1389        let target = self.file_target(Value::Obj(id))?;
1390        self.check_safety(&target, access)?;
1391        Ok(target)
1392    }
1393
1394    fn logical_arg(&self, index: usize, argc: u32) -> VmResult<bool> {
1395        if (index as u32) >= argc {
1396            return Ok(false);
1397        }
1398        match self.arg(index) {
1399            Value::True => Ok(true),
1400            Value::Nil => Ok(false),
1401            _ => Err(VmError::new(code::BAD_TYPE_BIF)),
1402        }
1403    }
1404
1405    fn file_name_call(&mut self, id: ObjId, index: u16, argc: u32) -> VmResult<Value> {
1406        let Some(name) = self.file_name(id) else {
1407            return Ok(Value::Nil);
1408        };
1409        let path = name.path.clone();
1410        Ok(match index {
1411            // getName()
1412            1 => self.try_new_str(&path)?,
1413            // getBaseName()
1414            2 => match root_name(&path) {
1415                "" => Value::Nil,
1416                root => self.try_new_str(root)?,
1417            },
1418            // getPath()
1419            3 => match path_name(&path) {
1420                "" => Value::Nil,
1421                dir => Value::Obj(self.new_file_name(dir)),
1422            },
1423            // toUniversal()
1424            5 => self.try_new_str(&path)?,
1425            // addToPath(name)
1426            6 => {
1427                let Some(name) = self.path_of(self.arg(0)) else {
1428                    return Err(VmError::new(code::BAD_TYPE_BIF));
1429                };
1430                Value::Obj(self.new_file_name(&combine(&path, &name, false)))
1431            }
1432            // isAbsolute()
1433            7 => Value::logical(is_absolute(&path)),
1434            // getAbsolutePath()
1435            8 => match self.host.absolute_path(&path) {
1436                Some(full) => self.try_new_str(&full)?,
1437                None => Value::Nil,
1438            },
1439            // getFileType()
1440            10 => {
1441                let target = self.file_name_target(id, Access::GetInfo)?;
1442                self.sync_files();
1443                let info = target
1444                    .name
1445                    .and_then(|name| self.host.file_info(&name, true));
1446                match info {
1447                    Some(info) => Value::Int(info.kind as i32 | special_link_flags(&path)),
1448                    None => Value::Nil,
1449                }
1450            }
1451            // getFileInfo()
1452            11 => {
1453                let target = self.file_name_target(id, Access::GetInfo)?;
1454                self.sync_files();
1455                let Some(info) = target
1456                    .name
1457                    .and_then(|name| self.host.file_info(&name, true))
1458                else {
1459                    return Ok(Value::Nil);
1460                };
1461                let target = match &info.link_target {
1462                    Some(target) if info.kind & file_type::LINK != 0 => self.try_new_str(target)?,
1463                    _ => Value::Nil,
1464                };
1465                let size = match i32::try_from(info.size) {
1466                    Ok(size) => Value::Int(size),
1467                    Err(_) => {
1468                        let size = crate::decimal::Big::from_u64(info.size, 20);
1469                        self.new_big(size)
1470                    }
1471                };
1472                let kind = Value::Int(info.kind as i32 | special_link_flags(&path));
1473                // The arguments of the FileInfo constructor, first one
1474                // first. The reference VM creates them last one first.
1475                let mut time = |seconds: Option<i64>| match seconds {
1476                    Some(seconds) if seconds != 0 => self.date_from_unix(seconds),
1477                    _ => Value::Nil,
1478                };
1479                let accessed = time(info.accessed);
1480                let modified = time(info.modified);
1481                let created = time(info.created);
1482                let args = [
1483                    kind,
1484                    size,
1485                    created,
1486                    modified,
1487                    accessed,
1488                    target,
1489                    Value::Int(info.attrs as i32),
1490                ];
1491                let class = self.predef.file_info;
1492                if class.is_valid() {
1493                    self.check_stack(args.len())?;
1494                    for &arg in args.iter().rev() {
1495                        self.push(arg);
1496                    }
1497                    self.create_instance(class, args.len() as u32)?;
1498                    match self.r0 {
1499                        Value::Obj(_) => self.r0,
1500                        _ => return Err(VmError::new(code::OBJ_VAL_REQD)),
1501                    }
1502                } else {
1503                    self.new_list(args.to_vec())
1504                }
1505            }
1506            // deleteFile()
1507            12 => {
1508                let target = self.file_name_target(id, Access::Delete)?;
1509                self.delete_target(&target)?;
1510                Value::Nil
1511            }
1512            // renameFile(newName)
1513            13 => {
1514                let from = self.file_name_target(id, Access::RenameFrom)?;
1515                let to = self.file_target(self.arg(0))?;
1516                self.check_safety(&to, Access::RenameTo)?;
1517                self.sync_files();
1518                let renamed = match (&from.name, &to.name) {
1519                    (Some(from), Some(to)) => {
1520                        self.host.file_info(to, true).is_none()
1521                            && self.host.rename_file(from, to).is_ok()
1522                    }
1523                    _ => false,
1524                };
1525                if !renamed {
1526                    return Err(VmError::new(code::RENAME_FILE));
1527                }
1528                // An open file goes on being written under its new name.
1529                self.note_renamed(from.name.as_deref(), to.name.as_deref());
1530                Value::Nil
1531            }
1532            // listDir()
1533            14 => {
1534                let target = self.file_name_target(id, Access::ReadDir)?;
1535                self.sync_files();
1536                let entries = target.name.and_then(|name| self.host.list_dir(&name));
1537                let Some(entries) = entries else {
1538                    return Err(self.file_exc(FileExc::OpenDir));
1539                };
1540                let list = self.new_list(vec![Value::Nil; entries.len()]);
1541                let names: Vec<Value> = entries
1542                    .iter()
1543                    .map(|entry| Value::Obj(self.new_file_name(&combine(&path, entry, true))))
1544                    .collect();
1545                self.fill_list(list, names);
1546                list
1547            }
1548            // forEachFile(func, recursive?)
1549            15 => {
1550                let target = self.file_name_target(id, Access::ReadDir)?;
1551                let recursive = self.logical_arg(1, argc)?;
1552                let callback = self.arg(0);
1553                self.sync_files();
1554                let listed = match &target.name {
1555                    Some(name) => self.for_each_file(name, &path, callback, recursive)?,
1556                    None => false,
1557                };
1558                if !listed {
1559                    return Err(self.file_exc(FileExc::OpenDir));
1560                }
1561                Value::Nil
1562            }
1563            // createDirectory(createParents?)
1564            16 => {
1565                let target = self.file_name_target(id, Access::MakeDir)?;
1566                let parents = self.logical_arg(0, argc)?;
1567                let created = target
1568                    .name
1569                    .is_some_and(|name| self.host.create_dir(&name, parents).is_ok());
1570                if !created {
1571                    return Err(VmError::new(code::CREATE_FILE));
1572                }
1573                Value::Nil
1574            }
1575            // removeDirectory(removeContents?)
1576            17 => {
1577                let target = self.file_name_target(id, Access::RemoveDir)?;
1578                let contents = self.logical_arg(0, argc)?;
1579                self.sync_files();
1580                let removed = target
1581                    .name
1582                    .is_some_and(|name| self.host.remove_dir(&name, contents).is_ok());
1583                if !removed {
1584                    return Err(VmError::new(code::DELETE_FILE));
1585                }
1586                Value::Nil
1587            }
1588            _ => Value::Nil,
1589        })
1590    }
1591
1592    /// Change the name an open file will be written back under.
1593    fn note_renamed(&mut self, from: Option<&str>, to: Option<&str>) {
1594        let (Some(from), Some(to)) = (from, to) else {
1595            return;
1596        };
1597        for id in self.io.open_files.clone() {
1598            if let Some(Object::File(file)) = self.objects.get_mut(id)
1599                && let Some(open) = &mut file.open
1600                && open.name.as_deref() == Some(from)
1601            {
1602                open.name = Some(to.to_owned());
1603            }
1604        }
1605    }
1606
1607    /// Call a function with the FileName of each entry of a directory.
1608    /// `name` is the directory for the host, and `shown` the same
1609    /// directory as the program named it. False if it cannot be listed.
1610    fn for_each_file(
1611        &mut self,
1612        name: &str,
1613        shown: &str,
1614        callback: Value,
1615        recursive: bool,
1616    ) -> VmResult<bool> {
1617        let Some(entries) = self.host.list_dir(name) else {
1618            return Ok(false);
1619        };
1620        for entry in entries {
1621            let entry_shown = combine(shown, &entry, true);
1622            let file_name = Value::Obj(self.new_file_name(&entry_shown));
1623            // Keep the name alive while the function runs.
1624            self.push(file_name);
1625            let native = NativeCall::named("FileName.forEachFile");
1626            let result = self.call_value(callback, &[file_name], native);
1627            self.pop();
1628            result?;
1629            if recursive && entry != "." && entry != ".." {
1630                let entry_name = combine(name, &entry, true);
1631                let is_dir = self
1632                    .host
1633                    .file_info(&entry_name, false)
1634                    .is_some_and(|info| info.kind & file_type::DIR != 0);
1635                if is_dir {
1636                    self.for_each_file(&entry_name, &entry_shown, callback, true)?;
1637                }
1638            }
1639        }
1640        Ok(true)
1641    }
1642
1643    // ---- TemporaryFile ----
1644
1645    /// `new TemporaryFile()`.
1646    pub(crate) fn create_temp_file(&mut self, argc: u32) -> VmResult<ObjId> {
1647        if argc != 0 {
1648            return Err(VmError::new(code::WRONG_NUM_OF_ARGS));
1649        }
1650        let Some(name) = self.host.temp_file_name() else {
1651            return Err(VmError::new(code::CREATE_FILE));
1652        };
1653        let id = self.alloc_obj(Object::TempFile(name));
1654        self.objects.set_transient(id);
1655        Ok(id)
1656    }
1657
1658    pub(crate) fn temp_file_method(
1659        &mut self,
1660        id: ObjId,
1661        index: u16,
1662        argc: Option<&mut u32>,
1663    ) -> VmResult<Option<Value>> {
1664        if !matches!(index, 1 | 2) {
1665            return Ok(None);
1666        }
1667        self.native_method(argc, NativeDesc::fixed(0), |vm, _| {
1668            let name = match vm.objects.get(id) {
1669                Some(Object::TempFile(name)) => name.clone(),
1670                _ => String::new(),
1671            };
1672            if name.is_empty() {
1673                return Ok(Value::Nil);
1674            }
1675            Ok(if index == 1 {
1676                // getFilename()
1677                vm.try_new_str(&name)?
1678            } else {
1679                // deleteFile(). The object goes on naming the file.
1680                vm.sync_files();
1681                let _ = vm.host.delete_file(&name);
1682                Value::Nil
1683            })
1684        })
1685        .map(Some)
1686    }
1687}
1688
1689/// A file's contents as the host has them, for the functions that work
1690/// on whole files.
1691pub(crate) type Resources = std::collections::HashMap<String, Rc<[u8]>>;