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:2139–2202  ·  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

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