Bug 21633 – anonymous class local scope confusion

Status
NEW
Severity
enhancement
Priority
P4
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2021-02-13T02:09:25Z
Last change time
2024-12-13T19:14:43Z
Assigned to
No Owner
Creator
Adam D. Ruppe
Moved to GitHub: dmd#19873 →

Comments

Comment #0 by destructionator — 2021-02-13T02:09:25Z
Can you guess what this code does: --- class A { int a; } A createMyClass() { int a; return new class A { this() { this.a = a; } }; } --- It is a self-assignment, since `a` inside the anonymous class refers to `this.a`, not the immediately-obvious local variable. Here, you probably saw it kinda quickly, but now imagine class A was out of sight, out of mind and the variable was some protected thing or something you would barely think about. That happened to me recently and I was perplexed for a while. dmd's behavior isn't wrong per spec, thus I'm calling this an enhancement, but it certainly isn't useful to have code that looks right, compiles just fine, but then does nothing. Perhaps ALL self-assignments should be an error, but that'd probably be a pain in the butt. This pattern though surely should be *something* since it definitely isn't what I'd ever intend to write intentionally. Moreover, there's currently no way to actually access that local `a` inside that constructor. Just have to rename the variable when the silent conflict is diagnosed. Not fun.
Comment #1 by destructionator — 2021-02-13T02:25:32Z
Well, upon a review of Java and the D spec, there is a way, pass it as a constructor arg: return new class (a) A { this(int a) { this.a = a; } }; What a weird syntax. In Java it is `new A(a) { }` which is a little less strange. But whatever, this is a possible solution to use the var without renaming it. So I retract that part. I still think the scope behavior, while legal, is problematic to the human eye though, so leaving this enhancement request open.
Comment #2 by robert.schadek — 2024-12-13T19:14:43Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/19873 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB