Skip to content
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

Implement PEP-696 #1141

Merged
merged 14 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions libcst/_nodes/statement.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Optional, Pattern, Sequence, Union
from typing import Literal, Optional, Pattern, Sequence, Union

from libcst._add_slots import add_slots
from libcst._maybe_sentinel import MaybeSentinel
Expand Down Expand Up @@ -3653,8 +3653,34 @@
#: with a comma only if a comma is required.
comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT

#: The equal sign used to denote assignment if there is a default.
equal: Union[AssignEqual, MaybeSentinel] = MaybeSentinel.DEFAULT

#: The star used to denote a variadic default
star: Literal["", "*"] = ""

#: The whitespace between the star and the type.
whitespace_after_star: SimpleWhitespace = SimpleWhitespace.field("")

#: Any optional default value, used when the argument is not supplied.
default: Optional[BaseExpression] = None

def _codegen_impl(self, state: CodegenState, default_comma: bool = False) -> None:
self.param._codegen(state)

equal = self.equal
if equal is MaybeSentinel.DEFAULT and self.default is not None:
state.add_token(" = ")
elif isinstance(equal, AssignEqual):
equal._codegen(state)

state.add_token(self.star)
self.whitespace_after_star._codegen(state)

default = self.default
if default is not None:
default._codegen(state)

comma = self.comma
if isinstance(comma, MaybeSentinel):
if default_comma:
Expand All @@ -3663,10 +3689,27 @@
comma._codegen(state)

def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "TypeParam":
return TypeParam(
ret = TypeParam(
param=visit_required(self, "param", self.param, visitor),
equal=visit_sentinel(self, "equal", self.equal, visitor),
star=self.star,
whitespace_after_star=visit_required(
self, "whitespace_after_star", self.whitespace_after_star, visitor
),
default=visit_optional(self, "default", self.default, visitor),
comma=visit_sentinel(self, "comma", self.comma, visitor),
)
return ret

def _validate(self) -> None:
if self.default is None and isinstance(self.equal, AssignEqual):
raise CSTValidationError(

Check warning on line 3706 in libcst/_nodes/statement.py

View check run for this annotation

Codecov / codecov/patch

libcst/_nodes/statement.py#L3706

Added line #L3706 was not covered by tests
"Must have a default when specifying an AssignEqual."
)
if self.star and not (self.default or isinstance(self.equal, AssignEqual)):
raise CSTValidationError("Star can only be present if a default")

Check warning on line 3710 in libcst/_nodes/statement.py

View check run for this annotation

Codecov / codecov/patch

libcst/_nodes/statement.py#L3710

Added line #L3710 was not covered by tests
if isinstance(self.star, str) and self.star not in ("", "*"):
raise CSTValidationError("Must specify either '' or '*' for star.")

Check warning on line 3712 in libcst/_nodes/statement.py

View check run for this annotation

Codecov / codecov/patch

libcst/_nodes/statement.py#L3712

Added line #L3712 was not covered by tests


@add_slots
Expand Down
124 changes: 124 additions & 0 deletions libcst/_nodes/tests/test_type_alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,79 @@ class TypeAliasCreationTest(CSTNodeTest):
"code": "type foo[T: str, *Ts, **KW] = bar | baz",
"expected_position": CodeRange((1, 0), (1, 39)),
},
{
"node": cst.TypeAlias(
cst.Name("foo"),
type_parameters=cst.TypeParameters(
[
cst.TypeParam(
cst.TypeVar(cst.Name("T")), default=cst.Name("str")
),
]
),
value=cst.Name("bar"),
),
"code": "type foo[T = str] = bar",
"expected_position": CodeRange((1, 0), (1, 23)),
},
{
"node": cst.TypeAlias(
cst.Name("foo"),
type_parameters=cst.TypeParameters(
[
cst.TypeParam(
cst.ParamSpec(cst.Name("P")),
default=cst.List(
elements=[
cst.Element(cst.Name("int")),
cst.Element(cst.Name("str")),
]
),
),
]
),
value=cst.Name("bar"),
),
"code": "type foo[**P = [int, str]] = bar",
"expected_position": CodeRange((1, 0), (1, 32)),
},
{
"node": cst.TypeAlias(
cst.Name("foo"),
type_parameters=cst.TypeParameters(
[
cst.TypeParam(
cst.TypeVarTuple(cst.Name("T")),
equal=cst.AssignEqual(),
default=cst.Name("default"),
star="*",
),
]
),
value=cst.Name("bar"),
),
"code": "type foo[*T = *default] = bar",
"expected_position": CodeRange((1, 0), (1, 29)),
},
{
"node": cst.TypeAlias(
cst.Name("foo"),
type_parameters=cst.TypeParameters(
[
cst.TypeParam(
cst.TypeVarTuple(cst.Name("T")),
equal=cst.AssignEqual(),
default=cst.Name("default"),
star="*",
whitespace_after_star=cst.SimpleWhitespace(" "),
),
]
),
value=cst.Name("bar"),
),
"code": "type foo[*T = * default] = bar",
"expected_position": CodeRange((1, 0), (1, 31)),
},
)
)
def test_valid(self, **kwargs: Any) -> None:
Expand Down Expand Up @@ -125,6 +198,57 @@ class TypeAliasParserTest(CSTNodeTest):
"code": "type foo [T:str,** KW , ] = bar ; \n",
"parser": parse_statement,
},
{
"node": cst.SimpleStatementLine(
[
cst.TypeAlias(
cst.Name("foo"),
type_parameters=cst.TypeParameters(
[
cst.TypeParam(
cst.TypeVarTuple(cst.Name("P")),
star="*",
equal=cst.AssignEqual(),
default=cst.Name("default"),
),
]
),
value=cst.Name("bar"),
whitespace_after_name=cst.SimpleWhitespace(" "),
whitespace_after_type_parameters=cst.SimpleWhitespace(" "),
)
]
),
"code": "type foo [*P = *default] = bar\n",
"parser": parse_statement,
},
{
"node": cst.SimpleStatementLine(
[
cst.TypeAlias(
cst.Name("foo"),
type_parameters=cst.TypeParameters(
[
cst.TypeParam(
cst.TypeVarTuple(cst.Name("P")),
star="*",
whitespace_after_star=cst.SimpleWhitespace(
" "
),
equal=cst.AssignEqual(),
default=cst.Name("default"),
),
]
),
value=cst.Name("bar"),
whitespace_after_name=cst.SimpleWhitespace(" "),
whitespace_after_type_parameters=cst.SimpleWhitespace(" "),
)
]
),
"code": "type foo [*P = * default] = bar\n",
"parser": parse_statement,
},
)
)
def test_valid(self, **kwargs: Any) -> None:
Expand Down
Loading
Loading