tracing icon indicating copy to clipboard operation
tracing copied to clipboard

`instrument` attribute incompatible with inner attributes inside function

Open dtolnay opened this issue 3 years ago • 2 comments

Bug Report

Version

└── tracing v0.1.36
    ├── tracing-attributes v0.1.22 (proc-macro)
    └── tracing-core v0.1.29

Platform

Linux rust 5.15.0-46-generic #49-Ubuntu SMP Thu Aug 4 18:03:25 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

Description

use tracing::instrument;

#[instrument]
fn foo() {
    #![allow(dead_code)]

    struct Struct {}
}
$ cargo check

error: an inner attribute is not permitted in this context
 --> src/main.rs:5:5
  |
3 | #[instrument]
  | ------------- the inner attribute doesn't annotate this function
4 | fn foo() {
5 |     #![allow(dead_code)]
  |     ^^^^^^^^^^^^^^^^^^^^
  |
  = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files
help: to annotate the function, change the attribute from inner to outer style
  |
5 -     #![allow(dead_code)]
5 +     #[allow(dead_code)]
  |

This works without the instrument macro and it seems like it should be reasonable for instrument to support.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9c6afbe0ad161308d88f9cf02dfd1178

dtolnay avatar Aug 31 '22 19:08 dtolnay

Thanks for the report, it definitely should be possible to use inner attributes!

My guess is that the issue is because #[instrument] currently just captures the entire function body as a block, and generates a function body that consists of code generated by #[instrument] followed by the entire contents of the function body. If the function body begins with inner attributes, that would mean that we insert the code generated by #[instrument] before the inner attributes, making them invalid.

To fix this, we would need to handle the case where the function body begins with inner attributes by capturing them separately and inserting them before the code added by #[instrument].

hawkw avatar Aug 31 '22 21:08 hawkw

This would probably be a fairly straightforward fix for a new contributor to tracing who has some familiarity with proc-macros in general, so I'm adding the good first issue label. Happy to provide guidance for anyone who wants to look into this!

hawkw avatar Aug 31 '22 21:08 hawkw