ratasm 0.3.0

A terminal IDE and debugger for x86_64 assembly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! The set of open documents and the file operations on them.

use std::io::Write;
use std::path::{Path, PathBuf};

use super::document::Document;

/// Errors from opening and saving files.
#[derive(Debug, thiserror::Error)]
pub enum FileError {
    /// The file could not be read.
    #[error("cannot read {path}: {source}")]
    Read {
        /// The file that could not be read.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// The file could not be written.
    #[error("cannot write {path}: {source}")]
    Write {
        /// The file that could not be written.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        source: std::io::Error,
    },
    /// The file is not valid UTF-8.
    #[error("{path} is not valid UTF-8 text")]
    NotUtf8 {
        /// The offending file.
        path: PathBuf,
    },
    /// A save was requested for a document that has no path yet.
    #[error("this buffer has no file name; use 'save as'")]
    NoPath,
    /// The requested document index does not exist.
    #[error("no document at index {index}")]
    NoSuchDocument {
        /// The index that was out of range.
        index: usize,
    },
}

/// Reads a file as UTF-8 text, refusing rather than lossy-decoding it.
pub fn read_file(path: &Path) -> Result<String, FileError> {
    let bytes = std::fs::read(path).map_err(|source| FileError::Read {
        path: path.to_path_buf(),
        source,
    })?;
    String::from_utf8(bytes).map_err(|_| FileError::NotUtf8 {
        path: path.to_path_buf(),
    })
}

/// Writes `contents` to `path` atomically.
pub fn write_file_atomically(path: &Path, contents: &str) -> Result<(), FileError> {
    let directory = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty());
    let directory = match directory {
        Some(directory) => directory.to_path_buf(),
        None => PathBuf::from("."),
    };

    std::fs::create_dir_all(&directory).map_err(|source| FileError::Write {
        path: path.to_path_buf(),
        source,
    })?;

    let mut temporary =
        tempfile::NamedTempFile::new_in(&directory).map_err(|source| FileError::Write {
            path: path.to_path_buf(),
            source,
        })?;

    temporary
        .write_all(contents.as_bytes())
        .and_then(|()| temporary.flush())
        .map_err(|source| FileError::Write {
            path: path.to_path_buf(),
            source,
        })?;

    temporary.persist(path).map_err(|error| FileError::Write {
        path: path.to_path_buf(),
        source: error.error,
    })?;

    Ok(())
}

/// Renders a path for a message, preferring the file name when it is long.
pub fn display_path(path: &Path) -> String {
    let path = path.strip_prefix(".").unwrap_or(path);
    let full = path.display().to_string();
    if full.chars().count() <= 60 {
        return full;
    }
    path.file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or(full)
}

/// Completes `text` as a filesystem path.
pub fn complete_path(text: &str) -> (String, Vec<String>) {
    let (directory, prefix) = match text.rfind('/') {
        Some(index) => (&text[..=index], &text[index + 1..]),
        None => ("", text),
    };
    let search = if directory.is_empty() {
        Path::new(".")
    } else {
        Path::new(directory)
    };

    let Ok(entries) = std::fs::read_dir(search) else {
        return (text.to_owned(), Vec::new());
    };

    let mut candidates: Vec<String> = entries
        .flatten()
        .filter_map(|entry| {
            let name = entry.file_name().to_string_lossy().into_owned();
            if !name.starts_with(prefix) || (name.starts_with('.') && !prefix.starts_with('.')) {
                return None;
            }
            let directory = entry.path().is_dir();
            Some(if directory { format!("{name}/") } else { name })
        })
        .collect();
    candidates.sort();

    let Some(first) = candidates.first() else {
        return (text.to_owned(), candidates);
    };

    let shared = candidates
        .iter()
        .skip(1)
        .fold(first.clone(), |shared, next| {
            let keep = shared
                .chars()
                .zip(next.chars())
                .take_while(|(a, b)| a == b)
                .count();
            shared.chars().take(keep).collect()
        });

    (format!("{directory}{shared}"), candidates)
}

