Skip to content

Commit

Permalink
Improve diagnostics for mismatched type in async main
Browse files Browse the repository at this point in the history
Previously, we wrapped the body of the `async main` function in an
`async` block, which we passed to `block_on`. However, `block_on` is
generic, so an incorrect return type ends up creating a diagnostic
pointing a `block_on`, not the user's code. Since the call to `block_on`
is generated by the `#[tokio::main]` macro, it ended up with a span of
the `#[tokio::main]` attribute, producing a confusing diagnostic.

We now wrap the body of the `async main` function in a new
`async main_inner` function. This asserts a return type of `()` earlier
on, producing a diagnostic.

Given this code:

```rust
async fn main() {
    Ok(())
}
```

We currently produce the error:

```
error[E0308]: mismatched types
 --> src/main.rs:1:1
  |
1 | #[tokio::main]
  | ^^^^^^^^^^^^^^- help: try adding a semicolon: `;`
  | |
  | expected `()`, found enum `std::result::Result`
  |
  = note: expected unit type `()`
                  found enum `std::result::Result<(), _>`
  = note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
```

With this PR, we produce:

```
error[E0308]: mismatched types
 --> src/main.rs:3:5
  |
3 |     Ok(())
  |     ^^^^^^- help: try adding a semicolon: `;`
  |     |
  |     expected `()`, found enum `std::result::Result`
  |
  = note: expected unit type `()`
                  found enum `std::result::Result<(), _>`
```
  • Loading branch information
Aaron1011 committed Oct 24, 2020
1 parent ce173fd commit 8b060aa
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion tokio-macros/src/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,15 +240,21 @@ fn parse_knobs(
}
};

let ret_ty = &sig.output;

let result = quote! {
#header
#(#attrs)*
#vis #sig {
// Asssert the return type here,
// which produces a better diagnostic
async fn main_inner() #ret_ty #body

#rt
.enable_all()
.build()
.unwrap()
.block_on(async { #body })
.block_on(main_inner())
}
};

Expand Down

0 comments on commit 8b060aa

Please sign in to comment.