Bug 13575 – Unreachable scope(failure) should be warned
Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P4
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-10-06T12:47:53Z
Last change time
2023-11-14T17:20:42Z
Keywords
diagnostic
Assigned to
No Owner
Creator
Kenji Hara
Comments
Comment #0 by k.hara.pg — 2014-10-06T12:47:53Z
From issue 11574:
import std.stdio;
void someFunc()
{
scope(failure) { writeln("What?");} // <-- never executed.
scope(failure) {
writeln("Failed in someFunc()");
return;
}
throw new Exception("Exception!");
}
void main() {
try {
someFunc();
writeln("Yay, someFunc() is nothrow");
} catch(Exception e) {
writeln("An exception in main!");
}
}
In someFunc, the first scope(failure) is never executed. There's no bug, but I think, if -w specified, dmd should warn the code as that it is not reachable.
Comment #1 by witold.baryluk+d — 2020-01-17T16:28:46Z
Your example is pretty good, but not good enough as it introduces other issue, that prevents compiler from optimizing it properly.
The writeln("Failed in someFunc()") can fail with the exception (i.e. if the stdout was a pipe into other process, and that process died, or it was redirected to a file, and there was IO error or disk is full / out of quota, just some examples)! And then the first scope(failure) which can in fact execute!
Better example:
```
int i = 0;
size_t f(string x) nothrow {
scope(failure) {
i = 5;
return 30;
}
scope(failure) {
i = 10;
return 42;
}
throw new Exception("a");
}
int main(string[] args) {
return cast(int)f(args[0]) + i*i;
}
```
Notice that I also added `nothrow` and made scopes use code that can't throw on its own.
The compiler doesn't even recognize that the first `scope(failure)` is not dead code. I still see it in the disassembly of the binary.
When I run the code it does return 142, as expected.
If I change the code to:
```
int i = 0;
size_t f(string x) nothrow {
scope(failure) {
i = 5;
return 30;
}
scope(failure) {
i = 10;
throw new Exception("b");
}
throw new Exception("a");
}
int main(string[] args) {
return cast(int)f(args[0]) + i*i;
}
```
The code correctly returns 55.
Comment #2 by witold.baryluk+d — 2020-01-17T16:29:23Z
Ah, obviously I did forgot to mention that compiler does not warn about my first example.
But it should.