Skip to content

Commit 4d80e43

Browse files
committed
Combine validation into a single function
1 parent 60f597c commit 4d80e43

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

Python/codegen.c

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5352,12 +5352,8 @@ codegen_slice(compiler *c, expr_ty s)
53525352
#define WILDCARD_STAR_CHECK(N) \
53535353
((N)->kind == MatchStar_kind && !(N)->v.MatchStar.name)
53545354

5355-
// Limit permitted subexpressions, even if the parser & AST validator let them through
5356-
#define MATCH_VALUE_EXPR(N) \
5357-
((N)->kind == Constant_kind || (N)->kind == Attribute_kind)
5358-
53595355
// Expressions such as '1+2j' or '1-2j'
5360-
static inline bool is_complex_binop(expr_ty e) {
5356+
static inline bool is_complex_literal(expr_ty e) {
53615357
return e->kind == BinOp_kind
53625358
&& (e->v.BinOp.op == Add || e->v.BinOp.op == Sub)
53635359
&& e->v.BinOp.left->kind == Constant_kind
@@ -5367,6 +5363,16 @@ static inline bool is_complex_binop(expr_ty e) {
53675363
&& PyComplex_CheckExact(e->v.BinOp.right->v.Constant.value);
53685364
}
53695365

5366+
// Limit permitted subexpressions, even if the parser & AST validator let them through
5367+
static inline bool is_match_value_expr(expr_ty e) {
5368+
// The permitted expressions in a case pattern value are constants,
5369+
// attribute lookups, and complex literals. However,
5370+
// complex literals are represented as a binary add or sub in
5371+
// the AST rather than a constant, so we need to check for them
5372+
// manually here.
5373+
return e->kind == Constant_kind || e->kind == Attribute_kind || is_complex_literal(e);
5374+
}
5375+
53705376
// Allocate or resize pc->fail_pop to allow for n items to be popped on failure.
53715377
static int
53725378
ensure_fail_pop(compiler *c, pattern_context *pc, Py_ssize_t n)
@@ -6030,18 +6036,11 @@ codegen_pattern_value(compiler *c, pattern_ty p, pattern_context *pc)
60306036
{
60316037
assert(p->kind == MatchValue_kind);
60326038
expr_ty value = p->v.MatchValue.value;
6033-
// The permitted expressions in a case pattern are constants,
6034-
// attribute lookups, and complex literals. However,
6035-
// complex literals are represented as a binary operation in
6036-
// the AST rather than a constant, so we need to check for them
6037-
// manually here.
6038-
if (MATCH_VALUE_EXPR(value) || is_complex_binop(value)) {
6039-
VISIT(c, expr, value);
6040-
}
6041-
else {
6039+
if (!is_match_value_expr(value)) {
60426040
const char *e = "patterns may only match literals and attribute lookups";
60436041
return _PyCompile_Error(c, LOC(p), e);
60446042
}
6043+
VISIT(c, expr, value);
60456044
ADDOP_COMPARE(c, LOC(p), Eq);
60466045
ADDOP(c, LOC(p), TO_BOOL);
60476046
RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));

0 commit comments

Comments
 (0)