Skip to content

Commit 8f59ee0

Browse files
bpo-35224: PEP 572 Implementation (#10497)
* Add tokenization of := - Add token to Include/token.h. Add token to documentation in Doc/library/token.rst. - Run `./python Lib/token.py` to regenerate Lib/token.py. - Update Parser/tokenizer.c: add case to handle `:=`. * Add initial usage of := in grammar. * Update Python.asdl to match the grammar updates. Regenerated Include/Python-ast.h and Python/Python-ast.c * Update AST and compiler files in Python/ast.c and Python/compile.c. Basic functionality, this isn't scoped properly * Regenerate Lib/symbol.py using `./python Lib/symbol.py` * Tests - Fix failing tests in test_parser.py due to changes in token numbers for internal representation * Tests - Add simple test for := token * Tests - Add simple tests for named expressions using expr and suite * Tests - Update number of levels for nested expressions to prevent stack overflow * Update symbol table to handle NamedExpr * Update Grammar to allow assignment expressions in if statements. Regenerate Python/graminit.c accordingly using `make regen-grammar` * Tests - Add additional tests for named expressions in RoundtripLegalSyntaxTestCase, based on examples and information directly from PEP 572 Note: failing tests are currently commented out (4 out of 24 tests currently fail) * Tests - Add temporary syntax test failure tests in test_parser.py Note: There is an outstanding TODO for this -- syntax tests need to be moved to a different file (presumably test_syntax.py), but this is covering what needs to be tested at the moment, and it's more convenient to run a single test for the time being * Add support for allowing assignment expressions as function argument annotations. Uncomment tests for these cases because they all pass now! * Tests - Move existing syntax tests out of test_parser.py and into test_named_expressions.py. Refactor syntax tests to use unittest * Add TargetScopeError exception to extend SyntaxError Note: This simply creates the TargetScopeError exception, it is not yet used anywhere * Tests - Update tests per PEP 572 Continue refactoring test suite: The named expression test suite now checks for any invalid cases that throw exceptions (no longer limited to SyntaxErrors), assignment tests to ensure that variables are properly assigned, and scope tests to ensure that variable availability and values are correct Note: - There are still tests that are marked to skip, as they are not yet implemented - There are approximately 300 lines of the PEP that have not yet been addressed, though these may be deferred * Documentation - Small updates to XXX/todo comments - Remove XXX from child description in ast.c - Add comment with number of previously supported nested expressions for 3.7.X in test_parser.py * Fix assert in seq_for_testlist() * Cleanup - Denote "Not implemented -- No keyword args" on failing test case. Fix PEP8 error for blank lines at beginning of test classes in test_parser.py * Tests - Wrap all file opens in `with...as` to ensure files are closed * WIP: handle f(a := 1) * Tests and Cleanup - No longer skips keyword arg test. Keyword arg test now uses a simpler test case and does not rely on an external file. Remove print statements from ast.c * Tests - Refactor last remaining test case that relied on on external file to use a simpler test case without the dependency * Tests - Add better description of remaning skipped tests. Add test checking scope when using assignment expression in a function argument * Tests - Add test for nested comprehension, testing value and scope. Fix variable name in skipped comprehension scope test * Handle restriction of LHS for named expressions - can only assign to LHS of type NAME. Specifically, restrict assignment to tuples This adds an alternative set_context specifically for named expressions, set_namedexpr_context. Thus, context is now set differently for standard assignment versus assignment for named expressions in order to handle restrictions. * Tests - Update negative test case for assigning to lambda to match new error message. Add negative test case for assigning to tuple * Tests - Reorder test cases to group invalid syntax cases and named assignment target errors * Tests - Update test case for named expression in function argument - check that result and variable are set correctly * Todo - Add todo for TargetScopeError based on Guido's comment (2b3acd3#r30472562) * Tests - Add named expression tests for assignment operator in function arguments Note: One of two tests are skipped, as function arguments are currently treating an assignment expression inside of parenthesis as one child, which does not properly catch the named expression, nor does it count arguments properly * Add NamedStore to expr_context. Regenerate related code with `make regen-ast` * Add usage of NamedStore to ast_for_named_expr in ast.c. Update occurances of checking for Store to also handle NamedStore where appropriate * Add ste_comprehension to _symtable_entry to track if the namespace is a comprehension. Initialize ste_comprehension to 0. Set set_comprehension to 1 in symtable_handle_comprehension * s/symtable_add_def/symtable_add_def_helper. Add symtable_add_def to handle grabbing st->st_cur and passing it to symtable_add_def_helper. This now allows us to call the original code from symtable_add_def by instead calling symtable_add_def_helper with a different ste. * Refactor symtable_record_directive to take lineno and col_offset as arguments instead of stmt_ty. This allows symtable_record_directive to be used for stmt_ty and expr_ty * Handle elevating scope for named expressions in comprehensions. * Handle error for usage of named expression inside a class block * Tests - No longer skip scope tests. Add additional scope tests * Cleanup - Update error message for named expression within a comprehension within a class. Update comments. Add assert for symtable_extend_namedexpr_scope to validate that we always find at least a ModuleScope if we don't find a Class or FunctionScope * Cleanup - Add missing case for NamedStore in expr_context_name. Remove unused var in set_namedexpr_content * Refactor - Consolidate set_context and set_namedexpr_context to reduce duplicated code. Special cases for named expressions are handled by checking if ctx is NamedStore * Cleanup - Add additional use cases for ast_for_namedexpr in usage comment. Fix multiple blank lines in test_named_expressions * Tests - Remove unnecessary test case. Renumber test case function names * Remove TargetScopeError for now. Will add back if needed * Cleanup - Small comment nit for consistency * Handle positional argument check with named expression * Add TargetScopeError exception definition. Add documentation for TargetScopeError in c-api docs. Throw TargetScopeError instead of SyntaxError when using a named expression in a comprehension within a class scope * Increase stack size for parser by 200. This is a minimal change (approx. 5kb) and should not have an impact on any systems. Update parser test to allow 99 nested levels again * Add TargetScopeError to exception_hierarchy.txt for test_baseexception.py_ * Tests - Major update for named expression tests, both in test_named_expressions and test_parser - Add test for TargetScopeError - Add tests for named expressions in comprehension scope and edge cases - Add tests for named expressions in function arguments (declarations and call sites) - Reorganize tests to group them more logically * Cleanup - Remove unnecessary comment * Cleanup - Comment nitpicks * Explicitly disallow assignment expressions to a name inside parentheses, e.g.: ((x) := 0) - Add check for LHS types to detect a parenthesis then a name (see note) - Add test for this scenario - Update tests for changed error message for named assignment to a tuple (also, see note) Note: This caused issues with the previous error handling for named assignment to a LHS that contained an expression, such as a tuple. Thus, the check for the LHS of a named expression must be changed to be more specific if we wish to maintain the previous error messages * Cleanup - Wrap lines more strictly in test file * Revert "Explicitly disallow assignment expressions to a name inside parentheses, e.g.: ((x) := 0)" This reverts commit f153140. * Add NEWS.d entry * Tests - Fix error in test_pickle.test_exceptions by adding TargetScopeError to list of exceptions * Tests - Update error message tests to reflect improved messaging convention (s/can't/cannot) * Remove cases that cannot be reached in compile.c. Small linting update. * Update Grammar/Tokens to add COLONEQUAL. Regenerate all files * Update TargetScopeError PRE_INIT and POST_INIT, as this was purposefully left out when fixing rebase conflicts * Add NamedStore back and regenerate files * Pass along line number and end col info for named expression * Simplify News entry * Fix compiler warning and explicity mark fallthrough
1 parent 1fd06f1 commit 8f59ee0

27 files changed

+1472
-655
lines changed

Doc/c-api/exceptions.rst

+3
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,7 @@ the variables:
800800
single: PyExc_SystemError
801801
single: PyExc_SystemExit
802802
single: PyExc_TabError
803+
single: PyExc_TargetScopeError
803804
single: PyExc_TimeoutError
804805
single: PyExc_TypeError
805806
single: PyExc_UnboundLocalError
@@ -901,6 +902,8 @@ the variables:
901902
+-----------------------------------------+---------------------------------+----------+
902903
| :c:data:`PyExc_TabError` | :exc:`TabError` | |
903904
+-----------------------------------------+---------------------------------+----------+
905+
| :c:data:`PyExc_TargetScopeError` | :exc:`TargetScopeError` | |
906+
+-----------------------------------------+---------------------------------+----------+
904907
| :c:data:`PyExc_TimeoutError` | :exc:`TimeoutError` | |
905908
+-----------------------------------------+---------------------------------+----------+
906909
| :c:data:`PyExc_TypeError` | :exc:`TypeError` | |

Doc/library/token-list.inc

+4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Grammar/Grammar

+4-2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ assert_stmt: 'assert' test [',' test]
6969

7070
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt
7171
async_stmt: 'async' (funcdef | with_stmt | for_stmt)
72-
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
72+
if_stmt: 'if' namedexpr_test ':' suite ('elif' namedexpr_test ':' suite)* ['else' ':' suite]
7373
while_stmt: 'while' test ':' suite ['else' ':' suite]
7474
for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
7575
try_stmt: ('try' ':' suite
@@ -83,6 +83,7 @@ with_item: test ['as' expr]
8383
except_clause: 'except' [test ['as' NAME]]
8484
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
8585

86+
namedexpr_test: test [':=' test]
8687
test: or_test ['if' or_test 'else' test] | lambdef
8788
test_nocond: or_test | lambdef_nocond
8889
lambdef: 'lambda' [varargslist] ':' test
@@ -108,7 +109,7 @@ atom: ('(' [yield_expr|testlist_comp] ')' |
108109
'[' [testlist_comp] ']' |
109110
'{' [dictorsetmaker] '}' |
110111
NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
111-
testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
112+
testlist_comp: (namedexpr_test|star_expr) ( comp_for | (',' (namedexpr_test|star_expr))* [','] )
112113
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
113114
subscriptlist: subscript (',' subscript)* [',']
114115
subscript: test | [test] ':' [test] [sliceop]
@@ -134,6 +135,7 @@ arglist: argument (',' argument)* [',']
134135
# multiple (test comp_for) arguments are blocked; keyword unpackings
135136
# that precede iterable unpackings are blocked; etc.
136137
argument: ( test [comp_for] |
138+
test ':=' test |
137139
test '=' test |
138140
'**' test |
139141
'*' test )

Grammar/Tokens

+1
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ AT '@'
5252
ATEQUAL '@='
5353
RARROW '->'
5454
ELLIPSIS '...'
55+
COLONEQUAL ':='
5556

5657
OP
5758
ERRORTOKEN

Include/Python-ast.h

+18-9
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Include/graminit.h

+39-38
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Include/pyerrors.h

+1
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ PyAPI_DATA(PyObject *) PyExc_NotImplementedError;
108108
PyAPI_DATA(PyObject *) PyExc_SyntaxError;
109109
PyAPI_DATA(PyObject *) PyExc_IndentationError;
110110
PyAPI_DATA(PyObject *) PyExc_TabError;
111+
PyAPI_DATA(PyObject *) PyExc_TargetScopeError;
111112
PyAPI_DATA(PyObject *) PyExc_ReferenceError;
112113
PyAPI_DATA(PyObject *) PyExc_SystemError;
113114
PyAPI_DATA(PyObject *) PyExc_SystemExit;

Include/symtable.h

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ typedef struct _symtable_entry {
5050
including free refs to globals */
5151
unsigned ste_generator : 1; /* true if namespace is a generator */
5252
unsigned ste_coroutine : 1; /* true if namespace is a coroutine */
53+
unsigned ste_comprehension : 1; /* true if namespace is a list comprehension */
5354
unsigned ste_varargs : 1; /* true if block has varargs */
5455
unsigned ste_varkeywords : 1; /* true if block has varkeywords */
5556
unsigned ste_returns_value : 1; /* true if namespace uses return with

Include/token.h

+4-3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Lib/_compat_pickle.py

+1
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@
128128
"SystemError",
129129
"SystemExit",
130130
"TabError",
131+
"TargetScopeError",
131132
"TypeError",
132133
"UnboundLocalError",
133134
"UnicodeDecodeError",

Lib/symbol.py

+39-38
Original file line numberDiff line numberDiff line change
@@ -61,44 +61,45 @@
6161
with_item = 302
6262
except_clause = 303
6363
suite = 304
64-
test = 305
65-
test_nocond = 306
66-
lambdef = 307
67-
lambdef_nocond = 308
68-
or_test = 309
69-
and_test = 310
70-
not_test = 311
71-
comparison = 312
72-
comp_op = 313
73-
star_expr = 314
74-
expr = 315
75-
xor_expr = 316
76-
and_expr = 317
77-
shift_expr = 318
78-
arith_expr = 319
79-
term = 320
80-
factor = 321
81-
power = 322
82-
atom_expr = 323
83-
atom = 324
84-
testlist_comp = 325
85-
trailer = 326
86-
subscriptlist = 327
87-
subscript = 328
88-
sliceop = 329
89-
exprlist = 330
90-
testlist = 331
91-
dictorsetmaker = 332
92-
classdef = 333
93-
arglist = 334
94-
argument = 335
95-
comp_iter = 336
96-
sync_comp_for = 337
97-
comp_for = 338
98-
comp_if = 339
99-
encoding_decl = 340
100-
yield_expr = 341
101-
yield_arg = 342
64+
namedexpr_test = 305
65+
test = 306
66+
test_nocond = 307
67+
lambdef = 308
68+
lambdef_nocond = 309
69+
or_test = 310
70+
and_test = 311
71+
not_test = 312
72+
comparison = 313
73+
comp_op = 314
74+
star_expr = 315
75+
expr = 316
76+
xor_expr = 317
77+
and_expr = 318
78+
shift_expr = 319
79+
arith_expr = 320
80+
term = 321
81+
factor = 322
82+
power = 323
83+
atom_expr = 324
84+
atom = 325
85+
testlist_comp = 326
86+
trailer = 327
87+
subscriptlist = 328
88+
subscript = 329
89+
sliceop = 330
90+
exprlist = 331
91+
testlist = 332
92+
dictorsetmaker = 333
93+
classdef = 334
94+
arglist = 335
95+
argument = 336
96+
comp_iter = 337
97+
sync_comp_for = 338
98+
comp_for = 339
99+
comp_if = 340
100+
encoding_decl = 341
101+
yield_expr = 342
102+
yield_arg = 343
102103
#--end constants--
103104

104105
sym_name = {}

Lib/test/exception_hierarchy.txt

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ BaseException
4242
| +-- NotImplementedError
4343
| +-- RecursionError
4444
+-- SyntaxError
45+
| +-- TargetScopeError
4546
| +-- IndentationError
4647
| +-- TabError
4748
+-- SystemError

0 commit comments

Comments
 (0)