DIP 1017--Add Bottom Type--Final Review

Meta jared771 at gmail.com
Tue Jan 15 19:05:00 UTC 2019


On Tuesday, 15 January 2019 at 18:51:13 UTC, Johannes Loher wrote:
> Will inference only work if expressions evaluating to `Tbottom` 
> are returned, or is inference for simple things like
>
> ```
> auto fun()
> {
>     while(true) {}
> }
> ```
>
> planned? (Obviously this cannot be done in all cases as it is 
> equivalent to the halting problem)

Looks like the compiler already some some kind of analysis to 
determine if there's a common type for different runtime branches:

import std.stdio;

auto test(int n, float f)
{
     if (n > 0)
         return n;
     else
         return f;
}

auto test2(int n, string s)
{
     if (n > 0)
         return n;
     else
         return s; // Error: mismatched function return type 
inference of string and int
}

void main()
{
     //Works the same way in CTFE as at runtime
     pragma(msg, test(0, 0.1), " ", typeof(test(0, 
0.1)).stringof); // prints "0.1 float"
     writeln(test(0, 0.1), " ", typeof(test(0, 0.1)).stringof);    
  // ditto

     pragma(msg, test(1, 0.1), " ", typeof(test(1, 
0.1)).stringof); // prints "1.0000 float
     writeln(test(1, 0.1), " ", typeof(test(1, 0.1)).stringof);    
  // ditto
}


This is actually pretty cool, because if the type checker finds 
that one branch of the function returns Bottom, it can 
automatically assume that the return type is the type of the 
other branch, because a function returning T | Bottom can be 
simplified to a function returning just T. This is because iff 
the function returns, it must return a value of type T; 
otherwise, it will not return at all.


More information about the Digitalmars-d mailing list