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:2134–2197  ·  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

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