Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic type alias #823

Merged
merged 13 commits into from
Dec 1, 2021
Merged

Generic type alias #823

merged 13 commits into from
Dec 1, 2021

Conversation

soutaro
Copy link
Member

@soutaro soutaro commented Nov 11, 2021

This PR adds the key feature for RBS 1.8, generic type alias!

You can now define generic type aliases like:

type list[T] = [T, list[T]] | nil  # Defines linked list of `T`

type int_list = list[Integer]      # List of Integer
type object_list = list[Object]    # List of Object

We also provide new DefinitionBuilder#expand_alias variants to unfold a type alias: #expand_alias1 and #expand_alias2.

builder.expand_alias2(list, [integer])   # Unfold type alias one step with application => [integer, list[integer]] | nil
builder.expand_alias1(list)              # Unfold type alias one step with `untyped` type arguments => [untyped, list[untyped]] | nil
builder.expand_alias(list)               # Raises a runtime error because `::list` type requires one type argument

So, the type checkers will continue working if no generic type alias is used in the application. Or, you can just replace your #expand_alias calls with #expand_alias1 for the minimal support.

Generic type alias also supports variance annotations.

# The type parameter `T` is covariant: list[Integer] <: list[Object]
type list[out T] = [T, list[T]] | nil

One limitation of defining generic type alias is the regularity. It prohibits polymorphic recursion. You cannot use a type alias polymorphic in its declaration.

type foo[T] = foo[Array[T]] | nil      # This is prohibited.
  • Update syntax.md

@soutaro soutaro marked this pull request as ready for review November 11, 2021 06:55
@soutaro soutaro enabled auto-merge December 1, 2021 02:11
@soutaro soutaro merged commit 3de717f into master Dec 1, 2021
@soutaro soutaro deleted the generic-alias branch December 1, 2021 02:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant