Removing all type inference from compiler and stdlib

Hi

Had a stupid idea, and wanted to see if it holds any water.
One thing that I have heard very often about the slower compilation speed of Crystal is that it is due to the global type inferencing.

I was wondering if we can do the following;

  1. add a call in a custom variant of the compiler where it lists out every instance of type inferencing alongwith the name and position of that initiatlization
  2. simply start adding types to the compiler and all stdlibs till we have worked down this list

Is is correct to assume that if most of initialized have the correct types upfront, we will actually have faster compilation speed?

We can even have a something like a “–use_strict_types” as a compiler flag so that all library authors can also try to reduce their type inference usage.

No. Right now it’s actually the other way around: when you put a type restriction, the compiler has to check that it holds.

There’s the method sum in Enumerable:

module Enumerable(T)
  def sum
    # something
  end
end

The interesting thing here is that you can do:

[1, 2, 3].sum

but if you try to do:

['a', 'b', 'c'].sum

it will give a compile error. But sum has no types! And there’s no way to add types to it. The type is in T, so we’d need to restrict T to something that has + on it. But every Array is an Enumerable!

As you can see, the solution doesn’t seem to be as easy as adding types everywhere.

3 Likes

For better understanding, maybe it’s helpful to say that the way type annotations work in Crystal, doesn’t help with this. It would need a different kind of type restrictions, more like in C or Java for example.

2 Likes

Thanks both of you for patiently answering something which I suppose you both have had to explain a hundred times over. :grin:

OTOH having type annotations (when possible) on stdlib helps a lot since it also works as documentation.

3 Likes

IIUC @oprypin has done a lot work adding type annotations to the stdlib precisely for this reason

1 Like