Skip to content

Commit 54c3aa1

Browse files
[3.14] gh-133516: Raise ValueError when constants True, False or None are used as an identifier after NFKC normalization (GH-133523) (#133596)
1 parent c98b5a9 commit 54c3aa1

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

Lib/test/test_ast/test_ast.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -821,6 +821,17 @@ def test_constant_as_name(self):
821821
with self.assertRaisesRegex(ValueError, f"identifier field can't represent '{constant}' constant"):
822822
compile(expr, "<test>", "eval")
823823

824+
def test_constant_as_unicode_name(self):
825+
constants = [
826+
("True", b"Tru\xe1\xb5\x89"),
827+
("False", b"Fal\xc5\xbfe"),
828+
("None", b"N\xc2\xbane"),
829+
]
830+
for constant in constants:
831+
with self.assertRaisesRegex(ValueError,
832+
f"identifier field can't represent '{constant[0]}' constant"):
833+
ast.parse(constant[1], mode="eval")
834+
824835
def test_precedence_enum(self):
825836
class _Precedence(enum.IntEnum):
826837
"""Precedence table that originated from python grammar."""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Raise :exc:`ValueError` when constants ``True``, ``False`` or ``None`` are
2+
used as an identifier after NFKC normalization.

Parser/pegen.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -549,6 +549,21 @@ _PyPegen_new_identifier(Parser *p, const char *n)
549549
}
550550
id = id2;
551551
}
552+
static const char * const forbidden[] = {
553+
"None",
554+
"True",
555+
"False",
556+
NULL
557+
};
558+
for (int i = 0; forbidden[i] != NULL; i++) {
559+
if (_PyUnicode_EqualToASCIIString(id, forbidden[i])) {
560+
PyErr_Format(PyExc_ValueError,
561+
"identifier field can't represent '%s' constant",
562+
forbidden[i]);
563+
Py_DECREF(id);
564+
goto error;
565+
}
566+
}
552567
PyInterpreterState *interp = _PyInterpreterState_GET();
553568
_PyUnicode_InternImmortal(interp, &id);
554569
if (_PyArena_AddPyObject(p->arena, id) < 0)

0 commit comments

Comments
 (0)