[GDScript]: Add a strong type for the self
identifier
#110764
+117
−0
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 PR introduces a
Self
type, enabling developers to strongly type theself
identifier. Which is particularly useful for fluent APIs, static helpers and object managers, where the type used to describeself
, or an instance of such a type, would be repetitive, or constraining.Motivation
Currently there is no native way to refer to the type of the current class (
self
). Users must resort to workarounds like:class_name
, globally loading the class, and repeating the identifier a lot.const Self := preload(<current filename>)
.These approaches rely on the user to make right and understand the pitfalls. GDScript could help out. Since the current class is always known in context, a
Self
type provides a natural and ergonomic solution.Example:
The type of the object is automatically preserved when used in a fluent interface, and maintains meaningful auto-complete! As a bonus,
Self
also survives refactorings without modifying the code as it is always current.Implementation
The implementation is minimal, modifying only three areas in the GDScript analyzer and compiler to handle
Self
as a special case, similar to howVariant
is already treated today. This ensures compatibility with existing codebases that may already useSelf
as a type or variable name. This path is a clean way to onboard the feature and expand upon down the line, if required.Testing
Comprehensive tests have been added to validate
Self
in various scenarios and edge-cases. You may prune them to your liking, I wanted to ensure the correctness of the code, as its simplicity was surprising.The primary use cases are best demonstrated in
runtime/features/self_type.gd
.