non-hygienic lifetime-shadowing check can make macros non-modular

35174fb
Opened by Felix S Klock II at 2024-12-12 23:11:06

non-hygienic lifetime-shadowing check can make macros non-modular

This is sort of related to #24278

Here is some example code (playpen)

macro_rules! foo {
    ($m:ident) => {
        fn $m<'a>(x: &'a i8) -> i8 { *x }
    }
}

struct Foo<'a>(&'a i8);

impl<'a> Foo<'a> {
    foo!(bar);
    fn baz() -> i8 {
        let x = 3_i8;
        Foo::bar(&x)
    }
}

fn main() {
    println!("{}", Foo::baz());
}

This yields the error:

<anon>:3:15: 3:17 error: lifetime name `'a` shadows a lifetime name that is already in scope
<anon>:3         fn $m<'a>(x: &'a i8) -> i8 { *x }

The problem is that there is no way for the macro author to make their macro robust against all possible contexts here. In other words, the referential transparency component of hygiene demands that the lifetimes introduced by an expansion be treated as fresh, but they are not.

(Of course, there are plenty of other ways that our macro system is not hygienic, so this is likely to be filed away as a known weakness in macro_rules!. I just wanted to have a place to reference this problem.)

  1. Triage: no change

    Steve Klabnik at 2017-01-03 17:50:39

  2. Triage: still no change. I'm not sure that this is going to ever be fixed.

    Steve Klabnik at 2019-12-25 16:12:31

  3. At this point, I think we'd want an RFC before changing this.

    Aaron Hill at 2022-01-15 18:11:49

  4. Note that while lifetime resolution strips away the 'mixed-site' hygiene generated by macro_rules!, it does not remove the 'def-site' hygiene created by macros 2.0. As a result, the following code compiles:

    #![feature(decl_macro)]
    
    macro foo {
        () => {
            fn dummy<'a>(x: &'a i8) -> i8 { *x }
        }
    }
    
    struct Foo<'a>(&'a i8);
    
    impl<'a> Foo<'a> {
        foo!();
        fn baz() {
            let x = 3_i8;
        }
    }
    
    fn main() {}
    

    The 'a lifetime created by macro foo has opaque (def-site) hygiene, which does not conflict with the 'a lifetime declared in impl<'a>

    Aaron Hill at 2022-01-16 22:42:19