Skip to content

bug: #[tracing::instrument] reorders async and unsafe keywords #2576

@ParkMyCar

Description

@ParkMyCar

Bug Report

Version

tracing v0.1.37

Platform

Darwin Parkers-MacBook-Pro.local 22.4.0 Darwin Kernel Version 22.4.0: Mon Mar  6 20:59:58 PST 2023; root:xnu-8796.101.5~3/RELEASE_ARM64_T6020 arm64

Crates

tracing

Description

Currently you cannot use the #[tracing::instrument] macro to instrument an unsafe async function. The problem is the macro re-orders the async and unsafe keywords in the wrong order.

Minimum Repro:

use tracing;

#[tracing::instrument]
async unsafe fn foo() -> usize {
    42
}

Playground

This fails to compile with the error:

error: expected one of `extern` or `fn`, found keyword `async`
 --> src/lib.rs:4:1
  |
4 | async unsafe fn foo() -> usize {
  | ^^^^^-------
  | |
  | expected one of `extern` or `fn`
  | help: `async` must come before `unsafe`: `async unsafe`
  |
  = note: keyword order for functions declaration is `pub`, `default`, `const`, `async`, `unsafe`, `extern`

error: could not compile `playground` due to previous error

Using rust-analyzer you can see what this expands to:

unsafe async fn bar< >() -> usize {
  {}
  let __tracing_attr_span = tracing::span!(target:module_path!(),tracing::Level::INFO,"bar",);
  let __tracing_instrument_future = async move {
    #[allow(unreachable_code,clippy::diverging_sub_expression,clippy::let_unit_value,clippy::unreachable)]
    if false {
      let __tracing_attr_fake_return:usize = unreachable!("this is just for type inference, and is unreachable code");
      return __tracing_attr_fake_return;
    }{
      42
    }
  };
  if!__tracing_attr_span.is_disabled(){
    tracing::Instrument::instrument(__tracing_instrument_future,__tracing_attr_span).await
  }else {
    __tracing_instrument_future.await
  }
}

And indeed if you look at the first line of the expansion you can see unsafe async when it should be async unsafe.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions