metrics-rs / metrics

A metrics ecosystem for Rust.
MIT License
1.1k stars 151 forks source link

Strange macro compilation error with aliasing of `metrics` #357

Closed CinchBlue closed 1 year ago

CinchBlue commented 1 year ago

Not sure if this is just a nightly compiler bug, but here's what I see:

I am trying to use the macros like so:


use framework::*; // This exposes mod `framework::metrics`.
use ::metrics::{Key, Label, recorder};

const UPLOAD_METRIC_NAME: &'static str = "some_metric"; 
const UPLOAD_METRIC_LABEL_SUCCESS: &'static str = "success";
const UPLOAD_METRIC_LABEL_PROCESS_TYPE: &'static str = "process_type"; 

#[inline]
pub fn register_metrics() {
    ::metrics::register_counter!(UPLOAD_METRIC_NAME,
        &[
            (UPLOAD_METRIC_LABEL_COMP_ID, ""),
            (UPLOAD_METRIC_LABEL_SUCCESS, ""),
        ]
    );
}

this results in a compilation error. with RUSTFLAGS='-Z macro-backtrace' cargo build on my workspace:

error[E0425]: cannot find function `recorder` in crate `metrics`
   --> ingestion-utils/src/upload_game.rs:20:5
    |
20  | /     ::metrics::register_counter!(UPLOAD_METRIC_NAME,
21  | |         &[
22  | |             (UPLOAD_METRIC_LABEL_COMP_ID, ""),
23  | |             (UPLOAD_METRIC_LABEL_SUCCESS, ""),
24  | |         ]
25  | |     );
    | |     ^
    | |     |
    | |_____not found in `metrics`
    |       in this macro invocation
    |
   ::: /home/dev/.cargo/registry/src/github.com-1ecc6299db9ec823/metrics-macros-0.6.0/src/lib.rs:130:1
    |
130 |   pub fn register_counter(input: TokenStream) -> TokenStream {
    |   ---------------------------------------------------------- in this expansion of `::metrics::register_counter!`
    |
help: consider importing one of these items
    |
1   | use crate::upload_game::recorder;
    |
1   | use metrics::recorder;

Maybe a macro scoping issue? Not exactly sure what's going on. But it's preventing me from using metrics in my crate right now.

CinchBlue commented 1 year ago
$ cargo --version
cargo 1.66.0-nightly (f5fed93ba 2022-09-27)
CinchBlue commented 1 year ago

I have just created a PR for a fix. Essentially it seems we want something like $crate in the procedural macro, but I don't know spans well enough to mutate the current implementation to use it. So this should be a nice to still allow ::metrics to be used even if some use foo::metrics is imported.

CinchBlue commented 1 year ago

I can also confirm that this fixes my compilation issue locally if I use the PR branch with my workspace:

[workspace.dependencies]
metrics = { git = "https://github.com/CinchBlue/metrics", branch = "refactor/metrics-macros/global-paths" }