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
//! What the interface is currently doing: editing, or asking a question.

use crate::command::Command;

/// What a prompt is asking for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PromptKind {
    /// A file to create in the project.
    NewFile,
    /// A file to open.
    OpenFile,
    /// A name to save under.
    SaveAs,
    /// A name to save under before closing the buffer.
    SaveAsAndClose,
    /// A line number.
    GoToLine,
    /// An address expression.
    GoToAddress,
    /// The new name of the active file.
    RenameFile,
    /// Confirmation that the active file should be deleted.
    DeleteFile,
    /// An expression to watch.
    Watch,
    /// The selected breakpoint's condition.
    BreakpointCondition,
    /// A register assignment.
    SetRegister,
    /// Text to search for.
    Search,
    /// Text to replace matches with.
    Replace,
    /// Confirmation before discarding unsaved changes.
    ConfirmQuit,
    /// Choice of saving, discarding, or cancelling before closing a buffer.
    ConfirmClose,
}

impl PromptKind {
    /// The label shown before the input.
    pub const fn label(self) -> &'static str {
        match self {
            PromptKind::NewFile => "New file",
            PromptKind::OpenFile => "Open file",
            PromptKind::SaveAs => "Save as",
            PromptKind::SaveAsAndClose => "Save and close as",
            PromptKind::GoToLine => "Go to line",
            PromptKind::GoToAddress => "Go to address",
            PromptKind::RenameFile => "Rename to",
            PromptKind::DeleteFile => "Delete the file? Type yes",
            PromptKind::Watch => "Watch",
            PromptKind::BreakpointCondition => "Stop only if",
            PromptKind::SetRegister => "Set register",
            PromptKind::Search => "Find",
            PromptKind::Replace => "Replace with",
            PromptKind::ConfirmQuit => "Unsaved changes. Quit anyway? (y/n)",
            PromptKind::ConfirmClose => {
                "Unsaved changes. Save and close, discard, or cancel? (s/d/c)"
            }
        }
    }

    /// A hint shown when the input is empty.
    pub const fn hint(self) -> &'static str {
        match self {
            PromptKind::NewFile => "path in the project, such as src/util.asm",
            PromptKind::OpenFile => "path to an .asm file",
            PromptKind::SaveAs => "path to write to",
            PromptKind::SaveAsAndClose => "path to write to",
            PromptKind::GoToLine => "line number",
            PromptKind::GoToAddress => "0x4000b0, rsp-0x20, rbp+8",
            PromptKind::RenameFile => "new path",
            PromptKind::DeleteFile => "yes",
            PromptKind::Watch => "$rax, (int)counter, *(long *)0x402000",
            PromptKind::BreakpointCondition => "$rcx == 3; empty removes it",
            PromptKind::SetRegister => "rax=0x10",
            PromptKind::Search => "text to find",
            PromptKind::Replace => "replacement text",
            PromptKind::ConfirmQuit => "y or n",
            PromptKind::ConfirmClose => "s, d, or c",
        }
    }

    /// Whether the prompt takes a single keypress rather than a line of text.
    pub const fn is_confirmation(self) -> bool {
        matches!(self, PromptKind::ConfirmQuit | PromptKind::ConfirmClose)
    }

    /// Whether Tab should complete the input against the filesystem.
    pub const fn completes_paths(self) -> bool {
        matches!(
            self,
            PromptKind::OpenFile
                | PromptKind::NewFile
                | PromptKind::RenameFile
                | PromptKind::SaveAs
                | PromptKind::SaveAsAndClose
        )
    }
}

/// A single-line text input.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Prompt {
    /// What is being asked.
    kind: Option<PromptKind>,
    /// The text typed so far.
    text: String,
    /// The cursor position, as a character index.
    cursor: usize,
}

impl Prompt {
    /// Creates a prompt asking for `kind`, pre-filled with `text`.
    pub fn new(kind: PromptKind, text: impl Into<String>) -> Self {
        let text = text.into();
        let cursor = text.chars().count();
        Self {
            kind: Some(kind),
            text,
            cursor,
        }
    }

    /// What is being asked.
    pub fn kind(&self) -> Option<PromptKind> {
        self.kind
    }

    /// The text typed so far.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// The cursor position as a character index.
    pub fn cursor(&self) -> usize {
        self.cursor
    }

