radian-software / apheleia

🌷 Run code formatter on buffer contents without moving point, using RCS patches and dynamic programming.
MIT License
558 stars 75 forks source link

Use cargo to run rustfmt #140

Closed jtdowney closed 1 year ago

jtdowney commented 1 year ago

While attempting to format Rust code that uses async functions and new syntax, apheleia runs rustfmt without an edition specified, which causes an error. This change uses cargo fmt instead, which uses the configured Rust edition from the Cargo.toml file to invoke rustfmt.

This is the error I was getting before the change:

$ rustfmt --quiet --emit stdout

error[E0670]: `async fn` is not permitted in Rust 2015
 --> <stdin>:5:1
  |
5 | async fn main() -> Result<(), Box<dyn std::error::Error>> {
  | ^^^^^ to use `async fn`, switch to Rust 2018 or later
  |
  = help: pass `--edition 2021` to `rustc`
  = note: for more on editions, read https://doc.rust-lang.org/edition-guide

error: expected one of `!`, `)`, `,`, `.`, `::`, `?`, `{`, or an operator, found keyword `move`
  --> <stdin>:11:21
   |
11 |     tokio::spawn(async move {
   |                        ^^^^ expected one of 8 possible tokens

Command failed with exit code 1.
jtdowney commented 1 year ago

I'll get the tests fixed and push another commit when I get some time.

jtdowney commented 1 year ago

After digging into this, it appears I was mistaken, and cargo fmt can't be used because it formats everything, not a single file. However, as a workaround, you can tell rustfmt about the edition in rustfmt.toml as well, and that works with apheleia as is.

raxod502 commented 1 year ago

Ah gotcha. Cool, thanks!

dallagi commented 1 year ago

FYI you can also set the rust edition within your emacs config as an argument to rustfmt instead of an external rustfmt.toml file, like this:

(add-to-list 'apheleia-formatters '(rustfmt . ("rustfmt" "--quiet" "--emit" "stdout" "--edition" "2021")))