5

I am using the Rust extension on vscode and NOT rust-analyzer. However, when I am saving a file, vscode is using rustfmt to format my file but it doesn't automatically insert semicolons. I have a trivial function like this

fn call_me() {
  let x = 5
  println!(x)
}

It doesn't add the necessary semicolons. How do I make it add semicolons? Are my installations somehow messed up?

Also, I have tried rust-analyzer and it doesn't add semicolons either.

Aritra Dattagupta
  • 760
  • 1
  • 7
  • 22
  • 2
    Why would you want semicolon insertion? Rust semicolons change program behavior so inserting them could break stuff? – PiRocks May 01 '21 at 21:26
  • You're right. But shouldn't the editor scream at me with red squiggly lines complaining about possible errors? Vim coc-rust-analyzer screams at me but vscode doesn't. Only when I am trying to compile the file, it shows me the possible error. – Aritra Dattagupta May 01 '21 at 21:38
  • 1
    Why aren't you using rust-analyzer? It is 1000x better. – Ibraheem Ahmed May 01 '21 at 22:17
  • 1
    rust-analyzer is also not showing errors until I compile. vim coc-rust-analyzer is working flawlessly though. Any idea why vscode rust isn't showing me errors? – Aritra Dattagupta May 02 '21 at 07:41
  • 1
    "semicolons change program behavior" This is only true in certain situations, in the given example it would be safe to insert a semicolon on line 2. – chantey Dec 09 '22 at 00:22

2 Answers2

10

Unlike JavaScript, semicolons are not syntactically optional in Rust. Thus, leaving them out is a syntax error, not just a matter of style, and rustfmt (the standard Rust code formatting tool) doesn't ever attempt to fix any syntax errors, no matter how “obvious” they might be — if it reads a file with errors it will not make any formatting changes.

(I don't know if there's a way to get rust-analyzer, vim, or VS Code to auto-insert semicolons as a matter of editing rather than formatting.)

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
3

Maybe not what you're looking for but there are language-agnostic options to reduce the friction of semicolon insertion.

For instance the vs code extension colonize adds the shortcut alt+enter which appends a semicolon and newline, no matter where in the line the cursor is.

chantey
  • 4,252
  • 1
  • 35
  • 40