/// Whether an open document's path is the file a tool named.
pub fn same_file(open: &Path, reported: &Path) -> bool {
    if open == reported {
        return true;
    }
    let open: Vec<_> = open.components().collect();
    let reported: Vec<_> = reported.components().collect();
    if reported.is_empty() || reported.len() > open.len() {
        return false;
    }
    open[open.len() - reported.len()..] == reported[..]
}

/// Whether `a` and `b` name the same file on disk, however each is spelled.
pub fn same_target(a: &Path, b: &Path) -> bool {
    a == b
        || matches!(
            (std::fs::canonicalize(a), std::fs::canonicalize(b)),
            (Ok(a), Ok(b)) if a == b
        )
}

/// The open documents and which one is active; always holds at least one.
#[derive(Debug)]
pub struct Workspace {
    documents: Vec<Document>,
    active: usize,
    recent_files: Vec<PathBuf>,
    stamps: std::collections::HashMap<PathBuf, Stamp>,
}

type Stamp = (std::time::SystemTime, u64);

fn stamp(path: &Path) -> Option<Stamp> {
    let meta = std::fs::metadata(path).ok()?;
    Some((meta.modified().ok()?, meta.len()))
}

/// A file that changed on disk behind the editor's back.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiskChange {
    /// It had no unsaved changes, so the new text was loaded.
    Reloaded(PathBuf),
    /// It has unsaved changes, so the buffer was kept.
    Conflict(PathBuf),
    /// It no longer exists.
    Deleted(PathBuf),
}

impl Workspace {
    /// Maximum number of recently opened files remembered.
    pub const MAX_RECENT: usize = 16;

    /// Creates a workspace holding one empty, untitled document.
    pub fn new() -> Self {
        Self {
            documents: vec![Document::new()],
            active: 0,
            recent_files: Vec::new(),
            stamps: std::collections::HashMap::new(),
        }
    }

    /// All open documents, in tab order.
    pub fn documents(&self) -> &[Document] {
        &self.documents
    }

    /// The number of open documents, always at least one.
    pub fn len(&self) -> usize {
        self.documents.len()
    }

    /// Always `false`; a workspace always holds a document.
    pub fn is_empty(&self) -> bool {
        false
    }

    /// The index of the active document.
    pub fn active_index(&self) -> usize {
        self.active
    }

    /// The active document.
    pub fn active(&self) -> &Document {
        self.documents
            .get(self.active)
            .unwrap_or(&self.documents[0])
    }

    /// The active document, mutably.
    pub fn active_mut(&mut self) -> &mut Document {
        let index = self.active.min(self.documents.len() - 1);
        self.active = index;
        &mut self.documents[index]
    }

    /// Selects a document by index, ignoring out-of-range values.
    pub fn set_active(&mut self, index: usize) {
        if index < self.documents.len() {
            self.active = index;
        }
    }

    /// Activates the next document, wrapping around.
    pub fn next_document(&mut self) {
        self.active = (self.active + 1) % self.documents.len();
    }

    /// Activates the previous document, wrapping around.
    pub fn previous_document(&mut self) {
        self.active = (self.active + self.documents.len() - 1) % self.documents.len();
    }

    /// Recently opened files, most recent first.
    pub fn recent_files(&self) -> &[PathBuf] {
        &self.recent_files
    }

    /// Records a path in the recent list, moving it to the front if present.
    fn remember(&mut self, path: &Path) {
        self.recent_files.retain(|existing| existing != path);
        self.recent_files.insert(0, path.to_path_buf());
        self.recent_files.truncate(Self::MAX_RECENT);
    }

