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
//! Entry point for the `ratasm` binary.

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use anyhow::{Context, Result};
use clap::{Parser, Subcommand};

use ratasm::assembler::{self, BuildOptions};
use ratasm::project::Project;

/// A terminal IDE and debugger for x86-64 assembly.
#[derive(Debug, Parser)]
#[command(
    name = "ratasm",
    version,
    about,
    long_about = None,
    disable_help_subcommand = true
)]
struct Cli {
    /// Assembly files, or one project directory, to open.
    #[arg(value_name = "PATH")]
    paths: Vec<PathBuf>,

    /// Write diagnostics to this file.
    #[arg(long, value_name = "FILE", global = true)]
    log_file: Option<PathBuf>,

    /// Log filter, in `RUST_LOG` syntax.
    #[arg(long, value_name = "FILTER", default_value = "info", global = true)]
    log_filter: String,

    #[command(subcommand)]
    command: Option<Command>,
}

/// What the binary was asked to do.
#[derive(Debug, Subcommand)]
enum Command {
    /// Create a new project with a working hello-world program.
    New {
        /// Directory to create the project in.
        #[arg(value_name = "NAME")]
        name: String,
        /// Start from a `main` that calls printf, linked with libc by gcc.
        #[arg(long, conflicts_with = "make")]
        libc: bool,
        /// Build with a Makefile instead of a .ratasm.toml.
        #[arg(long)]
        make: bool,
    },
    /// Assemble and link the project, then exit.
    Build {
        /// Project directory or source file.
        #[arg(value_name = "PATH")]
        path: Option<PathBuf>,
        /// Ask the assembler for debug information.
        #[arg(long)]
        debug: bool,
    },
    /// Build the project and run the result, then exit.
    Run {
        /// Project directory or source file.
        #[arg(value_name = "PATH")]
        path: Option<PathBuf>,
    },
    /// Report which external tools are installed.
    Doctor,
}

fn main() -> ExitCode {
    ratasm::ui::install_panic_hook();

    let cli = Cli::parse();

    if let Some(path) = &cli.log_file {
        if let Err(error) = ratasm::logging::init_file_logging(path, &cli.log_filter) {
            eprintln!("ratasm: cannot start logging: {error}");
            return ExitCode::FAILURE;
        }
    }

    match run(cli) {
        Ok(code) => code,
        Err(error) => {
            eprintln!("ratasm: {error:#}");
            ExitCode::FAILURE
        }
    }
}

/// Dispatches to the requested command.
fn run(cli: Cli) -> Result<ExitCode> {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .context("cannot start the async runtime")?;

    match cli.command {
        Some(Command::New { name, libc, make }) => {
            runtime.block_on(async { new_project(&name, libc, make) })
        }
        Some(Command::Build { path, debug }) => {
            runtime.block_on(build_project(path.as_deref(), debug))
        }
        Some(Command::Run { path }) => runtime.block_on(run_project(path.as_deref())),
        Some(Command::Doctor) => Ok(doctor()),
        None => runtime.block_on(open_interface(&cli.paths)),
    }
}

/// Creates a project directory and reports what was written.
fn new_project(name: &str, libc: bool, make: bool) -> Result<ExitCode> {
    let root = PathBuf::from(name);
    if root.exists() && root.read_dir().is_ok_and(|mut dir| dir.next().is_some()) {
        anyhow::bail!("{} already exists and is not empty", root.display());
    }

    let created = if make {
        Project::create_with_make(&root, name)
    } else if libc {
        Project::create_with_libc(&root, name)
    } else {
        Project::create(&root, name)
    };
    created.with_context(|| format!("cannot create a project in {}", root.display()))?;

    println!("Created {}", root.display());
    println!("  {}", root.join("src").join("main.asm").display());
    let described = if make { "Makefile" } else { Project::FILE_NAME };
    println!("  {}", root.join(described).display());
    println!();
    println!("Next:");
    println!("  cd {name}");
    println!("  ratasm");
    Ok(ExitCode::SUCCESS)
}

/// Resolves the project a path refers to.
fn resolve_project(path: Option<&Path>) -> Result<Project> {
    let path = path.map_or_else(|| PathBuf::from("."), Path::to_path_buf);
    let project = Project::open(&path)?;
    if project.is_empty() && !project.is_explicit() {
        anyhow::bail!(
            "no assembly source in {}; add a .asm file or run `ratasm new`",
            project.root().display()
        );
    }
    Ok(project)
}

/// Builds a project and prints the tool output.
async fn build_project(path: Option<&Path>, debug: bool) -> Result<ExitCode> {
    let project = resolve_project(path)?;
    let options = if debug {
        BuildOptions::debug()
    } else {
        BuildOptions::release()
    };

    let outcome = assembler::build(&project, options)
        .await
        .context("the build could not be run")?;

    print!("{}", outcome.raw_output());
    println!("{}", outcome.summary());

    Ok(if outcome.success {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    })
}

