ruby / ruby/rbs

Proposal: making `Class` and `Module` classes generic -- `Class[I]` and `Module[I]`

Open
#1,542 12 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
2.2k
Forks
256
Avg merge
6d 17h
Merged PRs (30d)
37

Description

Currently, we model module/class themselves (as opposed to instances) as singleton(Klass), whereas the Module/Class classes can only represent the module/class of untyped.

I suggest combining those two by giving Module and Class a type variable representing their instances. For example, Class[String] (and Module[String] too to under covariance) is equivlaent to singleton(String).
For backward compatibility, singleton(I) can be a alternate (read: legacy) syntax for Module[I].

The immediate benefit is Class[I] RBS finally able to write def new: (…) -> I and def allocate: () -> I (rather than expecting type checkers to infer from singleton(I)).

Speaking of singleton(I)
https://github.com/ruby/rbs/blob/6e5a2893b4c2782cc9e71f76e193e9592b0c1ebf/docs/syntax.md?plain=1#L9
[I < Bound] … singleton(I) is invalid. (Update: this is #558) [I < singleton(Bound)] -> I works the limitation around, but what if I has other duties?

# Modules can’t inherit Classes, so I’m stuck with this design.
class MyClassWrapper[I < MyObject] < MyComponent
  def initialize: (singleton(I) klass) -> void #FIXME: Class[I] when
  def customized_new: (*args) -> I
end

This is also how Java does it (as early as their type args were born).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked section of docs/syntax.md and the examples of Class[I], Module[I], and singleton(I) in the issue. Work out the generic and backward-compatibility semantics before locating the affected implementation and tests; done requires an agreed design, implementation, and coverage for the proposed syntax.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.