-
Notifications
You must be signed in to change notification settings - Fork 33
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
RFC: Constraints on generic parameters #50
Open
SecondNewtonLaw
wants to merge
4
commits into
luau-lang:master
Choose a base branch
from
SecondNewtonLaw:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
d7f68a1
Create type-constraints-on-generic-parameters.md
SecondNewtonLaw ebfaa89
Update type-constraints-on-generic-parameters.md
SecondNewtonLaw 01d2bc8
Improve
SecondNewtonLaw eefb5e5
Improvements, remove things outside of the scope of the RFC.
SecondNewtonLaw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,207 @@ | ||
# Type Constraints on Generic Functions | ||
|
||
## Summary | ||
|
||
Modify the current generics implementation to allow generic types to be constrained by a type. | ||
|
||
## Motivation | ||
|
||
When writing generic functions currently, it is as if you were simply using any unless you make your own type, being that the generic type has no constraints. | ||
|
||
Take this snippet for example: | ||
|
||
```luau | ||
type Entity = { | ||
-- ... | ||
} | ||
|
||
type Gun = { | ||
IsEmpty: (self: Gun) -> boolean, | ||
FireGun: (self: Gun) -> (), | ||
-- ... | ||
} | ||
|
||
type WeaponResult = { | ||
HittedEntity: Entity, | ||
DamageDealt: number, | ||
} | ||
|
||
type ShotgunWeaponResult = { | ||
PelletCount: number, | ||
AmountOfPelletsHit: number, | ||
} & WeaponResult | ||
|
||
type Shotgun = { | ||
-- ... | ||
} & Gun | ||
|
||
local function fireGun<T: Gun, U: WeaponResult>(self: T): U? | ||
if not self:IsEmpty() then -- No error | ||
return self:FireGun() -- No error | ||
end | ||
|
||
return nil | ||
end | ||
|
||
local gun: Gun | ||
local shotgun: Shotgun | ||
|
||
local fireResult = fireGun(gun) :: WeaponResult -- No error | ||
local shotgunFireResult = fireGun(shotgun) :: ShotgunWeaponResult -- No error | ||
|
||
fireGun("Hello, world!") -- Type Error: type 'string' and 'Gun' are not related to one another. | ||
``` | ||
|
||
On this snippet, we are trying to implement a theoretical Gun system, we may have many implementations for the Gun, like a Shotgun or a Pistol. In this implementation, we want to make a generic function that can take a gun of type `T` constrained by the base `Gun` type. But we also want to be able to return a result which is constrained by the type `WeaponResult`, however, the current system for generics does not allow for this without getting type errors. | ||
|
||
This is the main reasoning behind this modification. Many other languages have a feature to limit what types does a generic allow as a baseline. Languages like C# have this implemented on the form of the `where T : BaseClass` syntax, which delimits the type that `T` can be or inherit from. It supports cases in which you may want to use a strucutre, but not know its implementation details, like an interface. | ||
|
||
However, we can use this pattern to improve the reliability of code, a function such as the following that takes a string and returns a type, without having to type cast into `any` before type casting into `T`. | ||
|
||
|
||
```luau | ||
type GameService = { | ||
-- ... | ||
} | ||
|
||
type GameManager = { | ||
Disconnect: (self: GameManager) -> (), | ||
-- ... | ||
} & GameService | ||
|
||
type ServiceContainer = { | ||
ServiceList: { [string]: GameService }, | ||
Require: <T: GameService>(self: ServiceContainer, serviceName: string) -> T | ||
} | ||
|
||
local ServiceContainer = { | ||
Require = function<T: GameService>(self: ServiceContainer, serviceName: string): T | ||
return self.ServiceList[serviceName] :: T | ||
end | ||
} | ||
|
||
-- ... | ||
|
||
local GameManager = ServiceContainer:Require("@game/GameManager") :: GameManager | ||
GameManager:Disconnect() | ||
``` | ||
|
||
## Design | ||
|
||
The design of this feature will reuse the already existing generics syntax, with little modification. | ||
|
||
```luau | ||
type Entity = { | ||
-- ... | ||
} | ||
|
||
type Gun = { | ||
IsEmpty: (self: Gun) -> boolean, | ||
FireGun: (self: Gun) -> (), | ||
-- ... | ||
} | ||
|
||
type WeaponResult = { | ||
HittedEntity: Entity, | ||
DamageDealt: number, | ||
} | ||
|
||
type ShotgunWeaponResult = { | ||
PelletCount: number, | ||
AmountOfPelletsHit: number, | ||
} & WeaponResult | ||
|
||
type Shotgun = { | ||
-- ... | ||
} & Gun | ||
|
||
local function fireGun<T: Gun, U: WeaponResult>(self: T): U? | ||
if not self:IsEmpty() then -- No error | ||
return self:FireGun() -- No error | ||
end | ||
|
||
return nil | ||
end | ||
|
||
local gun: Gun | ||
local shotgun: Shotgun | ||
|
||
local fireResult = fireGun(gun) :: WeaponResult -- No error | ||
local shotgunFireResult = fireGun(shotgun) :: ShotgunWeaponResult -- No error | ||
|
||
fireGun("Hello, world!") -- Type Error: type 'string' and 'Gun' are not related to one another. | ||
``` | ||
|
||
The syntax for defining a generic function would remain the same, except, instead of simply taking a `T`, we would take a `T : TypeConstraint`, the syntax remains similar to other features of the language, and it would work by checking if the type that `T` is inferred to be has any kind of relationship with `TypeConstraint`. However, we may also want to be explicit when we are doing generics on this way, therefore a syntax to properly and explicitly specify which types the function takes in its current call would be preferred, this way, we no longer have to use turbofish to type cast into the correct return type `U` constrained by `WeaponResult`. | ||
|
||
This would allow us to be more explicit with what types our generic function takes when calling it, improving overall reliability for the generic functions we write, as they would no longer be an inferred `any` that cannot be type-casted. This also allows for more flexible coding styles, and to implement custom require-like functions without them returning `any` and requiring an explicit type cast. This would also be enforced by the type checker, making it so if `GameManager` is not related to `GameService` it warns or errors at the programmer for it, like any other type safe language. | ||
|
||
```luau | ||
type GameService = { | ||
-- ... | ||
} | ||
|
||
type GameManager = { | ||
Disconnect: (self: GameManager) -> (), | ||
-- ... | ||
} & GameService | ||
|
||
type ServiceContainer = { | ||
ServiceList: { [string]: GameService }, | ||
Require: <T: GameService>(self: ServiceContainer, serviceName: string) -> T | ||
} | ||
|
||
local ServiceContainer = { | ||
Require = function<T: GameService>(self: ServiceContainer, serviceName: string): T | ||
return self.ServiceList[serviceName] :: T | ||
end | ||
} | ||
|
||
-- ... | ||
|
||
local GameManager = ServiceContainer:Require("@game/GameManager") :: GameManager | ||
GameManager:Disconnect() | ||
``` | ||
|
||
|
||
## Drawbacks | ||
|
||
The main deterrant to implementing type constraints on generics is type intersection. Type intesection allows us to implement this snippet without fighting much of anything relating to the type system. | ||
|
||
```luau | ||
type Gun = { | ||
IsEmpty: (self: Gun) -> boolean, | ||
FireGun: (self: Gun) -> (), | ||
-- ... | ||
} | ||
|
||
type Shotgun = { | ||
-- ... | ||
} & Gun | ||
|
||
local function fireGun(self: Gun) | ||
if not self:IsEmpty() then | ||
self:FireGun() | ||
end | ||
end | ||
|
||
local gun: Gun = nil | ||
local shotgun: Shotgun = nil | ||
|
||
fireGun(gun) -- Works as intended. | ||
fireGun(shotgun) -- Works as intended. | ||
fireGun("Hello, world!") -- Type Error: type 'string' could not be converted into 'Gun' | ||
|
||
``` | ||
|
||
Using type intersection would not require any changes to generics, and makes the function take an input that is of any type, as long as the type is intersected with, this solution is type safe and does not require any modification to the current way generics work. | ||
|
||
This is one of the cases in which type constraints on generic parameters would have no significant benefit to the language, and may complicate some aspects, as it is another way of achieving the same end goal: Enforcing a certain type as a parameter. | ||
|
||
## Alternatives | ||
|
||
The unspoken of alternative to this, is simple type intersection, yet another reason as to why this should be implemented is that the future of `Luau` is bleeding more into a safer language in what types respect to, by adding this feature we are improving an existing one which was added with such idea in mind, improving it by adding something that was originally not thought of and that could overall improve the current implementation for generics, and allow for more flexible patterns when programming with Luau. | ||
|
||
The design given on the Drawbacks section is indicative of another way of designing the system so that it plays nicely with the current type checker, however, this leads generics in a place where they have nowhere to belong to. | ||
|
||
However an implementation that could benefit of the enforcing type constraints on generic functions is that of the require-like function, a possible implementation without type constraints would be marginally less type safe, as we would need to first cast into any to do any conversion into the type `T`. In the case this can be avoided, there could be room for improvement on Luau internals in what relates to native code generation, allowing it to generate performant native versions for functions that fit the type constraint, which could be benefitial overall. |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't know why you're mentioning turbofish, that doesn't exist in Luau, and can't because it's ambiguous with
:: <T>() -> ()
.No turbofish is also not an option for the exact same reasons it's necessary in Rust.
...is perfectly valid code today.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I remember discussing with Drak that
f.<T, U>()
isn't the worst syntax in the world, but also it feels out of scope for this RFC anyway?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You're right, it feels out of scope for this RFC to add on about, and it was already somewhat addressed on the original generic functions rfc
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
although I did not know that that snippet was valid ever, however, all I keep getting from attempting it is syntax errors