/// Builds and runs a project, forwarding its exit status.
async fn run_project(path: Option<&Path>) -> Result<ExitCode> {
    let project = resolve_project(path)?;
    let outcome = assembler::build(&project, BuildOptions::release())
        .await
        .context("the build could not be run")?;

    if !outcome.success {
        print!("{}", outcome.raw_output());
        println!("{}", outcome.summary());
        return Ok(ExitCode::FAILURE);
    }

    let executable = outcome
        .executable
        .clone()
        .context("the build reported success but produced no executable")?;

    let spec = assembler::run_command(&project, &executable);
    let outcome = ratasm::process::run_attached(&spec)
        .await
        .with_context(|| format!("cannot run {}", executable.display()))?;

    match outcome {
        ratasm::process::Outcome::Exited(0) => Ok(ExitCode::SUCCESS),
        other => {
            eprintln!("ratasm: program {}", other.description());
            Ok(ExitCode::FAILURE)
        }
    }
}

/// Reports whether the external tools ratasm needs are installed.
fn doctor() -> ExitCode {
    use ratasm::process::is_available;

    let checks: [(&str, &str, bool); 5] = [
        ("nasm", "assembling", true),
        ("ld", "linking", true),
        ("gdb", "debugging", false),
        ("gcc", "linking with libc (ratasm new --libc)", false),
        (
            "nvim",
            "editing with breakpoints and errors in the editor",
            false,
        ),
    ];

    let mut missing_required = false;
    println!("ratasm {}", env!("CARGO_PKG_VERSION"));
    println!();

    for (tool, purpose, required) in checks {
        let found = is_available(Path::new(tool));
        let mark = if found {
            "found"
        } else if required {
            missing_required = true;
            "MISSING"
        } else {
            "missing (optional)"
        };
        println!("  {tool:<5} {mark:<20} {purpose}");
    }

    if missing_required {
        println!();
        println!("Install the missing tools:");
        println!("  Debian/Ubuntu:  sudo apt install nasm binutils gdb");
        println!("  Fedora:         sudo dnf install nasm binutils gdb");
        println!("  Arch:           sudo pacman -S nasm binutils gdb");
        return ExitCode::FAILURE;
    }

    ExitCode::SUCCESS
}

