Fixing spurious "statement is not reachable" in template code

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Tue Oct 27 05:28:40 PDT 2015


On 10/26/15 1:08 PM, tsbockman wrote:
> On Monday, 26 October 2015 at 12:31:37 UTC, Steven Schveighoffer wrote:
>>> Some possible solutions:
>>>
>>> 1. Defer "not reachable" warnings until compilation has been completed,
>>> and only issue the warning if *all* instantiations of the statement were
>>> unreachable.
>>
>> This isn't good either. One instantiation of reachIf being able to
>> compile shouldn't be dependent on whether another one was ever used.
>
> I agree this is not ideal, however it would be much better than what we
> have currently, and the compiler implementation should be relatively
> simple.
>
>>> 2. For semantic analysis purposes, first instantiate each template using
>>> dummy parameters with the widest possible VRP ranges. Only statements
>>> found to be "not reachable" in this dummy run should actually generate
>>> warnings.
>>
>> How does the compiler figure this out? This seems like the halting
>> problem to me.
>
> My solution #2 is the same as the one you proposed - the dummy parameter
> stuff is my vague proposal for a way to actual implement this behavior
> in the compiler.
>
> The halting problem is no more of an issue than it is for the compiler
> today. (That is to say, the halting problem leads to false negatives,
> but not false positives.)

OK, as long as the default behavior isn't to reject the code, I suppose 
this is simply an optimization. But the problem I see is that only 
static ifs that reduce to static if(true) would be considered to cause a 
short-circuit (e.g. someint <= int.max). Unless the compiler can VRP 
according to the template constraint, which may be possible in simple 
circumstances, but not in all circumstances.

It just seems like it's an unnecessary layer. I think we should start 
with the simple accept all code that branches based on compile-time 
variables.

> The reason solution #2 could end up being a ton of work, is that a dummy
> type will have to be created to apply this solution to cases like:
>
> module main;
>
> import std.stdio;
>
> void reachIf(T...)()
> {
>      if(T.length != 1 || T[0].sizeof != 4)
>          return;
>      writeln("reached"); // Warning: statement is not reachable
> }

Inherent properties of types that can be variable could be considered 
variables just like any other size_t or int. Therefore, branching based 
on that would fall under the same issue.

I think the "ton of work" is avoidable.

-Steve


More information about the Digitalmars-d mailing list