Commit Graph

984 Commits

Author SHA1 Message Date
Batuhan Taskaya ec8759b060
bpo-43950: optimize column table assembling with pre-sizing object (GH-26997)
The new resizing system works like this;
```
$ cat t.py
a + a + a + b + c + a + a + a + b + c + a + a + a + b + c + a + a + a + b + c
[repeated 99 more times]
$ ./python t.py
RESIZE: prev len = 32, new len = 66
FINAL SIZE: 56
-----------------------------------------------------
RESIZE: prev len = 32, new len = 66
RESIZE: prev len = 66, new len = 134
RESIZE: prev len = 134, new len = 270
RESIZE: prev len = 270, new len = 542
RESIZE: prev len = 542, new len = 1086
RESIZE: prev len = 1086, new len = 2174
RESIZE: prev len = 2174, new len = 4350
RESIZE: prev len = 4350, new len = 8702
FINAL SIZE: 8004
```

So now we do considerably lower number of `_PyBytes_Resize` calls.

Automerge-Triggered-By: GH:isidentical
2021-07-02 12:03:58 -07:00
Pablo Galindo 98eee94421
bpo-43950: Add code.co_positions (PEP 657) (GH-26955)
This PR is part of PEP 657 and augments the compiler to emit ending
line numbers as well as starting and ending columns from the AST
into compiled code objects. This allows bytecodes to be correlated
to the exact source code ranges that generated them.

This information is made available through the following public APIs:

* The `co_positions` method on code objects.
* The C API function `PyCode_Addr2Location`.

Co-authored-by: Batuhan Taskaya <isidentical@gmail.com>
Co-authored-by: Ammar Askar <ammar@ammaraskar.com>
2021-07-02 15:10:11 +01:00
Batuhan Taskaya 1b28187a0e
bpo-44313: generate LOAD_ATTR/CALL_FUNCTION for top-level imported objects (GH-26677) 2021-06-30 23:53:36 +01:00
Mark Shannon 18ba1ff6a4
Make sure that line number is set correctly for call to __exit__ when handling exception in body of a with statement. (GH-26890) 2021-06-24 15:12:48 +01:00
Guido van Rossum 355f5dd36a
bpo-43693: Turn localspluskinds into an object (GH-26749)
Managing it as a bare pointer to malloc'ed bytes is just too awkward in a few places.
2021-06-21 13:53:04 -07:00
Mark Shannon 82e5c28af7
bpo-44297: Fix missing line number in generator expressions (GH-26801)
* Make sure that line number is set when entering comprehension scope in compiler.
2021-06-21 10:55:15 +01:00
Eric Snow ac38a9f2df
bpo-43693: Eliminate unused "fast locals". (gh-26587)
Currently, if an arg value escapes (into the closure for an inner function) we end up allocating two indices in the fast locals even though only one gets used.  Additionally, using the lower index would be better in some cases, such as with no-arg `super()`.  To address this, we update the compiler to fix the offsets so each variable only gets one "fast local".  As a consequence, now some cell offsets are interspersed with the locals (only when an arg escapes to an inner function).