/// Opens the terminal interface.
async fn open_interface(paths: &[PathBuf]) -> Result<ExitCode> {
    let settings = ratasm::config::Settings::load_default().unwrap_or_else(|error| {
        eprintln!("ratasm: {error}");
        ratasm::config::Settings::default()
    });

    let start = paths.first().map_or(Path::new("."), PathBuf::as_path);
    let project = match Project::open(start) {
        Ok(project) => project,
        Err(error) => {
            eprintln!("ratasm: {error}");
            Project::open(Path::new(".")).context("cannot open the current directory")?
        }
    };

    let mut app =
        ratasm::app::App::new(project, settings).context("cannot load the built-in databases")?;

    let (keymap, errors) = app.settings.keymap();
    app.keymap = keymap;
    if let Some(error) = errors.first() {
        app.status = ratasm::app::Status::warning(error.to_string());
    }

    let (files, missing): (Vec<&Path>, Vec<&Path>) = paths
        .iter()
        .map(PathBuf::as_path)
        .filter(|path| !path.is_dir())
        .partition(|path| path.is_file());

    if files.is_empty() {
        ratasm::app::run::open_project_entry(&mut app);
    } else {
        for path in files.iter().rev() {
            ratasm::app::run::open_initial_file(&mut app, path);
        }
    }

    if let Some(first) = missing.first() {
        app.status = ratasm::app::Status::warning(match missing.len() {
            1 => format!("{}: no such file", first.display()),
            count => format!("{}: no such file, and {} more", first.display(), count - 1),
        });
    }

    let indent = app.settings.indent_width();
    for index in 0..app.workspace.len() {
        app.workspace.set_active(index);
        app.workspace.active_mut().set_indent_width(indent);
    }
    app.workspace.set_active(0);
    if let Some(path) = ratasm::app::session::path_for(app.project.root()) {
        ratasm::app::session::restore(&mut app, &path, files.is_empty());
    }
    app.refresh_project_files();

    let mut guard = ratasm::ui::TerminalGuard::new()
        .context("cannot set up the terminal; is this running in a real terminal?")?;

    let result = ratasm::app::run(app, guard.terminal_mut()).await;
    drop(guard);
    result?;
    Ok(ExitCode::SUCCESS)
}

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

    #[test]
    fn the_command_line_definition_is_valid() {
        Cli::command().debug_assert();
    }

    #[test]
    fn no_arguments_opens_the_interface() {
        let cli = Cli::try_parse_from(["ratasm"]).expect("parse");
        assert!(cli.command.is_none());
        assert!(cli.paths.is_empty());
    }

    #[test]
    fn a_bare_path_is_the_file_to_open() {
        let cli = Cli::try_parse_from(["ratasm", "src/main.asm"]).expect("parse");
        assert_eq!(cli.paths, vec![PathBuf::from("src/main.asm")]);
        assert!(cli.command.is_none());
    }

    #[test]
    fn several_paths_are_all_files_to_open() {
        let cli = Cli::try_parse_from(["ratasm", "src/main.asm", "src/util.asm"]).expect("parse");
        assert_eq!(
            cli.paths,
            vec![PathBuf::from("src/main.asm"), PathBuf::from("src/util.asm")]
        );
    }

    #[test]
    fn subcommands_parse_with_their_arguments() {
        let cli = Cli::try_parse_from(["ratasm", "new", "hello"]).expect("parse");
        assert!(
            matches!(cli.command, Some(Command::New { name, libc: false, make: false }) if name == "hello")
        );
        let cli = Cli::try_parse_from(["ratasm", "new", "--make", "m"]).expect("parse");
        assert!(matches!(cli.command, Some(Command::New { make: true, .. })));
        assert!(Cli::try_parse_from(["ratasm", "new", "--make", "--libc", "m"]).is_err());
        let cli = Cli::try_parse_from(["ratasm", "new", "--libc", "c"]).expect("parse");
        assert!(matches!(cli.command, Some(Command::New { libc: true, .. })));

        let cli = Cli::try_parse_from(["ratasm", "build", "--debug"]).expect("parse");
        assert!(matches!(
            cli.command,
            Some(Command::Build { debug: true, .. })
        ));

        let cli = Cli::try_parse_from(["ratasm", "run", "demo"]).expect("parse");
        assert!(
            matches!(cli.command, Some(Command::Run { path: Some(p) }) if p == Path::new("demo"))
        );

        let cli = Cli::try_parse_from(["ratasm", "doctor"]).expect("parse");
        assert!(matches!(cli.command, Some(Command::Doctor)));
    }

    #[test]
    fn version_and_help_are_available() {
        let error = Cli::try_parse_from(["ratasm", "--version"]).expect_err("exits");
        assert_eq!(error.kind(), clap::error::ErrorKind::DisplayVersion);
        assert!(error.to_string().contains(env!("CARGO_PKG_VERSION")));

        let error = Cli::try_parse_from(["ratasm", "--help"]).expect_err("exits");
        assert_eq!(error.kind(), clap::error::ErrorKind::DisplayHelp);
    }

    #[test]
    fn a_word_that_is_not_a_subcommand_is_taken_as_a_path() {
        let cli = Cli::try_parse_from(["ratasm", "frobnicate", "x"]).expect("parse");
        assert!(cli.command.is_none());
        assert_eq!(cli.paths.len(), 2);
    }

    #[test]
    fn an_unknown_flag_is_still_rejected() {
        assert!(Cli::try_parse_from(["ratasm", "--frobnicate"]).is_err());
    }

    #[test]
    fn log_options_are_global() {
        let cli =
            Cli::try_parse_from(["ratasm", "build", "--log-file", "/tmp/r.log"]).expect("parse");
        assert_eq!(cli.log_file, Some(PathBuf::from("/tmp/r.log")));
        assert_eq!(cli.log_filter, "info");
    }

    #[test]
    fn resolving_a_project_from_a_lone_file_succeeds() {
        let dir = tempfile::tempdir().expect("temp dir");
        let source = dir.path().join("lone.asm");
        std::fs::write(&source, "ret\n").expect("write");

        let project = resolve_project(Some(&source)).expect("resolve");
        assert_eq!(project.entry_path(), source);
    }

    #[test]
    fn a_folder_of_sources_is_a_project_and_an_empty_one_is_explained() {
        let dir = tempfile::tempdir().expect("temp dir");
        let error = resolve_project(Some(dir.path())).expect_err("nothing to build");
        assert!(error.to_string().contains("no assembly source"), "{error}");

        std::fs::write(dir.path().join("prog.asm"), "global _start\n_start:\n").expect("write");
        let project = resolve_project(Some(dir.path())).expect("resolve");
        assert!(project.entry_path().ends_with("prog.asm"));
    }

    #[test]
    fn creating_a_project_into_a_non_empty_directory_is_refused() {
        let dir = tempfile::tempdir().expect("temp dir");
        std::fs::write(dir.path().join("existing.txt"), "keep me").expect("write");

        let previous = std::env::current_dir().expect("cwd");
        std::env::set_current_dir(dir.path()).expect("chdir");
        std::fs::create_dir("taken").expect("mkdir");
        std::fs::write("taken/file.txt", "keep me").expect("write");

        let result = new_project("taken", false, false);
        std::env::set_current_dir(previous).expect("restore cwd");

        assert!(result.is_err(), "must not overwrite an occupied directory");
    }
}