[Concept / Pre-RFC] Self Correcting Compiler

EDIT: Turns out this already exists. If you want it, you can use cargo fix, or cargo clippy --fix. Thanks to people in the replies for letting me know about this!

I'll leave the idea here for archival purposes.


My idea is to make the compiler be able to self-correct in certain circumstances.

Let's say you're working on a Hello World program, by example.

fn main() {
  let hello_world = "Hello world!";
  priintln!(hello_world);

This will return an error.

error: format argument must be a string literal
 --> test.rs:3:14
  |
3 |     println!(hello_world);
  |              ^^^^^^^^^^^
  |
help: you might be missing a string literal to format with
  |
3 |     println!("{}", hello_world);
  |              +++++

But the compiler already knows the solution and gives it to the user. So, why not expand on this and have the compiler self-correct?

error: format argument must be a string literal
 --> test.rs:3:14
  |
3 |     println!(hello_world);
  |              ^^^^^^^^^^^
  |
help: you may be missing a string literal to format with
  |
3 |     println!("{}", hello_world);
  |              +++++
autocorrect: would you like to autocorrect this error? (y/n)

You could either type in 'y' or 'n', and if you type in 'y' it will self-correct. There could also be a compiler flag "--auto-correct" to automatically correct these small errors for you without having to type in y/n.

This could be useful in large projects where compilation takes an extremely long time. You don't want to recompile the whole thing because someone missed a string literal or a symbol. It could also help save the developers a small amount of time - they don't have to go back, find the file, add the missing thing and then recompile.

I don't know in practice how well this would work, so I'm posting this as a concept/pre-rfc here to get feedback.

1 Like

There is an existing command line flag for this: cargo check --fix. This is implemented by the compiler emitting structured diagnostics, then cargo reads these suggestions and applies them to the source code; if you look at this example you can see in the second line there's a suggested_replacement for the macro name (though in this case it won't auto-apply because "suggestion_applicability":"MaybeIncorrect", it only applies guaranteed correct fixes unless you pass more flags). It would be possible to build an interactive tool using these same suggestions, which is also how I assume some of rust-analyzer's IDE suggestions work.

3 Likes

cargo check --fix

Just to correct this, it should be cargo fix.

2 Likes

Ah, whoops, I only ever interact with it through cargo clippy --fix nowadays, forgot the UI was different without clippy.

What's the difference between cargo fix and cargo clippy --fix?

I presume cargo clippy --fix handles clippy diagnostics, not just rustc diagnostics.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.