rhaiscript / lsp

Language server for Rhai.
Apache License 2.0
43 stars 4 forks source link

First-class types and type inference #81

Closed tamasfe closed 2 years ago

tamasfe commented 2 years ago

closes #16, and closes #5

Type Inference

There is a very basic one-way type inference algorithm involved, types are known for literals and from items with type annotations, the rest of the types are all deducted from these.

In the example below the type of foo is the union of the types of bar and baz, the type-checker will not attempt to reverse the logic, even if foo has previously known types, neither bar nor baz will be deducted from it.

foo = if true {
  bar
} else {
  baz
};

The operators defined in definition files will also determine the type of binary (and unary) expressions.

The current goal of this type system is enhancing DX rather than enforcing correctness, as currently Rhai won't have tools for overriding inferred types and providing type annotations inline anytime soon.

Peek 2022-08-07 19-27.webm

Peek 2022-08-07 19-31.webm

schungx commented 2 years ago

Great deal!

For methods and property getters/setters, I suppose once the type info gets in, they would start to pop out, correct? Depending on the type of the object, the correct properties and methods will be recognized?

How about if the object is a union type (say String | int)? Would all the possibilities be shown? Say, if the doc-comments for the two possible types are different.

tamasfe commented 2 years ago

For methods and property getters/setters, I suppose once the type info gets in, they would start to pop out, correct? Depending on the type of the object, the correct properties and methods will be recognized?

Right now only properties inferred from objects literals or object type hints (const obj_with_foo: #{ foo: String };) are known, the next step would be to traverse the standalone function definitions and include them in completions/references as well.

How about if the object is a union type (say String | int)? Would all the possibilities be shown? Say, if the doc-comments for the two possible types are different.

Not yet, unions will need some special treatment, they are not even merged in every case right now, aliasing a type will cause it to be a different type.