https://bugs.python.org/issue43693
2021-06-15 16:35:25 -06:00
Eric Snow 3e1c7167d8
bpo-43693: Un-revert commit f3fa63e. (#26609)
This was reverted in GH-26596 (commit 6d518bb) due to some bad memory accesses.

* Add the MAKE_CELL opcode. (gh-26396)

The memory accesses have been fixed.

https://bugs.python.org/issue43693
2021-06-08 16:01:34 -06:00
Pablo Galindo 3fe921cd49
Revert "bpo-43693: Add the MAKE_CELL opcode and interleave fast locals offsets. (gh-26396)" (GH-26597)
This reverts commit 631f9938b1.
2021-06-08 13:17:55 +01:00
Pablo Galindo 781dc76577
Fix compiler errors for unused variables (GH-26601) 2021-06-08 13:16:24 +01:00
Eric Snow 631f9938b1
bpo-43693: Add the MAKE_CELL opcode and interleave fast locals offsets. (gh-26396)
This moves logic out of the frame initialization code and into the compiler and eval loop.  Doing so simplifies the runtime code and allows us to optimize it better.

https://bugs.python.org/issue43693
2021-06-07 16:52:00 -06:00
Eric Snow 2ab27c4af4
bpo-43693: Un-revert commits 2c1e258 and b2bf2bc. (gh-26577)
These were reverted in gh-26530 (commit 17c4edc) due to refleaks.

* 2c1e258 - Compute deref offsets in compiler (gh-25152)
* b2bf2bc - Add new internal code objects fields: co_fastlocalnames and co_fastlocalkinds. (gh-26388)

This change fixes the refleaks.

https://bugs.python.org/issue43693
2021-06-07 12:22:26 -06:00
Pablo Galindo 17c4edc4e0
bpo-43693: Revert commits 2c1e2583fd and b2bf2bc1ec (GH-26530)
* Revert "bpo-43693: Compute deref offsets in compiler (gh-25152)"

This reverts commit b2bf2bc1ec.

* Revert "bpo-43693: Add new internal code objects fields: co_fastlocalnames and co_fastlocalkinds. (gh-26388)"

This reverts commit 2c1e2583fd.

These two commits are breaking the refleak buildbots.
2021-06-04 17:51:05 +01:00
Mark Shannon b2bf2bc1ec
bpo-43693: Compute deref offsets in compiler (gh-25152)
Merges locals and cells into a single array.
Saves a pointer in the interpreter and means that we don't need the LOAD_CLOSURE opcode any more

https://bugs.python.org/issue43693
2021-06-03 18:03:54 -06:00
Eric Snow 2c1e2583fd
bpo-43693: Add new internal code objects fields: co_fastlocalnames and co_fastlocalkinds. (gh-26388)
A number of places in the code base (notably ceval.c and frameobject.c) rely on mapping variable names to indices in the frame "locals plus" array (AKA fast locals), and thus opargs.  Currently the compiler indirectly encodes that information on the code object as the tuples co_varnames, co_cellvars, and co_freevars.  At runtime the dependent code must calculate the proper mapping from those, which isn't ideal and impacts performance-sensitive sections.  This is something we can easily address in the compiler instead.

This change addresses the situation by replacing internal use of co_varnames, etc. with a single combined tuple of names in locals-plus order, along with a minimal array mapping each to its kind (local vs. cell vs. free).  These two new PyCodeObject fields, co_fastlocalnames and co_fastllocalkinds, are not exposed to Python code for now, but co_varnames, etc. are still available with the same values as before (though computed lazily).

Aside from the (mild) performance impact, there are a number of other benefits:

* there's now a clear, direct relationship between locals-plus and variables
* code that relies on the locals-plus-to-name mapping is simpler
* marshaled code objects are smaller and serialize/de-serialize faster

Also note that we can take this approach further by expanding the possible values in co_fastlocalkinds to include specific argument types (e.g. positional-only, kwargs).  Doing so would allow further speed-ups in _PyEval_MakeFrameVector(), which is where args get unpacked into the locals-plus array.  It would also allow us to shrink marshaled code objects even further.

https://bugs.python.org/issue43693
2021-06-03 10:28:27 -06:00
Mark Shannon 937cebc93b
bpo-44298: Fix line numbers for early exits in with statements. (GH-26513) 2021-06-03 16:45:58 +01:00
Eric Snow 9f494d4929
bpo-43693: Add _PyCode_New(). (gh-26375)
This is an internal-only API that helps us manage the many values used to create a code object.

https://bugs.python.org/issue43693
2021-05-27 09:54:34 -06:00
Ken Jin 29669245d4
bpo-44156: Make cached string constants in compile.c subinterpreter compatible (GH-26161) 2021-05-25 15:55:34 +02:00
Ken Jin f24afda591
bpo-26110: Add ``CALL_METHOD_KW`` opcode to speedup method calls with keywords (GH-26014)
* Add CALL_METHOD_KW

* Make CALL_METHOD branchless too since it shares the same code

* Place parentheses in STACK_SHRINK
2021-05-15 16:15:23 +01:00
Mark Shannon cb6f3d7163
bpo-43933: Force RETURN_VALUE bytecodes to have line numbers (GH-26054) 2021-05-12 11:25:44 +01:00
Batuhan Taskaya b2ec37a722
bpo-44063: set the missing end locations on the compiler (GH-25956) 2021-05-07 20:49:06 +03:00
Mark Shannon adcd220556
bpo-40222: "Zero cost" exception handling (GH-25729)
"Zero cost" exception handling.

* Uses a lookup table to determine how to handle exceptions.
* Removes SETUP_FINALLY and POP_TOP block instructions, eliminating (most of) the runtime overhead of try statements.
* Reduces the size of the frame object by about 60%.
2021-05-07 15:19:19 +01:00
Pablo Galindo 39494285e1
bpo-43754: Fix compiler warning in Python/compile.c (GH-25855)
This fixes the following warning:

'initializing': conversion from 'Py_ssize_t' to 'int', possible loss of data [D:\a\cpython\cpython\PCbuild\pythoncore.vcxproj]
2021-05-03 16:20:46 +01:00
Brandt Bucher 0ad1e0384c
bpo-43754: Eliminate bindings for partial pattern matches (GH-25229) 2021-05-02 13:02:10 -07:00
Mark Shannon 5979e81a21
bpo-43933: Set frame.f_lineno during call to __exit__ (GH-25719)
* Set line number of __exit__ call in a with statement to be that of the with keyword.
2021-04-30 14:32:47 +01:00
Brandt Bucher dbe60ee09d
bpo-43892: Validate the first term of complex literal value patterns (GH-25735) 2021-04-29 17:19:28 -07:00
Mark Shannon c76da79b37
bpo-42739: Don't use sentinels to mark end of line table. (GH-25657)
* Add length parameter to PyLineTable_InitAddressRange and doen't use sentinel values at end of table. Makes the line number table more robust.

* Update PyCodeAddressRange to match PEP 626.
2021-04-29 13:12:51 +01:00
Nick Coghlan 1e7b858575
bpo-43892: Make match patterns explicit in the AST (GH-25585)
Co-authored-by: Brandt Bucher <brandtbucher@gmail.com>
2021-04-28 22:58:44 -07:00
Batuhan Taskaya 8cc3cfa8af
bpo-42737: annotations with complex targets no longer causes any runtime effects (GH-23952) 2021-04-25 05:31:20 +03:00
Pablo Galindo a77aac4fca
bpo-43914: Highlight invalid ranges in SyntaxErrors (#25525)
To improve the user experience understanding what part of the error messages associated with SyntaxErrors is wrong, we can highlight the whole error range and not only place the caret at the first character. In this way:

>>> foo(x, z for z in range(10), t, w)
  File "<stdin>", line 1
    foo(x, z for z in range(10), t, w)
           ^
SyntaxError: Generator expression must be parenthesized

becomes

>>> foo(x, z for z in range(10), t, w)
  File "<stdin>", line 1
    foo(x, z for z in range(10), t, w)
           ^^^^^^^^^^^^^^^^^^^^
SyntaxError: Generator expression must be parenthesized
2021-04-23 14:27:05 +01:00
Pablo Galindo b0544ba77c
bpo-38605: Revert making 'from __future__ import annotations' the default (GH-25490)
This reverts commits 044a1048ca and 1be456ae9d, adapting the code to changes that happened after it.
2021-04-21 12:41:19 +01:00
Inada Naoki 8a232c7b17
bpo-41323: compiler: Reuse tuple in constant tuple folding (GH-25419) 2021-04-16 14:01:04 +09:00
Mark Shannon 11e0b295de
bpo-43846: Use less stack for large literals and calls (GH-25403)
* Modify compiler to reduce stack consumption for large expressions.

* Add more tests for stack usage.

* Add NEWS item.

* Raise SystemError for truly excessive stack use.
2021-04-15 14:28:56 +01:00
tomKPZ 7a7ba3d343
bpo-43495 : Push missing frame block in compile.c (GH-24865) 2021-04-07 15:43:45 +01:00
Mark Shannon 67969f5eb8
Correct micro release number and add a couple of asserts. (GH-25224) 2021-04-07 10:52:07 +01:00
Mark Shannon b37181e692
bpo-43683: Handle generator entry in bytecode (GH-25138)
* Handle check for sending None to starting generator and coroutine into bytecode.

* Document new bytecode and make it fail gracefully if mis-compiled.
2021-04-06 11:48:59 +01:00
Mark Shannon fcb55c0037
bpo-27129: Use instruction offsets, not byte offsets, in bytecode and internally. (GH-25069)
* Use instruction offset, rather than bytecode offset. Streamlines interpreter dispatch a bit, and removes most EXTENDED_ARGs for jumps.

* Change some uses of PyCode_Addr2Line to PyFrame_GetLineNumber
2021-04-01 16:00:31 +01:00
Victor Stinner a81fca6ec8
bpo-43244: Add pycore_compile.h header file (GH-25000)
Remove the compiler functions using "struct _mod" type, because the
public AST C API was removed:

* PyAST_Compile()
* PyAST_CompileEx()
* PyAST_CompileObject()
* PyFuture_FromAST()
* PyFuture_FromASTObject()

These functions were undocumented and excluded from the limited C API.

Rename functions:

* PyAST_CompileObject() => _PyAST_Compile()
* PyFuture_FromASTObject() => _PyFuture_FromAST()

Moreover, _PyFuture_FromAST() is no longer exported (replace
PyAPI_FUNC() with extern). _PyAST_Compile() remains exported for
test_peg_generator.

Remove also compatibility functions:

* PyAST_Compile()
* PyAST_CompileEx()
* PyFuture_FromAST()
2021-03-24 00:51:50 +01:00
Victor Stinner 28ad12f8fe
bpo-43244: Remove symtable.h header file (GH-24910)
Rename Include/symtable.h to to Include/internal/pycore_symtable.h,
don't export symbols anymore (replace PyAPI_FUNC and PyAPI_DATA with
extern) and rename functions:

* PyST_GetScope() to _PyST_GetScope()
* PySymtable_BuildObject() to _PySymtable_Build()
* PySymtable_Free() to _PySymtable_Free()

Remove PySymtable_Build(), Py_SymtableString() and
Py_SymtableStringObject() functions.

The Py_SymtableString() function was part the stable ABI by mistake
but it could not be used, since the symtable.h header file was
excluded from the limited C API.

The Python symtable module remains available and is unchanged.
2021-03-19 12:41:49 +01:00
Victor Stinner 526fdeb227
bpo-43244: Add pycore_ast.h header file (GH-24908)
Move _PyAST_GetDocString() and _PyAST_ExprAsUnicode() functions the
internal C API: from Include/ast.h to a new
Include/internal/pycore_ast.h header file. Don't export these
functions anymore: replace PyAPI_FUNC() with extern.

Remove also unused includes.
2021-03-17 23:50:50 +01:00
tsukasa-au a8ef4572a6
bpo-43497: Emit SyntaxWarnings for assertions with tuple constants. (GH-24867)
* bpo-43497: Emit SyntaxWarnings for assertions with tuple constants.

Add a test that shows that a tuple constant (a tuple, where all of its
members are also compile-time constants) produces a SyntaxWarning. Then
fix this failure.

* Make SyntaxWarnings also work when "optimized".

* Split tests for SyntaxWarning to SyntaxError conversion

SyntaxWarnings emitted by the compiler when configured to be errors are
actually raised as SyntaxError exceptions.

Move these tests into their own method and add a test to ensure they are
raised. Previously we only tested that they were not raised for a
"valid" assertion statement.
2021-03-16 11:14:41 +00:00
Mark Shannon c5440937ef
Mark POP_TOP at end of expression statement as artificial, to conform to PEP 626. (GH-24860) 2021-03-15 14:24:25 +00:00
Mark Shannon d48848c83e
bpo-39316: Make sure that attribute accesses and stores, including method calls, conform to PEP 626. (GH-24859) 2021-03-14 18:01:30 +00:00
Ikko Ashimine 57827f8754
Fix typo in compile.c (GH-24812)
guranteed -> guaranteed
2021-03-10 10:39:51 +00:00
Alex Henrie 503627fc2a
bpo-43358: Fix bad free in assemble function (GH-24697) 2021-03-02 10:20:25 +00:00
Brandt Bucher 145bf269df
bpo-42128: Structural Pattern Matching (PEP 634) (GH-22917)
Co-authored-by: Guido van Rossum <guido@python.org>
Co-authored-by: Talin <viridia@gmail.com>
Co-authored-by: Pablo Galindo <pablogsal@gmail.com>
2021-02-26 14:51:55 -08:00
Inada Naoki bdb941be42
bpo-42217: compiler: merge same co_code and co_linetable objects (GH-23056) 2021-02-10 09:20:42 +09:00
Mark Shannon 802b645e81
Only eliminate jumps to successor block if jump is unconditional. (GH-24417)
* Prevents elimination of the sole test of a value in statements like:
   if x or True: ...
2021-02-02 14:59:15 +00:00
Pablo Galindo 86e322f141
bpo-40455: Fix gcc10+ warning about writing into a section of offset 0 (GH-24384) 2021-01-30 22:54:22 +09:00
Victor Stinner ba7a99ddb5
bpo-38631: Replace compiler fatal errors with exceptions (GH-24369)
* Replace Py_FatalError() calls with regular SystemError exceptions.
* compiler_exit_scope() calls _PyErr_WriteUnraisableMsg() to log the
  PySequence_DelItem() failure.
* compiler_unit_check() uses _PyMem_IsPtrFreed().
* compiler_make_closure(): remove "(reftype == FREE)" comment since
  reftype can also be LOCAL or GLOBAL_EXPLICIT.
2021-01-30 01:46:44 +01:00
Pablo Galindo 7fdab8331b
Fix a reference leak in the compiler for compiler_lambda() (GH-24382) 2021-01-29 22:40:59 +00:00
Victor Stinner a6192635f1
bpo-42979: Use _Py_CheckSlotResult() to check slots result (GH-24356)
When Python is built in debug mode (with C assertions), calling a
type slot like sq_length (__len__() in Python) now fails with a fatal
error if the slot succeeded with an exception set, or failed with no
exception set. The error message contains the slot, the type name,
and the current exception (if an exception is set).

* Check the result of all slots using _Py_CheckSlotResult().
* No longer pass op_name to ternary_op() in release mode.
* Replace operator with dunder Python method name in error messages.
  For example, replace "*" with "__mul__".
* Fix compiler_exit_scope() when an exception is set.
* Fix bytearray.extend() when an exception is set: don't call
  bytearray_setslice() with an exception set.
2021-01-29 16:53:03 +01:00
Irit Katriel dea5bf9d15
bpo-33387: update documentation for exception handling opcode changes (GH-24334)
* bpo-33387: remove obsolete comment

* bpo-33387: update SETUP_WITH opcode documentation
2021-01-26 10:17:13 +00:00
Mark Shannon e56d54e447
Mark instructions at end of class scope as artificial. (GH-24222) 2021-01-15 13:52:00 +00:00
Mark Shannon 1659ad1c64
Eliminate NOPs in extended blocks. (GH-24209) 2021-01-13 15:05:04 +00:00
Mark Shannon 3bd6035b6b
bpo-42908: Mark cleanup code at end of try-except and with artificial (#24202)
* Mark bytecodes at end of try-except as artificial.

* Make sure that the CFG is consistent throughout optimiization. 

* Extend line-number propagation logic so that implicit returns after 'try-except' or 'with' have the correct line numbers.

* Update importlib
2021-01-13 12:05:43 +00:00
Mark Shannon ee9f98d9f4
bpo-42823: Fix frame lineno when frame.f_trace is set (GH-24099)
* Add test for frame.f_lineno with/without tracing.

* Make sure that frame.f_lineno is correct regardless of whether frame.f_trace is set.

* Update importlib

* Add NEWS
2021-01-05 12:04:10 +00:00
Mark Shannon 127dde5916
bpo-42810: Mark jumps at end of if and try statements as artificial. (GH-24091)
* Mark jumps at end of if and try statements as artificial.

* Update importlib

* Add comment explaining the purpose of ADDOP_JUMP_NOLINE.
2021-01-04 18:06:55 +00:00
Mark Shannon bf06b209da
Delete the now unused c_do_not_emit_bytecode field. (#24094) 2021-01-04 13:51:17 +00:00
Mark Shannon 28b75c80dc
bpo-42246: Don't eliminate jumps to jumps, if it will break PEP 626. (GH-23896) 2020-12-23 11:43:10 +00:00
Mark Shannon f2dbfd7e20
bpo-42634: Mark reraise after except blocks as artificial. (GH-23877)
* Mark reraise after except blocks as artificial.

* Update importlib

* Update dis test.
2020-12-21 13:53:50 +00:00
Mark Shannon bf353f3c2d
bpo-42246: Make sure that `f_lasti`, and thus `f_lineno`, is set correctly after raising or reraising an exception (GH-23803)
* Ensure that f_lasti is set correctly after an exception is raised to conform to PEP 626.

* Update importlib

* Add NEWS.
2020-12-17 13:55:28 +00:00
Mark Shannon 5274b682bc
bpo-42645: Make sure that return/break/continue are only traced once when exiting via a finally block. (GH-23780)
* Make sure that return/break/continue are only traced once when exiting via a finally block.

* Add test for return in try-finally.

* Update importlib
2020-12-16 13:07:01 +00:00
Om G c71581c7a4
bpo-42615: Delete redundant jump instructions that only bypass empty blocks (GH-23733)
* Delete jump instructions that bypass empty blocks

* Add news entry

* Explicitly check for unconditional jump opcodes

Using the is_jump function results in the inclusion of instructions like
returns for which this optimization is not really valid. So, instead
explicitly check that the instruction is an unconditional jump.

* Handle conditional jumps, delete jumps gracefully

* Ensure b_nofallthrough and b_reachable are valid

* Add test for redundant jumps

* Regenerate importlib.h and edit Misc/ACKS

* Fix bad whitespace
2020-12-16 12:18:05 +00:00
Mark Shannon 8473cf89bd
bpo-42246: Remove DO_NOT_EMIT_BYTECODE macros, so that while loops and if statements conform to PEP 626. (GH-23743) 2020-12-15 11:07:50 +00:00
Mark Shannon f5e97b72fe
bpo-42635: Mark JUMP_ABSOLUTE at end of 'for' loop as artificial to avoid spurious line events. (GH-23761) 2020-12-14 11:28:39 +00:00
Mark Shannon 56aa20f9eb
Don't generate spurious line number in try-except-finally. (#23760) 2020-12-14 10:19:10 +00:00
Mark Shannon eaccc12aa9
bpo-42246: Don't forget the entry block when ensuring that all exits have a line number (GH-23636)
Don't forget the entry block when ensuring that all exits have a line number.
2020-12-04 15:22:12 +00:00
Mark Shannon 5977a7989d
bpo-42246: Make sure that line number is correct after a return, as required by PEP 626 (GH-23495)
Make sure that line number is correct after a return, as defined by PEP 626.
2020-12-02 13:31:40 +00:00
Yurii Karabas 7301979b23
bpo-42202: Store func annotations as a tuple (GH-23316)
Reduce memory footprint and improve performance of loading modules having many func annotations.

  >>> sys.getsizeof({"a":"int","b":"int","return":"int"})
  232
  >>> sys.getsizeof(("a","int","b","int","return","int"))
  88

The tuple is converted into dict on the fly when `func.__annotations__` is accessed first.

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
Co-authored-by: Inada Naoki <songofacandy@gmail.com>
2020-11-25 19:43:18 +09:00
Mark Shannon 266b462238
bpo-42349: Compiler clean up. More yak-shaving for PEP 626. (GH-23267)
Make sure that CFG from compiler front-end is correct. Be a bit more aggressive in the compiler back-end.
2020-11-17 19:30:14 +00:00
Mark Shannon fd009e606a
bpo-42246: Fix memory leak in compiler (GH-23256)
* Fix potential memory leak in assembler init.

* Fix reference leak when encountering error during compilation of function body.
2020-11-13 12:53:53 +00:00
Mark Shannon cc75ab791d
bpo-42246: Eliminate jumps to exit blocks by copying those blocks. (#23251)
* Compiler: eliminate jumps to short exit blocks by copying.
2020-11-12 19:49:33 +00:00
Mark Shannon 877df851c3
bpo-42246: Partial implementation of PEP 626. (GH-23113)
* Implement new line number table format, as defined in PEP 626.
2020-11-12 09:43:29 +00:00
Victor Stinner c9bc290dd6
bpo-42161: Use _PyLong_GetZero() and _PyLong_GetOne() (GH-22995)
Use _PyLong_GetZero() and _PyLong_GetOne()
in Objects/ and Python/ directories.
2020-10-27 02:24:34 +01:00
Serhiy Storchaka fb5db7ec58
bpo-42006: Stop using PyDict_GetItem, PyDict_GetItemString and _PyDict_GetItemId. (GH-22648)
These functions are considered not safe because they suppress all internal errors
and can return wrong result.  PyDict_GetItemString and _PyDict_GetItemId can
also silence current exception in rare cases.

Remove no longer used _PyDict_GetItemId.
Add _PyDict_ContainsId and rename _PyDict_Contains into
_PyDict_Contains_KnownHash.
2020-10-26 08:43:39 +02:00
Batuhan Taskaya 044a1048ca
bpo-38605: Make 'from __future__ import annotations' the default (GH-20434)
The hard part was making all the tests pass; there are some subtle issues here, because apparently the future import wasn't tested very thoroughly in previous Python versions.

For example, `inspect.signature()` returned type objects normally (except for forward references), but strings with the future import. We changed it to try and return type objects by calling `typing.get_type_hints()`, but fall back on returning strings if that function fails (which it may do if there are future references in the annotations that require passing in a specific namespace to resolve).
2020-10-06 13:03:02 -07:00
Mark Shannon 02d126aa09
bpo-39934: Account for control blocks in 'except' in compiler. (GH-22395)
* Account for control blocks in 'except' in compiler. Fixes #39934.
2020-09-25 14:04:19 +01:00
Victor Stinner 71f2ff4ccf
bpo-40941: Fix fold_tuple_on_constants() compiler warnings (GH-22378)
Add explicit casts to fix compiler warnings in
fold_tuple_on_constants().

The limit of constants per code is now INT_MAX, rather than UINT_MAX.
2020-09-23 14:06:55 +02:00
Pablo Galindo a5634c4067
bpo-41746: Add type information to asdl_seq objects (GH-22223)
* Add new capability to the PEG parser to type variable assignments. For instance:
```
       | a[asdl_stmt_seq*]=';'.small_stmt+ [';'] NEWLINE { a }
```

* Add new sequence types from the asdl definition (automatically generated)
* Make `asdl_seq` type a generic aliasing pointer type.
* Create a new `asdl_generic_seq` for the generic case using `void*`.
* The old `asdl_seq_GET`/`ast_seq_SET` macros now are typed.
* New `asdl_seq_GET_UNTYPED`/`ast_seq_SET_UNTYPED` macros for dealing with generic sequences.
* Changes all possible `asdl_seq` types to use specific versions everywhere.
2020-09-16 19:42:00 +01:00
Pablo Galindo c51db0ea40
bpo-41531: Fix compilation of dict literals with more than 0xFFFF elements (GH-21850) 2020-08-13 09:48:41 +01:00
Mark Shannon 582aaf19e8
bpo-41463: Generate information about jumps from 'opcode.py' rather than duplicating it in 'compile.c' (GH-21714)
Generate information about jumps from 'opcode.py' rather than duplicate it in 'compile.c'
2020-08-04 17:30:11 +01:00
Mark Shannon 6e8128f02e
bpo-41323: Perform 'peephole' optimizations directly on the CFG. (GH-21517)
* Move 'peephole' optimizations into compile.c and perform them directly on the CFG.
2020-07-30 10:03:00 +01:00
Matthias Bussonnier bd46174a5a
bpo-41218: Only mark async code with CO_COROUTINE. (#21357)
3.8.3 had a regression where compiling with
ast.PyCF_ALLOW_TOP_LEVEL_AWAIT woudl agressively mark things are
coroutine even if there were not.
2020-07-06 23:26:52 +02:00
Pablo Galindo 60eb9f1ab5
bpo-39151: Simplify DFS in the assembler (GH-17733) 2020-06-28 01:55:47 +01:00
Pablo Galindo 1ed83adb0e
bpo-40939: Remove the old parser (GH-20768)
This commit removes the old parser, the deprecated parser module, the old parser compatibility flags and environment variables and all associated support code and documentation.
2020-06-11 17:30:46 +01:00
Mark Shannon db64f12e4d
Make sure that keyword arguments are merged into the arguments dictionary when dict unpacking and keyword arguments are interleaved. (GH-20553) 2020-06-01 10:42:42 +01:00
Pablo Galindo ee40e4b856
bpo-40334: Don't downcast from Py_ssize_t to int (GH-19671) 2020-04-23 03:43:08 +01:00
Pablo Galindo c5fc156852
bpo-40334: PEP 617 implementation: New PEG parser for CPython (GH-19503)
Co-authored-by: Guido van Rossum <guido@python.org>
Co-authored-by: Lysandros Nikolaou <lisandrosnik@gmail.com>
2020-04-22 23:29:27 +01:00
Victor Stinner da7933ecc3
bpo-40268: Add _PyInterpreterState_GetConfig() (GH-19492)
Don't access PyInterpreterState.config member directly anymore, but
use new functions:

* _PyInterpreterState_GetConfig()
* _PyInterpreterState_SetConfig()
* _Py_GetConfig()
2020-04-13 03:04:28 +02:00
Zackery Spytz 08050e959e
bpo-40147: Fix a compiler warning on Windows in Python/compile.c (GH-19389)
Change the type of nkeywords to Py_ssize_t.
2020-04-06 07:47:47 +01:00
Pablo Galindo 254ec78341
bpo-40147: Move the check for duplicate keywords to the compiler (GH-19289) 2020-04-03 20:37:13 +01:00
Furkan Önder cb6534e1a8
bpo-40067: Improve error messages for multiple star expressions in assignments (GH-19168)
Co-Authored-By: Batuhan Taşkaya <isidentical@gmail.com>
Co-Authored-By: Pablo Galindo <Pablogsal@gmail.com>
2020-03-26 01:54:31 +00:00
Victor Stinner 87d3b9db4a
bpo-39882: Add _Py_FatalErrorFormat() function (GH-19157) 2020-03-25 19:27:36 +01:00
Andy Lester 7668a8bc93
Use calloc-based functions, not malloc. (GH-19152) 2020-03-24 23:26:44 -05:00
Batuhan Taşkaya 9052f7a41b
bpo-39562: Allow executing asynchronous comprehensions in the asyncio REPL (GH-18968)
Co-authored-by: Pablo Galindo <Pablogsal@gmail.com>
2020-03-19 11:35:44 +00:00
Pablo Galindo d112c600ab
bpo-39220: Do not optimise annotation if 'from __future__ import annotations' is used (GH-17866)
Do not apply AST-based optimizations if 'from __future__ import annotations' is used in order to
prevent information lost in the final version of the annotations.
2020-03-18 23:02:09 +00:00
Serhiy Storchaka 6b97598fb6
bpo-39988: Remove ast.AugLoad and ast.AugStore node classes. (GH-19038) 2020-03-17 23:41:08 +02:00
Serhiy Storchaka 61cb3d02b8
bpo-39987: Simplify setting lineno in the compiler. (GH-19037) 2020-03-17 18:07:30 +02:00
Batuhan Taşkaya 8689209e03
bpo-39969: Remove ast.Param node class as is no longer used (GH-19020) 2020-03-15 19:32:17 +00:00
Pablo Galindo 90235810ec
bpo-39965: Correctly raise SyntaxError if await is used outside async functions when PyCF_ALLOW_TOP_LEVEL_AWAIT is set (GH-19010) 2020-03-15 04:29:22 +00:00
Andy Lester 76d5877b72
closes bpo-39922: Remove unused args from four functions. (GH-18893) 2020-03-10 19:18:12 -07:00
Serhiy Storchaka 13d52c2686
bpo-34822: Simplify AST for subscription. (GH-9605)
* Remove the slice type.
* Make Slice a kind of the expr type instead of the slice type.
* Replace ExtSlice(slices) with Tuple(slices, Load()).
* Replace Index(value) with a value itself.

All non-terminal nodes in AST for expressions are now of the expr type.
2020-03-10 18:52:34 +02:00
Brandt Bucher d5aa2e941c
bpo-39890: Don't mutate the AST when compiling starred assignments (GH-18833) 2020-03-08 03:44:18 +00:00
Batuhan Taşkaya d82e469048
bpo-39639: Remove the AST "Suite" node and associated code (GH-18513)
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>
2020-03-04 16:16:46 +00:00
Serhiy Storchaka 8c579b1cc8
bpo-32856: Optimize the assignment idiom in comprehensions. (GH-16814)
Now `for y in [expr]` in comprehensions is as fast as a simple
assignment `y = expr`.
2020-02-12 12:18:59 +02:00
Victor Stinner a102ed7d2f
bpo-39573: Use Py_TYPE() macro in Python and Include directories (GH-18391)
Replace direct access to PyObject.ob_type with Py_TYPE().
2020-02-07 02:24:48 +01:00
Mark Shannon 8a4cd700a7
bpo-39320: Handle unpacking of **values in compiler (GH-18141)
* 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.
2020-01-27 09:57:45 +00:00
Mark Shannon 13bc13960c
bpo-39320: Handle unpacking of *values in compiler (GH-17984)
* 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.
2020-01-23 09:25:17 +00:00
Ammar Askar e92d39303f Fix compiler warning on Windows (GH-18012)
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 c96be811fa
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.
2020-01-15 10:48:40 -06:00
Mark Shannon 9af0e47b17
bpo-39156: Break up COMPARE_OP into four logically distinct opcodes. (GH-17754)
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.
2020-01-14 10:12:45 +00:00
Mark Shannon 88dce26da6
Fix handling of line numbers around finally-blocks. (#17737) 2019-12-30 09:53:36 +00:00
Brandt Bucher 6dd9b64770 bpo-38328: Speed up the creation time of constant list and set display. (GH-17114) 2019-11-26 15:16:53 +09:00
Mark Shannon fee552669f
Produce cleaner bytecode for 'with' and 'async with' by generating separate 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.
2019-11-21 09:11:43 +00:00
Pablo Galindo 6c3e66a34b
bpo-38640: Allow break and continue in always false while loops (GH-16992) 2019-10-30 11:53:26 +00:00
Hansraj Das 01171ebd96 Typo fix: "empy" should be "empty". (GH-16666) 2019-10-08 19:24:02 -07:00
T. Wouters 99b54d6817 Revert "Fix depth-first-search computation in compile.c (GH-16042)" (GH-16050)
This reverts commit 355f3e1e5c.

bpo-38135
2019-09-12 15:05:33 +01:00
Mark Shannon 355f3e1e5c Fix depth-first-search computation in compile.c (GH-16042) 2019-09-12 06:42:23 -07:00
Zackery Spytz ce6a070414 bpo-34880: Add the LOAD_ASSERTION_ERROR opcode. (GH-15073)
Fix assert statement misbehavior if AssertionError is shadowed.
2019-08-25 12:44:09 +03:00
Serhiy Storchaka ef61c524dd
bpo-37830: Fix compilation of break and continue in finally. (GH-15320)
Fix compilation of "break" and "continue" in the
"finally" block when the corresponding "try" block
contains "return" with a non-constant value.
2019-08-24 13:11:52 +03:00
Min ho Kim c4cacc8c5e Fix typos in comments, docs and test names (#15018)
* 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.
2019-07-30 18:16:13 -04:00
Pablo Galindo 18c5f9d44d bpo-37500: Make sure dead code does not generate bytecode but also detect 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
2019-07-15 02:15:01 -07:00
Pablo Galindo 4a2edc34a4 bpo-37221: Add PyCode_NewWithPosOnlyArgs to be used internally and set PyCode_New as a compatibility wrapper (GH-13959)
Add PyCode_NewEx to be used internally and set PyCode_New as a compatibility wrapper
2019-07-01 12:35:05 +02:00
Jörn Heissler c8a35417db bpo-35224: Reverse evaluation order of key: value in dict comprehensions (GH-14139)
… as proposed in PEP 572; key is now evaluated before value.





https://bugs.python.org/issue35224
2019-06-22 07:40:55 -07:00
Victor Stinner 37d66d7d4b
bpo-37253: Add _PyCompilerFlags_INIT macro (GH-14018)
Add a new _PyCompilerFlags_INIT macro to initialize PyCompilerFlags
variables, rather than initializing cf_flags and cf_feature_version
explicitly in each variable.
2019-06-13 02:16:41 +02:00
Pablo Galindo cd74e66a8c
bpo-37122: Make co->co_argcount represent the total number of positonal arguments in the code object (GH-13726) 2019-06-01 18:08:04 +01:00
Pablo Galindo a0c01bf136
bpo-37115: Support annotations in positional-only arguments (GH-13698) 2019-05-31 15:19:50 +01:00
Eric V. Smith 6f6ff8a565
bpo-37050: Remove expr_text from FormattedValue ast node, use Constant node 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.
2019-05-27 15:31:52 -04:00
Victor Stinner 331a6a56e9
bpo-36763: Implement the PEP 587 (GH-13592)
* 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()
2019-05-27 16:39:22 +02:00
Matthias Bussonnier 565b4f1ac7 bpo-34616: Add PyCF_ALLOW_TOP_LEVEL_AWAIT to allow top-level await (GH-13148)
Co-Authored-By: Yury Selivanov <yury@magic.io>
2019-05-21 16:12:02 -04:00
Chris Angelico ad098b6750 Annotate the unexplained assignment in exception unbinding (GH-11448) 2019-05-21 09:34:19 -04:00
David Carlier 27ee0f8551 Fix couple of dead code paths (GH-7418) 2019-05-17 19:46:22 -04:00
Pablo Galindo af8646c805
bpo-1875: Raise SyntaxError in invalid blocks that will be optimised away (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.
2019-05-17 11:37:08 +01:00
Victor Stinner c96be811fa
bpo-36900: Replace global conf vars with config (GH-13299)
Replace global configuration variables with core_config read from the
current interpreter.

Cleanup dynload_hpux.c.
2019-05-14 17:34:56 +02:00
Eric V. Smith 9a4135e939
bpo-36817: Add f-string debugging using '='. (GH-13123)
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.
2019-05-08 16:28:48 -04:00
Pablo Galindo 8c77b8cb91
bpo-36540: PEP 570 -- Implementation (GH-12701)
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
2019-04-29 13:36:57 +01:00
Simeon 63b5fc5f42 Fix typos in compile.c comments (GH-12752) 2019-04-09 16:36:57 -07:00
Zackery Spytz 97f5de01ad bpo-35284: Fix the error handling in the compiler's compiler_call(). (GH-10625)
compiler_call() needs to check if an error occurred during the
maybe_optimize_method_call() call.
2019-03-22 09:30:32 +02:00
Zackery Spytz 9b4a1b1e23 bpo-36374: Fix a possible null pointer dereference (GH-12449)
https://bugs.python.org/issue36374
2019-03-20 02:16:25 -07:00
Guido van Rossum 495da29225 bpo-35975: Support parsing earlier minor versions of Python 3 (GH-12086)
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
2019-03-07 12:38:08 -08:00
Serhiy Storchaka d8b3a98c90
bpo-36187: Remove NamedStore. (GH-12167)
NamedStore has been replaced with Store. The difference between
NamedStore and Store is handled when precess the NamedExpr node
one level upper.
2019-03-05 20:42:06 +02:00
Serhiy Storchaka 4583525835
bpo-35798: Fix duplicate SyntaxWarning: "is" with a literal. (GH-11639) 2019-02-16 08:29:46 +02:00
Serhiy Storchaka 62e4481238
bpo-15248: Emit a compiler warning when missed a comma before tuple or list. (GH-11757) 2019-02-16 08:12:19 +02:00
Emily Morehouse 8f59ee01be
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 (2b3acd37bd (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-24 16:49:56 -07:00
Ivan Levkivskyi 9932a22897
bpo-33416: Add end positions to Python AST (GH-11605)
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.
2019-01-22 11:18:22 +00:00
Serhiy Storchaka 3bcbedc9f1
bpo-34850: Emit a warning for "is" and "is not" with a literal. (GH-9642) 2019-01-18 07:47:48 +02:00
INADA Naoki f7e4d3642f bpo-34100: compile: Re-enable frozenset merging (GH-10760)
This reverts commit 1005c84535.
2018-11-28 16:58:46 +01:00
Victor Stinner 1005c84535
bpo-34100: Partially revert merge_consts_recursive() (GH-10743)
Partically revert commit c2e1607a51 to
fix a reference leak.
2018-11-27 15:12:47 +01:00
INADA Naoki c2e1607a51 bpo-34100: Merge constants recursively (GH-8341)
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
2018-11-26 04:23:22 -08:00
Victor Stinner 5f2df88b63
bpo-35177: Add dependencies between header files (GH-10361)
* 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
2018-11-12 00:56:19 +01:00
Serhiy Storchaka 95b6acf951
bpo-34876: Change the lineno of the AST for decorated function and class. (GH-9731)
It was overridden by the lineno of the first decorator. Now it is
the lineno of 'def' or 'class'.
2018-10-30 13:16:02 +02:00
Serhiy Storchaka d31e7730cd
bpo-35029: Replace the SyntaxWarning exception with a SyntaxError. (GH-9999)
If SyntaxWarning was raised as an exception, it will be replaced
with a SyntaxError for better error reporting.
2018-10-21 10:09:39 +03:00
Zackery Spytz 53ebf4b070 Fix an incorrect check in compiler_try_except(). (GH-9810) 2018-10-12 08:54:03 +03:00
Serhiy Storchaka 3f22811fef
bpo-32892: Use ast.Constant instead of specific constant AST types. (GH-9445) 2018-09-27 17:42:37 +03:00
Ammar Askar 025eb98dc0 bpo-34683: Make SyntaxError column offsets consistently 1-indexed (gh-9338)
Also point to start of tokens in parsing errors.

Fixes bpo-34683
2018-09-24 14:12:49 -07:00
Serhiy Storchaka 7bdf28265a
bpo-32455: Add jump parameter to dis.stack_effect(). (GH-6610)
Add C API function PyCompile_OpcodeStackEffectWithJump().
2018-09-18 09:54:26 +03:00
Serhiy Storchaka da8d72c953
bpo-12458: Fix line numbers for multiline expressions. (GH-8774) 2018-09-17 15:17:29 +03:00
Benjamin Peterson e502451781
closes bpo-34646: Remove PyAPI_* macros from declarations. (GH-9218) 2018-09-12 12:06:42 -07:00
Serhiy Storchaka 143ce5c6db
bpo-33691: Add _PyAST_GetDocString(). (GH-7236) 2018-05-30 10:56:16 +03:00
Serhiy Storchaka 73cbe7a01a
bpo-32911: Revert bpo-29463. (GH-7121) (GH-7197)
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-05-29 12:04:55 +03:00
Serhiy Storchaka 64fddc423f bpo-33475: Fix and improve converting annotations to strings. (GH-6774) 2018-05-16 23:17:48 -04:00
Zsolt Dollenstein e239650660 bpo-33363: raise SyntaxError for async for/with outside async functions (#6616) 2018-04-27 11:58:56 -04:00
Serhiy Storchaka 57faf34887
bpo-33334: Support NOP and EXTENDED_ARG in dis.stack_effect(). (#6566)
Added tests to ensure that all defined opcodes are supported.
2018-04-25 22:04:06 +03:00
Serhiy Storchaka d70c2a6894
bpo-33298: Wrap only constants with _PyCode_ConstantKey() in the compiler. (GH-6512) 2018-04-20 16:01:25 +03:00
Serhiy Storchaka b7e1eff843
bpo-33299: Return an object itself for some types in _PyCode_ConstantKey(). (GH-6513) 2018-04-19 08:28:04 +03:00
Zackery Spytz f303639e3a bpo-33270: Intern names for all anonymous code objects (#6472) 2018-04-16 01:12:29 +03:00
Serhiy Storchaka aa8e51f5eb
bpo-33132: Fix more reference counting issues in the compiler. (GH-6323) 2018-04-01 00:29:37 +03:00
Serhiy Storchaka a95d98607e
bpo-33132: Fix reference counting issues in the compiler. (GH-6209) 2018-03-24 22:42:35 +02:00
Serhiy Storchaka 702f8f3611
bpo-33041: Rework compiling an "async for" loop. (#6142)
* Added new opcode END_ASYNC_FOR.
* Setting global StopAsyncIteration no longer breaks "async for" loops.
* Jumping into an "async for" loop is now disabled.
* Jumping out of an "async for" loop no longer corrupts the stack.
* Simplify the compiler.
2018-03-23 14:34:35 +02:00
Serhiy Storchaka fe2bbb1869
bpo-32489: Allow 'continue' in 'finally' clause. (GH-5822) 2018-03-18 09:56:52 +02:00
Serhiy Storchaka 67ee07795b
bpo-33041: Add missed error checks when compile "async for" (#6053)
and remove redundant code.
2018-03-10 18:49:26 +02:00
Serhiy Storchaka 24d3201eb7
bpo-33041: Fixed bytecode generation for "async for" with a complex target. (#6052)
A StopAsyncIteration raised on assigning or unpacking will be now propagated
instead of stopping the iteration.
2018-03-10 18:22:34 +02:00
Serhiy Storchaka 520b7ae27e
bpo-17611. Move unwinding of stack for "pseudo exceptions" from interpreter to compiler. (GH-5006)
Co-authored-by: Mark Shannon <mark@hotpy.org>
Co-authored-by: Antoine Pitrou <antoine@python.org>
2018-02-22 23:33:30 +02:00
Mark Shannon 332cd5ee4f bpo-32550. Remove the STORE_ANNOTATION bytecode. (GH-5181) 2018-01-29 16:41:04 -08:00
Guido van Rossum 95e4d58913 String annotations [PEP 563] (#4390)
* Document `from __future__ import annotations`
* Provide plumbing and tests for `from __future__ import annotations`
* Implement unparsing the AST back to string form

This is required for PEP 563 and as such only implements a part of the
unparsing process that covers expressions.
2018-01-26 08:20:18 -08:00
Serhiy Storchaka 782d6fe443
bpo-31113: Get rid of recursion in the compiler for normal control flow. (#3015) 2018-01-11 20:20:13 +02:00
Serhiy Storchaka d4864c61e3
bpo-24340: Fix estimation of the code stack size. (#5076) 2018-01-09 21:54:52 +02:00
Serhiy Storchaka 02b9ef2775
bpo-32439: Clean up the code for compiling comparison expressions. (#5029) 2017-12-30 09:47:42 +02:00
Serhiy Storchaka 3dfbaf51f0
bpo-32372: Move __debug__ optimization to the AST level. (#4925) 2017-12-25 12:47:50 +02:00
Serhiy Storchaka bd6ec4d79e
bpo-32365: Fix a reference leak when compile __debug__. (#4916)
It was introduced in bpo-27169.
2017-12-18 14:29:12 +02:00
Serhiy Storchaka 3325a6780c
bpo-27169: The __debug__ constant is now optimized out at compile time. (#4880)
This fixes also bpo-22091.
2017-12-15 12:35:48 +02:00
INADA Naoki 7ea143ae79
bpo-29469: Move constant folding to AST optimizer (GH-2858) 2017-12-14 16:47:20 +09:00
Nick Coghlan 078f1814f1
bpo-32176: Set CO_NOFREE in the code object constructor (GH-4675)
Previously, CO_NOFREE was set in the compiler, which meant
it could end up being set incorrectly when code objects
were created directly. Setting it in the constructor based
on freevars and cellvars ensures it is always accurate,
regardless of how the code object is defined.
2017-12-03 11:12:20 +10:00
Serhiy Storchaka e2f92de6a9
Add the const qualifier to "char *" variables that refer to literal strings. (#4370) 2017-11-11 13:06:26 +02:00
Yury Selivanov b8ab9d3fc8 bpo-31708: Allow async generator expressions in synchronous functions (#3905) 2017-10-06 02:58:28 -04:00
Yury Selivanov faa135acbf bpo-31709: Drop support for asynchronous __aiter__. (#3903) 2017-10-06 02:08:57 -04:00
Barry Warsaw b2e5794870 bpo-31338 (#3374)
* Add Py_UNREACHABLE() as an alias to abort().
* Use Py_UNREACHABLE() instead of assert(0)
* Convert more unreachable code to use Py_UNREACHABLE()
* Document Py_UNREACHABLE() and a few other macros.
2017-09-14 18:13:16 -07:00
Serhiy Storchaka 265fcc5fc2 bpo-31286, bpo-30024: Fixed stack usage in absolute imports with (#3217)
binding a submodule to a name.
2017-08-29 15:47:44 +03:00
Stefan Krah f432a3234f bpo-30923: Silence fall-through warnings included in -Wextra since gcc-7.0. (#3157) 2017-08-21 13:09:59 +02:00
Serhiy Storchaka 36ff451eba bpo-30501: Make the compiler producing optimized code for condition expressions. (#1851) 2017-06-11 14:50:22 +03:00
Serhiy Storchaka f93234bb8a bpo-30024: Circular imports involving absolute imports with binding (#1264)
a submodule to a name are now supported.
2017-05-09 22:31:05 +03:00
Serhiy Storchaka ba85d69a3e bpo-29878: Add global instances of int for 0 and 1. (#852) 2017-03-30 09:09:41 +03:00
INADA Naoki cb41b2766d bpo-29463: Add docstring field to some AST nodes. (#46)
* 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-02-22 16:31:59 +01:00
Matthieu Dartiailh 3a9ac827c7 bpo-29607: Fix stack_effect computation for CALL_FUNCTION_EX (#202) 2017-02-21 15:25:22 +02:00
Serhiy Storchaka 5ab81d787f Issue #28959: Added private macro PyDict_GET_SIZE for retrieving the size of dict. 2016-12-16 16:18:57 +02:00
Yury Selivanov f2392133eb Issue #26110: Add LOAD_METHOD/CALL_METHOD opcodes.
Special thanks to INADA Naoki for pushing the patch through
the last mile, Serhiy Storchaka for reviewing the code, and to
Victor Stinner for suggesting the idea (originally implemented
in the PyPy project).
2016-12-13 19:03:51 -05:00
Serhiy Storchaka 0f6373c34f Issue #28739: f-string expressions no longer accepted as docstrings and
by ast.literal_eval() even if they do not include subexpressions.
2016-12-11 19:39:36 +02:00
Serhiy Storchaka 4cc30ae313 Issue #28739: f-string expressions no longer accepted as docstrings and
by ast.literal_eval() even if they do not include subexpressions.
2016-12-11 19:37:19 +02:00
Nick Coghlan d77e5b7211 Merge #23722 from 3.6 2016-12-05 16:59:22 +10:00
Nick Coghlan 19d246745d Issue #23722: improve __classcell__ compatibility
Handling zero-argument super() in __init_subclass__ and
__set_name__ involved moving __class__ initialisation to
type.__new__. This requires cooperation from custom
metaclasses to ensure that the new __classcell__ entry
is passed along appropriately.

The initial implementation of that change resulted in abruptly
broken zero-argument super() support in metaclasses that didn't
adhere to the new requirements (such as Django's metaclass for
Model definitions).

The updated approach adopted here instead emits a deprecation
warning for those cases, and makes them work the same way they
did in Python 3.5.

This patch also improves the related class machinery documentation
to cover these details and to include more reader-friendly
cross-references and index entries.
2016-12-05 16:47:55 +10:00