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

Method parse_class_definition

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

Parses a class definition. The given `start` offset is the start of either the `def` token or the `@` token if the class definition has decorators. # Panics If the parser isn't positioned at a `class` token. See:

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

Source from the content-addressed store, hash-verified

2121 ///
2122 /// See: <https://docs.python.org/3/reference/compound_stmts.html#grammar-token-python-grammar-classdef>
2123 fn parse_class_definition(
2124 &mut self,
2125 decorator_list: DecoratorList,
2126 start: TextSize,
2127 ) -> ast::StmtClassDef {
2128 self.bump(TokenKind::Class);
2129
2130 // test_err class_def_missing_name
2131 // class : ...
2132 // class (): ...
2133 // class (metaclass=ABC): ...
2134 let name = self.parse_identifier();
2135
2136 // test_err class_def_unclosed_type_param_list
2137 // class Foo[T1, *T2(a, b):
2138 // pass
2139 // x = 10
2140 let type_params = self.try_parse_type_params();
2141
2142 // test_ok class_type_params_py312
2143 // # parse_options: {"target-version": "3.12"}
2144 // class Foo[S: (str, bytes), T: float, *Ts, **P]: ...
2145
2146 // test_err class_type_params_py311
2147 // # parse_options: {"target-version": "3.11"}
2148 // class Foo[S: (str, bytes), T: float, *Ts, **P]: ...
2149 // class Foo[]: ...
2150 if let Some(ast::TypeParams { range, .. }) = &type_params {
2151 self.add_unsupported_syntax_error(
2152 UnsupportedSyntaxErrorKind::TypeParameterList,
2153 *range,
2154 );
2155 }
2156
2157 // test_ok class_def_arguments
2158 // class Foo: ...
2159 // class Foo(): ...
2160 // class Foo((base for base in bases)): ...
2161 // class Foo(*(base for base in bases)): ...
2162
2163 // test_err class_def_unparenthesized_generator_argument
2164 // class Foo(base for base in bases): ...
2165 let arguments = self
2166 .at(TokenKind::Lpar)
2167 .then(|| Box::new(self.parse_arguments(ArgumentsContext::ClassDefinition)));
2168
2169 self.expect(TokenKind::Colon);
2170
2171 // test_err class_def_empty_body
2172 // class Foo:
2173 // class Foo():
2174 // x = 42
2175 let body = self.parse_body(Clause::Class);
2176
2177 ast::StmtClassDef {
2178 range: self.node_range(start),
2179 decorator_list,
2180 name,

Callers 2

parse_statementMethod · 0.80
parse_decoratorsMethod · 0.80

Calls 10

parse_identifierMethod · 0.80
try_parse_type_paramsMethod · 0.80
parse_argumentsMethod · 0.80
expectMethod · 0.80
parse_bodyMethod · 0.80
node_rangeMethod · 0.80
bumpMethod · 0.45
atMethod · 0.45
mapMethod · 0.45

Tested by

no test coverage detected