    /// Opens `path`, activating it; a file already open is activated, not reopened.
    pub fn open(&mut self, path: &Path) -> Result<usize, FileError> {
        if let Some(index) = self
            .documents
            .iter()
            .position(|document| document.path().is_some_and(|open| same_target(open, path)))
        {
            self.active = index;
            self.remember(path);
            return Ok(index);
        }

        let contents = read_file(path)?;
        let document = Document::from_file_contents(path, &contents);
        self.record(path);

        let index = if self.documents.len() == 1
            && self.documents[0].path().is_none()
            && !self.documents[0].is_modified()
            && self.documents[0].buffer().is_empty()
        {
            self.documents[0] = document;
            0
        } else {
            self.documents.push(document);
            self.documents.len() - 1
        };

        self.active = index;
        self.remember(path);
        Ok(index)
    }

    fn record(&mut self, path: &Path) {
        if let Some(stamp) = stamp(path) {
            self.stamps.insert(path.to_path_buf(), stamp);
        }
    }

    /// Finds open files that changed on disk, reloading those without
    /// unsaved changes. Each change is reported once.
    pub fn check_disk(&mut self) -> Vec<DiskChange> {
        let mut changes = Vec::new();
        for document in &mut self.documents {
            let Some(path) = document.path().map(Path::to_path_buf) else {
                continue;
            };
            let Some(known) = self.stamps.get(&path).copied() else {
                continue;
            };
            let Some(now) = stamp(&path) else {
                self.stamps.remove(&path);
                changes.push(DiskChange::Deleted(path));
                continue;
            };
            if now == known {
                continue;
            }
            self.stamps.insert(path.clone(), now);
            if document.is_modified() {
                changes.push(DiskChange::Conflict(path));
                continue;
            }
            match read_file(&path) {
                Ok(text) if text != document.buffer().to_text() => {
                    document.reload(&text);
                    changes.push(DiskChange::Reloaded(path));
                }
                _ => {}
            }
        }
        changes
    }

    /// Adds an empty untitled document and activates it.
    pub fn new_document(&mut self) -> usize {
        self.documents.push(Document::new());
        self.active = self.documents.len() - 1;
        self.active
    }

    /// Adds a document with the given contents and activates it.
    pub fn add_document(&mut self, document: Document) -> usize {
        self.documents.push(document);
        self.active = self.documents.len() - 1;
        self.active
    }

    /// Saves the active document to its existing path.
    pub fn save_active(&mut self) -> Result<PathBuf, FileError> {
        let path = self
            .active()
            .path()
            .map(Path::to_path_buf)
            .ok_or(FileError::NoPath)?;
        self.save_active_as(&path)
    }

    /// Saves the active document to `path` and associates it with that path.
    pub fn save_active_as(&mut self, path: &Path) -> Result<PathBuf, FileError> {
        let contents = self.active().buffer().to_text();
        write_file_atomically(path, &contents)?;
        self.record(path);

        let document = self.active_mut();
        document.set_path(path);
        document.mark_saved();
        self.remember(path);
        Ok(path.to_path_buf())
    }

    /// Saves every modified document that has a path.
    pub fn save_all(&mut self) -> Result<(usize, usize), FileError> {
        let mut written = 0;
        let mut skipped = 0;

        for index in 0..self.documents.len() {
            if !self.documents[index].is_modified() {
                continue;
            }
            let Some(path) = self.documents[index].path().map(Path::to_path_buf) else {
                skipped += 1;
                continue;
            };
            write_file_atomically(&path, &self.documents[index].buffer().to_text())?;
            self.record(&path);
            self.documents[index].mark_saved();
            written += 1;
        }

        Ok((written, skipped))
    }

    /// Closes the document at `index`, returning whether it had unsaved changes.
    pub fn close(&mut self, index: usize) -> Result<bool, FileError> {
        if index >= self.documents.len() {
            return Err(FileError::NoSuchDocument { index });
        }
        let was_modified = self.documents[index].is_modified();
        self.documents.remove(index);
        if self.documents.is_empty() {
            self.documents.push(Document::new());
        }
        self.active = self.active.min(self.documents.len() - 1);
        Ok(was_modified)
    }

