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:2004–2120  ·  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

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