Skip to content

Proc macros can cause non-json output in stdout despite message-format=json #8179

@roblabla

Description

@roblabla

Problem

When proc macros print to stdout, the output is reflected in the cargo output. For instance, the following proc macro will cause Hello to be printed in the compiler output, even when message-format=json is passed, even though it's not a valid JSON object. This will cause various tools (such as cargo-metadata, rust-analyzer, jq...) to fail to parse the message, and give up.

extern crate proc_macro;
use proc_macro::TokenStream;

#[proc_macro_attribute]
pub fn hello(_attr: TokenStream, item: TokenStream) -> TokenStream {
    println!("Hello");
    item
}

I'm not sure if this is considered a cargo or a rustc bug ^^'.

Steps

  1. Install jq
  2. git clone https://github.com/roblabla/cargo-proc-macro-print-bug
  3. cargo build --message-format=json | jq .

This will cause jq to error with "parse error: Invalid numeric literal at line 3, column 0", which is caused by the string "Hello", printed by the proc macro, to appear in stdout.

Possible Solution(s)
I imagine the proc macro output could be:

  • Ignored/silenced
  • Wrapped in a CompilerMessage JSON object
  • Wrapped in a new kind of JSON object, maybe a GenericMessage?

Notes

cargo 1.42.0 (8633429 2020-01-31)
rustc 1.42.0 (b8cedc004 2020-03-09)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-documenting-cargo-itselfArea: Cargo's documentationA-json-outputArea: JSON message outputC-bugCategory: bugS-blocked-externalStatus: ❌ blocked on something out of the direct control of the Cargo project, e.g., upstream fix

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions