sunjay / dino

Compiler / PL Experimentation
Mozilla Public License 2.0
8 stars 0 forks source link

Better Type Inference for Operators #27

Open sunjay opened 5 years ago

sunjay commented 5 years ago

The Rust compiler has special cases that make it so you don't have to explicitly annotate the type of items on either side of most operators. We should consider similar special casing so we don't need 5int + 6 all the time.

For more info, read this whole file:

https://github.com/rust-lang/rust/blob/f54911c6f2971b98ede2d21ab8cabd7daa1110ba/src/librustc_typeck/check/op.rs#L109-L145

https://github.com/sunjay/dino/blob/bd8803d816130dbb1a6b4a53aa058966738bb466/src/ast/parser.rs#L290-L301

sunjay commented 5 years ago

Idea: Whenever we try to resolve a method we don't know the type for, we can add a new "method constraint" to a list. Each method constraint contains the method that was called, the type variable for the Self type, and the type variables for the types of each expression. After the first pass of type inference, before we check for ambiguous variables, we can go through each method constraint and try the following steps:

  1. If the Self type variable of the method constraint has been solved to a concrete type, use that to perform method dispatch based on the method name
  2. Otherwise, try to guess a set of applicable types: a. If the variable is an int var, the set of applicable types is {int, real, complex} b. If the variable is a real var, the set of applicable types is {real, complex} c. If the variable is both, the set of applicable types is the intersection of those two sets d. If the variable is neither, the set of applicable types is empty
  3. If the set of applicable types is empty, return an ambiguous type error
  4. Otherwise, go through each type in the set of applicable types: a. Assume that the Self type is that type, then try to do method dispatch based on the provided method name b. If that fails, try the next type in the set of applicable types
  5. If none of the applicable types works, pick one of them and produce an error that says that the type does not have any such method