summaryrefslogtreecommitdiff
path: root/Python/Python-ast.c
AgeCommit message (Collapse)AuthorLines
2019-02-01bpo-35766 follow-up: Kill half-support for FunctionType in PyAST_obj2mod ↵Guido van Rossum-3/+2
(#11714) See https://github.com/python/cpython/pull/11645/files/229874c612df868e7ae3e997e159915f49d16542#r252631862 https://bugs.python.org/issue35766
2019-01-31bpo-35766: Merge typed_ast back into CPython (GH-11645)Guido van Rossum-46/+466
2019-01-24bpo-35224: PEP 572 Implementation (#10497)Emily Morehouse-1/+110
* 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 (https://github.com/python/cpython/commit/2b3acd37bdfc2d35e5094228c6684050d2aa8b0a#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 f1531400ca7d7a2d148830c8ac703f041740896d. * 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
2019-01-22bpo-33416: Add end positions to Python AST (GH-11605)Ivan Levkivskyi-124/+454
The majority of this PR is tediously passing `end_lineno` and `end_col_offset` everywhere. Here are non-trivial points: * It is not possible to reconstruct end positions in AST "on the fly", some information is lost after an AST node is constructed, so we need two more attributes for every AST node `end_lineno` and `end_col_offset`. * I add end position information to both CST and AST. Although it may be technically possible to avoid adding end positions to CST, the code becomes more cumbersome and less efficient. * Since the end position is not known for non-leaf CST nodes while the next token is added, this requires a bit of extra care (see `_PyNode_FinalizeEndPos`). Unless I made some mistake, the algorithm should be linear. * For statements, I "trim" the end position of suites to not include the terminal newlines and dedent (this seems to be what people would expect), for example in ```python class C: pass pass ``` the end line and end column for the class definition is (2, 8). * For `end_col_offset` I use the common Python convention for indexing, for example for `pass` the `end_col_offset` is 4 (not 3), so that `[0:4]` gives one the source code that corresponds to the node. * I added a helper function `ast.get_source_segment()`, to get source text segment corresponding to a given AST node. It is also useful for testing. An (inevitable) downside of this PR is that AST now takes almost 25% more memory. I think however it is probably justified by the benefits.
2018-09-27bpo-32892: Use ast.Constant instead of specific constant AST types. (GH-9445)Serhiy Storchaka-308/+4
2018-05-31bpo-33677: Fix signatures of tp_clear handlers for AST and deque. (GH-7196)Serhiy Storchaka-1/+2
2018-05-29bpo-32911: Revert bpo-29463. (GH-7121) (GH-7197)Serhiy Storchaka-102/+17
Remove the docstring attribute of AST types and restore docstring expression as a first stmt in their body. Co-authored-by: INADA Naoki <methane@users.noreply.github.com>
2018-01-25 bpo-32571: Avoid raising unneeded AttributeError and silencing it in C code ↵Serhiy Storchaka-1016/+1174
(GH-5222) Add two new private APIs: _PyObject_LookupAttr() and _PyObject_LookupAttrId()
2017-11-11bpo-31572: Get rid of _PyObject_HasAttrId() in the ASDL parser. (#3725)Serhiy Storchaka-610/+774
Silence only expected AttributeError.
2017-08-24bpo-31095: fix potential crash during GC (GH-2974)INADA Naoki-0/+2
2017-08-04Fix a shadow-compatible-local warning (#2180)Yuan Chao Chou-165/+165
Change the shadowing naming, 'value' (Python-ast.c:4652), to 'val' to prevent the variables from being misused.
2017-02-24bpo-29622: Make AST constructor to accept less than enough number of ↵INADA Naoki-19/+17
positional arguments (GH-249) bpo-29463 added optional "docstring" field to 4 AST types. While it is optional, it breaks backward compatibility because AST constructor requires number of positional argument is same to number of fields. AST types accepts empty arguments, and incomplete keyword arguments. But it's not big problem because field can be filled after creation, and checked when compiling. So stop requiring complete set of fields for positional arguments too.
2017-02-22bpo-29463: Add docstring field to some AST nodes. (#46)INADA Naoki-17/+90
* bpo-29463: Add docstring field to some AST nodes. ClassDef, ModuleDef, FunctionDef, and AsyncFunctionDef has docstring field for now. It was first statement of there body. * fix document. thanks travis! * doc fixes
2017-01-25Issue #29369: Use Py_IDENTIFIER in Python-ast.cINADA Naoki-6/+12
2017-01-23Issue #28999: Use Py_RETURN_NONE, Py_RETURN_TRUE and Py_RETURN_FALSE whereverSerhiy Storchaka-22/+11
possible. Patch is writen with Coccinelle.
2016-10-07Issue #24098: Fixed possible crash when AST is changed in process ofSerhiy Storchaka-0/+220
compiling it.
2016-10-07Issue #24098: Fixed possible crash when AST is changed in process ofSerhiy Storchaka-0/+216
compiling it.
2016-09-09Issue #28008: Implement PEP 530 -- asynchronous comprehensions.Yury Selivanov-3/+24
2016-09-08Issue #27985: Implement PEP 526 -- Syntax for Variable Annotations.Yury Selivanov-1/+123
Patch by Ivan Levkivskyi.
2016-01-27Issue #26146: remove useless codeVictor Stinner-7/+0
obj2ast_constant() code is baesd on obj2ast_object() which has a special case for Py_None. But in practice, we don't need to have a special case for constants. Issue noticed by Joseph Jevnik on a review.
2016-01-26Add ast.ConstantVictor Stinner-0/+79
Issue #26146: Add a new kind of AST node: ast.Constant. It can be used by external AST optimizers, but the compiler does not emit directly such node. An optimizer can replace the following AST nodes with ast.Constant: * ast.NameConstant: None, False, True * ast.Num: int, float, complex * ast.Str: str * ast.Bytes: bytes * ast.Tuple if items are constants too: tuple * frozenset Update code to accept ast.Constant instead of ast.Num and/or ast.Str: * compiler * docstrings * ast.literal_eval() * Tools/parser/unparse.py
2015-11-06Issue #25555: Fix parser and AST: fill lineno and col_offset of "arg" node whenVictor Stinner-2/+29
compiling AST from Python objects.
2015-09-19Issue #24965: Implement PEP 498 "Literal String Interpolation". ↵Eric V. Smith-0/+165
Documentation is still needed, I'll open an issue for that.
2015-09-06Issue #15989: Fixed some scarcely probable integer overflows.Serhiy Storchaka-1/+1
It is very unlikely that they can occur in real code for now.
2015-05-11PEP 0492 -- Coroutines with async and await syntax. Issue #24017.Yury Selivanov-0/+473
2015-05-05PEP 448: additional unpacking generalizations (closes #2292)Benjamin Peterson-93/+12
Patch by Neil Girdhar.
2014-04-09PEP 465: a dedicated infix operator for matrix multiplication (closes #21176)Benjamin Peterson-3/+21
2014-02-10merge 3.3 (#20588)Benjamin Peterson-2/+6
2014-02-10don't put runtime values in array initializer for C89 compliance (closes #20588)Benjamin Peterson-2/+6
2013-10-12Issue #4555: All exported C symbols are now prefixed with either "Py" or "_Py".Antoine Pitrou-48/+48
("make smelly" now clean)
2013-07-27Issue #18552: Check return value of PyArena_AddPyObject() in obj2ast_object().Christian Heimes-3/+7
2013-07-27Issue #18552: Check return value of PyArena_AddPyObject() in obj2ast_object().Christian Heimes-3/+7
2013-07-27(Merge 3.3) Parser/asdl_c.py: use Py_CLEAR()Victor Stinner-266/+133
2013-07-27Parser/asdl_c.py: use Py_CLEAR()Victor Stinner-268/+134
2013-07-27(Merge 3.3) According to the PEP 7, C code must "use 4-space indents"Victor Stinner-5771/+5726
Replace 8 spaces with 4.
2013-07-27According to the PEP 7, C code must "use 4-space indents"Victor Stinner-5739/+5694
Replace 8 spaces with 4.
2013-07-17Issue #18408: Fix Python-ast.c: handle init_types() failure (ex: MemoryError)Victor Stinner-3/+6
2013-05-20Issue #17917: Use PyModule_AddIntMacro() instead of PyModule_AddIntConstant()Charles-Francois Natali-1/+1
when applicable.
2013-03-18bump Python-ast.cBenjamin Peterson-1/+2
2013-03-18refactor to fix refleaksBenjamin Peterson-22/+34
2013-03-18unify some ast.argument's attrs; change Attribute column offset (closes #16795)Benjamin Peterson-102/+81
Patch from Sven Brauch.
2012-12-25Replace IOError with OSError (#16715)Andrew Svetlov-1/+0
2012-12-06create NameConstant AST class for None, True, and False literals (closes #16619)Benjamin Peterson-0/+73
2012-11-25Issue #16546: make ast.YieldFrom argument mandatory.Mark Dickinson-1/+7
2012-07-08add gc support to the AST base type (closes #15293)Benjamin Peterson-4/+17
2012-07-08Issue #15291: Fix a memory leak where AST nodes where not properly deallocated.Antoine Pitrou-0/+1
2012-05-15use Py_ssize_t for ast sequence lengthsBenjamin Peterson-2/+2
2012-05-15Document f4d7ad6c9d6e.Martin v. Löwis-2/+2
2012-05-15Widen ASDL sequences to Py_ssize_t lengths to better match PEP 353.Martin v. Löwis-2/+2
2012-03-14free AST's dictBenjamin Peterson-1/+7