ratasm 0.2.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
//! What the interface is currently doing: browsing, 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 open.
    OpenFile,
    /// A file to create in the external editor.
    NewFile,
    /// The line of the active file to add or remove a breakpoint on.
    BreakpointLine,
    /// An address expression.
    GoToAddress,
}

impl PromptKind {
    /// The label shown before the input.
    pub const fn label(self) -> &'static str {
        match self {
            PromptKind::OpenFile => "Open file",
            PromptKind::NewFile => "New file",
            PromptKind::BreakpointLine => "Toggle breakpoint at line",
            PromptKind::GoToAddress => "Go to address",
        }
    }

    /// A hint shown when the input is empty.
    pub const fn hint(self) -> &'static str {
        match self {
            PromptKind::OpenFile => "path to an .asm file",
            PromptKind::NewFile => "path of the file to create",
            PromptKind::BreakpointLine => "line number",
            PromptKind::GoToAddress => "0x4000b0, rsp-0x20, rbp+8",
        }
    }

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

/// 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 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),
}

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::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::GoToAddress, "rax");
        assert_eq!(prompt.text(), "rax");
        assert_eq!(prompt.cursor(), 3);
    }

    #[test]
    fn typing_inserts_at_the_cursor() {
        let mut prompt = Prompt::new(PromptKind::GoToAddress, "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::GoToAddress, "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::GoToAddress, "ö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::GoToAddress, "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::NewFile,
            PromptKind::BreakpointLine,
            PromptKind::GoToAddress,
        ] {
            assert!(!kind.label().is_empty());
            assert!(!kind.hint().is_empty());
        }
    }

    #[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::BreakpointLine, "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");
    }
}