PSA: rejecting duplicate loop labels

In order to future-proof potential future changes to the language, I am currently planning to add a static check to the compiler that will reject code that uses the same label multiple times within a single function body.

(The motivation for this is to future-proof support for using such labels as a way to identify code-extents explicitly, for use with a &'a expr expression form; currently borrow-expressions cannot be given an explicit lifetime, but that may change in the future.)


In particular, code like this will start to be rejected at compile-time:

fn foo() {
    'a: while test() {
        'a: loop { ... more stuff ... }
        ...
    }
}

while code like this will continue to be accepted:

fn bar() {
    'a: while test() {
        fn baz() { 'a: loop { ... more stuff ... } }
        ...
    }
}

This is obviously a breaking change. My hope is that it will not break too much code, but I have not yet attempted to evaluate the actual scope of the breakage.

If you have a strong opinion on the matter, feel free to voice it here.


See also discussion here, which documents my original (less aggressive) block-local plan for change here, and the problem with that plan:

I didn’t even realize duplicate loop labels was valid. I’m guessing that this change will impact very little code.

I’m assuming this would also disallow having a loop label with the same name as a lifetime bound?

For example:

fn hi<'a>(s: &'a str) -> &'a str {
    'a: loop {
        break 'a;
    }
    return s;
}

No, I did not go that far.

(Maybe I should have...; let me go skim over how niko did those hard-errors on lifetime shadowing)

Ok, just checking that. It seems like if in the future loop labels would be allowed as lifetime bounds, they wouldn’t want to conflict with existing lifetime bounds as well.

Yes, I ended up revising the Pull Request to treat lifetime names in scope as conflicting with labels as well (and vice-versa) – i.e. basically the recent change to make lifetime-shadowing a hard-error has been strengthened to also reject shadowing of/by labels.

Thanks for the note, it was a good catch.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.