summaryrefslogtreecommitdiffstats
path: root/Python/compile.c
Commit message (Collapse)AuthorAgeFilesLines
* bpo-39890: Don't mutate the AST when compiling starred assignments (GH-18833)Brandt Bucher2020-03-081-2/+4
|
* bpo-39639: Remove the AST "Suite" node and associated code (GH-18513)Batuhan Taşkaya2020-03-041-4/+0
| | | | | | | | The AST "Suite" node is no longer used and it can be removed from the ASDL definition and related structures (compiler, visitors, ...). Co-Authored-By: Victor Stinner <vstinner@python.org> Co-authored-by: Brett Cannon <54418+brettcannon@users.noreply.github.com> Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
* bpo-32856: Optimize the assignment idiom in comprehensions. (GH-16814)Serhiy Storchaka2020-02-121-18/+52
| | | | | Now `for y in [expr]` in comprehensions is as fast as a simple assignment `y = expr`.
* bpo-39573: Use Py_TYPE() macro in Python and Include directories (GH-18391)Victor Stinner2020-02-071-1/+1
| | | Replace direct access to PyObject.ob_type with Py_TYPE().
* bpo-39320: Handle unpacking of **values in compiler (GH-18141)Mark Shannon2020-01-271-32/+58
| | | | | | | | | | | | | * Add DICT_UPDATE and DICT_MERGE bytecodes. Use them for ** unpacking. * Remove BUILD_MAP_UNPACK and BUILD_MAP_UNPACK_WITH_CALL, as they are now unused. * Update magic number for ** unpacking opcodes. * Update dis.rst to incorporate new bytecodes. * Add blurb entry.
* bpo-39320: Handle unpacking of *values in compiler (GH-17984)Mark Shannon2020-01-231-96/+107
| | | | | | | | * Add three new bytecodes: LIST_TO_TUPLE, LIST_EXTEND, SET_UPDATE. Use them to implement star unpacking expressions. * Remove four bytecodes BUILD_LIST_UNPACK, BUILD_TUPLE_UNPACK, BUILD_SET_UNPACK and BUILD_TUPLE_UNPACK_WITH_CALL opcodes as they are now unused. * Update magic number and dis.rst for new bytecodes.
* Fix compiler warning on Windows (GH-18012)Ammar Askar2020-01-151-1/+1
| | | | | | | | Python-ast.h contains a macro named Yield that conflicts with the Yield macro in Windows system headers. While Python-ast.h has an "undef Yield" directive to prevent this, it means that Python-ast.h must be included before Windows header files or we run into a re-declaration warning. In commit c96be811fa7d an include for pycore_pystate.h was added which indirectly includes Windows header files. In this commit we re-order the includes to fix this warning.
* bpo-39156: Break up COMPARE_OP into four logically distinct opcodes. (GH-17754)Mark Shannon2020-01-141-27/+44
| | | | | | | | Break up COMPARE_OP into four logically distinct opcodes: * COMPARE_OP for rich comparisons * IS_OP for 'is' and 'is not' tests * CONTAINS_OP for 'in' and 'is not' tests * JUMP_IF_NOT_EXC_MATCH for checking exceptions in 'try-except' statements.
* Fix handling of line numbers around finally-blocks. (#17737)Mark Shannon2019-12-301-0/+4
|
* bpo-38328: Speed up the creation time of constant list and set display. ↵Brandt Bucher2019-11-261-0/+22
| | | | (GH-17114)
* Produce cleaner bytecode for 'with' and 'async with' by generating separate ↵Mark Shannon2019-11-211-213/+233
| | | | | | code for normal and exceptional paths. (#6641) Remove BEGIN_FINALLY, END_FINALLY, CALL_FINALLY and POP_FINALLY bytecodes. Implement finally blocks by code duplication. Reimplement frame.lineno setter using line numbers rather than bytecode offsets.
* bpo-38640: Allow break and continue in always false while loops (GH-16992)Pablo Galindo2019-10-301-0/+8
|
* Typo fix: "empy" should be "empty". (GH-16666)Hansraj Das2019-10-091-1/+1
|
* Revert "Fix depth-first-search computation in compile.c (GH-16042)" (GH-16050)T. Wouters2019-09-121-24/+30
| | | | | This reverts commit 355f3e1e5caf16198255df573a1f5e8b98b30105. bpo-38135
* Fix depth-first-search computation in compile.c (GH-16042)Mark Shannon2019-09-121-30/+24
|
* bpo-34880: Add the LOAD_ASSERTION_ERROR opcode. (GH-15073)Zackery Spytz2019-08-251-7/+3
| | | | Fix assert statement misbehavior if AssertionError is shadowed.
* bpo-37830: Fix compilation of break and continue in finally. (GH-15320)Serhiy Storchaka2019-08-241-11/+55
| | | | | | Fix compilation of "break" and "continue" in the "finally" block when the corresponding "try" block contains "return" with a non-constant value.
* Fix typos in comments, docs and test names (#15018)Min ho Kim2019-07-301-1/+1
| | | | | | | | | | | | | | | | | | | | | | | | * Fix typos in comments, docs and test names * Update test_pyparse.py account for change in string length * Apply suggestion: splitable -> splittable Co-Authored-By: Terry Jan Reedy <tjreedy@udel.edu> * Apply suggestion: splitable -> splittable Co-Authored-By: Terry Jan Reedy <tjreedy@udel.edu> * Apply suggestion: Dealloccte -> Deallocate Co-Authored-By: Terry Jan Reedy <tjreedy@udel.edu> * Update posixmodule checksum. * Reverse idlelib changes.
* bpo-37500: Make sure dead code does not generate bytecode but also detect ↵Pablo Galindo2019-07-151-5/+64
| | | | | | | | | | | | syntax errors (GH-14612) https://bugs.python.org/issue37500 Add a new field to the compiler structure that allows to be configured so no bytecode is emitted. In this way is possible to detect errors by walking the nodes while preserving optimizations. https://bugs.python.org/issue37500
* bpo-37221: Add PyCode_NewWithPosOnlyArgs to be used internally and set ↵Pablo Galindo2019-07-011-7/+5
| | | | | | PyCode_New as a compatibility wrapper (GH-13959) Add PyCode_NewEx to be used internally and set PyCode_New as a compatibility wrapper
* bpo-35224: Reverse evaluation order of key: value in dict comprehensions ↵Jörn Heissler2019-06-221-4/+4
| | | | | | | | | | | (GH-14139) … as proposed in PEP 572; key is now evaluated before value. https://bugs.python.org/issue35224
* bpo-37253: Add _PyCompilerFlags_INIT macro (GH-14018)Victor Stinner2019-06-131-3/+1
| | | | | Add a new _PyCompilerFlags_INIT macro to initialize PyCompilerFlags variables, rather than initializing cf_flags and cf_feature_version explicitly in each variable.
* bpo-37122: Make co->co_argcount represent the total number of positonal ↵Pablo Galindo2019-06-011-4/+4
| | | | arguments in the code object (GH-13726)
* bpo-37115: Support annotations in positional-only arguments (GH-13698)Pablo Galindo2019-05-311-0/+2
|
* bpo-37050: Remove expr_text from FormattedValue ast node, use Constant node ↵Eric V. Smith2019-05-271-11/+0
| | | | | instead (GH-13597) When using the "=" debug functionality of f-strings, use another Constant node (or a merged constant node) instead of adding expr_text to the FormattedValue node.
* bpo-36763: Implement the PEP 587 (GH-13592)Victor Stinner2019-05-271-2/+2
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
* bpo-34616: Add PyCF_ALLOW_TOP_LEVEL_AWAIT to allow top-level await (GH-13148)Matthias Bussonnier2019-05-211-7/+21
| | | Co-Authored-By: Yury Selivanov <yury@magic.io>
* Annotate the unexplained assignment in exception unbinding (GH-11448)Chris Angelico2019-05-211-1/+1
|
* Fix couple of dead code paths (GH-7418)David Carlier2019-05-171-1/+0
|
* bpo-1875: Raise SyntaxError in invalid blocks that will be optimised away ↵Pablo Galindo2019-05-171-5/+4
| | | | | | | (GH-13332) Move the check for dead conditionals (if 0) to the peephole optimizer and make sure that the code block is still compiled to report any existing syntax errors within.
* bpo-36900: Replace global conf vars with config (GH-13299)Victor Stinner2019-05-141-1/+3
| | | | | | Replace global configuration variables with core_config read from the current interpreter. Cleanup dynload_hpux.c.
* bpo-36817: Add f-string debugging using '='. (GH-13123)Eric V. Smith2019-05-081-6/+19
| | | If a "=" is specified a the end of an f-string expression, the f-string will evaluate to the text of the expression, followed by '=', followed by the repr of the value of the expression.
* bpo-36540: PEP 570 -- Implementation (GH-12701)Pablo Galindo2019-04-291-2/+7
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This commit contains the implementation of PEP570: Python positional-only parameters. * Update Grammar/Grammar with new typedarglist and varargslist * Regenerate grammar files * Update and regenerate AST related files * Update code object * Update marshal.c * Update compiler and symtable * Regenerate importlib files * Update callable objects * Implement positional-only args logic in ceval.c * Regenerate frozen data * Update standard library to account for positional-only args * Add test file for positional-only args * Update other test files to account for positional-only args * Add News entry * Update inspect module and related tests
* Fix typos in compile.c comments (GH-12752)Simeon2019-04-091-2/+2
|
* bpo-35284: Fix the error handling in the compiler's compiler_call(). (GH-10625)Zackery Spytz2019-03-221-2/+5
| | | | | compiler_call() needs to check if an error occurred during the maybe_optimize_method_call() call.
* bpo-36374: Fix a possible null pointer dereference (GH-12449)Zackery Spytz2019-03-201-1/+1
| | | https://bugs.python.org/issue36374
* bpo-35975: Support parsing earlier minor versions of Python 3 (GH-12086)Guido van Rossum2019-03-071-0/+1
| | | | | | | This adds a `feature_version` flag to `ast.parse()` (documented) and `compile()` (hidden) that allow tweaking the parser to support older versions of the grammar. In particular if `feature_version` is 5 or 6, the hacks for the `async` and `await` keyword from PEP 492 are reinstated. (For 7 or higher, these are unconditionally treated as keywords, but they are still special tokens rather than `NAME` tokens that the parser driver recognizes.) https://bugs.python.org/issue35975
* bpo-36187: Remove NamedStore. (GH-12167)Serhiy Storchaka2019-03-051-7/+2
| | | | | NamedStore has been replaced with Store. The difference between NamedStore and Store is handled when precess the NamedExpr node one level upper.
* bpo-35798: Fix duplicate SyntaxWarning: "is" with a literal. (GH-11639)Serhiy Storchaka2019-02-161-3/+3
|
* bpo-15248: Emit a compiler warning when missed a comma before tuple or list. ↵Serhiy Storchaka2019-02-161-6/+140
| | | | (GH-11757)
* bpo-35224: PEP 572 Implementation (#10497)Emily Morehouse2019-01-241-6/+24
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * 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
* bpo-33416: Add end positions to Python AST (GH-11605)Ivan Levkivskyi2019-01-221-2/+4
| | | | | | | | | | | | | | | | | | 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.
* bpo-34850: Emit a warning for "is" and "is not" with a literal. (GH-9642)Serhiy Storchaka2019-01-181-0/+47
|
* bpo-34100: compile: Re-enable frozenset merging (GH-10760)INADA Naoki2018-11-281-2/+57
| | | This reverts commit 1005c84535191a72ebb7587d8c5636a065b7ed79.
* bpo-34100: Partially revert merge_consts_recursive() (GH-10743)Victor Stinner2018-11-271-50/+0
| | | | | Partically revert commit c2e1607a51d7a17f143b5a34e8cff7c6fc58a091 to fix a reference leak.
* bpo-34100: Merge constants recursively (GH-8341)INADA Naoki2018-11-261-8/+161
| | | | | | | There are some same consts in a module. This commit merges them into single instance. It reduces number of objects in memory after loading modules. https://bugs.python.org/issue34100
* bpo-35177: Add dependencies between header files (GH-10361)Victor Stinner2018-11-111-1/+0
| | | | | | | | | | | | | | * ast.h now includes Python-ast.h and node.h * parsetok.h now includes node.h and grammar.h * symtable.h now includes Python-ast.h * Modify asdl_c.py to enhance Python-ast.h: * Add #ifndef/#define Py_PYTHON_AST_H to be able to include the header twice * Add "extern { ... }" for C++ * Undefine "Yield" macro conflicting with winbase.h * Remove "#undef Yield" from C files, it's now done in Python-ast.h * Remove now useless includes in C files
* bpo-34876: Change the lineno of the AST for decorated function and class. ↵Serhiy Storchaka2018-10-301-3/+14
| | | | | | | (GH-9731) It was overridden by the lineno of the first decorator. Now it is the lineno of 'def' or 'class'.
* bpo-35029: Replace the SyntaxWarning exception with a SyntaxError. (GH-9999)Serhiy Storchaka2018-10-211-11/+31
| | | | If SyntaxWarning was raised as an exception, it will be replaced with a SyntaxError for better error reporting.
* Fix an incorrect check in compiler_try_except(). (GH-9810)Zackery Spytz2018-10-121-1/+2
|