MCPcopy Create free account
hub / github.com/astral-sh/ruff / parse_function_definition

Method parse_function_definition

crates/ruff_python_parser/src/parser/statement.rs:2006–2122  ·  view source on GitHub ↗

Parses a function definition. The given `start` offset is the start of either of the following: - `def` token - `async` token if it's an asynchronous function definition with no decorators - `@` token if the function definition has decorators # Panics If the parser isn't positioned at a `def` token. See:

(
        &mut self,
        decorator_list: DecoratorList,
        start: TextSize,
    )

Source from the content-addressed store, hash-verified

2004 ///
2005 /// See: <https://docs.python.org/3/reference/compound_stmts.html#function-definitions>
2006 fn parse_function_definition(
2007 &mut self,
2008 decorator_list: DecoratorList,
2009 start: TextSize,
2010 ) -> ast::StmtFunctionDef {
2011 self.bump(TokenKind::Def);
2012
2013 // test_err function_def_missing_identifier
2014 // def (): ...
2015 // def () -> int: ...
2016 let name = self.parse_identifier();
2017
2018 // test_err function_def_unclosed_type_param_list
2019 // def foo[T1, *T2(a, b):
2020 // return a + b
2021 // x = 10
2022 let type_params = self.try_parse_type_params();
2023
2024 // test_ok function_type_params_py312
2025 // # parse_options: {"target-version": "3.12"}
2026 // def foo[T](): ...
2027
2028 // test_err function_type_params_py311
2029 // # parse_options: {"target-version": "3.11"}
2030 // def foo[T](): ...
2031 // def foo[](): ...
2032 if let Some(ast::TypeParams { range, .. }) = &type_params {
2033 self.add_unsupported_syntax_error(
2034 UnsupportedSyntaxErrorKind::TypeParameterList,
2035 *range,
2036 );
2037 }
2038
2039 // test_ok function_def_parameter_range
2040 // def foo(
2041 // first: int,
2042 // second: int,
2043 // ) -> int: ...
2044
2045 // test_err function_def_unclosed_parameter_list
2046 // def foo(a: int, b:
2047 // def foo():
2048 // return 42
2049 // def foo(a: int, b: str
2050 // x = 10
2051 let parameters = self.parse_parameters(FunctionKind::FunctionDef);
2052
2053 let returns = if self.eat(TokenKind::Rarrow) {
2054 if self.at_expr() {
2055 // test_ok function_def_valid_return_expr
2056 // def foo() -> int | str: ...
2057 // def foo() -> lambda x: x: ...
2058 // def foo() -> int if True else str: ...
2059
2060 // test_err function_def_invalid_return_expr
2061 // def foo() -> *int: ...
2062 // def foo() -> (*int): ...
2063 // def foo() -> yield x: ...

Callers 3

parse_statementMethod · 0.80
parse_async_statementMethod · 0.80
parse_decoratorsMethod · 0.80

Calls 15

parse_identifierMethod · 0.80
try_parse_type_paramsMethod · 0.80
parse_parametersMethod · 0.80
at_exprMethod · 0.80
parse_expression_listMethod · 0.80
current_token_rangeMethod · 0.80
expectMethod · 0.80
parse_bodyMethod · 0.80
node_rangeMethod · 0.80
defaultFunction · 0.50
bumpMethod · 0.45

Tested by

no test coverage detected