Skip to content
This repository was archived by the owner on Jul 27, 2023. It is now read-only.

Commit dba9ff1

Browse files
committed
Parse type parameters in function definitions (RustPython#96)
* Parse type parameters in function definitions * Add test for combined items
1 parent a57ef0b commit dba9ff1

5 files changed

+4718
-3200
lines changed

parser/src/parser.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,6 +663,33 @@ class Foo[X, Y: str, *U, **P]():
663663
";
664664
insta::assert_debug_snapshot!(ast::Suite::parse(source, "<test>").unwrap());
665665
}
666+
#[test]
667+
#[cfg(feature = "all-nodes-with-ranges")]
668+
fn test_parse_function_definition() {
669+
let source = "\
670+
def func(a):
671+
...
672+
673+
def func[T](a: T) -> T:
674+
...
675+
676+
def func[T: str](a: T) -> T:
677+
...
678+
679+
def func[T: (str, bytes)](a: T) -> T:
680+
...
681+
682+
def func[*Ts](*a: *Ts):
683+
...
684+
685+
def func[**P](*args: P.args, **kwargs: P.kwargs):
686+
...
687+
688+
def func[T, U: str, *Ts, **P]():
689+
pass
690+
";
691+
insta::assert_debug_snapshot!(ast::Suite::parse(source, "<test>").unwrap());
692+
}
666693

667694
#[test]
668695
fn test_parse_dict_comprehension() {

parser/src/python.lalrpop

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -965,16 +965,15 @@ WithItem<Goal>: ast::WithItem = {
965965
};
966966

967967
FuncDef: ast::Stmt = {
968-
<location:@L> <decorator_list:Decorator*> <is_async:"async"?> "def" <name:Identifier> <args:Parameters> <r:("->" <Test<"all">>)?> ":" <body:Suite> => {
968+
<decorator_list:Decorator*> <location:@L> <is_async:"async"?> "def" <name:Identifier> <type_params:TypeParamList?> <args:Parameters> <r:("->" <Test<"all">>)?> ":" <body:Suite> => {
969969
let args = Box::new(args);
970970
let returns = r.map(|x| Box::new(x));
971971
let end_location = body.last().unwrap().end();
972972
let type_comment = None;
973-
let type_params = Vec::new();
974973
if is_async.is_some() {
975-
ast::StmtAsyncFunctionDef { name, args, body, decorator_list, returns, type_comment, type_params, range: (location..end_location).into() }.into()
974+
ast::StmtAsyncFunctionDef { name, args, body, decorator_list, returns, type_comment, type_params: type_params.unwrap_or_default(), range: (location..end_location).into() }.into()
976975
} else {
977-
ast::StmtFunctionDef { name, args, body, decorator_list, returns, type_comment, type_params, range: (location..end_location).into() }.into()
976+
ast::StmtFunctionDef { name, args, body, decorator_list, returns, type_comment, type_params: type_params.unwrap_or_default(), range: (location..end_location).into() }.into()
978977
}
979978
},
980979
};

0 commit comments

Comments
 (0)