    /// Whether any open document has unsaved changes.
    pub fn has_unsaved_changes(&self) -> bool {
        self.documents.iter().any(Document::is_modified)
    }

    /// The documents with unsaved changes, for a quit confirmation prompt.
    pub fn modified_documents(&self) -> Vec<&Document> {
        self.documents
            .iter()
            .filter(|document| document.is_modified())
            .collect()
    }

    /// Finds the index of an open document by path.
    pub fn index_of(&self, path: &Path) -> Option<usize> {
        self.documents
            .iter()
            .position(|document| document.path() == Some(path))
    }
}

impl Default for Workspace {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn temp_dir() -> tempfile::TempDir {
        tempfile::tempdir().expect("temp dir")
    }

    #[test]
    fn saving_everything_writes_each_modified_file() {
        let dir = temp_dir();
        let first = dir.path().join("main.asm");
        let second = dir.path().join("util.asm");
        std::fs::write(&first, "old\n").expect("write");
        std::fs::write(&second, "old\n").expect("write");

        let mut workspace = Workspace::new();
        workspace.open(&first).expect("open");
        workspace.active_mut().insert("new ");
        workspace.open(&second).expect("open");
        workspace.active_mut().insert("new ");

        assert_eq!(workspace.save_all().expect("save"), (2, 0));
        assert!(std::fs::read_to_string(&first)
            .expect("read")
            .starts_with("new"));
        assert!(std::fs::read_to_string(&second)
            .expect("read")
            .starts_with("new"));
        assert!(!workspace.has_unsaved_changes());
        assert_eq!(workspace.save_all().expect("save"), (0, 0));
    }

    #[test]
    fn saving_everything_counts_buffers_with_no_file_name() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        std::fs::write(&path, "old\n").expect("write");

        let mut workspace = Workspace::new();
        workspace.open(&path).expect("open");
        workspace.active_mut().insert("x");
        workspace.new_document();
        workspace.active_mut().insert("scratch");

