Implement user-defined type guard method #1501
Draft
+313
−8
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This implements the minimal version of user-defined type guard method. A user-defined type guard methos is a method defined by user that is able to guarantee the type of the objects (receiver or arguments).
At present, Steep supports type guard methods provided by ruby-core (ex.
#is_a?
,#nil?
, and so on). But we also have many kinds of user-defined methods that are able to check the type of the objects.Therefore user-defined type guard will help checking the type of these applications by narrowing types.
This implementation uses an annotation to declare user-defined type guard method.
For example, the following method
Example#integer?
is a user-defined type guard method that narrows the Example object itself to an Integer if the conditional branch passed.In this PR, the predicate of type guards only supports "self is TYPE" statement. I have a plan to extend it:
%a{guard:self is arg}
%a{guard:self is_a arg}
%a{guard:self is TYPE_PARAM}
%a{guard:arg is TYPE}
Note: The compatibility of RBS syntax is the large reason of using annotations. I'm afraid that adding a new syntax to define it will bring breaking change to the RBS, and difficult to use it on common repository or generators (ex. gem_rbs_collection and rbs_rails).
refs: