diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index a81a6704142dcc..b0feca5dbb372c 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -58,7 +58,7 @@ objects considered false: * zero of any numeric type: ``0``, ``0.0``, ``0j``, ``Decimal(0)``, ``Fraction(0, 1)`` -* empty sequences and collections: ``''``, ``()``, ``[]``, ``{}``, ``set()``, +* empty sequences and collections: ``''``, ``()``, ``[]``, ``{}``, ``{/}``, ``range(0)`` .. index:: @@ -4668,6 +4668,7 @@ The constructors for both classes work the same: Sets can be created by several means: + * Use a slash within braces, for the empty set: ``{/}`` * Use a comma-separated list of elements within braces: ``{'jack', 'sjoerd'}`` * Use a set comprehension: ``{c for c in 'abracadabra' if c not in 'abc'}`` * Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', 'foo'])`` diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 7af3457070b84a..10bae42fd78418 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -450,11 +450,14 @@ There are currently two intrinsic set types: Sets .. index:: pair: object; set - - These represent a mutable set. They are created by the built-in :func:`set` - constructor and can be modified afterwards by several methods, such as - :meth:`~set.add`. - + pair: empty; set + + The items of a set are arbitrary Python objects. + Sets are formed by placing a comma-separated list of expressions in + curly brackets. For sets of length 1, the comma may be ommitted. + An empty set can be formed by ``{/}``. + Sets are mutable (see section :ref:`set`) and can be modified afterwards + by several methods, such as :meth:`~set.add`. Frozen sets .. index:: pair: object; frozenset diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst index 9aca25e3214a16..99ac66dbc20e7a 100644 --- a/Doc/reference/expressions.rst +++ b/Doc/reference/expressions.rst @@ -356,25 +356,25 @@ Set displays .. index:: pair: set; display pair: set; comprehensions + pair: empty; set pair: object; set + single: {/}; set display single: {} (curly brackets); set expression single: , (comma); expression list + single: / (fowarard slash); in set displays A set display is denoted by curly braces and distinguishable from dictionary displays by the lack of colons separating keys and values: .. productionlist:: python-grammar - set_display: "{" (`flexible_expression_list` | `comprehension`) "}" + set_display: "{" ("/" | `flexible_expression_list` | `comprehension`) "}" A set display yields a new mutable set object, the contents being specified by -either a sequence of expressions or a comprehension. When a comma-separated -list of expressions is supplied, its elements are evaluated from left to right -and added to the set object. When a comprehension is supplied, the set is -constructed from the elements resulting from the comprehension. - -An empty set cannot be constructed with ``{}``; this literal constructs an empty -dictionary. - +either a slash (for the empty set), a sequence of expressions, or a comprehension. +When a comma-separated list of expressions is supplied, its elements +are evaluated from left to right and added to the set object. +When a comprehension is supplied, the set is constructed from +the elements resulting from the comprehension. .. _dict: diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst index cbe780e075baf5..c30afa7ff34290 100644 --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -450,9 +450,11 @@ with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference. -Curly braces or the :func:`set` function can be used to create sets. Note: to -create an empty set you have to use ``set()``, not ``{}``; the latter creates an -empty dictionary, a data structure that we discuss in the next section. +Curly braces or the :func:`set` function can be used to create sets. +``{/}`` is a special case that means the empty set, similar to :math:`\emptyset`. + +.. hint:: ``{}`` will create an empty dictionary, not an empty set. + We will discuss this data structure in the next section. Here is a brief demonstration:: diff --git a/Doc/whatsnew/3.15.rst b/Doc/whatsnew/3.15.rst index 9f01b52f1aff3b..3cfb1db544f77f 100644 --- a/Doc/whatsnew/3.15.rst +++ b/Doc/whatsnew/3.15.rst @@ -70,6 +70,33 @@ Summary --- release highlights New features ============ +.. _whatsnew315-pep-802: + +Display Syntax for the Empty Set +-------------------------------- + +There is a new notation for the empty set, ``{/}``. +As part of this, the :func:`:str` and :func:`repr` of an empty :class:`set` +will now return ``'{/}'``. + +This complements the existing notation for empty tuples, lists, and +dictionaries, which use ``()``, ``[]``, and ``{}`` respectively. + +.. code-block:: python + + >>> type({/}) + + >>> {/} == set() + True + >>> repr({/}) + '{/}' + >>> str(set()) + '{/}' + >>> str({/}) == str(set()) == repr({/}) == repr(set()) + True + +(Contributed by Adam Turner in :pep:`802`.) + .. _whatsnew315-sampling-profiler: High frequency statistical sampling profiler diff --git a/Grammar/python.gram b/Grammar/python.gram index ff54e42111005a..4c9ff6e97bd3e2 100644 --- a/Grammar/python.gram +++ b/Grammar/python.gram @@ -993,13 +993,17 @@ strings[expr_ty] (memo): | a[asdl_expr_seq*]=tstring+ { _PyPegen_concatenate_tstrings(p, a, EXTRA) } list[expr_ty]: + | invalid_list_slash | '[' a=[star_named_expressions] ']' { _PyAST_List(a, Load, EXTRA) } tuple[expr_ty]: + | invalid_tuple_slash | '(' a=[y=star_named_expression ',' z=[star_named_expressions] { _PyPegen_seq_insert_in_front(p, y, z) } ] ')' { _PyAST_Tuple(a, Load, EXTRA) } -set[expr_ty]: '{' a=star_named_expressions '}' { _PyAST_Set(a, EXTRA) } +set[expr_ty]: + | '{' '/' '}' { _PyAST_Set(NULL, EXTRA) } + | '{' a=star_named_expressions '}' { _PyAST_Set(a, EXTRA) } # Dicts # ----- @@ -1572,3 +1576,11 @@ invalid_type_params: RAISE_SYNTAX_ERROR_STARTING_FROM( token, "Type parameter list cannot be empty")} + +invalid_list_slash: + | '[' a='/' ']' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, + "invalid syntax. Perhaps you meant '[]' instead of '[/]'?") } + +invalid_tuple_slash: + | '(' a='/' ')' { RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, + "invalid syntax. Perhaps you meant '()' instead of '(/)'?") } diff --git a/Lib/_ast_unparse.py b/Lib/_ast_unparse.py index 16cf56f62cc1e5..b20aef18db0171 100644 --- a/Lib/_ast_unparse.py +++ b/Lib/_ast_unparse.py @@ -772,9 +772,7 @@ def visit_Set(self, node): with self.delimit("{", "}"): self.interleave(lambda: self.write(", "), self.traverse, node.elts) else: - # `{}` would be interpreted as a dictionary literal, and - # `set` might be shadowed. Thus: - self.write('{*()}') + self.write('{/}') def visit_Dict(self, node): def write_key_value_pair(k, v): diff --git a/Lib/reprlib.py b/Lib/reprlib.py index ab18247682b69a..33bb44a2904fc3 100644 --- a/Lib/reprlib.py +++ b/Lib/reprlib.py @@ -139,7 +139,7 @@ def repr_array(self, x, level): def repr_set(self, x, level): if not x: - return 'set()' + return '{/}' x = _possibly_sorted(x) return self._repr_iterable(x, level, '{', '}', self.maxset) diff --git a/Lib/test/test_ast/data/ast_repr.txt b/Lib/test/test_ast/data/ast_repr.txt index 1c1985519cd8b4..b7d489490d35df 100644 --- a/Lib/test/test_ast/data/ast_repr.txt +++ b/Lib/test/test_ast/data/ast_repr.txt @@ -156,6 +156,7 @@ Module(body=[Expr(value=Lambda(args=arguments(...), body=Constant(...)))], type_ Module(body=[Expr(value=Dict(keys=[Constant(...)], values=[Constant(...)]))], type_ignores=[]) Module(body=[Expr(value=Dict(keys=[], values=[]))], type_ignores=[]) Module(body=[Expr(value=Set(elts=[Constant(...)]))], type_ignores=[]) +Module(body=[Expr(value=Set(elts=[]))], type_ignores=[]) Module(body=[Expr(value=Dict(keys=[Constant(...)], values=[Constant(...)]))], type_ignores=[]) Module(body=[Expr(value=List(elts=[Constant(...), Constant(...)], ctx=Load(...)))], type_ignores=[]) Module(body=[Expr(value=Tuple(elts=[Constant(...)], ctx=Load(...)))], type_ignores=[]) diff --git a/Lib/test/test_ast/snippets.py b/Lib/test/test_ast/snippets.py index b76f98901d2ad8..d1a19bda14c195 100644 --- a/Lib/test/test_ast/snippets.py +++ b/Lib/test/test_ast/snippets.py @@ -265,6 +265,8 @@ "{}", # Set "{None,}", + # Empty set + "{/}", # Multiline dict (test for .lineno & .col_offset) """{ 1 @@ -552,6 +554,7 @@ def main(): ('Expression', ('Dict', (1, 0, 1, 7), [('Constant', (1, 2, 1, 3), 1, None)], [('Constant', (1, 4, 1, 5), 2, None)])), ('Expression', ('Dict', (1, 0, 1, 2), [], [])), ('Expression', ('Set', (1, 0, 1, 7), [('Constant', (1, 1, 1, 5), None, None)])), +('Expression', ('Set', (1, 0, 1, 3), [])), ('Expression', ('Dict', (1, 0, 5, 6), [('Constant', (2, 6, 2, 7), 1, None)], [('Constant', (4, 10, 4, 11), 2, None)])), ('Expression', ('List', (1, 0, 5, 6), [('Constant', (2, 6, 2, 7), 1, None), ('Constant', (4, 8, 4, 9), 1, None)], ('Load',))), ('Expression', ('Tuple', (1, 0, 4, 6), [('Constant', (2, 6, 2, 7), 1, None)], ('Load',))), diff --git a/Lib/test/test_ast/test_ast.py b/Lib/test/test_ast/test_ast.py index 1e6f60074308e2..3d87b7c4415c56 100644 --- a/Lib/test/test_ast/test_ast.py +++ b/Lib/test/test_ast/test_ast.py @@ -1908,7 +1908,8 @@ def test_literal_eval(self): self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None)) self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3}) self.assertEqual(ast.literal_eval('b"hi"'), b"hi") - self.assertEqual(ast.literal_eval('set()'), set()) + self.assertEqual(ast.literal_eval('{/}'), {/}) + self.assertEqual(ast.literal_eval('set()'), {/}) self.assertRaises(ValueError, ast.literal_eval, 'foo()') self.assertEqual(ast.literal_eval('6'), 6) self.assertEqual(ast.literal_eval('+6'), 6) diff --git a/Lib/test/test_free_threading/test_set.py b/Lib/test/test_free_threading/test_set.py index a66e03bcc4c9d1..0af4f0f2cc568f 100644 --- a/Lib/test/test_free_threading/test_set.py +++ b/Lib/test/test_free_threading/test_set.py @@ -34,7 +34,7 @@ def repr_set(): t.join() for set_repr in set_reprs: - self.assertIn(set_repr, ("set()", "{1, 2, 3, 4, 5, 6, 7, 8}")) + self.assertIn(set_repr, ("{/}", "{1, 2, 3, 4, 5, 6, 7, 8}")) if __name__ == "__main__": diff --git a/Lib/test/test_gdb/test_pretty_print.py b/Lib/test/test_gdb/test_pretty_print.py index dfc77d65ab16a4..d32092231b1ac0 100644 --- a/Lib/test/test_gdb/test_pretty_print.py +++ b/Lib/test/test_gdb/test_pretty_print.py @@ -162,7 +162,7 @@ def test_sets(self): 'Verify the pretty-printing of sets' if GDB_VERSION < (7, 3): self.skipTest("pretty-printing of sets needs gdb 7.3 or later") - self.assertGdbRepr(set(), "set()") + self.assertGdbRepr(set(), "{/}") self.assertGdbRepr(set(['a']), "{'a'}") # PYTHONHASHSEED is need to get the exact frozenset item order if not sys.flags.ignore_environment: diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py index 7f5d48b9c63ab7..1df4a864582e92 100644 --- a/Lib/test/test_grammar.py +++ b/Lib/test/test_grammar.py @@ -1685,6 +1685,7 @@ def test_atoms(self): x = {'one': 1, 'two': 2,} x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} + x = {/} x = {'one'} x = {'one', 1,} x = {'one', 'two', 'three'} diff --git a/Lib/test/test_pprint.py b/Lib/test/test_pprint.py index 41c337ade7eca1..af914201d1030f 100644 --- a/Lib/test/test_pprint.py +++ b/Lib/test/test_pprint.py @@ -833,7 +833,8 @@ def test_subclassing(self): self.assertEqual(dotted_printer.pformat(o2), exp2) def test_set_reprs(self): - self.assertEqual(pprint.pformat(set()), 'set()') + self.assertEqual(pprint.pformat({/}), '{/}') + self.assertEqual(pprint.pformat(set()), '{/}') self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}') self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\ {0, diff --git a/Lib/test/test_reprlib.py b/Lib/test/test_reprlib.py index 22a55b57c076eb..bb5889d9d9abbc 100644 --- a/Lib/test/test_reprlib.py +++ b/Lib/test/test_reprlib.py @@ -103,7 +103,7 @@ def test_container(self): eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]") # Sets give up after 6 as well - eq(r(set([])), "set()") + eq(r(set([])), "{/}") eq(r(set([1])), "{1}") eq(r(set([1, 2, 3])), "{1, 2, 3}") eq(r(set([1, 2, 3, 4, 5, 6])), "{1, 2, 3, 4, 5, 6}") diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py index c0df9507bd7f5e..a091025b5148d3 100644 --- a/Lib/test/test_set.py +++ b/Lib/test/test_set.py @@ -864,7 +864,7 @@ class TestFrozenSetSubclassWithSlots(TestSetSubclassWithSlots): # Tests taken from test_sets.py ============================================= -empty_set = set() +empty_set = {/} #============================================================================== @@ -981,7 +981,7 @@ def setUp(self): self.set = set(self.values) self.dup = set(self.values) self.length = 0 - self.repr = "set()" + self.repr = "{/}" #------------------------------------------------------------------------------ diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py index c52d24219410c2..6a475833f8c2e4 100644 --- a/Lib/test/test_syntax.py +++ b/Lib/test/test_syntax.py @@ -350,6 +350,25 @@ Traceback (most recent call last): SyntaxError: invalid syntax. Perhaps you forgot a comma? +# Suggest the correct form of an empty literal collection. +# A slash ('/') is only valid for sets. + +>>> [/] +Traceback (most recent call last): +SyntaxError: invalid syntax. Perhaps you meant '[]' instead of '[/]'? + +>>> [ / ] +Traceback (most recent call last): +SyntaxError: invalid syntax. Perhaps you meant '[]' instead of '[/]'? + +>>> (/) +Traceback (most recent call last): +SyntaxError: invalid syntax. Perhaps you meant '()' instead of '(/)'? + +>>> ( / ) +Traceback (most recent call last): +SyntaxError: invalid syntax. Perhaps you meant '()' instead of '(/)'? + # Make sure soft keywords constructs don't raise specialized # errors regarding missing commas or other spezialiced errors diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py index 0d6b05bc660b76..1d254bbe9ae2d6 100644 --- a/Lib/test/test_unparse.py +++ b/Lib/test/test_unparse.py @@ -301,10 +301,7 @@ def test_set_literal(self): self.check_ast_roundtrip("{'a', 'b', 'c'}") def test_empty_set(self): - self.assertASTEqual( - ast.parse(ast.unparse(ast.Set(elts=[]))), - ast.parse('{*()}') - ) + self.check_ast_roundtrip("{/}") def test_set_comprehension(self): self.check_ast_roundtrip("{x for x in range(5)}") diff --git a/Objects/setobject.c b/Objects/setobject.c index 6e4fc5957cad7f..0e42b595997b2c 100644 --- a/Objects/setobject.c +++ b/Objects/setobject.c @@ -565,6 +565,9 @@ set_repr_lock_held(PySetObject *so) /* shortcut for the empty set */ if (!so->used) { Py_ReprLeave((PyObject*)so); + if (PySet_CheckExact(so)) { + return PyUnicode_FromString("{/}"); + } return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); } diff --git a/Parser/parser.c b/Parser/parser.c index de5cdc9b6f7f34..31268321980e31 100644 --- a/Parser/parser.c +++ b/Parser/parser.c @@ -353,182 +353,184 @@ static char *soft_keywords[] = { #define invalid_arithmetic_type 1266 #define invalid_factor_type 1267 #define invalid_type_params_type 1268 -#define _loop0_1_type 1269 -#define _loop1_2_type 1270 -#define _loop0_3_type 1271 -#define _gather_4_type 1272 -#define _tmp_5_type 1273 -#define _tmp_6_type 1274 -#define _tmp_7_type 1275 -#define _tmp_8_type 1276 -#define _tmp_9_type 1277 -#define _tmp_10_type 1278 -#define _tmp_11_type 1279 -#define _loop1_12_type 1280 -#define _loop0_13_type 1281 -#define _gather_14_type 1282 -#define _tmp_15_type 1283 -#define _tmp_16_type 1284 -#define _loop0_17_type 1285 -#define _loop1_18_type 1286 -#define _loop0_19_type 1287 -#define _gather_20_type 1288 -#define _tmp_21_type 1289 -#define _loop0_22_type 1290 -#define _gather_23_type 1291 -#define _loop1_24_type 1292 -#define _tmp_25_type 1293 -#define _tmp_26_type 1294 -#define _loop0_27_type 1295 -#define _loop0_28_type 1296 -#define _loop1_29_type 1297 -#define _loop1_30_type 1298 -#define _loop0_31_type 1299 -#define _loop1_32_type 1300 -#define _loop0_33_type 1301 -#define _gather_34_type 1302 -#define _tmp_35_type 1303 -#define _loop1_36_type 1304 -#define _loop1_37_type 1305 -#define _loop1_38_type 1306 -#define _loop0_39_type 1307 -#define _gather_40_type 1308 -#define _tmp_41_type 1309 -#define _tmp_42_type 1310 -#define _tmp_43_type 1311 -#define _loop0_44_type 1312 -#define _gather_45_type 1313 -#define _loop0_46_type 1314 -#define _gather_47_type 1315 -#define _tmp_48_type 1316 -#define _loop0_49_type 1317 -#define _gather_50_type 1318 -#define _loop0_51_type 1319 -#define _gather_52_type 1320 -#define _loop0_53_type 1321 -#define _gather_54_type 1322 -#define _loop1_55_type 1323 -#define _loop1_56_type 1324 -#define _loop0_57_type 1325 -#define _gather_58_type 1326 -#define _loop1_59_type 1327 -#define _loop1_60_type 1328 -#define _loop1_61_type 1329 -#define _tmp_62_type 1330 -#define _loop0_63_type 1331 -#define _gather_64_type 1332 -#define _tmp_65_type 1333 -#define _tmp_66_type 1334 -#define _tmp_67_type 1335 -#define _tmp_68_type 1336 -#define _tmp_69_type 1337 -#define _loop0_70_type 1338 -#define _loop0_71_type 1339 -#define _loop1_72_type 1340 -#define _loop1_73_type 1341 -#define _loop0_74_type 1342 -#define _loop1_75_type 1343 -#define _loop0_76_type 1344 -#define _loop0_77_type 1345 -#define _loop0_78_type 1346 -#define _loop0_79_type 1347 -#define _loop1_80_type 1348 -#define _loop1_81_type 1349 -#define _tmp_82_type 1350 -#define _loop0_83_type 1351 -#define _gather_84_type 1352 -#define _loop1_85_type 1353 -#define _loop0_86_type 1354 -#define _tmp_87_type 1355 -#define _loop0_88_type 1356 -#define _gather_89_type 1357 -#define _tmp_90_type 1358 -#define _loop0_91_type 1359 -#define _gather_92_type 1360 -#define _loop0_93_type 1361 -#define _gather_94_type 1362 -#define _loop0_95_type 1363 -#define _loop0_96_type 1364 -#define _gather_97_type 1365 -#define _loop1_98_type 1366 -#define _tmp_99_type 1367 -#define _loop0_100_type 1368 -#define _gather_101_type 1369 -#define _loop0_102_type 1370 -#define _gather_103_type 1371 -#define _tmp_104_type 1372 -#define _tmp_105_type 1373 -#define _loop0_106_type 1374 -#define _gather_107_type 1375 -#define _tmp_108_type 1376 -#define _tmp_109_type 1377 -#define _tmp_110_type 1378 -#define _tmp_111_type 1379 -#define _tmp_112_type 1380 -#define _loop1_113_type 1381 -#define _tmp_114_type 1382 -#define _tmp_115_type 1383 -#define _tmp_116_type 1384 -#define _tmp_117_type 1385 -#define _tmp_118_type 1386 -#define _loop0_119_type 1387 -#define _loop0_120_type 1388 -#define _tmp_121_type 1389 -#define _tmp_122_type 1390 -#define _tmp_123_type 1391 -#define _tmp_124_type 1392 -#define _tmp_125_type 1393 -#define _tmp_126_type 1394 -#define _tmp_127_type 1395 -#define _tmp_128_type 1396 -#define _tmp_129_type 1397 -#define _loop0_130_type 1398 -#define _gather_131_type 1399 -#define _tmp_132_type 1400 -#define _tmp_133_type 1401 -#define _tmp_134_type 1402 -#define _tmp_135_type 1403 -#define _loop0_136_type 1404 -#define _gather_137_type 1405 -#define _tmp_138_type 1406 -#define _loop0_139_type 1407 -#define _gather_140_type 1408 -#define _loop0_141_type 1409 -#define _gather_142_type 1410 -#define _tmp_143_type 1411 -#define _loop0_144_type 1412 -#define _tmp_145_type 1413 -#define _tmp_146_type 1414 -#define _tmp_147_type 1415 -#define _tmp_148_type 1416 -#define _tmp_149_type 1417 -#define _tmp_150_type 1418 -#define _tmp_151_type 1419 -#define _tmp_152_type 1420 -#define _tmp_153_type 1421 -#define _tmp_154_type 1422 -#define _tmp_155_type 1423 -#define _tmp_156_type 1424 -#define _tmp_157_type 1425 -#define _tmp_158_type 1426 -#define _tmp_159_type 1427 -#define _tmp_160_type 1428 -#define _tmp_161_type 1429 -#define _tmp_162_type 1430 -#define _tmp_163_type 1431 -#define _tmp_164_type 1432 -#define _tmp_165_type 1433 -#define _tmp_166_type 1434 -#define _tmp_167_type 1435 -#define _tmp_168_type 1436 -#define _tmp_169_type 1437 -#define _tmp_170_type 1438 -#define _loop0_171_type 1439 -#define _tmp_172_type 1440 -#define _tmp_173_type 1441 -#define _tmp_174_type 1442 -#define _tmp_175_type 1443 -#define _tmp_176_type 1444 +#define invalid_list_slash_type 1269 +#define invalid_tuple_slash_type 1270 +#define _loop0_1_type 1271 +#define _loop1_2_type 1272 +#define _loop0_3_type 1273 +#define _gather_4_type 1274 +#define _tmp_5_type 1275 +#define _tmp_6_type 1276 +#define _tmp_7_type 1277 +#define _tmp_8_type 1278 +#define _tmp_9_type 1279 +#define _tmp_10_type 1280 +#define _tmp_11_type 1281 +#define _loop1_12_type 1282 +#define _loop0_13_type 1283 +#define _gather_14_type 1284 +#define _tmp_15_type 1285 +#define _tmp_16_type 1286 +#define _loop0_17_type 1287 +#define _loop1_18_type 1288 +#define _loop0_19_type 1289 +#define _gather_20_type 1290 +#define _tmp_21_type 1291 +#define _loop0_22_type 1292 +#define _gather_23_type 1293 +#define _loop1_24_type 1294 +#define _tmp_25_type 1295 +#define _tmp_26_type 1296 +#define _loop0_27_type 1297 +#define _loop0_28_type 1298 +#define _loop1_29_type 1299 +#define _loop1_30_type 1300 +#define _loop0_31_type 1301 +#define _loop1_32_type 1302 +#define _loop0_33_type 1303 +#define _gather_34_type 1304 +#define _tmp_35_type 1305 +#define _loop1_36_type 1306 +#define _loop1_37_type 1307 +#define _loop1_38_type 1308 +#define _loop0_39_type 1309 +#define _gather_40_type 1310 +#define _tmp_41_type 1311 +#define _tmp_42_type 1312 +#define _tmp_43_type 1313 +#define _loop0_44_type 1314 +#define _gather_45_type 1315 +#define _loop0_46_type 1316 +#define _gather_47_type 1317 +#define _tmp_48_type 1318 +#define _loop0_49_type 1319 +#define _gather_50_type 1320 +#define _loop0_51_type 1321 +#define _gather_52_type 1322 +#define _loop0_53_type 1323 +#define _gather_54_type 1324 +#define _loop1_55_type 1325 +#define _loop1_56_type 1326 +#define _loop0_57_type 1327 +#define _gather_58_type 1328 +#define _loop1_59_type 1329 +#define _loop1_60_type 1330 +#define _loop1_61_type 1331 +#define _tmp_62_type 1332 +#define _loop0_63_type 1333 +#define _gather_64_type 1334 +#define _tmp_65_type 1335 +#define _tmp_66_type 1336 +#define _tmp_67_type 1337 +#define _tmp_68_type 1338 +#define _tmp_69_type 1339 +#define _loop0_70_type 1340 +#define _loop0_71_type 1341 +#define _loop1_72_type 1342 +#define _loop1_73_type 1343 +#define _loop0_74_type 1344 +#define _loop1_75_type 1345 +#define _loop0_76_type 1346 +#define _loop0_77_type 1347 +#define _loop0_78_type 1348 +#define _loop0_79_type 1349 +#define _loop1_80_type 1350 +#define _loop1_81_type 1351 +#define _tmp_82_type 1352 +#define _loop0_83_type 1353 +#define _gather_84_type 1354 +#define _loop1_85_type 1355 +#define _loop0_86_type 1356 +#define _tmp_87_type 1357 +#define _loop0_88_type 1358 +#define _gather_89_type 1359 +#define _tmp_90_type 1360 +#define _loop0_91_type 1361 +#define _gather_92_type 1362 +#define _loop0_93_type 1363 +#define _gather_94_type 1364 +#define _loop0_95_type 1365 +#define _loop0_96_type 1366 +#define _gather_97_type 1367 +#define _loop1_98_type 1368 +#define _tmp_99_type 1369 +#define _loop0_100_type 1370 +#define _gather_101_type 1371 +#define _loop0_102_type 1372 +#define _gather_103_type 1373 +#define _tmp_104_type 1374 +#define _tmp_105_type 1375 +#define _loop0_106_type 1376 +#define _gather_107_type 1377 +#define _tmp_108_type 1378 +#define _tmp_109_type 1379 +#define _tmp_110_type 1380 +#define _tmp_111_type 1381 +#define _tmp_112_type 1382 +#define _loop1_113_type 1383 +#define _tmp_114_type 1384 +#define _tmp_115_type 1385 +#define _tmp_116_type 1386 +#define _tmp_117_type 1387 +#define _tmp_118_type 1388 +#define _loop0_119_type 1389 +#define _loop0_120_type 1390 +#define _tmp_121_type 1391 +#define _tmp_122_type 1392 +#define _tmp_123_type 1393 +#define _tmp_124_type 1394 +#define _tmp_125_type 1395 +#define _tmp_126_type 1396 +#define _tmp_127_type 1397 +#define _tmp_128_type 1398 +#define _tmp_129_type 1399 +#define _loop0_130_type 1400 +#define _gather_131_type 1401 +#define _tmp_132_type 1402 +#define _tmp_133_type 1403 +#define _tmp_134_type 1404 +#define _tmp_135_type 1405 +#define _loop0_136_type 1406 +#define _gather_137_type 1407 +#define _tmp_138_type 1408 +#define _loop0_139_type 1409 +#define _gather_140_type 1410 +#define _loop0_141_type 1411 +#define _gather_142_type 1412 +#define _tmp_143_type 1413 +#define _loop0_144_type 1414 +#define _tmp_145_type 1415 +#define _tmp_146_type 1416 +#define _tmp_147_type 1417 +#define _tmp_148_type 1418 +#define _tmp_149_type 1419 +#define _tmp_150_type 1420 +#define _tmp_151_type 1421 +#define _tmp_152_type 1422 +#define _tmp_153_type 1423 +#define _tmp_154_type 1424 +#define _tmp_155_type 1425 +#define _tmp_156_type 1426 +#define _tmp_157_type 1427 +#define _tmp_158_type 1428 +#define _tmp_159_type 1429 +#define _tmp_160_type 1430 +#define _tmp_161_type 1431 +#define _tmp_162_type 1432 +#define _tmp_163_type 1433 +#define _tmp_164_type 1434 +#define _tmp_165_type 1435 +#define _tmp_166_type 1436 +#define _tmp_167_type 1437 +#define _tmp_168_type 1438 +#define _tmp_169_type 1439 +#define _tmp_170_type 1440 +#define _loop0_171_type 1441 +#define _tmp_172_type 1442 +#define _tmp_173_type 1443 +#define _tmp_174_type 1444 +#define _tmp_175_type 1445 +#define _tmp_176_type 1446 static mod_ty file_rule(Parser *p); static mod_ty interactive_rule(Parser *p); @@ -799,6 +801,8 @@ static void *invalid_string_tstring_concat_rule(Parser *p); static void *invalid_arithmetic_rule(Parser *p); static void *invalid_factor_rule(Parser *p); static void *invalid_type_params_rule(Parser *p); +static void *invalid_list_slash_rule(Parser *p); +static void *invalid_tuple_slash_rule(Parser *p); static asdl_seq *_loop0_1_rule(Parser *p); static asdl_seq *_loop1_2_rule(Parser *p); static asdl_seq *_loop0_3_rule(Parser *p); @@ -17241,7 +17245,7 @@ strings_rule(Parser *p) return _res; } -// list: '[' star_named_expressions? ']' +// list: invalid_list_slash | '[' star_named_expressions? ']' static expr_ty list_rule(Parser *p) { @@ -17263,6 +17267,25 @@ list_rule(Parser *p) UNUSED(_start_lineno); // Only used by EXTRA macro int _start_col_offset = p->tokens[_mark]->col_offset; UNUSED(_start_col_offset); // Only used by EXTRA macro + if (p->call_invalid_rules) { // invalid_list_slash + if (p->error_indicator) { + p->level--; + return NULL; + } + D(fprintf(stderr, "%*c> list[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "invalid_list_slash")); + void *invalid_list_slash_var; + if ( + (invalid_list_slash_var = invalid_list_slash_rule(p)) // invalid_list_slash + ) + { + D(fprintf(stderr, "%*c+ list[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "invalid_list_slash")); + _res = invalid_list_slash_var; + goto done; + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s list[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "invalid_list_slash")); + } { // '[' star_named_expressions? ']' if (p->error_indicator) { p->level--; @@ -17308,7 +17331,9 @@ list_rule(Parser *p) return _res; } -// tuple: '(' [star_named_expression ',' star_named_expressions?] ')' +// tuple: +// | invalid_tuple_slash +// | '(' [star_named_expression ',' star_named_expressions?] ')' static expr_ty tuple_rule(Parser *p) { @@ -17330,6 +17355,25 @@ tuple_rule(Parser *p) UNUSED(_start_lineno); // Only used by EXTRA macro int _start_col_offset = p->tokens[_mark]->col_offset; UNUSED(_start_col_offset); // Only used by EXTRA macro + if (p->call_invalid_rules) { // invalid_tuple_slash + if (p->error_indicator) { + p->level--; + return NULL; + } + D(fprintf(stderr, "%*c> tuple[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "invalid_tuple_slash")); + void *invalid_tuple_slash_var; + if ( + (invalid_tuple_slash_var = invalid_tuple_slash_rule(p)) // invalid_tuple_slash + ) + { + D(fprintf(stderr, "%*c+ tuple[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "invalid_tuple_slash")); + _res = invalid_tuple_slash_var; + goto done; + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s tuple[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "invalid_tuple_slash")); + } { // '(' [star_named_expression ',' star_named_expressions?] ')' if (p->error_indicator) { p->level--; @@ -17375,7 +17419,7 @@ tuple_rule(Parser *p) return _res; } -// set: '{' star_named_expressions '}' +// set: '{' '/' '}' | '{' star_named_expressions '}' static expr_ty set_rule(Parser *p) { @@ -17397,6 +17441,45 @@ set_rule(Parser *p) UNUSED(_start_lineno); // Only used by EXTRA macro int _start_col_offset = p->tokens[_mark]->col_offset; UNUSED(_start_col_offset); // Only used by EXTRA macro + { // '{' '/' '}' + if (p->error_indicator) { + p->level--; + return NULL; + } + D(fprintf(stderr, "%*c> set[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'{' '/' '}'")); + Token * _literal; + Token * _literal_1; + Token * _literal_2; + if ( + (_literal = _PyPegen_expect_token(p, 25)) // token='{' + && + (_literal_1 = _PyPegen_expect_token(p, 17)) // token='/' + && + (_literal_2 = _PyPegen_expect_token(p, 26)) // token='}' + ) + { + D(fprintf(stderr, "%*c+ set[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'{' '/' '}'")); + Token *_token = _PyPegen_get_last_nonnwhitespace_token(p); + if (_token == NULL) { + p->level--; + return NULL; + } + int _end_lineno = _token->end_lineno; + UNUSED(_end_lineno); // Only used by EXTRA macro + int _end_col_offset = _token->end_col_offset; + UNUSED(_end_col_offset); // Only used by EXTRA macro + _res = _PyAST_Set ( NULL , EXTRA ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; + return NULL; + } + goto done; + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s set[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'{' '/' '}'")); + } { // '{' star_named_expressions '}' if (p->error_indicator) { p->level--; @@ -27403,6 +27486,104 @@ invalid_type_params_rule(Parser *p) return _res; } +// invalid_list_slash: '[' '/' ']' +static void * +invalid_list_slash_rule(Parser *p) +{ + if (p->level++ == MAXSTACK || _Py_ReachedRecursionLimitWithMargin(PyThreadState_Get(), 1)) { + _Pypegen_stack_overflow(p); + } + if (p->error_indicator) { + p->level--; + return NULL; + } + void * _res = NULL; + int _mark = p->mark; + { // '[' '/' ']' + if (p->error_indicator) { + p->level--; + return NULL; + } + D(fprintf(stderr, "%*c> invalid_list_slash[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'[' '/' ']'")); + Token * _literal; + Token * _literal_1; + Token * a; + if ( + (_literal = _PyPegen_expect_token(p, 9)) // token='[' + && + (a = _PyPegen_expect_token(p, 17)) // token='/' + && + (_literal_1 = _PyPegen_expect_token(p, 10)) // token=']' + ) + { + D(fprintf(stderr, "%*c+ invalid_list_slash[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'[' '/' ']'")); + _res = RAISE_SYNTAX_ERROR_KNOWN_LOCATION ( a , "invalid syntax. Perhaps you meant '[]' instead of '[/]'?" ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; + return NULL; + } + goto done; + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s invalid_list_slash[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'[' '/' ']'")); + } + _res = NULL; + done: + p->level--; + return _res; +} + +// invalid_tuple_slash: '(' '/' ')' +static void * +invalid_tuple_slash_rule(Parser *p) +{ + if (p->level++ == MAXSTACK || _Py_ReachedRecursionLimitWithMargin(PyThreadState_Get(), 1)) { + _Pypegen_stack_overflow(p); + } + if (p->error_indicator) { + p->level--; + return NULL; + } + void * _res = NULL; + int _mark = p->mark; + { // '(' '/' ')' + if (p->error_indicator) { + p->level--; + return NULL; + } + D(fprintf(stderr, "%*c> invalid_tuple_slash[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'(' '/' ')'")); + Token * _literal; + Token * _literal_1; + Token * a; + if ( + (_literal = _PyPegen_expect_token(p, 7)) // token='(' + && + (a = _PyPegen_expect_token(p, 17)) // token='/' + && + (_literal_1 = _PyPegen_expect_token(p, 8)) // token=')' + ) + { + D(fprintf(stderr, "%*c+ invalid_tuple_slash[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'(' '/' ')'")); + _res = RAISE_SYNTAX_ERROR_KNOWN_LOCATION ( a , "invalid syntax. Perhaps you meant '()' instead of '(/)'?" ); + if (_res == NULL && PyErr_Occurred()) { + p->error_indicator = 1; + p->level--; + return NULL; + } + goto done; + } + p->mark = _mark; + D(fprintf(stderr, "%*c%s invalid_tuple_slash[%d-%d]: %s failed!\n", p->level, ' ', + p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'(' '/' ')'")); + } + _res = NULL; + done: + p->level--; + return _res; +} + // _loop0_1: NEWLINE static asdl_seq * _loop0_1_rule(Parser *p) diff --git a/Python/ast_unparse.c b/Python/ast_unparse.c index c25699978cf651..930a2ce59ddefa 100644 --- a/Python/ast_unparse.c +++ b/Python/ast_unparse.c @@ -354,13 +354,16 @@ append_ast_set(PyUnicodeWriter *writer, expr_ty e) { Py_ssize_t i, elem_count; - APPEND_CHAR('{'); elem_count = asdl_seq_LEN(e->v.Set.elts); + if (elem_count == 0) { + APPEND_STR_FINISH("{/}"); + } + + APPEND_CHAR('{'); for (i = 0; i < elem_count; i++) { APPEND_STR_IF(i > 0, ", "); APPEND_EXPR((expr_ty)asdl_seq_GET(e->v.Set.elts, i), PR_TEST); } - APPEND_CHAR_FINISH('}'); }