Skip to content

Commit

Permalink
Merge branch 'master' into remove-atan2-helpers-122681
Browse files Browse the repository at this point in the history
  • Loading branch information
skirpichev committed Aug 6, 2024
2 parents c096fad + 8ce70d6 commit a4aff45
Show file tree
Hide file tree
Showing 21 changed files with 802 additions and 430 deletions.
25 changes: 25 additions & 0 deletions Doc/library/inspect.rst
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,19 @@ attributes (see :ref:`import-mod-attrs` for module attributes):
| | f_trace | tracing function for this |
| | | frame, or ``None`` |
+-----------------+-------------------+---------------------------+
| | f_trace_lines | indicate whether a |
| | | tracing event is |
| | | triggered for each source |
| | | source line |
+-----------------+-------------------+---------------------------+
| | f_trace_opcodes | indicate whether |
| | | per-opcode events are |
| | | requested |
+-----------------+-------------------+---------------------------+
| | clear() | used to clear all |
| | | references to local |
| | | variables |
+-----------------+-------------------+---------------------------+
| code | co_argcount | number of arguments (not |
| | | including keyword only |
| | | arguments, \* or \*\* |
Expand Down Expand Up @@ -214,6 +227,18 @@ attributes (see :ref:`import-mod-attrs` for module attributes):
| | | arguments and local |
| | | variables |
+-----------------+-------------------+---------------------------+
| | co_lines() | returns an iterator that |
| | | yields successive |
| | | bytecode ranges |
+-----------------+-------------------+---------------------------+
| | co_positions() | returns an iterator of |
| | | source code positions for |
| | | each bytecode instruction |
+-----------------+-------------------+---------------------------+
| | replace() | returns a copy of the |
| | | code object with new |
| | | values |
+-----------------+-------------------+---------------------------+
| generator | __name__ | name |
+-----------------+-------------------+---------------------------+
| | __qualname__ | qualified name |
Expand Down
19 changes: 19 additions & 0 deletions Include/internal/pycore_parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,20 @@ extern "C" {
struct _parser_runtime_state {
#ifdef Py_DEBUG
long memo_statistics[_PYPEGEN_NSTATISTICS];
#ifdef Py_GIL_DISABLED
PyMutex mutex;
#endif
#else
int _not_used;
#endif
struct _expr dummy_name;
};

_Py_DECLARE_STR(empty, "")
#if defined(Py_DEBUG) && defined(Py_GIL_DISABLED)
#define _parser_runtime_state_INIT \
{ \
.mutex = {0}, \
.dummy_name = { \
.kind = Name_kind, \
.v.Name.id = &_Py_STR(empty), \
Expand All @@ -40,6 +45,20 @@ _Py_DECLARE_STR(empty, "")
.end_col_offset = 0, \
}, \
}
#else
#define _parser_runtime_state_INIT \
{ \
.dummy_name = { \
.kind = Name_kind, \
.v.Name.id = &_Py_STR(empty), \
.v.Name.ctx = Load, \
.lineno = 1, \
.col_offset = 0, \
.end_lineno = 1, \
.end_col_offset = 0, \
}, \
}
#endif

extern struct _mod* _PyParser_ASTFromString(
const char *str,
Expand Down
128 changes: 100 additions & 28 deletions Lib/_android_support.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import io
import sys

from threading import RLock
from time import sleep, time

# The maximum length of a log message in bytes, including the level marker and
# tag, is defined as LOGGER_ENTRY_MAX_PAYLOAD in
# platform/system/logging/liblog/include/log/log.h. As of API level 30, messages
# longer than this will be be truncated by logcat. This limit has already been
# reduced at least once in the history of Android (from 4076 to 4068 between API
# level 23 and 26), so leave some headroom.
# tag, is defined as LOGGER_ENTRY_MAX_PAYLOAD at
# https://cs.android.com/android/platform/superproject/+/android-14.0.0_r1:system/logging/liblog/include/log/log.h;l=71.
# Messages longer than this will be be truncated by logcat. This limit has already
# been reduced at least once in the history of Android (from 4076 to 4068 between
# API level 23 and 26), so leave some headroom.
MAX_BYTES_PER_WRITE = 4000

# UTF-8 uses a maximum of 4 bytes per character, so limiting text writes to this
# size ensures that TextIOWrapper can always avoid exceeding MAX_BYTES_PER_WRITE.
# size ensures that we can always avoid exceeding MAX_BYTES_PER_WRITE.
# However, if the actual number of bytes per character is smaller than that,
# then TextIOWrapper may still join multiple consecutive text writes into binary
# then we may still join multiple consecutive text writes into binary
# writes containing a larger number of characters.
MAX_CHARS_PER_WRITE = MAX_BYTES_PER_WRITE // 4

Expand All @@ -26,18 +27,22 @@ def init_streams(android_log_write, stdout_prio, stderr_prio):
if sys.executable:
return # Not embedded in an app.

global logcat
logcat = Logcat(android_log_write)

sys.stdout = TextLogStream(
android_log_write, stdout_prio, "python.stdout", errors=sys.stdout.errors)
stdout_prio, "python.stdout", errors=sys.stdout.errors)
sys.stderr = TextLogStream(
android_log_write, stderr_prio, "python.stderr", errors=sys.stderr.errors)
stderr_prio, "python.stderr", errors=sys.stderr.errors)


class TextLogStream(io.TextIOWrapper):
def __init__(self, android_log_write, prio, tag, **kwargs):
def __init__(self, prio, tag, **kwargs):
kwargs.setdefault("encoding", "UTF-8")
kwargs.setdefault("line_buffering", True)
super().__init__(BinaryLogStream(android_log_write, prio, tag), **kwargs)
self._CHUNK_SIZE = MAX_BYTES_PER_WRITE
super().__init__(BinaryLogStream(prio, tag), **kwargs)
self._lock = RLock()
self._pending_bytes = []
self._pending_bytes_count = 0

def __repr__(self):
return f"<TextLogStream {self.buffer.tag!r}>"
Expand All @@ -52,19 +57,48 @@ def write(self, s):
s = str.__str__(s)

# We want to emit one log message per line wherever possible, so split
# the string before sending it to the superclass. Note that
# "".splitlines() == [], so nothing will be logged for an empty string.
for line in s.splitlines(keepends=True):
while line:
super().write(line[:MAX_CHARS_PER_WRITE])
line = line[MAX_CHARS_PER_WRITE:]
# the string into lines first. Note that "".splitlines() == [], so
# nothing will be logged for an empty string.
with self._lock:
for line in s.splitlines(keepends=True):
while line:
chunk = line[:MAX_CHARS_PER_WRITE]
line = line[MAX_CHARS_PER_WRITE:]
self._write_chunk(chunk)

return len(s)

# The size and behavior of TextIOWrapper's buffer is not part of its public
# API, so we handle buffering ourselves to avoid truncation.
def _write_chunk(self, s):
b = s.encode(self.encoding, self.errors)
if self._pending_bytes_count + len(b) > MAX_BYTES_PER_WRITE:
self.flush()

self._pending_bytes.append(b)
self._pending_bytes_count += len(b)
if (
self.write_through
or b.endswith(b"\n")
or self._pending_bytes_count > MAX_BYTES_PER_WRITE
):
self.flush()

def flush(self):
with self._lock:
self.buffer.write(b"".join(self._pending_bytes))
self._pending_bytes.clear()
self._pending_bytes_count = 0

# Since this is a line-based logging system, line buffering cannot be turned
# off, i.e. a newline always causes a flush.
@property
def line_buffering(self):
return True


class BinaryLogStream(io.RawIOBase):
def __init__(self, android_log_write, prio, tag):
self.android_log_write = android_log_write
def __init__(self, prio, tag):
self.prio = prio
self.tag = tag

Expand All @@ -85,10 +119,48 @@ def write(self, b):

# Writing an empty string to the stream should have no effect.
if b:
# Encode null bytes using "modified UTF-8" to avoid truncating the
# message. This should not affect the return value, as the caller
# may be expecting it to match the length of the input.
self.android_log_write(self.prio, self.tag,
b.replace(b"\x00", b"\xc0\x80"))

logcat.write(self.prio, self.tag, b)
return len(b)


# When a large volume of data is written to logcat at once, e.g. when a test
# module fails in --verbose3 mode, there's a risk of overflowing logcat's own
# buffer and losing messages. We avoid this by imposing a rate limit using the
# token bucket algorithm, based on a conservative estimate of how fast `adb
# logcat` can consume data.
MAX_BYTES_PER_SECOND = 1024 * 1024

# The logcat buffer size of a device can be determined by running `logcat -g`.
# We set the token bucket size to half of the buffer size of our current minimum
# API level, because other things on the system will be producing messages as
# well.
BUCKET_SIZE = 128 * 1024

# https://cs.android.com/android/platform/superproject/+/android-14.0.0_r1:system/logging/liblog/include/log/log_read.h;l=39
PER_MESSAGE_OVERHEAD = 28


class Logcat:
def __init__(self, android_log_write):
self.android_log_write = android_log_write
self._lock = RLock()
self._bucket_level = 0
self._prev_write_time = time()

def write(self, prio, tag, message):
# Encode null bytes using "modified UTF-8" to avoid them truncating the
# message.
message = message.replace(b"\x00", b"\xc0\x80")

with self._lock:
now = time()
self._bucket_level += (
(now - self._prev_write_time) * MAX_BYTES_PER_SECOND)
self._bucket_level = min(self._bucket_level, BUCKET_SIZE)
self._prev_write_time = now

self._bucket_level -= PER_MESSAGE_OVERHEAD + len(tag) + len(message)
if self._bucket_level < 0:
sleep(-self._bucket_level / MAX_BYTES_PER_SECOND)

self.android_log_write(prio, tag, message)
33 changes: 24 additions & 9 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,11 +264,16 @@ def isfunction(object):
Function objects provide these attributes:
__doc__ documentation string
__name__ name with which this function was defined
__qualname__ qualified name of this function
__module__ name of the module the function was defined in or None
__code__ code object containing compiled function bytecode
__defaults__ tuple of any default values for arguments
__globals__ global namespace in which this function was defined
__annotations__ dict of parameter annotations
__kwdefaults__ dict of keyword only parameters with defaults"""
__kwdefaults__ dict of keyword only parameters with defaults
__dict__ namespace which is supporting arbitrary function attributes
__closure__ a tuple of cells or None
__type_params__ tuple of type parameters"""
return isinstance(object, types.FunctionType)

def _has_code_flag(f, flag):
Expand Down Expand Up @@ -333,17 +338,18 @@ def isgenerator(object):
"""Return true if the object is a generator.
Generator objects provide these attributes:
__iter__ defined to support iteration over container
close raises a new GeneratorExit exception inside the
generator to terminate the iteration
gi_code code object
gi_frame frame object or possibly None once the generator has
been exhausted
gi_running set to 1 when generator is executing, 0 otherwise
next return the next item from the container
send resumes the generator and "sends" a value that becomes
gi_yieldfrom object being iterated by yield from or None
__iter__() defined to support iteration over container
close() raises a new GeneratorExit exception inside the
generator to terminate the iteration
send() resumes the generator and "sends" a value that becomes
the result of the current yield-expression
throw used to raise an exception inside the generator"""
throw() used to raise an exception inside the generator"""
return isinstance(object, types.GeneratorType)

def iscoroutine(object):
Expand Down Expand Up @@ -378,7 +384,11 @@ def isframe(object):
f_lasti index of last attempted instruction in bytecode
f_lineno current line number in Python source code
f_locals local namespace seen by this frame
f_trace tracing function for this frame, or None"""
f_trace tracing function for this frame, or None
f_trace_lines is a tracing event triggered for each source line?
f_trace_opcodes are per-opcode events being requested?
clear() used to clear all references to local variables"""
return isinstance(object, types.FrameType)

def iscode(object):
Expand All @@ -403,7 +413,12 @@ def iscode(object):
co_names tuple of names other than arguments and function locals
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables"""
co_varnames tuple of names of arguments and local variables
co_qualname fully qualified function name
co_lines() returns an iterator that yields successive bytecode ranges
co_positions() returns an iterator of source code positions for each bytecode instruction
replace() returns a copy of the code object with a new values"""
return isinstance(object, types.CodeType)

def isbuiltin(object):
Expand Down
2 changes: 1 addition & 1 deletion Lib/re/_casefix.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Auto-generated by Tools/scripts/generate_re_casefix.py.
# Auto-generated by Tools/build/generate_re_casefix.py.

# Maps the code of lowercased character to codes of different lowercased
# characters which have the same uppercase.
Expand Down
Loading

0 comments on commit a4aff45

Please sign in to comment.