dmd icon indicating copy to clipboard operation
dmd copied to clipboard

WIP: Deprecate using variables declared in loops from closures

Open tim-dlang opened this issue 2 months ago • 1 comments

Using variables declared in loops from a closure can have unexpected results and be unsafe (issue #19929). Fixing the problem would silently change the behaviour of code and result in more allocations, so deprecating the affected code first avoids surprises. A new implementation could later be introduced using a preview switch or editions.

Limitations:

  • Loops manually created with goto are not detected.
  • Problems involving lazy can be undetected, because of separate issues like #18669.
  • Local functions, which don't escape, can result in false positives, because the compiler does not always know they don't escape. This can sometimes be fixed by marking delegate parameters as scope. This can also affect range based code.
  • Loops with at most one iteration are still treated as loops and could be considered false positives.
  • Closures, which are only used in the last iteration of a loop, still can result in the deprecation warning, which could be considered a false positive.
  • There can also be false negatives, when a scope delegate escapes the loop, but not the function.

tim-dlang avatar Oct 04 '25 09:10 tim-dlang

Thanks for your pull request and interest in making D better, @tim-dlang! We are looking forward to reviewing it, and you should be hearing from a maintainer soon. Please verify that your PR follows this checklist:

  • My PR is fully covered with tests (you can see the coverage diff by visiting the details link of the codecov check)
  • My PR is as minimal as possible (smaller, focused PRs are easier to review than big ones)
  • I have provided a detailed rationale explaining my changes
  • New or modified functions have Ddoc comments (with Params: and Returns:)

Please see CONTRIBUTING.md for more information.


If you have addressed all reviews or aren't sure how to proceed, don't hesitate to ping us with a simple comment.

Bugzilla references

Your PR doesn't reference any Bugzilla issue.

If your PR contains non-trivial changes, please reference a Bugzilla issue or create a manual changelog.

⚠️⚠️⚠️ Warnings ⚠️⚠️⚠️

  • In preparation for migrating from Bugzilla to GitHub Issues, the issue reference syntax has changed. Please add the word "Bugzilla" to issue references. For example, Fix Bugzilla Issue 12345 or Fix Bugzilla 12345.(Reminder: the edit needs to be done in the Git commit message, not the GitHub pull request.)

Testing this PR locally

If you don't have a local development environment setup, you can use Digger to test this PR:

dub run digger -- build "master + dmd#21936"

dlang-bot avatar Oct 04 '25 09:10 dlang-bot