    /// Replaces the text, putting the cursor at its end.
    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
        self.cursor = self.text.chars().count();
    }

    /// Inserts a character at the cursor.
    pub fn insert(&mut self, ch: char) {
        let offset = self.byte_offset(self.cursor);
        self.text.insert(offset, ch);
        self.cursor += 1;
    }

    /// Deletes the character before the cursor.
    pub fn backspace(&mut self) {
        if self.cursor == 0 {
            return;
        }
        let offset = self.byte_offset(self.cursor - 1);
        self.text.remove(offset);
        self.cursor -= 1;
    }

    /// Deletes the character after the cursor.
    pub fn delete(&mut self) {
        if self.cursor >= self.text.chars().count() {
            return;
        }
        let offset = self.byte_offset(self.cursor);
        self.text.remove(offset);
    }

    /// Moves the cursor one character left.
    pub fn move_left(&mut self) {
        self.cursor = self.cursor.saturating_sub(1);
    }

    /// Moves the cursor one character right.
    pub fn move_right(&mut self) {
        self.cursor = (self.cursor + 1).min(self.text.chars().count());
    }

    /// Moves the cursor to the start.
    pub fn move_home(&mut self) {
        self.cursor = 0;
    }

    /// Moves the cursor to the end.
    pub fn move_end(&mut self) {
        self.cursor = self.text.chars().count();
    }

    /// Removes all text.
    pub fn clear(&mut self) {
        self.text.clear();
        self.cursor = 0;
    }

    /// Whether nothing has been typed.
    pub fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// Converts a character index to a byte offset.
    fn byte_offset(&self, index: usize) -> usize {
        self.text
            .char_indices()
            .nth(index)
            .map_or(self.text.len(), |(offset, _)| offset)
    }
}

/// The command palette's state.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Palette {
    /// The query typed so far.
    prompt: Prompt,
    /// The commands matching the query, best first.
    matches: Vec<Command>,
    /// Which match is highlighted.
    selected: usize,
}

impl Palette {
    /// Opens the palette with every command listed.
    pub fn open() -> Self {
        let mut palette = Self {
            prompt: Prompt::default(),
            matches: Vec::new(),
            selected: 0,
        };
        palette.refresh();
        palette
    }

    /// The query prompt.
    pub fn prompt(&self) -> &Prompt {
        &self.prompt
    }

    /// The query prompt, mutably.
    pub fn prompt_mut(&mut self) -> &mut Prompt {
        &mut self.prompt
    }

    /// The current matches, best first.
    pub fn matches(&self) -> &[Command] {
        &self.matches
    }

    /// The index of the highlighted match.
    pub fn selected(&self) -> usize {
        self.selected
    }

    /// The highlighted command, if there is one.
    pub fn selected_command(&self) -> Option<&Command> {
        self.matches.get(self.selected)
    }

    /// Recomputes the matches for the current query.
    pub fn refresh(&mut self) {
        let commands = Command::all();
        let texts: Vec<String> = commands.iter().map(Command::search_text).collect();
        let ranked =
            crate::command::palette::rank(self.prompt.text(), texts.iter().map(String::as_str));

        self.matches = ranked
            .into_iter()
            .filter_map(|(index, _)| commands.get(index).cloned())
            .collect();
        self.selected = 0;
    }

    /// Highlights the next match, wrapping around.
    pub fn select_next(&mut self) {
        if self.matches.is_empty() {
            return;
        }
        self.selected = (self.selected + 1) % self.matches.len();
    }

    /// Highlights the previous match, wrapping around.
    pub fn select_previous(&mut self) {
        if self.matches.is_empty() {
            return;
        }
        self.selected = (self.selected + self.matches.len() - 1) % self.matches.len();
    }
}

/// What a picker lists.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PickerKind {
    /// Symbols defined anywhere in the project.
    Symbols,
    /// Lines containing the query in any project file.
    Search,
    /// Targets of the project's Makefile.
    MakeTargets,
}

impl PickerKind {
    /// The title of the picker.
    pub const fn title(self) -> &'static str {
        match self {
            PickerKind::Symbols => "Go to symbol",
            PickerKind::Search => "Search in files",
            PickerKind::MakeTargets => "Run a make target",
        }
    }

    /// A hint shown when the query is empty.
    pub const fn hint(self) -> &'static str {
        match self {
            PickerKind::Symbols => "type part of a label, constant or macro",
            PickerKind::Search => "type at least two characters",
            PickerKind::MakeTargets => "type to filter the targets",
        }
    }
}

