rust-lang / rust-lang/rust

An unexpected expanded result from procedural macro

Open
#125,138 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-pretty A-proc-macros C-bug T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code to check the expanded HIR by flag -Z unpretty=hir:

// file proc_macro
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Expr};

#[proc_macro]
pub fn mdriver(input: TokenStream) -> TokenStream {
    let expr = parse_macro_input!(input as Expr);

    let expanded = quote! {
        fn foo() {
            #expr?;
        }
    };

    TokenStream::from(expanded)
}

//file call the macro
mdriver!(0..10);

I expected to see this happen:

fn foo() {
        match #[lang = "branch"](#[lang = "Range"]{ start: 0,  end: 10,}) {
                #[lang = "Break"] {  0: residual } =>
                    #[allow(unreachable_code)]
                    return #[lang = "from_residual"](residual),
                #[lang = "Continue"] {  0: val } =>
                    #[allow(unreachable_code)]
                    val,
            };
    }

Instead, this happened:

fn foo() {
        #[lang = "Range"]{
            start: 0,

            end:
                match #[lang = "branch"](10) {
                        #[lang = "Break"] {  0: residual } =>
                            #[allow(unreachable_code)]
                            return #[lang = "from_residual"](residual),
                        #[lang = "Continue"] {  0: val } =>
                            #[allow(unreachable_code)]
                            val,
                    },};
    }
Meta

rustc --version --verbose:

rustc 1.80.0-nightly (ef0027897 2024-05-12)
binary: rustc
commit-hash: ef0027897d2e9014766fb47dce9ddbb925d2f540
commit-date: 2024-05-12
host: x86_64-unknown-linux-gnu
release: 1.80.0-nightly
LLVM version: 18.1.4
Backtrace

<backtrace>

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the procedural-macro example with the nightly compiler and inspect its output using -Z unpretty=hir. Compare the expansion of mdriver!(0..10) with the expected and actual HIR shown in the issue; done means determining why the ? expression is expanded inside the range literal and correcting that behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.