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:2132–2195  ·  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

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