[red-knot] Literal special form (#13874)

Handling `Literal` type in annotations.

Resolves: #13672 

## Implementation

Since Literals are not a fully defined type in typeshed. I used a trick
to figure out when a special form is a literal.
When we are inferring assignment types I am checking if the type of that
assignment was resolved to typing.SpecialForm and the name of the target
is `Literal` if that is the case then I am re creating a new instance
type and set the known instance field to `KnownInstance:Literal`.

**Why not defining a new type?**

From this [issue](https://github.com/python/typeshed/issues/6219) I
learned that we want to resolve members to SpecialMethod class. So if we
create a new instance here we can rely on the member resolving in that
already exists.


## Tests


https://typing.readthedocs.io/en/latest/spec/literal.html#equivalence-of-two-literals
Since the type of the value inside Literal is evaluated as a
Literal(LiteralString, LiteralInt, ...) then the equality is only true
when types and value are equal.


https://typing.readthedocs.io/en/latest/spec/literal.html#legal-and-illegal-parameterizations

The illegal parameterizations are mostly implemented I'm currently
checking the slice expression and the slice type to make sure it's
valid.

https://typing.readthedocs.io/en/latest/spec/literal.html#shortening-unions-of-literals

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
This commit is contained in:
Shaygan Hooshyari 2024-11-05 02:45:46 +01:00 committed by GitHub
parent 6c56a7a868
commit 9dddd73c29
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 465 additions and 117 deletions

View file

@ -11,11 +11,9 @@ use crate::Db;
enum CoreStdlibModule {
Builtins,
Types,
// the Typing enum is currently only used in tests
#[allow(dead_code)]
Typing,
Typeshed,
TypingExtensions,
Typing,
}
impl CoreStdlibModule {