Commit graph

173 commits

Author SHA1 Message Date
Victor Stinner 45b9e6a61f
gh-108765: Move standard includes to Python.h (#108769)
* Move <ctype.h>, <limits.h> and <stdarg.h> standard includes to
  Python.h.
* Move "pystats.h" include from object.h to Python.h.
* Remove redundant "pymem.h" include in objimpl.h and "pyport.h"
  include in pymem.h; Python.h already includes them earlier.
* Remove redundant <wchar.h> include in unicodeobject.h; Python.h
  already includes it.
* Move _SGI_MP_SOURCE define from Python.h to pyport.h.
* pycore_condvar.h includes explicitly <unistd.h> for the
  _POSIX_THREADS macro.
2023-09-01 21:03:20 +02:00
Mark Shannon feec49c407
GH-101578: Normalize the current exception (GH-101607)
* Make sure that the current exception is always normalized.

* Remove redundant type and traceback fields for the current exception.

* Add new API functions: PyErr_GetRaisedException, PyErr_SetRaisedException

* Add new API functions: PyException_GetArgs, PyException_SetArgs
2023-02-08 09:31:12 +00:00
Victor Stinner 7ad6f74fcf
gh-87347: Add parenthesis around macro arguments (#93915)
Add unit test on Py_MEMBER_SIZE() and some other macros.
2022-06-20 16:04:52 +02:00
Victor Stinner 941d7054c1
gh-91320: Fix more old-style cast warnings in C++ (#93285)
Use _PyObject_CAST() in the public C API to fix C++ compiler
warnings: "use of old-style cast" (clang -Wold-style-cast).
2022-06-03 00:59:57 +02:00
Irit Katriel 5d421d7342
gh-90501: Add PyErr_GetHandledException and PyErr_SetHandledException (GH-30531) 2022-04-15 19:57:47 +01:00
Irit Katriel f30ad65dbf
bpo-45292: [PEP 654] add the ExceptionGroup and BaseExceptionGroup classes (GH-28569) 2021-10-23 00:13:46 +01:00
Victor Stinner 7076bef8ba
bpo-45434: Remove useless space in includes (GH-28963)
Micro-optimize spaces!
2021-10-15 01:50:04 +02:00
Inada Naoki 4827483f47
bpo-43510: Implement PEP 597 opt-in EncodingWarning. (GH-19481)
See [PEP 597](https://www.python.org/dev/peps/pep-0597/).

* Add `-X warn_default_encoding` and `PYTHONWARNDEFAULTENCODING`.
* Add EncodingWarning
* Add io.text_encoding()
* open(), TextIOWrapper() emits EncodingWarning when encoding is omitted and warn_default_encoding is enabled.
* _pyio.TextIOWrapper() uses UTF-8 as fallback default encoding used when failed to import locale module. (used during building Python)
* bz2, configparser, gzip, lzma, pathlib, tempfile modules use io.text_encoding().
* What's new entry
2021-03-29 12:28:14 +09:00
Antoine Pitrou ba251c2ae6
bpo-43356: Allow passing a signal number to interrupt_main() (GH-24755)
Also introduce a new C API ``PyErr_SetInterruptEx(int signum)``.
2021-03-11 23:35:45 +01:00
Victor Stinner a486054b24
bpo-43270: Remove private _PyErr_OCCURRED() macro (GH-24579)
Remove the private _PyErr_OCCURRED() macro: use the public
PyErr_Occurred() function instead.

CPython internals must use the internal _PyErr_Occurred(tstate)
function instead: it is the most efficient way to check if an
exception was raised.
2021-02-19 15:08:54 +01:00
Victor Stinner e822e37946
bpo-36020: Remove snprintf macro in pyerrors.h (GH-20889)
On Windows, #include "pyerrors.h" no longer defines "snprintf" and
"vsnprintf" macros.

PyOS_snprintf() and PyOS_vsnprintf() should be used to get portable
behavior.

Replace snprintf() calls with PyOS_snprintf() and replace vsnprintf()
calls with PyOS_vsnprintf().
2020-06-15 21:59:47 +02:00
Victor Stinner 9e5d30cc99
bpo-39882: Py_FatalError() logs the function name (GH-18819)
The Py_FatalError() function is replaced with a macro which logs
automatically the name of the current function, unless the
Py_LIMITED_API macro is defined.

Changes:

* Add _Py_FatalErrorFunc() function.
* Remove the function name from the message of Py_FatalError() calls
  which included the function name.
* Update tests.
2020-03-07 00:54:20 +01: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
Nick Coghlan 5dbe0f59b7
bpo-37757: Disallow PEP 572 cases that expose implementation details (GH-15131)
- drop TargetScopeError in favour of raising SyntaxError directly
  as per the updated PEP 572
- comprehension iteration variables are explicitly local, but
  named expression targets in comprehensions are nonlocal or
  global. Raise SyntaxError as specified in PEP 572
- named expression targets in the outermost iterable of a
  comprehension have an ambiguous target scope. Avoid resolving
  that question now by raising SyntaxError. PEP 572
  originally required this only for cases where the bound name
  conflicts with the iteration variable in the comprehension,
  but CPython can't easily restrict the exception to that case
  (as it doesn't know the target variable names when visiting
  the outermost iterator expression)
2019-08-25 23:45:40 +10:00
Victor Stinner c664b342a4
bpo-36475: Make PyThread_exit_thread with _Py_NO_RETURN (GH-13068) 2019-05-04 11:48:05 -04: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
Victor Stinner 5a8c240b1d
bpo-35134: Add Include/cpython/pyerrors.h (GH-10727)
Move pyerrors.h code surrounded by "#ifndef Py_LIMITED_API"
to a new Include/cpython/pyerrors.h header file.
2018-11-26 22:11:25 +01:00
Alexey Izbyshev e2ed5adcb5 bpo-35147: Fix _Py_NO_RETURN for GCC (GH-10300)
Use `__GNUC__` instead of non-existing `__GNUC_MAJOR__`.





https://bugs.python.org/issue35147
2018-11-02 09:32:26 -07:00
Victor Stinner cfc8831f5e
Define _Py_NO_RETURN for Microsoft C compiler (GH-8606) 2018-08-01 16:41:25 +02:00
Serhiy Storchaka ceeef10cdb
bpo-33818: PyExceptionClass_Name() will now return "const char *". (GH-7581) 2018-06-15 11:09:43 +03:00
Serhiy Storchaka 5cbefa9919
Clean up after bpo-33738. (GH-7627)
* Add declarations even if they are overridden by macros.
* Make the declaration and the definition of PyExceptionClass_Name
  consistent.
2018-06-11 15:01:47 +03:00
Christian Tismer 8398713cea bpo-33738: Address review comments in GH #7477 (GH-7585) 2018-06-10 18:48:28 -04:00
Christian Tismer ea62ce7f4f bpo-33738: Fix macros which contradict PEP 384 (GH-7477)
During development of the limited API support for PySide,
we saw an error in a macro that accessed a type field.

This patch fixes the 7 errors in the Python headers.
Macros which were not written as capitals were implemented
as function.

To do the necessary analysis again, a script was included that
parses all headers and looks for "->tp_" in serctions which can
be reached with active limited API.

It is easily possible to call this script as a test.

Error listing:

../../Include/objimpl.h:243
#define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \
    (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
Action: commented only

../../Include/objimpl.h:362
#define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0)
Action: commented only

../../Include/objimpl.h:364
#define PyObject_GET_WEAKREFS_LISTPTR(o) \
    ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset))
Action: commented only

../../Include/pyerrors.h:143
#define PyExceptionClass_Name(x) \
     ((char *)(((PyTypeObject*)(x))->tp_name))
Action: implemented function

../../Include/abstract.h:593
#define PyIter_Check(obj) \
    ((obj)->ob_type->tp_iternext != NULL && \
     (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented)
Action: implemented function

../../Include/abstract.h:713
#define PyIndex_Check(obj)                              \
    ((obj)->ob_type->tp_as_number != NULL &&            \
     (obj)->ob_type->tp_as_number->nb_index != NULL)
Action: implemented function

../../Include/abstract.h:924
#define PySequence_ITEM(o, i)\
    ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) )
Action: commented only
2018-06-09 14:32:25 -04:00
xdegaye 56d1f5ca32 bpo-30697: Fix PyErr_NormalizeException() when no memory (GH-2327) 2017-10-26 15:09:06 +02:00
Mark Shannon ae3087c638 Move exc state to generator. Fixes bpo-25612 (#1773)
Move exception state information from frame objects to coroutine (generator/thread) object where it belongs.
2017-10-22 23:41:51 +02:00
Segev Finer 7ff1e88a57 Delete sigcheck.c since it appears unused (#1723) 2017-05-25 13:00:18 +02:00
Serhiy Storchaka a171a03bd2 Issue #29058: All stable API extensions added after Python 3.2 are now
available only when Py_LIMITED_API is set to the PY_VERSION_HEX value of
the minimum Python version supporting this API.
2016-12-27 15:04:59 +02:00
Serhiy Storchaka 34d0ac8027 Issue #29058: All stable API extensions added after Python 3.2 are now
available only when Py_LIMITED_API is set to the PY_VERSION_HEX value of
the minimum Python version supporting this API.
2016-12-27 14:57:39 +02:00
Serhiy Storchaka 460bd0d284 Issue #19569: Compiler warnings are now emitted if use most of deprecated
functions.
2016-11-20 12:16:46 +02:00
Serhiy Storchaka 467ab194fc Issue #28410: Added _PyErr_FormatFromCause() -- the helper for raising
new exception with setting current exception as __cause__.

_PyErr_FormatFromCause(exception, format, args...) is equivalent to Python

    raise exception(format % args) from sys.exc_info()[1]
2016-10-21 17:09:17 +03:00
Eric Snow 46f97b85a8 Issue #15767: Use ModuleNotFoundError. 2016-09-07 16:56:15 -07:00
Eric Snow c943265ba5 Issue #15767: Add ModuleNotFoundError. 2016-09-07 15:42:32 -07:00
Yury Selivanov f488fb422a Issue #19235: Add new RecursionError exception. Patch by Georg Brandl. 2015-07-03 01:04:23 -04:00
Yury Selivanov 7544508f02 PEP 0492 -- Coroutines with async and await syntax. Issue #24017. 2015-05-11 22:57:16 -04:00
Nick Coghlan d600951748 Issue #22869: Split pythonrun into two modules
- interpreter startup and shutdown code moved to a new
  pylifecycle.c module
- Py_OptimizeFlag moved into the new module with the other
  global flags
2014-11-20 21:39:37 +10:00
Serhiy Storchaka 78184af9b5 Issue #21715: Extracted shared complicated code in the _io module to new
_PyErr_ChainExceptions() function.
2014-10-08 22:32:50 +03:00
Serhiy Storchaka e2bd2a7186 Issue #21715: Extracted shared complicated code in the _io module to new
_PyErr_ChainExceptions() function.
2014-10-08 22:31:52 +03:00
Antoine Pitrou 0676a406bf Issue #18711: Add a new PyErr_FormatV function, similar to PyErr_Format but accepting a va_list argument. 2014-09-30 21:16:27 +02:00
Larry Hastings 8f9f0f12e8 Issue #20517: Removed unnecessary new (short-lived) functions from PyErr. 2014-02-10 03:43:57 -08:00
Larry Hastings b082731fbb Issue #20517: Functions in the os module that accept two filenames
now register both filenames in the exception on failure.
This required adding new C API functions allowing OSError exceptions
to reference two filenames instead of one.
2014-02-09 22:05:19 -08:00
Martin v. Löwis 1c0689c613 Issue #19526: Exclude all new API from the stable ABI. 2014-01-03 21:36:49 +01:00
Christian Heimes af01f66817 Issue #16136: Remove VMS support and VMS-related code 2013-12-21 16:19:10 +01:00
Nick Coghlan 8b097b4ed7 Close #17828: better handling of codec errors
- output type errors now redirect users to the type-neutral
  convenience functions in the codecs module
- stateless errors that occur during encoding and decoding
  will now be automatically wrapped in exceptions that give
  the name of the codec involved
2013-11-13 23:49:21 +10:00
Antoine Pitrou 1cfa0ba883 Fix macro expansion of _PyErr_OCCURRED(), and make sure to use it in at least one place so as to avoid regressions. 2013-10-07 20:40:59 +02:00
Antoine Pitrou 59c900d3bf Fix macro expansion of _PyErr_OCCURRED(), and make sure to use it in at least one place so as to avoid regressions. 2013-10-07 20:38:51 +02:00
Raymond Hettinger 69492dab07 Factor-out the common code for setting a KeyError. 2013-09-02 15:59:26 -07:00
Victor Stinner 14e461d5b9 Close #11619: The parser and the import machinery do not encode Unicode
filenames anymore on Windows.
2013-08-26 22:28:21 +02:00
Brett Cannon 679ecb565b Issue #15767: back out 8a0ed9f63c6e, finishing the removal of
ModuleNotFoundError.
2013-07-04 17:51:50 -04:00
Brett Cannon 82da8886cc Issue #15767: Revert 3a50025f1900 for ModuleNotFoundError 2013-07-04 17:48:16 -04:00
Brett Cannon 8f5ac5106e Issue #15767: Touch up ModuleNotFoundError usage by import.
Forgot to raise ModuleNotFoundError when None is found in sys.modules.
This led to introducing the C function PyErr_SetImportErrorSubclass()
to make setting ModuleNotFoundError easier.

Also updated the reference docs to mention ModuleNotFoundError
appropriately. Updated the docs for ModuleNotFoundError to mention the
None in sys.modules case.

Lastly, it was noticed that PyErr_SetImportError() was not setting an
exception when returning None in one case. That issue is now fixed.
2013-06-12 23:29:18 -04:00