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:2011–2127  ·  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

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