/// A place a picker can jump to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PickItem {
    /// The main text.
    pub label: String,
    /// Where it is, shown dimmed.
    pub detail: String,
    /// The file.
    pub path: std::path::PathBuf,
    /// The one-based line.
    pub line: usize,
}

/// A query and the places that match it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Picker {
    kind: PickerKind,
    prompt: Prompt,
    items: Vec<PickItem>,
    selected: usize,
}

impl Picker {
    /// An empty picker of `kind`.
    pub fn new(kind: PickerKind) -> Self {
        Self {
            kind,
            prompt: Prompt::default(),
            items: Vec::new(),
            selected: 0,
        }
    }

    /// What it lists.
    pub fn kind(&self) -> PickerKind {
        self.kind
    }

    /// The query prompt.
    pub fn prompt(&self) -> &Prompt {
        &self.prompt
    }

    /// The query prompt, mutably.
    pub fn prompt_mut(&mut self) -> &mut Prompt {
        &mut self.prompt
    }

    /// The matches, best first.
    pub fn items(&self) -> &[PickItem] {
        &self.items
    }

    /// Replaces the matches, highlighting the first.
    pub fn set_items(&mut self, items: Vec<PickItem>) {
        self.items = items;
        self.selected = 0;
    }

    /// The index of the highlighted match.
    pub fn selected(&self) -> usize {
        self.selected
    }

    /// The highlighted match.
    pub fn selected_item(&self) -> Option<&PickItem> {
        self.items.get(self.selected)
    }

    /// Highlights the next match, wrapping around.
    pub fn select_next(&mut self) {
        if !self.items.is_empty() {
            self.selected = (self.selected + 1) % self.items.len();
        }
    }

    /// Highlights the previous match, wrapping around.
    pub fn select_previous(&mut self) {
        if !self.items.is_empty() {
            self.selected = (self.selected + self.items.len() - 1) % self.items.len();
        }
    }
}

/// What the interface is doing.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Mode {
    /// Editing, with keys going to the focused panel.
    #[default]
    Normal,
    /// The command palette is open.
    Palette(Palette),
    /// A prompt is open, and what to do with the answer.
    Prompt(Prompt),
    /// A picker is open.
    Picker(Picker),
}

impl Mode {
    /// Whether an overlay is capturing input.
    pub fn is_overlay(&self) -> bool {
        !matches!(self, Mode::Normal)
    }

    /// The prompt, when one is open.
    pub fn prompt(&self) -> Option<&Prompt> {
        match self {
            Mode::Prompt(prompt) => Some(prompt),
            Mode::Palette(palette) => Some(palette.prompt()),
            Mode::Picker(picker) => Some(picker.prompt()),
            Mode::Normal => None,
        }
    }