        assert_eq!(workspace.save_all().expect("save"), (1, 1));
    }

    #[test]
    fn completing_a_prefix_extends_it_as_far_as_the_candidates_agree() {
        let dir = temp_dir();
        std::fs::write(dir.path().join("alpha.asm"), "").expect("write");
        std::fs::write(dir.path().join("alps.asm"), "").expect("write");
        std::fs::write(dir.path().join("beta.asm"), "").expect("write");

        let base = format!("{}/", dir.path().display());
        let (completed, candidates) = complete_path(&format!("{base}al"));
        assert_eq!(completed, format!("{base}alp"));
        assert_eq!(candidates.len(), 2);

        let (completed, candidates) = complete_path(&format!("{base}b"));
        assert_eq!(completed, format!("{base}beta.asm"));
        assert_eq!(candidates.len(), 1);
    }

    #[test]
    fn completing_a_directory_adds_the_separator() {
        let dir = temp_dir();
        std::fs::create_dir(dir.path().join("sources")).expect("mkdir");

        let base = format!("{}/", dir.path().display());
        let (completed, _) = complete_path(&format!("{base}sou"));
        assert_eq!(completed, format!("{base}sources/"));
    }

    #[test]
    fn completing_something_with_no_match_leaves_it_alone() {
        let dir = temp_dir();
        let text = format!("{}/nothing", dir.path().display());
        let (completed, candidates) = complete_path(&text);
        assert_eq!(completed, text);
        assert!(candidates.is_empty());
    }

    #[test]
    fn a_reported_path_matches_on_whole_trailing_components() {
        assert!(same_file(
            Path::new("/w/src/main.asm"),
            Path::new("src/main.asm")
        ));
        assert!(same_file(
            Path::new("/w/src/main.asm"),
            Path::new("main.asm")
        ));
        assert!(same_file(Path::new("main.asm"), Path::new("main.asm")));
    }

    #[test]
    fn two_files_sharing_a_name_stay_apart() {
        assert!(!same_file(
            Path::new("/w/lib/main.asm"),
            Path::new("src/main.asm")
        ));
        assert!(!same_file(Path::new("/w/src/util.asm"), Path::new("m.asm")));
        assert!(!same_file(Path::new("main.asm"), Path::new("")));
    }

    #[test]
    fn a_new_workspace_holds_one_untitled_document() {
        let workspace = Workspace::new();
        assert_eq!(workspace.len(), 1);
        assert_eq!(workspace.active().display_name(), "[untitled]");
        assert!(!workspace.has_unsaved_changes());
    }

    #[test]
    fn opening_a_file_loads_its_contents() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        std::fs::write(&path, "section .text\nglobal _start\n").expect("write");

        let mut workspace = Workspace::new();
        workspace.open(&path).expect("open");
        assert_eq!(
            workspace.active().buffer().to_text(),
            "section .text\nglobal _start\n"
        );
        assert_eq!(workspace.active().display_name(), "main.asm");
        assert!(!workspace.active().is_modified());
    }

    #[test]
    fn opening_replaces_a_pristine_untitled_buffer() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        std::fs::write(&path, "ret\n").expect("write");

        let mut workspace = Workspace::new();
        workspace.open(&path).expect("open");
        assert_eq!(workspace.len(), 1, "the empty buffer should be reused");
    }

    #[test]
    fn opening_keeps_a_modified_untitled_buffer() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        std::fs::write(&path, "ret\n").expect("write");

        let mut workspace = Workspace::new();
        workspace.active_mut().insert_char('x');
        workspace.open(&path).expect("open");
        assert_eq!(workspace.len(), 2, "unsaved work must not be discarded");
    }

    #[test]
    fn opening_the_same_file_twice_activates_the_existing_buffer() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        std::fs::write(&path, "ret\n").expect("write");

        let mut workspace = Workspace::new();
        let first = workspace.open(&path).expect("open");
        workspace.new_document();
        let second = workspace.open(&path).expect("reopen");
        assert_eq!(first, second);
        assert_eq!(workspace.len(), 2);
    }

    #[test]
    fn opening_a_missing_file_reports_an_error_without_panicking() {
        let dir = temp_dir();
        let mut workspace = Workspace::new();
        let error = workspace
            .open(&dir.path().join("nope.asm"))
            .expect_err("must fail");
        assert!(matches!(error, FileError::Read { .. }));
        assert_eq!(workspace.len(), 1, "workspace must be unchanged");
    }

    #[test]
    fn opening_a_binary_file_reports_a_utf8_error() {
        let dir = temp_dir();
        let path = dir.path().join("binary.o");
        std::fs::write(&path, [0x7f, b'E', b'L', b'F', 0xff, 0xfe]).expect("write");

        let mut workspace = Workspace::new();
        let error = workspace.open(&path).expect_err("must fail");
        assert!(matches!(error, FileError::NotUtf8 { .. }));
    }

    #[test]
    fn saving_writes_the_buffer_and_clears_the_modified_flag() {
        let dir = temp_dir();
        let path = dir.path().join("out.asm");

        let mut workspace = Workspace::new();
        workspace.active_mut().insert("mov rax, 1\n");
        assert!(workspace.has_unsaved_changes());

        workspace.save_active_as(&path).expect("save");
        assert_eq!(
            std::fs::read_to_string(&path).expect("read"),
            "mov rax, 1\n"
        );
        assert!(!workspace.has_unsaved_changes());
        assert_eq!(workspace.active().display_name(), "out.asm");
    }

    #[test]
    fn saving_without_a_path_is_an_error_rather_than_a_guess() {
        let mut workspace = Workspace::new();
        workspace.active_mut().insert_char('x');
        assert!(matches!(workspace.save_active(), Err(FileError::NoPath)));
    }

    #[test]
    fn saving_an_opened_file_reuses_its_path() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        std::fs::write(&path, "ret\n").expect("write");

        let mut workspace = Workspace::new();
        workspace.open(&path).expect("open");
        workspace.active_mut().insert("nop\n");
        let saved = workspace.save_active().expect("save");
        assert_eq!(saved, path);
        assert_eq!(std::fs::read_to_string(&path).expect("read"), "nop\nret\n");
    }

    #[test]
    fn a_failed_save_leaves_the_original_file_intact() {
        let dir = temp_dir();
        let path = dir.path().join("subdir").join("main.asm");
        std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
        std::fs::write(&path, "original\n").expect("write");

        let blocked = dir.path().join("main.asm").join("impossible.asm");
        std::fs::write(dir.path().join("main.asm"), "blocker").expect("write");

        let result = write_file_atomically(&blocked, "new contents");
        assert!(result.is_err(), "expected the write to fail");
        assert_eq!(
            std::fs::read_to_string(&path).expect("read"),
            "original\n",
            "the untouched file must be unchanged"
        );
    }

    #[test]
    fn saving_creates_missing_parent_directories() {
        let dir = temp_dir();
        let path = dir.path().join("a/b/c/main.asm");
        write_file_atomically(&path, "ret\n").expect("save");
        assert_eq!(std::fs::read_to_string(&path).expect("read"), "ret\n");
    }

    #[test]
    fn saving_over_an_existing_file_replaces_it_completely() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        std::fs::write(&path, "a much longer original file\n").expect("write");
        write_file_atomically(&path, "short\n").expect("save");
        assert_eq!(std::fs::read_to_string(&path).expect("read"), "short\n");
    }

    #[test]
    fn saving_leaves_no_temporary_files_behind() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        write_file_atomically(&path, "ret\n").expect("save");
        let entries: Vec<_> = std::fs::read_dir(dir.path())
            .expect("read dir")
            .filter_map(Result::ok)
            .map(|entry| entry.file_name())
            .collect();
        assert_eq!(entries.len(), 1, "found stray files: {entries:?}");
    }

    #[test]
    fn documents_cycle_in_both_directions() {
        let mut workspace = Workspace::new();
        workspace.new_document();
        workspace.new_document();
        assert_eq!(workspace.active_index(), 2);

        workspace.next_document();
        assert_eq!(workspace.active_index(), 0, "must wrap around");
        workspace.previous_document();
        assert_eq!(workspace.active_index(), 2, "must wrap backwards");
    }

    #[test]
    fn setting_an_out_of_range_active_index_is_ignored() {
        let mut workspace = Workspace::new();
        workspace.set_active(99);
        assert_eq!(workspace.active_index(), 0);
    }

    #[test]
    fn closing_the_last_document_leaves_a_fresh_one() {
        let mut workspace = Workspace::new();
        workspace.active_mut().insert_char('x');
        let was_modified = workspace.close(0).expect("close");
        assert!(was_modified);
        assert_eq!(workspace.len(), 1);
        assert!(!workspace.active().is_modified());
    }

    #[test]
    fn closing_keeps_the_active_index_in_range() {
        let mut workspace = Workspace::new();
        workspace.new_document();
        workspace.new_document();
        workspace.set_active(2);
        workspace.close(2).expect("close");
        assert_eq!(workspace.active_index(), 1);
        assert_eq!(workspace.len(), 2);
    }

    #[test]
    fn a_leading_dot_is_not_shown() {
        assert_eq!(display_path(Path::new("./src/main.asm")), "src/main.asm");
        assert_eq!(display_path(Path::new("../x.asm")), "../x.asm");
    }

    #[test]
    fn changes_on_disk_are_reloaded_or_reported() {
        let dir = tempfile::tempdir().expect("temp dir");
        let clean = dir.path().join("clean.asm");
        let edited = dir.path().join("edited.asm");
        std::fs::write(&clean, "nop\n").expect("write");
        std::fs::write(&edited, "nop\n").expect("write");
        let mut workspace = Workspace::new();
        workspace.open(&clean).expect("open");
        let index = workspace.open(&edited).expect("open");
        workspace.set_active(index);
        workspace.active_mut().insert("; mine\n");
        assert!(workspace.check_disk().is_empty());

        std::thread::sleep(std::time::Duration::from_millis(20));
        std::fs::write(&clean, "ret\n").expect("write");
        std::fs::write(&edited, "ret\n").expect("write");
        let mut changes = workspace.check_disk();
        changes.sort_by_key(|change| format!("{change:?}"));
        assert_eq!(
            changes,
            [
                DiskChange::Conflict(edited.clone()),
                DiskChange::Reloaded(clean.clone())
            ]
        );
        assert_eq!(workspace.documents()[0].buffer().to_text(), "ret\n");
        assert!(workspace.documents()[1]
            .buffer()
            .to_text()
            .starts_with("; mine"));
        assert!(workspace.check_disk().is_empty(), "reported once");

        std::fs::remove_file(&clean).expect("remove");
        assert_eq!(workspace.check_disk(), [DiskChange::Deleted(clean)]);
    }

    #[test]
    fn a_file_is_opened_once_however_its_path_is_spelled() {
        let dir = tempfile::tempdir().expect("temp dir");
        let path = dir.path().join("a.asm");
        std::fs::write(&path, "nop\n").expect("write");
        let mut workspace = Workspace::new();
        workspace.open(&path).expect("open");
        let indirect = dir.path().join(".").join("a.asm");
        workspace.open(&indirect).expect("open again");
        assert_eq!(workspace.documents().len(), 1);
    }

    #[test]
    fn closing_an_unknown_index_is_an_error() {
        let mut workspace = Workspace::new();
        assert!(matches!(
            workspace.close(9),
            Err(FileError::NoSuchDocument { index: 9 })
        ));
    }

    #[test]
    fn recent_files_are_ordered_most_recent_first_without_duplicates() {
        let dir = temp_dir();
        let first = dir.path().join("a.asm");
        let second = dir.path().join("b.asm");
        std::fs::write(&first, "ret\n").expect("write");
        std::fs::write(&second, "nop\n").expect("write");

        let mut workspace = Workspace::new();
        workspace.open(&first).expect("open a");
        workspace.open(&second).expect("open b");
        workspace.open(&first).expect("reopen a");

        assert_eq!(workspace.recent_files(), [first, second]);
    }

    #[test]
    fn the_recent_list_is_bounded() {
        let dir = temp_dir();
        let mut workspace = Workspace::new();
        for index in 0..(Workspace::MAX_RECENT + 5) {
            let path = dir.path().join(format!("file{index}.asm"));
            std::fs::write(&path, "ret\n").expect("write");
            workspace.open(&path).expect("open");
        }
        assert_eq!(workspace.recent_files().len(), Workspace::MAX_RECENT);
    }

    #[test]
    fn modified_documents_are_reported_for_a_quit_prompt() {
        let mut workspace = Workspace::new();
        workspace.new_document();
        workspace.active_mut().insert_char('x');
        assert_eq!(workspace.modified_documents().len(), 1);
        assert!(workspace.has_unsaved_changes());
    }

    #[test]
    fn a_round_trip_through_disk_preserves_the_text_exactly() {
        let dir = temp_dir();
        let path = dir.path().join("main.asm");
        let source = "section .data\n    msg: db `hi\\n`, 0\n\nsection .text\n_start:\n    ret\n";
        std::fs::write(&path, source).expect("write");

        let mut workspace = Workspace::new();
        workspace.open(&path).expect("open");
        workspace.save_active().expect("save");
        assert_eq!(std::fs::read_to_string(&path).expect("read"), source);
    }
}