alanrgan / rust-interpreter

0 stars 0 forks source link

Static type inference and checking #6

Closed alanrgan closed 7 years ago

alanrgan commented 7 years ago

Problem Statement

Right now, since there is no type inference implemented, all variable declarations must be accompanied by a type annotation: let x: int = 3

This can quickly become cumbersome and unergonomic when defining lengthy types such as function pointers:

let foo: Func<(int, str, str, int),str> = fn (a: int, b: str, c: str, d: int) : str {
                                             return "bar";
                                          };

However, as the language is implemented now, there does exist dynamic type checking, as evidenced by the failure of the following line of code: let x: str = 3; // panics

There should be a way then to determine the type of a variable statically by looking at the rvalue.

Current related issues

  1. Return types are not checked statically The following code will not panic until the function foo is called.
    
    fn foo(a: int) : int {
     return "hello world";
    }

foo(3); // panics only at this line at runtime

This problem becomes worse when return types are muddled in conditional branches

fn foo(a: int) : int { if a > 5 { return 8; } else { return "bar"; } }

foo(6); // does not panic foo(2); // panics



## Use cases
1. Simplify variable declarations.
2. Function overloading
alanrgan commented 7 years ago

Simple type inference in assignment is implemented. Still need to check return types, but that should be moved to a separate issue.