    /// The palette, when it is open.
    pub fn palette(&self) -> Option<&Palette> {
        match self {
            Mode::Palette(palette) => Some(palette),
            _ => None,
        }
    }
}

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

    #[test]
    fn a_new_prompt_puts_the_cursor_after_the_prefilled_text() {
        let prompt = Prompt::new(PromptKind::Search, "rax");
        assert_eq!(prompt.text(), "rax");
        assert_eq!(prompt.cursor(), 3);
    }

    #[test]
    fn typing_inserts_at_the_cursor() {
        let mut prompt = Prompt::new(PromptKind::Search, "rax");
        prompt.move_home();
        prompt.insert('e');
        assert_eq!(prompt.text(), "erax");
        assert_eq!(prompt.cursor(), 1);
    }

    #[test]
    fn backspace_and_delete_remove_the_right_character() {
        let mut prompt = Prompt::new(PromptKind::Search, "abc");
        prompt.backspace();
        assert_eq!(prompt.text(), "ab");

        prompt.move_home();
        prompt.delete();
        assert_eq!(prompt.text(), "b");
    }

    #[test]
    fn editing_at_the_edges_does_nothing_rather_than_panicking() {
        let mut prompt = Prompt::default();
        prompt.backspace();
        prompt.delete();
        prompt.move_left();
        prompt.move_right();
        assert!(prompt.is_empty());
        assert_eq!(prompt.cursor(), 0);
    }

    #[test]
    fn multibyte_text_is_edited_by_character_not_byte() {
        let mut prompt = Prompt::new(PromptKind::Search, "ölçüm");
        prompt.backspace();
        assert_eq!(prompt.text(), "ölçü");
        prompt.move_home();
        prompt.delete();
        assert_eq!(prompt.text(), "lçü");
        prompt.insert('ÅŸ');
        assert_eq!(prompt.text(), "şlçü");
    }

    #[test]
    fn cursor_movement_is_clamped_to_the_text() {
        let mut prompt = Prompt::new(PromptKind::Search, "ab");
        for _ in 0..10 {
            prompt.move_right();
        }
        assert_eq!(prompt.cursor(), 2);
        for _ in 0..10 {
            prompt.move_left();
        }
        assert_eq!(prompt.cursor(), 0);
    }

    #[test]
    fn every_prompt_kind_has_a_label_and_a_hint() {
        for kind in [
            PromptKind::OpenFile,
            PromptKind::SaveAs,
            PromptKind::SaveAsAndClose,
            PromptKind::GoToLine,
            PromptKind::GoToAddress,
            PromptKind::Search,
            PromptKind::Replace,
            PromptKind::ConfirmQuit,
            PromptKind::ConfirmClose,
        ] {
            assert!(!kind.label().is_empty());
            assert!(!kind.hint().is_empty());
        }
    }

    #[test]
    fn destructive_prompts_are_confirmations() {
        assert!(PromptKind::ConfirmQuit.is_confirmation());
        assert!(PromptKind::ConfirmClose.is_confirmation());
        assert!(!PromptKind::Search.is_confirmation());
    }

    #[test]
    fn an_open_palette_lists_every_command() {
        let palette = Palette::open();
        assert_eq!(palette.matches().len(), Command::all().len());
        assert_eq!(palette.selected(), 0);
        assert!(palette.selected_command().is_some());
    }

    #[test]
    fn typing_narrows_the_palette() {
        let mut palette = Palette::open();
        for ch in "step over".chars() {
            palette.prompt_mut().insert(ch);
        }
        palette.refresh();

        assert!(palette.matches().len() < Command::all().len());
        assert_eq!(
            palette.selected_command().map(Command::id),
            Some("debug.step-over".to_owned())
        );
    }

    #[test]
    fn a_query_matching_nothing_leaves_no_selection() {
        let mut palette = Palette::open();
        for ch in "zzzznothing".chars() {
            palette.prompt_mut().insert(ch);
        }
        palette.refresh();

        assert!(palette.matches().is_empty());
        assert!(palette.selected_command().is_none());
    }

    #[test]
    fn selection_wraps_in_both_directions() {
        let mut palette = Palette::open();
        let count = palette.matches().len();

        palette.select_previous();
        assert_eq!(palette.selected(), count - 1, "wraps to the end");
        palette.select_next();
        assert_eq!(palette.selected(), 0, "wraps back to the start");
    }

    #[test]
    fn moving_the_selection_in_an_empty_palette_does_nothing() {
        let mut palette = Palette::open();
        for ch in "zzzz".chars() {
            palette.prompt_mut().insert(ch);
        }
        palette.refresh();

        palette.select_next();
        palette.select_previous();
        assert_eq!(palette.selected(), 0);
    }

    #[test]
    fn refreshing_resets_the_selection_to_the_best_match() {
        let mut palette = Palette::open();
        palette.select_next();
        palette.select_next();
        assert_ne!(palette.selected(), 0);

        palette.prompt_mut().insert('r');
        palette.refresh();
        assert_eq!(palette.selected(), 0);
    }

    #[test]
    fn the_default_mode_is_editing() {
        let mode = Mode::default();
        assert_eq!(mode, Mode::Normal);
        assert!(!mode.is_overlay());
        assert!(mode.prompt().is_none());
        assert!(mode.palette().is_none());
    }

    #[test]
    fn overlays_report_themselves_and_expose_their_prompt() {
        let mode = Mode::Prompt(Prompt::new(PromptKind::GoToLine, "42"));
        assert!(mode.is_overlay());
        assert_eq!(mode.prompt().map(Prompt::text), Some("42"));
        assert!(mode.palette().is_none());

        let mode = Mode::Palette(Palette::open());
        assert!(mode.is_overlay());
        assert!(mode.palette().is_some());
        assert!(mode.prompt().is_some(), "the palette has a query prompt");
    }
}