path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/third_party/python/Lib/xmlrpc/client.py
# # XML-RPC CLIENT LIBRARY # $Id$ # # an XML-RPC client interface for Python. # # the marshalling and response parser code can also be used to # implement XML-RPC servers. # # Notes: # this version is designed to work with Python 2.1 or newer. # # History: # 1999-01-14 fl Created # 1999-01-15 fl Changed dateTime to use localtime # 1999-01-16 fl Added Binary/base64 element, default to RPC2 service # 1999-01-19 fl Fixed array data element (from Skip Montanaro) # 1999-01-21 fl Fixed dateTime constructor, etc. # 1999-02-02 fl Added fault handling, handle empty sequences, etc. # 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro) # 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8) # 2000-11-28 fl Changed boolean to check the truth value of its argument # 2001-02-24 fl Added encoding/Unicode/SafeTransport patches # 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1) # 2001-03-28 fl Make sure response tuple is a singleton # 2001-03-29 fl Don't require empty params element (from Nicholas Riley) # 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2) # 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod) # 2001-09-03 fl Allow Transport subclass to override getparser # 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup) # 2001-10-01 fl Remove containers from memo cache when done with them # 2001-10-01 fl Use faster escape method (80% dumps speedup) # 2001-10-02 fl More dumps microtuning # 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum) # 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow # 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems) # 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix) # 2002-03-17 fl Avoid buffered read when possible (from James Rucker) # 2002-04-07 fl Added pythondoc comments # 2002-04-16 fl Added __str__ methods to datetime/binary wrappers # 2002-05-15 fl Added error constants (from Andrew Kuchling) # 2002-06-27 fl Merged with Python CVS version # 2002-10-22 fl Added basic authentication (based on code from Phillip Eby) # 2003-01-22 sm Add support for the bool type # 2003-02-27 gvr Remove apply calls # 2003-04-24 sm Use cStringIO if available # 2003-04-25 ak Add support for nil # 2003-06-15 gn Add support for time.struct_time # 2003-07-12 gp Correct marshalling of Faults # 2003-10-31 mvl Add multicall support # 2004-08-20 mvl Bump minimum supported Python version to 2.1 # 2014-12-02 ch/doko Add workaround for gzip bomb vulnerability # # Copyright (c) 1999-2002 by Secret Labs AB. # Copyright (c) 1999-2002 by Fredrik Lundh. # # [email protected] # http://www.pythonware.com # # -------------------------------------------------------------------- # The XML-RPC client interface is # # Copyright (c) 1999-2002 by Secret Labs AB # Copyright (c) 1999-2002 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- """ An XML-RPC client interface for Python. The marshalling and response parser code can also be used to implement XML-RPC servers. Exported exceptions: Error Base class for client errors ProtocolError Indicates an HTTP protocol error ResponseError Indicates a broken response package Fault Indicates an XML-RPC fault package Exported classes: ServerProxy Represents a logical connection to an XML-RPC server MultiCall Executor of boxcared xmlrpc requests DateTime dateTime wrapper for an ISO 8601 string or time tuple or localtime integer value to generate a "dateTime.iso8601" XML-RPC value Binary binary data wrapper Marshaller Generate an XML-RPC params chunk from a Python data structure Unmarshaller Unmarshal an XML-RPC response from incoming XML event message Transport Handles an HTTP transaction to an XML-RPC server SafeTransport Handles an HTTPS transaction to an XML-RPC server Exported constants: (none) Exported functions: getparser Create instance of the fastest available parser & attach to an unmarshalling object dumps Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). loads Convert an XML-RPC packet to unmarshalled data plus a method name (None if not present). """ import base64 import sys import time from datetime import datetime from decimal import Decimal import http.client import urllib.parse from xml.parsers import expat import errno from io import BytesIO try: import gzip except ImportError: gzip = None #python can be built without zlib/gzip support # -------------------------------------------------------------------- # Internal stuff def escape(s): s = s.replace("&", "&amp;") s = s.replace("<", "&lt;") return s.replace(">", "&gt;",) # used in User-Agent header sent __version__ = '%d.%d' % sys.version_info[:2] # xmlrpc integer limits MAXINT = 2**31-1 MININT = -2**31 # -------------------------------------------------------------------- # Error constants (from Dan Libby's specification at # http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php) # Ranges of errors PARSE_ERROR = -32700 SERVER_ERROR = -32600 APPLICATION_ERROR = -32500 SYSTEM_ERROR = -32400 TRANSPORT_ERROR = -32300 # Specific errors NOT_WELLFORMED_ERROR = -32700 UNSUPPORTED_ENCODING = -32701 INVALID_ENCODING_CHAR = -32702 INVALID_XMLRPC = -32600 METHOD_NOT_FOUND = -32601 INVALID_METHOD_PARAMS = -32602 INTERNAL_ERROR = -32603 # -------------------------------------------------------------------- # Exceptions ## # Base class for all kinds of client-side errors. class Error(Exception): """Base class for client errors.""" def __str__(self): return repr(self) ## # Indicates an HTTP-level protocol error. This is raised by the HTTP # transport layer, if the server returns an error code other than 200 # (OK). # # @param url The target URL. # @param errcode The HTTP error code. # @param errmsg The HTTP error message. # @param headers The HTTP header dictionary. class ProtocolError(Error): """Indicates an HTTP protocol error.""" def __init__(self, url, errcode, errmsg, headers): Error.__init__(self) self.url = url self.errcode = errcode self.errmsg = errmsg self.headers = headers def __repr__(self): return ( "<%s for %s: %s %s>" % (self.__class__.__name__, self.url, self.errcode, self.errmsg) ) ## # Indicates a broken XML-RPC response package. This exception is # raised by the unmarshalling layer, if the XML-RPC response is # malformed. class ResponseError(Error): """Indicates a broken response package.""" pass ## # Indicates an XML-RPC fault response package. This exception is # raised by the unmarshalling layer, if the XML-RPC response contains # a fault string. This exception can also be used as a class, to # generate a fault XML-RPC message. # # @param faultCode The XML-RPC fault code. # @param faultString The XML-RPC fault string. class Fault(Error): """Indicates an XML-RPC fault package.""" def __init__(self, faultCode, faultString, **extra): Error.__init__(self) self.faultCode = faultCode self.faultString = faultString def __repr__(self): return "<%s %s: %r>" % (self.__class__.__name__, self.faultCode, self.faultString) # -------------------------------------------------------------------- # Special values ## # Backwards compatibility boolean = Boolean = bool ## # Wrapper for XML-RPC DateTime values. This converts a time value to # the format used by XML-RPC. # <p> # The value can be given as a datetime object, as a string in the # format "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by # time.localtime()), or an integer value (as returned by time.time()). # The wrapper uses time.localtime() to convert an integer to a time # tuple. # # @param value The time, given as a datetime object, an ISO 8601 string, # a time tuple, or an integer time value. # Issue #13305: different format codes across platforms _day0 = datetime(1, 1, 1) if _day0.strftime('%Y') == '0001': # Mac OS X def _iso8601_format(value): return value.strftime("%Y%m%dT%H:%M:%S") elif _day0.strftime('%4Y') == '0001': # Linux def _iso8601_format(value): return value.strftime("%4Y%m%dT%H:%M:%S") else: def _iso8601_format(value): return value.strftime("%Y%m%dT%H:%M:%S").zfill(17) del _day0 def _strftime(value): if isinstance(value, datetime): return _iso8601_format(value) if not isinstance(value, (tuple, time.struct_time)): if value == 0: value = time.time() value = time.localtime(value) return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] class DateTime: """DateTime wrapper for an ISO 8601 string or time tuple or localtime integer value to generate 'dateTime.iso8601' XML-RPC value. """ def __init__(self, value=0): if isinstance(value, str): self.value = value else: self.value = _strftime(value) def make_comparable(self, other): if isinstance(other, DateTime): s = self.value o = other.value elif isinstance(other, datetime): s = self.value o = _iso8601_format(other) elif isinstance(other, str): s = self.value o = other elif hasattr(other, "timetuple"): s = self.timetuple() o = other.timetuple() else: otype = (hasattr(other, "__class__") and other.__class__.__name__ or type(other)) raise TypeError("Can't compare %s and %s" % (self.__class__.__name__, otype)) return s, o def __lt__(self, other): s, o = self.make_comparable(other) return s < o def __le__(self, other): s, o = self.make_comparable(other) return s <= o def __gt__(self, other): s, o = self.make_comparable(other) return s > o def __ge__(self, other): s, o = self.make_comparable(other) return s >= o def __eq__(self, other): s, o = self.make_comparable(other) return s == o def timetuple(self): return time.strptime(self.value, "%Y%m%dT%H:%M:%S") ## # Get date/time value. # # @return Date/time value, as an ISO 8601 string. def __str__(self): return self.value def __repr__(self): return "<%s %r at %#x>" % (self.__class__.__name__, self.value, id(self)) def decode(self, data): self.value = str(data).strip() def encode(self, out): out.write("<value><dateTime.iso8601>") out.write(self.value) out.write("</dateTime.iso8601></value>\n") def _datetime(data): # decode xml element contents into a DateTime structure. value = DateTime() value.decode(data) return value def _datetime_type(data): return datetime.strptime(data, "%Y%m%dT%H:%M:%S") ## # Wrapper for binary data. This can be used to transport any kind # of binary data over XML-RPC, using BASE64 encoding. # # @param data An 8-bit string containing arbitrary data. class Binary: """Wrapper for binary data.""" def __init__(self, data=None): if data is None: data = b"" else: if not isinstance(data, (bytes, bytearray)): raise TypeError("expected bytes or bytearray, not %s" % data.__class__.__name__) data = bytes(data) # Make a copy of the bytes! self.data = data ## # Get buffer contents. # # @return Buffer contents, as an 8-bit string. def __str__(self): return str(self.data, "latin-1") # XXX encoding?! def __eq__(self, other): if isinstance(other, Binary): other = other.data return self.data == other def decode(self, data): self.data = base64.decodebytes(data) def encode(self, out): out.write("<value><base64>\n") encoded = base64.encodebytes(self.data) out.write(encoded.decode('ascii')) out.write("</base64></value>\n") def _binary(data): # decode xml element contents into a Binary structure value = Binary() value.decode(data) return value WRAPPERS = (DateTime, Binary) # -------------------------------------------------------------------- # XML parsers class ExpatParser: # fast expat parser for Python 2.0 and later. def __init__(self, target): self._parser = parser = expat.ParserCreate(None, None) self._target = target parser.StartElementHandler = target.start parser.EndElementHandler = target.end parser.CharacterDataHandler = target.data encoding = None target.xml(encoding, None) def feed(self, data): self._parser.Parse(data, 0) def close(self): try: parser = self._parser except AttributeError: pass else: del self._target, self._parser # get rid of circular references parser.Parse(b"", True) # end of data # -------------------------------------------------------------------- # XML-RPC marshalling and unmarshalling code ## # XML-RPC marshaller. # # @param encoding Default encoding for 8-bit strings. The default # value is None (interpreted as UTF-8). # @see dumps class Marshaller: """Generate an XML-RPC params chunk from a Python data structure. Create a Marshaller instance for each set of parameters, and use the "dumps" method to convert your data (represented as a tuple) to an XML-RPC params chunk. To write a fault response, pass a Fault instance instead. You may prefer to use the "dumps" module function for this purpose. """ # by the way, if you don't understand what's going on in here, # that's perfectly ok. def __init__(self, encoding=None, allow_none=False): self.memo = {} self.data = None self.encoding = encoding self.allow_none = allow_none dispatch = {} def dumps(self, values): out = [] write = out.append dump = self.__dump if isinstance(values, Fault): # fault instance write("<fault>\n") dump({'faultCode': values.faultCode, 'faultString': values.faultString}, write) write("</fault>\n") else: # parameter block # FIXME: the xml-rpc specification allows us to leave out # the entire <params> block if there are no parameters. # however, changing this may break older code (including # old versions of xmlrpclib.py), so this is better left as # is for now. See @XMLRPC3 for more information. /F write("<params>\n") for v in values: write("<param>\n") dump(v, write) write("</param>\n") write("</params>\n") result = "".join(out) return result def __dump(self, value, write): try: f = self.dispatch[type(value)] except KeyError: # check if this object can be marshalled as a structure if not hasattr(value, '__dict__'): raise TypeError("cannot marshal %s objects" % type(value)) # check if this class is a sub-class of a basic type, # because we don't know how to marshal these types # (e.g. a string sub-class) for type_ in type(value).__mro__: if type_ in self.dispatch.keys(): raise TypeError("cannot marshal %s objects" % type(value)) # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix # for the p3yk merge, this should probably be fixed more neatly. f = self.dispatch["_arbitrary_instance"] f(self, value, write) def dump_nil (self, value, write): if not self.allow_none: raise TypeError("cannot marshal None unless allow_none is enabled") write("<value><nil/></value>") dispatch[type(None)] = dump_nil def dump_bool(self, value, write): write("<value><boolean>") write(value and "1" or "0") write("</boolean></value>\n") dispatch[bool] = dump_bool def dump_long(self, value, write): if value > MAXINT or value < MININT: raise OverflowError("int exceeds XML-RPC limits") write("<value><int>") write(str(int(value))) write("</int></value>\n") dispatch[int] = dump_long # backward compatible dump_int = dump_long def dump_double(self, value, write): write("<value><double>") write(repr(value)) write("</double></value>\n") dispatch[float] = dump_double def dump_unicode(self, value, write, escape=escape): write("<value><string>") write(escape(value)) write("</string></value>\n") dispatch[str] = dump_unicode def dump_bytes(self, value, write): write("<value><base64>\n") encoded = base64.encodebytes(value) write(encoded.decode('ascii')) write("</base64></value>\n") dispatch[bytes] = dump_bytes dispatch[bytearray] = dump_bytes def dump_array(self, value, write): i = id(value) if i in self.memo: raise TypeError("cannot marshal recursive sequences") self.memo[i] = None dump = self.__dump write("<value><array><data>\n") for v in value: dump(v, write) write("</data></array></value>\n") del self.memo[i] dispatch[tuple] = dump_array dispatch[list] = dump_array def dump_struct(self, value, write, escape=escape): i = id(value) if i in self.memo: raise TypeError("cannot marshal recursive dictionaries") self.memo[i] = None dump = self.__dump write("<value><struct>\n") for k, v in value.items(): write("<member>\n") if not isinstance(k, str): raise TypeError("dictionary key must be string") write("<name>%s</name>\n" % escape(k)) dump(v, write) write("</member>\n") write("</struct></value>\n") del self.memo[i] dispatch[dict] = dump_struct def dump_datetime(self, value, write): write("<value><dateTime.iso8601>") write(_strftime(value)) write("</dateTime.iso8601></value>\n") dispatch[datetime] = dump_datetime def dump_instance(self, value, write): # check for special wrappers if value.__class__ in WRAPPERS: self.write = write value.encode(self) del self.write else: # store instance attributes as a struct (really?) self.dump_struct(value.__dict__, write) dispatch[DateTime] = dump_instance dispatch[Binary] = dump_instance # XXX(twouters): using "_arbitrary_instance" as key as a quick-fix # for the p3yk merge, this should probably be fixed more neatly. dispatch["_arbitrary_instance"] = dump_instance ## # XML-RPC unmarshaller. # # @see loads class Unmarshaller: """Unmarshal an XML-RPC response, based on incoming XML event messages (start, data, end). Call close() to get the resulting data structure. Note that this reader is fairly tolerant, and gladly accepts bogus XML-RPC data without complaining (but not bogus XML). """ # and again, if you don't understand what's going on in here, # that's perfectly ok. def __init__(self, use_datetime=False, use_builtin_types=False): self._type = None self._stack = [] self._marks = [] self._data = [] self._value = False self._methodname = None self._encoding = "utf-8" self.append = self._stack.append self._use_datetime = use_builtin_types or use_datetime self._use_bytes = use_builtin_types def close(self): # return response tuple and target method if self._type is None or self._marks: raise ResponseError() if self._type == "fault": raise Fault(**self._stack[0]) return tuple(self._stack) def getmethodname(self): return self._methodname # # event handlers def xml(self, encoding, standalone): self._encoding = encoding # FIXME: assert standalone == 1 ??? def start(self, tag, attrs): # prepare to handle this element if ':' in tag: tag = tag.split(':')[-1] if tag == "array" or tag == "struct": self._marks.append(len(self._stack)) self._data = [] if self._value and tag not in self.dispatch: raise ResponseError("unknown tag %r" % tag) self._value = (tag == "value") def data(self, text): self._data.append(text) def end(self, tag): # call the appropriate end tag handler try: f = self.dispatch[tag] except KeyError: if ':' not in tag: return # unknown tag ? try: f = self.dispatch[tag.split(':')[-1]] except KeyError: return # unknown tag ? return f(self, "".join(self._data)) # # accelerator support def end_dispatch(self, tag, data): # dispatch data try: f = self.dispatch[tag] except KeyError: if ':' not in tag: return # unknown tag ? try: f = self.dispatch[tag.split(':')[-1]] except KeyError: return # unknown tag ? return f(self, data) # # element decoders dispatch = {} def end_nil (self, data): self.append(None) self._value = 0 dispatch["nil"] = end_nil def end_boolean(self, data): if data == "0": self.append(False) elif data == "1": self.append(True) else: raise TypeError("bad boolean value") self._value = 0 dispatch["boolean"] = end_boolean def end_int(self, data): self.append(int(data)) self._value = 0 dispatch["i1"] = end_int dispatch["i2"] = end_int dispatch["i4"] = end_int dispatch["i8"] = end_int dispatch["int"] = end_int dispatch["biginteger"] = end_int def end_double(self, data): self.append(float(data)) self._value = 0 dispatch["double"] = end_double dispatch["float"] = end_double def end_bigdecimal(self, data): self.append(Decimal(data)) self._value = 0 dispatch["bigdecimal"] = end_bigdecimal def end_string(self, data): if self._encoding: data = data.decode(self._encoding) self.append(data) self._value = 0 dispatch["string"] = end_string dispatch["name"] = end_string # struct keys are always strings def end_array(self, data): mark = self._marks.pop() # map arrays to Python lists self._stack[mark:] = [self._stack[mark:]] self._value = 0 dispatch["array"] = end_array def end_struct(self, data): mark = self._marks.pop() # map structs to Python dictionaries dict = {} items = self._stack[mark:] for i in range(0, len(items), 2): dict[items[i]] = items[i+1] self._stack[mark:] = [dict] self._value = 0 dispatch["struct"] = end_struct def end_base64(self, data): value = Binary() value.decode(data.encode("ascii")) if self._use_bytes: value = value.data self.append(value) self._value = 0 dispatch["base64"] = end_base64 def end_dateTime(self, data): value = DateTime() value.decode(data) if self._use_datetime: value = _datetime_type(data) self.append(value) dispatch["dateTime.iso8601"] = end_dateTime def end_value(self, data): # if we stumble upon a value element with no internal # elements, treat it as a string element if self._value: self.end_string(data) dispatch["value"] = end_value def end_params(self, data): self._type = "params" dispatch["params"] = end_params def end_fault(self, data): self._type = "fault" dispatch["fault"] = end_fault def end_methodName(self, data): if self._encoding: data = data.decode(self._encoding) self._methodname = data self._type = "methodName" # no params dispatch["methodName"] = end_methodName ## Multicall support # class _MultiCallMethod: # some lesser magic to store calls made to a MultiCall object # for batch execution def __init__(self, call_list, name): self.__call_list = call_list self.__name = name def __getattr__(self, name): return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name)) def __call__(self, *args): self.__call_list.append((self.__name, args)) class MultiCallIterator: """Iterates over the results of a multicall. Exceptions are raised in response to xmlrpc faults.""" def __init__(self, results): self.results = results def __getitem__(self, i): item = self.results[i] if type(item) == type({}): raise Fault(item['faultCode'], item['faultString']) elif type(item) == type([]): return item[0] else: raise ValueError("unexpected type in multicall result") class MultiCall: """server -> an object used to boxcar method calls server should be a ServerProxy object. Methods can be added to the MultiCall using normal method call syntax e.g.: multicall = MultiCall(server_proxy) multicall.add(2,3) multicall.get_address("Guido") To execute the multicall, call the MultiCall object e.g.: add_result, address = multicall() """ def __init__(self, server): self.__server = server self.__call_list = [] def __repr__(self): return "<%s at %#x>" % (self.__class__.__name__, id(self)) __str__ = __repr__ def __getattr__(self, name): return _MultiCallMethod(self.__call_list, name) def __call__(self): marshalled_list = [] for name, args in self.__call_list: marshalled_list.append({'methodName' : name, 'params' : args}) return MultiCallIterator(self.__server.system.multicall(marshalled_list)) # -------------------------------------------------------------------- # convenience functions FastMarshaller = FastParser = FastUnmarshaller = None ## # Create a parser object, and connect it to an unmarshalling instance. # This function picks the fastest available XML parser. # # return A (parser, unmarshaller) tuple. def getparser(use_datetime=False, use_builtin_types=False): """getparser() -> parser, unmarshaller Create an instance of the fastest available parser, and attach it to an unmarshalling object. Return both objects. """ if FastParser and FastUnmarshaller: if use_builtin_types: mkdatetime = _datetime_type mkbytes = base64.decodebytes elif use_datetime: mkdatetime = _datetime_type mkbytes = _binary else: mkdatetime = _datetime mkbytes = _binary target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault) parser = FastParser(target) else: target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types) if FastParser: parser = FastParser(target) else: parser = ExpatParser(target) return parser, target ## # Convert a Python tuple or a Fault instance to an XML-RPC packet. # # @def dumps(params, **options) # @param params A tuple or Fault instance. # @keyparam methodname If given, create a methodCall request for # this method name. # @keyparam methodresponse If given, create a methodResponse packet. # If used with a tuple, the tuple must be a singleton (that is, # it must contain exactly one element). # @keyparam encoding The packet encoding. # @return A string containing marshalled data. def dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All byte strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, where necessary. """ assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, tuple): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" if FastMarshaller: m = FastMarshaller(encoding) else: m = Marshaller(encoding, allow_none) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return "".join(data) ## # Convert an XML-RPC packet to a Python object. If the XML-RPC packet # represents a fault condition, this function raises a Fault exception. # # @param data An XML-RPC packet, given as an 8-bit string. # @return A tuple containing the unpacked data, and the method name # (None if not present). # @see Fault def loads(data, use_datetime=False, use_builtin_types=False): """data -> unmarshalled data, method name Convert an XML-RPC packet to unmarshalled data plus a method name (None if not present). If the XML-RPC packet represents a fault condition, this function raises a Fault exception. """ p, u = getparser(use_datetime=use_datetime, use_builtin_types=use_builtin_types) p.feed(data) p.close() return u.close(), u.getmethodname() ## # Encode a string using the gzip content encoding such as specified by the # Content-Encoding: gzip # in the HTTP header, as described in RFC 1952 # # @param data the unencoded data # @return the encoded data def gzip_encode(data): """data -> gzip encoded data Encode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError f = BytesIO() with gzip.GzipFile(mode="wb", fileobj=f, compresslevel=1) as gzf: gzf.write(data) return f.getvalue() ## # Decode a string using the gzip content encoding such as specified by the # Content-Encoding: gzip # in the HTTP header, as described in RFC 1952 # # @param data The encoded data # @keyparam max_decode Maximum bytes to decode (20MB default), use negative # values for unlimited decoding # @return the unencoded data # @raises ValueError if data is not correctly coded. # @raises ValueError if max gzipped payload length exceeded def gzip_decode(data, max_decode=20971520): """gzip encoded data -> unencoded data Decode data using the gzip content encoding as described in RFC 1952 """ if not gzip: raise NotImplementedError with gzip.GzipFile(mode="rb", fileobj=BytesIO(data)) as gzf: try: if max_decode < 0: # no limit decoded = gzf.read() else: decoded = gzf.read(max_decode + 1) except OSError: raise ValueError("invalid data") if max_decode >= 0 and len(decoded) > max_decode: raise ValueError("max gzipped payload length exceeded") return decoded ## # Return a decoded file-like object for the gzip encoding # as described in RFC 1952. # # @param response A stream supporting a read() method # @return a file-like object that the decoded data can be read() from class GzipDecodedResponse(gzip.GzipFile if gzip else object): """a file-like object to decode a response encoded with the gzip method, as described in RFC 1952. """ def __init__(self, response): #response doesn't support tell() and read(), required by #GzipFile if not gzip: raise NotImplementedError self.io = BytesIO(response.read()) gzip.GzipFile.__init__(self, mode="rb", fileobj=self.io) def close(self): try: gzip.GzipFile.close(self) finally: self.io.close() # -------------------------------------------------------------------- # request dispatcher class _Method: # some magic to bind an XML-RPC method to an RPC server. # supports "nested" methods (e.g. examples.getStateName) def __init__(self, send, name): self.__send = send self.__name = name def __getattr__(self, name): return _Method(self.__send, "%s.%s" % (self.__name, name)) def __call__(self, *args): return self.__send(self.__name, args) ## # Standard transport class for XML-RPC over HTTP. # <p> # You can create custom transports by subclassing this method, and # overriding selected methods. class Transport: """Handles an HTTP transaction to an XML-RPC server.""" # client identifier (may be overridden) user_agent = "Python-xmlrpc/%s" % __version__ #if true, we'll request gzip encoding accept_gzip_encoding = True # if positive, encode request using gzip if it exceeds this threshold # note that many servers will get confused, so only use it if you know # that they can decode such a request encode_threshold = None #None = don't encode def __init__(self, use_datetime=False, use_builtin_types=False): self._use_datetime = use_datetime self._use_builtin_types = use_builtin_types self._connection = (None, None) self._extra_headers = [] ## # Send a complete request, and parse the response. # Retry request if a cached connection has disconnected. # # @param host Target host. # @param handler Target PRC handler. # @param request_body XML-RPC request body. # @param verbose Debugging flag. # @return Parsed response. def request(self, host, handler, request_body, verbose=False): #retry request once if cached connection has gone cold for i in (0, 1): try: return self.single_request(host, handler, request_body, verbose) except http.client.RemoteDisconnected: if i: raise except OSError as e: if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE): raise def single_request(self, host, handler, request_body, verbose=False): # issue XML-RPC request try: http_conn = self.send_request(host, handler, request_body, verbose) resp = http_conn.getresponse() if resp.status == 200: self.verbose = verbose return self.parse_response(resp) except Fault: raise except Exception: #All unexpected errors leave connection in # a strange state, so we clear it. self.close() raise #We got an error response. #Discard any response data and raise exception if resp.getheader("content-length", ""): resp.read() raise ProtocolError( host + handler, resp.status, resp.reason, dict(resp.getheaders()) ) ## # Create parser. # # @return A 2-tuple containing a parser and an unmarshaller. def getparser(self): # get parser and unmarshaller return getparser(use_datetime=self._use_datetime, use_builtin_types=self._use_builtin_types) ## # Get authorization info from host parameter # Host may be a string, or a (host, x509-dict) tuple; if a string, # it is checked for a "user:pw@host" format, and a "Basic # Authentication" header is added if appropriate. # # @param host Host descriptor (URL or (URL, x509 info) tuple). # @return A 3-tuple containing (actual host, extra headers, # x509 info). The header and x509 fields may be None. def get_host_info(self, host): x509 = {} if isinstance(host, tuple): host, x509 = host auth, host = urllib.parse.splituser(host) if auth: auth = urllib.parse.unquote_to_bytes(auth) auth = base64.encodebytes(auth).decode("utf-8") auth = "".join(auth.split()) # get rid of whitespace extra_headers = [ ("Authorization", "Basic " + auth) ] else: extra_headers = [] return host, extra_headers, x509 ## # Connect to server. # # @param host Target host. # @return An HTTPConnection object def make_connection(self, host): #return an existing connection if possible. This allows #HTTP/1.1 keep-alive. if self._connection and host == self._connection[0]: return self._connection[1] # create a HTTP connection object from a host descriptor chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, http.client.HTTPConnection(chost) return self._connection[1] ## # Clear any cached connection object. # Used in the event of socket errors. # def close(self): host, connection = self._connection if connection: self._connection = (None, None) connection.close() ## # Send HTTP request. # # @param host Host descriptor (URL or (URL, x509 info) tuple). # @param handler Target RPC handler (a path relative to host) # @param request_body The XML-RPC request body # @param debug Enable debugging if debug is true. # @return An HTTPConnection. def send_request(self, host, handler, request_body, debug): connection = self.make_connection(host) headers = self._extra_headers[:] if debug: connection.set_debuglevel(1) if self.accept_gzip_encoding and gzip: connection.putrequest("POST", handler, skip_accept_encoding=True) headers.append(("Accept-Encoding", "gzip")) else: connection.putrequest("POST", handler) headers.append(("Content-Type", "text/xml")) headers.append(("User-Agent", self.user_agent)) self.send_headers(connection, headers) self.send_content(connection, request_body) return connection ## # Send request headers. # This function provides a useful hook for subclassing # # @param connection httpConnection. # @param headers list of key,value pairs for HTTP headers def send_headers(self, connection, headers): for key, val in headers: connection.putheader(key, val) ## # Send request body. # This function provides a useful hook for subclassing # # @param connection httpConnection. # @param request_body XML-RPC request body. def send_content(self, connection, request_body): #optionally encode the request if (self.encode_threshold is not None and self.encode_threshold < len(request_body) and gzip): connection.putheader("Content-Encoding", "gzip") request_body = gzip_encode(request_body) connection.putheader("Content-Length", str(len(request_body))) connection.endheaders(request_body) ## # Parse response. # # @param file Stream. # @return Response tuple and target method. def parse_response(self, response): # read response data from httpresponse, and parse it # Check for new http response object, otherwise it is a file object. if hasattr(response, 'getheader'): if response.getheader("Content-Encoding", "") == "gzip": stream = GzipDecodedResponse(response) else: stream = response else: stream = response p, u = self.getparser() while 1: data = stream.read(1024) if not data: break if self.verbose: print("body:", repr(data)) p.feed(data) if stream is not response: stream.close() p.close() return u.close() ## # Standard transport class for XML-RPC over HTTPS. class SafeTransport(Transport): """Handles an HTTPS transaction to an XML-RPC server.""" def __init__(self, use_datetime=False, use_builtin_types=False, *, context=None): super().__init__(use_datetime=use_datetime, use_builtin_types=use_builtin_types) self.context = context # FIXME: mostly untested def make_connection(self, host): if self._connection and host == self._connection[0]: return self._connection[1] if not hasattr(http.client, "HTTPSConnection"): raise NotImplementedError( "your version of http.client doesn't support HTTPS") # create a HTTPS connection object from a host descriptor # host may be a string, or a (host, x509-dict) tuple chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, http.client.HTTPSConnection(chost, None, context=self.context, **(x509 or {})) return self._connection[1] ## # Standard server proxy. This class establishes a virtual connection # to an XML-RPC server. # <p> # This class is available as ServerProxy and Server. New code should # use ServerProxy, to avoid confusion. # # @def ServerProxy(uri, **options) # @param uri The connection point on the server. # @keyparam transport A transport factory, compatible with the # standard transport class. # @keyparam encoding The default encoding used for 8-bit strings # (default is UTF-8). # @keyparam verbose Use a true value to enable debugging output. # (printed to standard output). # @see Transport class ServerProxy: """uri [,options] -> a logical connection to an XML-RPC server uri is the connection point on the server, given as scheme://host/target. The standard implementation always supports the "http" scheme. If SSL socket support is available (Python 2.0), it also supports "https". If the target part and the slash preceding it are both omitted, "/RPC2" is assumed. The following options can be given as keyword arguments: transport: a transport factory encoding: the request encoding (default is UTF-8) All 8-bit strings passed to the server proxy are assumed to use the given encoding. """ def __init__(self, uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, context=None): # establish a "logical" server connection # get the url type, uri = urllib.parse.splittype(uri) if type not in ("http", "https"): raise OSError("unsupported XML-RPC protocol") self.__host, self.__handler = urllib.parse.splithost(uri) if not self.__handler: self.__handler = "/RPC2" if transport is None: if type == "https": handler = SafeTransport extra_kwargs = {"context": context} else: handler = Transport extra_kwargs = {} transport = handler(use_datetime=use_datetime, use_builtin_types=use_builtin_types, **extra_kwargs) self.__transport = transport self.__encoding = encoding or 'utf-8' self.__verbose = verbose self.__allow_none = allow_none def __close(self): self.__transport.close() def __request(self, methodname, params): # call a method on the remote server request = dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none).encode(self.__encoding, 'xmlcharrefreplace') response = self.__transport.request( self.__host, self.__handler, request, verbose=self.__verbose ) if len(response) == 1: response = response[0] return response def __repr__(self): return ( "<%s for %s%s>" % (self.__class__.__name__, self.__host, self.__handler) ) __str__ = __repr__ def __getattr__(self, name): # magic method dispatcher return _Method(self.__request, name) # note: to call a remote object with a non-standard name, use # result getattr(server, "strange-python-name")(args) def __call__(self, attr): """A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__ """ if attr == "close": return self.__close elif attr == "transport": return self.__transport raise AttributeError("Attribute %r not found" % (attr,)) def __enter__(self): return self def __exit__(self, *args): self.__close() # compatibility Server = ServerProxy # -------------------------------------------------------------------- # test code if __name__ == "__main__": # simple test program (from the XML-RPC specification) # local server, available from Lib/xmlrpc/server.py server = ServerProxy("http://localhost:8000") try: print(server.currentTime.getCurrentTime()) except Error as v: print("ERROR", v) multi = MultiCall(server) multi.getData() multi.pow(2,9) multi.add(1,2) try: for response in multi(): print(response) except Error as v: print("ERROR", v)
48,988
1,519
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xmlrpc/server.py
r"""XML-RPC Servers. This module can be used to create simple XML-RPC servers by creating a server and either installing functions, a class instance, or by extending the SimpleXMLRPCServer class. It can also be used to handle XML-RPC requests in a CGI environment using CGIXMLRPCRequestHandler. The Doc* classes can be used to create XML-RPC servers that serve pydoc-style documentation in response to HTTP GET requests. This documentation is dynamically generated based on the functions and methods registered with the server. A list of possible usage patterns follows: 1. Install functions: server = SimpleXMLRPCServer(("localhost", 8000)) server.register_function(pow) server.register_function(lambda x,y: x+y, 'add') server.serve_forever() 2. Install an instance: class MyFuncs: def __init__(self): # make all of the sys functions available through sys.func_name import sys self.sys = sys def _listMethods(self): # implement this method so that system.listMethods # knows to advertise the sys methods return list_public_methods(self) + \ ['sys.' + method for method in list_public_methods(self.sys)] def pow(self, x, y): return pow(x, y) def add(self, x, y) : return x + y server = SimpleXMLRPCServer(("localhost", 8000)) server.register_introspection_functions() server.register_instance(MyFuncs()) server.serve_forever() 3. Install an instance with custom dispatch method: class Math: def _listMethods(self): # this method must be present for system.listMethods # to work return ['add', 'pow'] def _methodHelp(self, method): # this method must be present for system.methodHelp # to work if method == 'add': return "add(2,3) => 5" elif method == 'pow': return "pow(x, y[, z]) => number" else: # By convention, return empty # string if no help is available return "" def _dispatch(self, method, params): if method == 'pow': return pow(*params) elif method == 'add': return params[0] + params[1] else: raise ValueError('bad method') server = SimpleXMLRPCServer(("localhost", 8000)) server.register_introspection_functions() server.register_instance(Math()) server.serve_forever() 4. Subclass SimpleXMLRPCServer: class MathServer(SimpleXMLRPCServer): def _dispatch(self, method, params): try: # We are forcing the 'export_' prefix on methods that are # callable through XML-RPC to prevent potential security # problems func = getattr(self, 'export_' + method) except AttributeError: raise Exception('method "%s" is not supported' % method) else: return func(*params) def export_add(self, x, y): return x + y server = MathServer(("localhost", 8000)) server.serve_forever() 5. CGI script: server = CGIXMLRPCRequestHandler() server.register_function(pow) server.handle_request() """ # Written by Brian Quinlan ([email protected]). # Based on code written by Fredrik Lundh. from xmlrpc.client import Fault, dumps, loads, gzip_encode, gzip_decode from http.server import BaseHTTPRequestHandler import html import http.server import socketserver import sys import os import re import pydoc import inspect import traceback try: import fcntl except ImportError: fcntl = None def resolve_dotted_attribute(obj, attr, allow_dotted_names=True): """resolve_dotted_attribute(a, 'b.c.d') => a.b.c.d Resolves a dotted attribute name to an object. Raises an AttributeError if any attribute in the chain starts with a '_'. If the optional allow_dotted_names argument is false, dots are not supported and this function operates similar to getattr(obj, attr). """ if allow_dotted_names: attrs = attr.split('.') else: attrs = [attr] for i in attrs: if i.startswith('_'): raise AttributeError( 'attempt to access private attribute "%s"' % i ) else: obj = getattr(obj,i) return obj def list_public_methods(obj): """Returns a list of attribute strings, found in the specified object, which represent callable attributes""" return [member for member in dir(obj) if not member.startswith('_') and callable(getattr(obj, member))] class SimpleXMLRPCDispatcher: """Mix-in class that dispatches XML-RPC requests. This class is used to register XML-RPC method handlers and then to dispatch them. This class doesn't need to be instanced directly when used by SimpleXMLRPCServer but it can be instanced when used by the MultiPathXMLRPCServer """ def __init__(self, allow_none=False, encoding=None, use_builtin_types=False): self.funcs = {} self.instance = None self.allow_none = allow_none self.encoding = encoding or 'utf-8' self.use_builtin_types = use_builtin_types def register_instance(self, instance, allow_dotted_names=False): """Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called by SimpleXMLRPCServer. If a registered function matches an XML-RPC request, then it will be called instead of the registered instance. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch method, method names containing dots are supported and resolved, as long as none of the name segments start with an '_'. *** SECURITY WARNING: *** Enabling the allow_dotted_names options allows intruders to access your module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network. """ self.instance = instance self.allow_dotted_names = allow_dotted_names def register_function(self, function, name=None): """Registers a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function. """ if name is None: name = function.__name__ self.funcs[name] = function def register_introspection_functions(self): """Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html """ self.funcs.update({'system.listMethods' : self.system_listMethods, 'system.methodSignature' : self.system_methodSignature, 'system.methodHelp' : self.system_methodHelp}) def register_multicall_functions(self): """Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208""" self.funcs.update({'system.multicall' : self.system_multicall}) def _marshaled_dispatch(self, data, dispatch_method = None, path = None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the preferred means of changing method dispatch behavior. """ try: params, method = loads(data, use_builtin_types=self.use_builtin_types) # generate response if dispatch_method is not None: response = dispatch_method(method, params) else: response = self._dispatch(method, params) # wrap response in a singleton tuple response = (response,) response = dumps(response, methodresponse=1, allow_none=self.allow_none, encoding=self.encoding) except Fault as fault: response = dumps(fault, allow_none=self.allow_none, encoding=self.encoding) except: # report exception back to server exc_type, exc_value, exc_tb = sys.exc_info() try: response = dumps( Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none, ) finally: # Break reference cycle exc_type = exc_value = exc_tb = None return response.encode(self.encoding, 'xmlcharrefreplace') def system_listMethods(self): """system.listMethods() => ['add', 'subtract', 'multiple'] Returns a list of the methods supported by the server.""" methods = set(self.funcs.keys()) if self.instance is not None: # Instance can implement _listMethod to return a list of # methods if hasattr(self.instance, '_listMethods'): methods |= set(self.instance._listMethods()) # if the instance has a _dispatch method then we # don't have enough information to provide a list # of methods elif not hasattr(self.instance, '_dispatch'): methods |= set(list_public_methods(self.instance)) return sorted(methods) def system_methodSignature(self, method_name): """system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.""" # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html return 'signatures not supported' def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.""" method = None if method_name in self.funcs: method = self.funcs[method_name] elif self.instance is not None: # Instance can implement _methodHelp to return help for a method if hasattr(self.instance, '_methodHelp'): return self.instance._methodHelp(method_name) # if the instance has a _dispatch method then we # don't have enough information to provide help elif not hasattr(self.instance, '_dispatch'): try: method = resolve_dotted_attribute( self.instance, method_name, self.allow_dotted_names ) except AttributeError: pass # Note that we aren't checking that the method actually # be a callable object of some kind if method is None: return "" else: return pydoc.getdoc(method) def system_multicall(self, call_list): """system.multicall([{'methodName': 'add', 'params': [2, 2]}, ...]) => \ [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. See http://www.xmlrpc.com/discuss/msgReader$1208 """ results = [] for call in call_list: method_name = call['methodName'] params = call['params'] try: # XXX A marshalling error in any response will fail the entire # multicall. If someone cares they should fix this. results.append([self._dispatch(method_name, params)]) except Fault as fault: results.append( {'faultCode' : fault.faultCode, 'faultString' : fault.faultString} ) except: exc_type, exc_value, exc_tb = sys.exc_info() try: results.append( {'faultCode' : 1, 'faultString' : "%s:%s" % (exc_type, exc_value)} ) finally: # Break reference cycle exc_type = exc_value = exc_tb = None return results def _dispatch(self, method, params): """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch('add',(2,3)) If the registered instance does not have a _dispatch method then the instance will be searched to find a matching method and, if found, will be called. Methods beginning with an '_' are considered private and will not be called. """ try: # call the matching registered function func = self.funcs[method] except KeyError: pass else: if func is not None: return func(*params) raise Exception('method "%s" is not supported' % method) if self.instance is not None: if hasattr(self.instance, '_dispatch'): # call the `_dispatch` method on the instance return self.instance._dispatch(method, params) # call the instance's method directly try: func = resolve_dotted_attribute( self.instance, method, self.allow_dotted_names ) except AttributeError: pass else: if func is not None: return func(*params) raise Exception('method "%s" is not supported' % method) class SimpleXMLRPCRequestHandler(BaseHTTPRequestHandler): """Simple XML-RPC request handler class. Handles all HTTP POST requests and attempts to decode them as XML-RPC requests. """ # Class attribute listing the accessible path components; # paths not on this list will result in a 404 error. rpc_paths = ('/', '/RPC2') #if not None, encode responses larger than this, if possible encode_threshold = 1400 #a common MTU #Override form StreamRequestHandler: full buffering of output #and no Nagle. wbufsize = -1 disable_nagle_algorithm = True # a re to match a gzip Accept-Encoding aepattern = re.compile(r""" \s* ([^\s;]+) \s* #content-coding (;\s* q \s*=\s* ([0-9\.]+))? #q """, re.VERBOSE | re.IGNORECASE) def accept_encodings(self): r = {} ae = self.headers.get("Accept-Encoding", "") for e in ae.split(","): match = self.aepattern.match(e) if match: v = match.group(3) v = float(v) if v else 1.0 r[match.group(1)] = v return r def is_rpc_path_valid(self): if self.rpc_paths: return self.path in self.rpc_paths else: # If .rpc_paths is empty, just assume all paths are legal return True def do_POST(self): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. """ # Check that the path is legal if not self.is_rpc_path_valid(): self.report_404() return try: # Get arguments by reading body of request. # We read this in chunks to avoid straining # socket.read(); around the 10 or 15Mb mark, some platforms # begin to have problems (bug #792570). max_chunk_size = 10*1024*1024 size_remaining = int(self.headers["content-length"]) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = self.rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]) data = b''.join(L) data = self.decode_request_content(data) if data is None: return #response has been sent # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and dispatch # using that method if present. response = self.server._marshaled_dispatch( data, getattr(self, '_dispatch', None), self.path ) except Exception as e: # This should only happen if the module is buggy # internal error, report as HTTP server error self.send_response(500) # Send information about the exception if requested if hasattr(self.server, '_send_traceback_header') and \ self.server._send_traceback_header: self.send_header("X-exception", str(e)) trace = traceback.format_exc() trace = str(trace.encode('ASCII', 'backslashreplace'), 'ASCII') self.send_header("X-traceback", trace) self.send_header("Content-length", "0") self.end_headers() else: self.send_response(200) self.send_header("Content-type", "text/xml") if self.encode_threshold is not None: if len(response) > self.encode_threshold: q = self.accept_encodings().get("gzip", 0) if q: try: response = gzip_encode(response) self.send_header("Content-Encoding", "gzip") except NotImplementedError: pass self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response) def decode_request_content(self, data): #support gzip encoding of request encoding = self.headers.get("content-encoding", "identity").lower() if encoding == "identity": return data if encoding == "gzip": try: return gzip_decode(data) except NotImplementedError: self.send_response(501, "encoding %r not supported" % encoding) except ValueError: self.send_response(400, "error decoding gzip content") else: self.send_response(501, "encoding %r not supported" % encoding) self.send_header("Content-length", "0") self.end_headers() def report_404 (self): # Report a 404 error self.send_response(404) response = b'No such page' self.send_header("Content-type", "text/plain") self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response) def log_request(self, code='-', size='-'): """Selectively log an accepted request.""" if self.server.logRequests: BaseHTTPRequestHandler.log_request(self, code, size) class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): """Simple XML-RPC server. Simple XML-RPC server that allows functions and a single instance to be installed to handle requests. The default implementation attempts to dispatch XML-RPC calls to the functions or instance installed in the server. Override the _dispatch method inherited from SimpleXMLRPCDispatcher to change this behavior. """ allow_reuse_address = True # Warning: this is for debugging purposes only! Never set this to True in # production code, as will be sending out sensitive information (exception # and stack trace details) when exceptions are raised inside # SimpleXMLRPCRequestHandler.do_POST _send_traceback_header = False def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False): self.logRequests = logRequests SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types) socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) class MultiPathXMLRPCServer(SimpleXMLRPCServer): """Multipath XML-RPC Server This specialization of SimpleXMLRPCServer allows the user to create multiple Dispatcher instances and assign them to different HTTP request paths. This makes it possible to run two or more 'virtual XML-RPC servers' at the same port. Make sure that the requestHandler accepts the paths in question. """ def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False): SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, allow_none, encoding, bind_and_activate, use_builtin_types) self.dispatchers = {} self.allow_none = allow_none self.encoding = encoding or 'utf-8' def add_dispatcher(self, path, dispatcher): self.dispatchers[path] = dispatcher return dispatcher def get_dispatcher(self, path): return self.dispatchers[path] def _marshaled_dispatch(self, data, dispatch_method = None, path = None): try: response = self.dispatchers[path]._marshaled_dispatch( data, dispatch_method, path) except: # report low level exception back to server # (each dispatcher should have handled their own # exceptions) exc_type, exc_value = sys.exc_info()[:2] try: response = dumps( Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.encoding, allow_none=self.allow_none) response = response.encode(self.encoding, 'xmlcharrefreplace') finally: # Break reference cycle exc_type = exc_value = None return response class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): """Simple handler for XML-RPC data passed through CGI.""" def __init__(self, allow_none=False, encoding=None, use_builtin_types=False): SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types) def handle_xmlrpc(self, request_text): """Handle a single XML-RPC request""" response = self._marshaled_dispatch(request_text) print('Content-Type: text/xml') print('Content-Length: %d' % len(response)) print() sys.stdout.flush() sys.stdout.buffer.write(response) sys.stdout.buffer.flush() def handle_get(self): """Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method. """ code = 400 message, explain = BaseHTTPRequestHandler.responses[code] response = http.server.DEFAULT_ERROR_MESSAGE % \ { 'code' : code, 'message' : message, 'explain' : explain } response = response.encode('utf-8') print('Status: %d %s' % (code, message)) print('Content-Type: %s' % http.server.DEFAULT_ERROR_CONTENT_TYPE) print('Content-Length: %d' % len(response)) print() sys.stdout.flush() sys.stdout.buffer.write(response) sys.stdout.buffer.flush() def handle_request(self, request_text=None): """Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers. """ if request_text is None and \ os.environ.get('REQUEST_METHOD', None) == 'GET': self.handle_get() else: # POST data is normally available through stdin try: length = int(os.environ.get('CONTENT_LENGTH', None)) except (ValueError, TypeError): length = -1 if request_text is None: request_text = sys.stdin.read(length) self.handle_xmlrpc(request_text) # ----------------------------------------------------------------------------- # Self documenting XML-RPC Server. class ServerHTMLDoc(pydoc.HTMLDoc): """Class used to generate pydoc HTML document for a server""" def markup(self, text, escape=None, funcs={}, classes={}, methods={}): """Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.""" escape = escape or self.escape results = [] here = 0 # XXX Note that this regular expression does not allow for the # hyperlinking of arbitrary strings being used as method # names. Only methods with names consisting of word characters # and '.'s are hyperlinked. pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|' r'RFC[- ]?(\d+)|' r'PEP[- ]?(\d+)|' r'(self\.)?((?:\w|\.)+))\b') while 1: match = pattern.search(text, here) if not match: break start, end = match.span() results.append(escape(text[here:start])) all, scheme, rfc, pep, selfdot, name = match.groups() if scheme: url = escape(all).replace('"', '&quot;') results.append('<a href="%s">%s</a>' % (url, url)) elif rfc: url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif pep: url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep) results.append('<a href="%s">%s</a>' % (url, escape(all))) elif text[end:end+1] == '(': results.append(self.namelink(name, methods, funcs, classes)) elif selfdot: results.append('self.<strong>%s</strong>' % name) else: results.append(self.namelink(name, classes)) here = end results.append(escape(text[here:])) return ''.join(results) def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None): """Produce HTML documentation for a function or method object.""" anchor = (cl and cl.__name__ or '') + '-' + name note = '' title = '<a name="%s"><strong>%s</strong></a>' % ( self.escape(anchor), self.escape(name)) if inspect.ismethod(object): args = inspect.getfullargspec(object) # exclude the argument bound to the instance, it will be # confusing to the non-Python user argspec = inspect.formatargspec ( args.args[1:], args.varargs, args.varkw, args.defaults, annotations=args.annotations, formatvalue=self.formatvalue ) elif inspect.isfunction(object): args = inspect.getfullargspec(object) argspec = inspect.formatargspec( args.args, args.varargs, args.varkw, args.defaults, annotations=args.annotations, formatvalue=self.formatvalue) else: argspec = '(...)' if isinstance(object, tuple): argspec = object[0] or argspec docstring = object[1] or "" else: docstring = pydoc.getdoc(object) decl = title + argspec + (note and self.grey( '<font face="helvetica, arial">%s</font>' % note)) doc = self.markup( docstring, self.preformat, funcs, classes, methods) doc = doc and '<dd><tt>%s</tt></dd>' % doc return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc) def docserver(self, server_name, package_documentation, methods): """Produce HTML documentation for an XML-RPC server.""" fdict = {} for key, value in methods.items(): fdict[key] = '#-' + key fdict[value] = fdict[key] server_name = self.escape(server_name) head = '<big><big><strong>%s</strong></big></big>' % server_name result = self.heading(head, '#ffffff', '#7799ee') doc = self.markup(package_documentation, self.preformat, fdict) doc = doc and '<tt>%s</tt>' % doc result = result + '<p>%s</p>\n' % doc contents = [] method_items = sorted(methods.items()) for key, value in method_items: contents.append(self.docroutine(value, key, funcs=fdict)) result = result + self.bigsection( 'Methods', '#ffffff', '#eeaa77', ''.join(contents)) return result class XMLRPCDocGenerator: """Generates documentation for an XML-RPC server. This class is designed as mix-in and should not be constructed directly. """ def __init__(self): # setup variables used for HTML documentation self.server_name = 'XML-RPC Server Documentation' self.server_documentation = \ "This server exports the following methods through the XML-RPC "\ "protocol." self.server_title = 'XML-RPC Server Documentation' def set_server_title(self, server_title): """Set the HTML title of the generated server documentation""" self.server_title = server_title def set_server_name(self, server_name): """Set the name of the generated HTML server documentation""" self.server_name = server_name def set_server_documentation(self, server_documentation): """Set the documentation string for the entire server.""" self.server_documentation = server_documentation def generate_html_documentation(self): """generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring(method_name) method to provide the argument string used in the documentation and the _methodHelp(method_name) method to provide the help text used in the documentation.""" methods = {} for method_name in self.system_listMethods(): if method_name in self.funcs: method = self.funcs[method_name] elif self.instance is not None: method_info = [None, None] # argspec, documentation if hasattr(self.instance, '_get_method_argstring'): method_info[0] = self.instance._get_method_argstring(method_name) if hasattr(self.instance, '_methodHelp'): method_info[1] = self.instance._methodHelp(method_name) method_info = tuple(method_info) if method_info != (None, None): method = method_info elif not hasattr(self.instance, '_dispatch'): try: method = resolve_dotted_attribute( self.instance, method_name ) except AttributeError: method = method_info else: method = method_info else: assert 0, "Could not find method in self.functions and no "\ "instance installed" methods[method_name] = method documenter = ServerHTMLDoc() documentation = documenter.docserver( self.server_name, self.server_documentation, methods ) return documenter.page(html.escape(self.server_title), documentation) class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): """XML-RPC and documentation request handler class. Handles all HTTP POST requests and attempts to decode them as XML-RPC requests. Handles all HTTP GET requests and interprets them as requests for documentation. """ def do_GET(self): """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ # Check that the path is legal if not self.is_rpc_path_valid(): self.report_404() return response = self.server.generate_html_documentation().encode('utf-8') self.send_response(200) self.send_header("Content-type", "text/html") self.send_header("Content-length", str(len(response))) self.end_headers() self.wfile.write(response) class DocXMLRPCServer( SimpleXMLRPCServer, XMLRPCDocGenerator): """XML-RPC and HTML documentation server. Adds the ability to serve server documentation to the capabilities of SimpleXMLRPCServer. """ def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False): SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, allow_none, encoding, bind_and_activate, use_builtin_types) XMLRPCDocGenerator.__init__(self) class DocCGIXMLRPCRequestHandler( CGIXMLRPCRequestHandler, XMLRPCDocGenerator): """Handler for XML-RPC data and documentation requests passed through CGI""" def handle_get(self): """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ response = self.generate_html_documentation().encode('utf-8') print('Content-Type: text/html') print('Content-Length: %d' % len(response)) print() sys.stdout.flush() sys.stdout.buffer.write(response) sys.stdout.buffer.flush() def __init__(self): CGIXMLRPCRequestHandler.__init__(self) XMLRPCDocGenerator.__init__(self) if __name__ == '__main__': import datetime class ExampleService: def getData(self): return '42' class currentTime: @staticmethod def getCurrentTime(): return datetime.datetime.now() with SimpleXMLRPCServer(("localhost", 8000)) as server: server.register_function(pow) server.register_function(lambda x,y: x+y, 'add') server.register_instance(ExampleService(), allow_dotted_names=True) server.register_multicall_functions() print('Serving XML-RPC on localhost port 8000') print('It is advisable to run this example server within a secure, closed network.') try: server.serve_forever() except KeyboardInterrupt: print("\nKeyboard interrupt received, exiting.") sys.exit(0)
37,195
1,004
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/xmlrpc/__init__.py
# This directory is a Python package.
38
2
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/curses/ascii.py
"""Constants and membership tests for ASCII characters""" NUL = 0x00 # ^@ SOH = 0x01 # ^A STX = 0x02 # ^B ETX = 0x03 # ^C EOT = 0x04 # ^D ENQ = 0x05 # ^E ACK = 0x06 # ^F BEL = 0x07 # ^G BS = 0x08 # ^H TAB = 0x09 # ^I HT = 0x09 # ^I LF = 0x0a # ^J NL = 0x0a # ^J VT = 0x0b # ^K FF = 0x0c # ^L CR = 0x0d # ^M SO = 0x0e # ^N SI = 0x0f # ^O DLE = 0x10 # ^P DC1 = 0x11 # ^Q DC2 = 0x12 # ^R DC3 = 0x13 # ^S DC4 = 0x14 # ^T NAK = 0x15 # ^U SYN = 0x16 # ^V ETB = 0x17 # ^W CAN = 0x18 # ^X EM = 0x19 # ^Y SUB = 0x1a # ^Z ESC = 0x1b # ^[ FS = 0x1c # ^\ GS = 0x1d # ^] RS = 0x1e # ^^ US = 0x1f # ^_ SP = 0x20 # space DEL = 0x7f # delete controlnames = [ "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US", "SP" ] def _ctoi(c): if type(c) == type(""): return ord(c) else: return c def isalnum(c): return isalpha(c) or isdigit(c) def isalpha(c): return isupper(c) or islower(c) def isascii(c): return 0 <= _ctoi(c) <= 127 # ? def isblank(c): return _ctoi(c) in (9, 32) def iscntrl(c): return 0 <= _ctoi(c) <= 31 or _ctoi(c) == 127 def isdigit(c): return 48 <= _ctoi(c) <= 57 def isgraph(c): return 33 <= _ctoi(c) <= 126 def islower(c): return 97 <= _ctoi(c) <= 122 def isprint(c): return 32 <= _ctoi(c) <= 126 def ispunct(c): return isgraph(c) and not isalnum(c) def isspace(c): return _ctoi(c) in (9, 10, 11, 12, 13, 32) def isupper(c): return 65 <= _ctoi(c) <= 90 def isxdigit(c): return isdigit(c) or \ (65 <= _ctoi(c) <= 70) or (97 <= _ctoi(c) <= 102) def isctrl(c): return 0 <= _ctoi(c) < 32 def ismeta(c): return _ctoi(c) > 127 def ascii(c): if type(c) == type(""): return chr(_ctoi(c) & 0x7f) else: return _ctoi(c) & 0x7f def ctrl(c): if type(c) == type(""): return chr(_ctoi(c) & 0x1f) else: return _ctoi(c) & 0x1f def alt(c): if type(c) == type(""): return chr(_ctoi(c) | 0x80) else: return _ctoi(c) | 0x80 def unctrl(c): bits = _ctoi(c) if bits == 0x7f: rep = "^?" elif isprint(bits & 0x7f): rep = chr(bits & 0x7f) else: rep = "^" + chr(((bits & 0x7f) | 0x20) + 0x20) if bits & 0x80: return "!" + rep return rep
2,547
100
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/curses/has_key.py
# # Emulation of has_key() function for platforms that don't use ncurses # import _curses # Table mapping curses keys to the terminfo capability name _capability_names = { _curses.KEY_A1: 'ka1', _curses.KEY_A3: 'ka3', _curses.KEY_B2: 'kb2', _curses.KEY_BACKSPACE: 'kbs', _curses.KEY_BEG: 'kbeg', _curses.KEY_BTAB: 'kcbt', _curses.KEY_C1: 'kc1', _curses.KEY_C3: 'kc3', _curses.KEY_CANCEL: 'kcan', _curses.KEY_CATAB: 'ktbc', _curses.KEY_CLEAR: 'kclr', _curses.KEY_CLOSE: 'kclo', _curses.KEY_COMMAND: 'kcmd', _curses.KEY_COPY: 'kcpy', _curses.KEY_CREATE: 'kcrt', _curses.KEY_CTAB: 'kctab', _curses.KEY_DC: 'kdch1', _curses.KEY_DL: 'kdl1', _curses.KEY_DOWN: 'kcud1', _curses.KEY_EIC: 'krmir', _curses.KEY_END: 'kend', _curses.KEY_ENTER: 'kent', _curses.KEY_EOL: 'kel', _curses.KEY_EOS: 'ked', _curses.KEY_EXIT: 'kext', _curses.KEY_F0: 'kf0', _curses.KEY_F1: 'kf1', _curses.KEY_F10: 'kf10', _curses.KEY_F11: 'kf11', _curses.KEY_F12: 'kf12', _curses.KEY_F13: 'kf13', _curses.KEY_F14: 'kf14', _curses.KEY_F15: 'kf15', _curses.KEY_F16: 'kf16', _curses.KEY_F17: 'kf17', _curses.KEY_F18: 'kf18', _curses.KEY_F19: 'kf19', _curses.KEY_F2: 'kf2', _curses.KEY_F20: 'kf20', _curses.KEY_F21: 'kf21', _curses.KEY_F22: 'kf22', _curses.KEY_F23: 'kf23', _curses.KEY_F24: 'kf24', _curses.KEY_F25: 'kf25', _curses.KEY_F26: 'kf26', _curses.KEY_F27: 'kf27', _curses.KEY_F28: 'kf28', _curses.KEY_F29: 'kf29', _curses.KEY_F3: 'kf3', _curses.KEY_F30: 'kf30', _curses.KEY_F31: 'kf31', _curses.KEY_F32: 'kf32', _curses.KEY_F33: 'kf33', _curses.KEY_F34: 'kf34', _curses.KEY_F35: 'kf35', _curses.KEY_F36: 'kf36', _curses.KEY_F37: 'kf37', _curses.KEY_F38: 'kf38', _curses.KEY_F39: 'kf39', _curses.KEY_F4: 'kf4', _curses.KEY_F40: 'kf40', _curses.KEY_F41: 'kf41', _curses.KEY_F42: 'kf42', _curses.KEY_F43: 'kf43', _curses.KEY_F44: 'kf44', _curses.KEY_F45: 'kf45', _curses.KEY_F46: 'kf46', _curses.KEY_F47: 'kf47', _curses.KEY_F48: 'kf48', _curses.KEY_F49: 'kf49', _curses.KEY_F5: 'kf5', _curses.KEY_F50: 'kf50', _curses.KEY_F51: 'kf51', _curses.KEY_F52: 'kf52', _curses.KEY_F53: 'kf53', _curses.KEY_F54: 'kf54', _curses.KEY_F55: 'kf55', _curses.KEY_F56: 'kf56', _curses.KEY_F57: 'kf57', _curses.KEY_F58: 'kf58', _curses.KEY_F59: 'kf59', _curses.KEY_F6: 'kf6', _curses.KEY_F60: 'kf60', _curses.KEY_F61: 'kf61', _curses.KEY_F62: 'kf62', _curses.KEY_F63: 'kf63', _curses.KEY_F7: 'kf7', _curses.KEY_F8: 'kf8', _curses.KEY_F9: 'kf9', _curses.KEY_FIND: 'kfnd', _curses.KEY_HELP: 'khlp', _curses.KEY_HOME: 'khome', _curses.KEY_IC: 'kich1', _curses.KEY_IL: 'kil1', _curses.KEY_LEFT: 'kcub1', _curses.KEY_LL: 'kll', _curses.KEY_MARK: 'kmrk', _curses.KEY_MESSAGE: 'kmsg', _curses.KEY_MOVE: 'kmov', _curses.KEY_NEXT: 'knxt', _curses.KEY_NPAGE: 'knp', _curses.KEY_OPEN: 'kopn', _curses.KEY_OPTIONS: 'kopt', _curses.KEY_PPAGE: 'kpp', _curses.KEY_PREVIOUS: 'kprv', _curses.KEY_PRINT: 'kprt', _curses.KEY_REDO: 'krdo', _curses.KEY_REFERENCE: 'kref', _curses.KEY_REFRESH: 'krfr', _curses.KEY_REPLACE: 'krpl', _curses.KEY_RESTART: 'krst', _curses.KEY_RESUME: 'kres', _curses.KEY_RIGHT: 'kcuf1', _curses.KEY_SAVE: 'ksav', _curses.KEY_SBEG: 'kBEG', _curses.KEY_SCANCEL: 'kCAN', _curses.KEY_SCOMMAND: 'kCMD', _curses.KEY_SCOPY: 'kCPY', _curses.KEY_SCREATE: 'kCRT', _curses.KEY_SDC: 'kDC', _curses.KEY_SDL: 'kDL', _curses.KEY_SELECT: 'kslt', _curses.KEY_SEND: 'kEND', _curses.KEY_SEOL: 'kEOL', _curses.KEY_SEXIT: 'kEXT', _curses.KEY_SF: 'kind', _curses.KEY_SFIND: 'kFND', _curses.KEY_SHELP: 'kHLP', _curses.KEY_SHOME: 'kHOM', _curses.KEY_SIC: 'kIC', _curses.KEY_SLEFT: 'kLFT', _curses.KEY_SMESSAGE: 'kMSG', _curses.KEY_SMOVE: 'kMOV', _curses.KEY_SNEXT: 'kNXT', _curses.KEY_SOPTIONS: 'kOPT', _curses.KEY_SPREVIOUS: 'kPRV', _curses.KEY_SPRINT: 'kPRT', _curses.KEY_SR: 'kri', _curses.KEY_SREDO: 'kRDO', _curses.KEY_SREPLACE: 'kRPL', _curses.KEY_SRIGHT: 'kRIT', _curses.KEY_SRSUME: 'kRES', _curses.KEY_SSAVE: 'kSAV', _curses.KEY_SSUSPEND: 'kSPD', _curses.KEY_STAB: 'khts', _curses.KEY_SUNDO: 'kUND', _curses.KEY_SUSPEND: 'kspd', _curses.KEY_UNDO: 'kund', _curses.KEY_UP: 'kcuu1' } def has_key(ch): if isinstance(ch, str): ch = ord(ch) # Figure out the correct capability name for the keycode. capability_name = _capability_names.get(ch) if capability_name is None: return False #Check the current terminal description for that capability; #if present, return true, else return false. if _curses.tigetstr( capability_name ): return True else: return False if __name__ == '__main__': # Compare the output of this implementation and the ncurses has_key, # on platforms where has_key is already available try: L = [] _curses.initscr() for key in _capability_names.keys(): system = _curses.has_key(key) python = has_key(key) if system != python: L.append( 'Mismatch for key %s, system=%i, Python=%i' % (_curses.keyname( key ), system, python) ) finally: _curses.endwin() for i in L: print(i)
5,634
193
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/curses/panel.py
"""curses.panel Module for using panels with curses. """ from _curses_panel import *
87
7
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/curses/textpad.py
"""Simple textbox editing widget with Emacs-like keybindings.""" import curses import curses.ascii def rectangle(win, uly, ulx, lry, lrx): """Draw a rectangle with corners at the provided upper-left and lower-right coordinates. """ win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1) win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1) win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1) win.addch(uly, ulx, curses.ACS_ULCORNER) win.addch(uly, lrx, curses.ACS_URCORNER) win.addch(lry, lrx, curses.ACS_LRCORNER) win.addch(lry, ulx, curses.ACS_LLCORNER) class Textbox: """Editing widget using the interior of a window object. Supports the following Emacs-like key bindings: Ctrl-A Go to left edge of window. Ctrl-B Cursor left, wrapping to previous line if appropriate. Ctrl-D Delete character under cursor. Ctrl-E Go to right edge (stripspaces off) or end of line (stripspaces on). Ctrl-F Cursor right, wrapping to next line when appropriate. Ctrl-G Terminate, returning the window contents. Ctrl-H Delete character backward. Ctrl-J Terminate if the window is 1 line, otherwise insert newline. Ctrl-K If line is blank, delete it, otherwise clear to end of line. Ctrl-L Refresh screen. Ctrl-N Cursor down; move down one line. Ctrl-O Insert a blank line at cursor location. Ctrl-P Cursor up; move up one line. Move operations do nothing if the cursor is at an edge where the movement is not possible. The following synonyms are supported where possible: KEY_LEFT = Ctrl-B, KEY_RIGHT = Ctrl-F, KEY_UP = Ctrl-P, KEY_DOWN = Ctrl-N KEY_BACKSPACE = Ctrl-h """ def __init__(self, win, insert_mode=False): self.win = win self.insert_mode = insert_mode self._update_max_yx() self.stripspaces = 1 self.lastcmd = None win.keypad(1) def _update_max_yx(self): maxy, maxx = self.win.getmaxyx() self.maxy = maxy - 1 self.maxx = maxx - 1 def _end_of_line(self, y): """Go to the location of the first blank on the given line, returning the index of the last non-blank character.""" self._update_max_yx() last = self.maxx while True: if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP: last = min(self.maxx, last+1) break elif last == 0: break last = last - 1 return last def _insert_printable_char(self, ch): self._update_max_yx() (y, x) = self.win.getyx() backyx = None while y < self.maxy or x < self.maxx: if self.insert_mode: oldch = self.win.inch() # The try-catch ignores the error we trigger from some curses # versions by trying to write into the lowest-rightmost spot # in the window. try: self.win.addch(ch) except curses.error: pass if not self.insert_mode or not curses.ascii.isprint(oldch): break ch = oldch (y, x) = self.win.getyx() # Remember where to put the cursor back since we are in insert_mode if backyx is None: backyx = y, x if backyx is not None: self.win.move(*backyx) def do_command(self, ch): "Process a single editing command." self._update_max_yx() (y, x) = self.win.getyx() self.lastcmd = ch if curses.ascii.isprint(ch): if y < self.maxy or x < self.maxx: self._insert_printable_char(ch) elif ch == curses.ascii.SOH: # ^a self.win.move(y, 0) elif ch in (curses.ascii.STX,curses.KEY_LEFT, curses.ascii.BS,curses.KEY_BACKSPACE): if x > 0: self.win.move(y, x-1) elif y == 0: pass elif self.stripspaces: self.win.move(y-1, self._end_of_line(y-1)) else: self.win.move(y-1, self.maxx) if ch in (curses.ascii.BS, curses.KEY_BACKSPACE): self.win.delch() elif ch == curses.ascii.EOT: # ^d self.win.delch() elif ch == curses.ascii.ENQ: # ^e if self.stripspaces: self.win.move(y, self._end_of_line(y)) else: self.win.move(y, self.maxx) elif ch in (curses.ascii.ACK, curses.KEY_RIGHT): # ^f if x < self.maxx: self.win.move(y, x+1) elif y == self.maxy: pass else: self.win.move(y+1, 0) elif ch == curses.ascii.BEL: # ^g return 0 elif ch == curses.ascii.NL: # ^j if self.maxy == 0: return 0 elif y < self.maxy: self.win.move(y+1, 0) elif ch == curses.ascii.VT: # ^k if x == 0 and self._end_of_line(y) == 0: self.win.deleteln() else: # first undo the effect of self._end_of_line self.win.move(y, x) self.win.clrtoeol() elif ch == curses.ascii.FF: # ^l self.win.refresh() elif ch in (curses.ascii.SO, curses.KEY_DOWN): # ^n if y < self.maxy: self.win.move(y+1, x) if x > self._end_of_line(y+1): self.win.move(y+1, self._end_of_line(y+1)) elif ch == curses.ascii.SI: # ^o self.win.insertln() elif ch in (curses.ascii.DLE, curses.KEY_UP): # ^p if y > 0: self.win.move(y-1, x) if x > self._end_of_line(y-1): self.win.move(y-1, self._end_of_line(y-1)) return 1 def gather(self): "Collect and return the contents of the window." result = "" self._update_max_yx() for y in range(self.maxy+1): self.win.move(y, 0) stop = self._end_of_line(y) if stop == 0 and self.stripspaces: continue for x in range(self.maxx+1): if self.stripspaces and x > stop: break result = result + chr(curses.ascii.ascii(self.win.inch(y, x))) if self.maxy > 0: result = result + "\n" return result def edit(self, validate=None): "Edit in the widget window and collect the results." while 1: ch = self.win.getch() if validate: ch = validate(ch) if not ch: continue if not self.do_command(ch): break self.win.refresh() return self.gather() if __name__ == '__main__': def test_editbox(stdscr): ncols, nlines = 9, 4 uly, ulx = 15, 20 stdscr.addstr(uly-2, ulx, "Use Ctrl-G to end editing.") win = curses.newwin(nlines, ncols, uly, ulx) rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols) stdscr.refresh() return Textbox(win).edit() str = curses.wrapper(test_editbox) print('Contents of text box:', repr(str))
7,657
202
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/curses/__init__.py
"""curses The main package for curses support for Python. Normally used by importing the package, and perhaps a particular module inside it. import curses from curses import textpad curses.initscr() ... """ from _curses import * import os as _os import sys as _sys # Some constants, most notably the ACS_* ones, are only added to the C # _curses module's dictionary after initscr() is called. (Some # versions of SGI's curses don't define values for those constants # until initscr() has been called.) This wrapper function calls the # underlying C initscr(), and then copies the constants from the # _curses module to the curses package's dictionary. Don't do 'from # curses import *' if you'll be needing the ACS_* constants. def initscr(): import _curses, curses # we call setupterm() here because it raises an error # instead of calling exit() in error cases. setupterm(term=_os.environ.get("TERM", "unknown"), fd=_sys.__stdout__.fileno()) stdscr = _curses.initscr() for key, value in _curses.__dict__.items(): if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'): setattr(curses, key, value) return stdscr # This is a similar wrapper for start_color(), which adds the COLORS and # COLOR_PAIRS variables which are only available after start_color() is # called. def start_color(): import _curses, curses retval = _curses.start_color() if hasattr(_curses, 'COLORS'): curses.COLORS = _curses.COLORS if hasattr(_curses, 'COLOR_PAIRS'): curses.COLOR_PAIRS = _curses.COLOR_PAIRS return retval # Import Python has_key() implementation if _curses doesn't contain has_key() try: has_key except NameError: from .has_key import has_key # Wrapper for the entire curses-based application. Runs a function which # should be the rest of your curses-based application. If the application # raises an exception, wrapper() will restore the terminal to a sane state so # you can read the resulting traceback. def wrapper(func, *args, **kwds): """Wrapper function that initializes curses and calls another function, restoring normal keyboard/screen behavior on error. The callable object 'func' is then passed the main window 'stdscr' as its first argument, followed by any other arguments passed to wrapper(). """ try: # Initialize curses stdscr = initscr() # Turn off echoing of keys, and enter cbreak mode, # where no buffering is performed on keyboard input noecho() cbreak() # In keypad mode, escape sequences for special keys # (like the cursor keys) will be interpreted and # a special value like curses.KEY_LEFT will be returned stdscr.keypad(1) # Start color, too. Harmless if the terminal doesn't have # color; user can test with has_color() later on. The try/catch # works around a minor bit of over-conscientiousness in the curses # module -- the error return from C start_color() is ignorable. try: start_color() except: pass return func(stdscr, *args, **kwds) finally: # Set everything back to normal if 'stdscr' in locals(): stdscr.keypad(0) echo() nocbreak() endwin()
3,366
102
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/tix.py
# Tix.py -- Tix widget wrappers. # # For Tix, see http://tix.sourceforge.net # # - Sudhir Shenoy ([email protected]), Dec. 1995. # based on an idea of Jean-Marc Lugrin ([email protected]) # # NOTE: In order to minimize changes to Tkinter.py, some of the code here # (TixWidget.__init__) has been taken from Tkinter (Widget.__init__) # and will break if there are major changes in Tkinter. # # The Tix widgets are represented by a class hierarchy in python with proper # inheritance of base classes. # # As a result after creating a 'w = StdButtonBox', I can write # w.ok['text'] = 'Who Cares' # or w.ok['bg'] = w['bg'] # or even w.ok.invoke() # etc. # # Compare the demo tixwidgets.py to the original Tcl program and you will # appreciate the advantages. # import os import tkinter from tkinter import * from tkinter import _cnfmerge import _tkinter # If this fails your Python may not be configured for Tk # Some more constants (for consistency with Tkinter) WINDOW = 'window' TEXT = 'text' STATUS = 'status' IMMEDIATE = 'immediate' IMAGE = 'image' IMAGETEXT = 'imagetext' BALLOON = 'balloon' AUTO = 'auto' ACROSSTOP = 'acrosstop' # A few useful constants for the Grid widget ASCII = 'ascii' CELL = 'cell' COLUMN = 'column' DECREASING = 'decreasing' INCREASING = 'increasing' INTEGER = 'integer' MAIN = 'main' MAX = 'max' REAL = 'real' ROW = 'row' S_REGION = 's-region' X_REGION = 'x-region' Y_REGION = 'y-region' # Some constants used by Tkinter dooneevent() TCL_DONT_WAIT = 1 << 1 TCL_WINDOW_EVENTS = 1 << 2 TCL_FILE_EVENTS = 1 << 3 TCL_TIMER_EVENTS = 1 << 4 TCL_IDLE_EVENTS = 1 << 5 TCL_ALL_EVENTS = 0 # BEWARE - this is implemented by copying some code from the Widget class # in Tkinter (to override Widget initialization) and is therefore # liable to break. # Could probably add this to Tkinter.Misc class tixCommand: """The tix commands provide access to miscellaneous elements of Tix's internal state and the Tix application context. Most of the information manipulated by these commands pertains to the application as a whole, or to a screen or display, rather than to a particular window. This is a mixin class, assumed to be mixed to Tkinter.Tk that supports the self.tk.call method. """ def tix_addbitmapdir(self, directory): """Tix maintains a list of directories under which the tix_getimage and tix_getbitmap commands will search for image files. The standard bitmap directory is $TIX_LIBRARY/bitmaps. The addbitmapdir command adds directory into this list. By using this command, the image files of an applications can also be located using the tix_getimage or tix_getbitmap command. """ return self.tk.call('tix', 'addbitmapdir', directory) def tix_cget(self, option): """Returns the current value of the configuration option given by option. Option may be any of the options described in the CONFIGURATION OPTIONS section. """ return self.tk.call('tix', 'cget', option) def tix_configure(self, cnf=None, **kw): """Query or modify the configuration options of the Tix application context. If no option is specified, returns a dictionary all of the available options. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given option(s) to have the given value(s); in this case the command returns an empty string. Option may be any of the configuration options. """ # Copied from Tkinter.py if kw: cnf = _cnfmerge((cnf, kw)) elif cnf: cnf = _cnfmerge(cnf) if cnf is None: return self._getconfigure('tix', 'configure') if isinstance(cnf, str): return self._getconfigure1('tix', 'configure', '-'+cnf) return self.tk.call(('tix', 'configure') + self._options(cnf)) def tix_filedialog(self, dlgclass=None): """Returns the file selection dialog that may be shared among different calls from this application. This command will create a file selection dialog widget when it is called the first time. This dialog will be returned by all subsequent calls to tix_filedialog. An optional dlgclass parameter can be passed to specified what type of file selection dialog widget is desired. Possible options are tix FileSelectDialog or tixExFileSelectDialog. """ if dlgclass is not None: return self.tk.call('tix', 'filedialog', dlgclass) else: return self.tk.call('tix', 'filedialog') def tix_getbitmap(self, name): """Locates a bitmap file of the name name.xpm or name in one of the bitmap directories (see the tix_addbitmapdir command above). By using tix_getbitmap, you can avoid hard coding the pathnames of the bitmap files in your application. When successful, it returns the complete pathname of the bitmap file, prefixed with the character '@'. The returned value can be used to configure the -bitmap option of the TK and Tix widgets. """ return self.tk.call('tix', 'getbitmap', name) def tix_getimage(self, name): """Locates an image file of the name name.xpm, name.xbm or name.ppm in one of the bitmap directories (see the addbitmapdir command above). If more than one file with the same name (but different extensions) exist, then the image type is chosen according to the depth of the X display: xbm images are chosen on monochrome displays and color images are chosen on color displays. By using tix_ getimage, you can avoid hard coding the pathnames of the image files in your application. When successful, this command returns the name of the newly created image, which can be used to configure the -image option of the Tk and Tix widgets. """ return self.tk.call('tix', 'getimage', name) def tix_option_get(self, name): """Gets the options maintained by the Tix scheme mechanism. Available options include: active_bg active_fg bg bold_font dark1_bg dark1_fg dark2_bg dark2_fg disabled_fg fg fixed_font font inactive_bg inactive_fg input1_bg input2_bg italic_font light1_bg light1_fg light2_bg light2_fg menu_font output1_bg output2_bg select_bg select_fg selector """ # could use self.tk.globalgetvar('tixOption', name) return self.tk.call('tix', 'option', 'get', name) def tix_resetoptions(self, newScheme, newFontSet, newScmPrio=None): """Resets the scheme and fontset of the Tix application to newScheme and newFontSet, respectively. This affects only those widgets created after this call. Therefore, it is best to call the resetoptions command before the creation of any widgets in a Tix application. The optional parameter newScmPrio can be given to reset the priority level of the Tk options set by the Tix schemes. Because of the way Tk handles the X option database, after Tix has been has imported and inited, it is not possible to reset the color schemes and font sets using the tix config command. Instead, the tix_resetoptions command must be used. """ if newScmPrio is not None: return self.tk.call('tix', 'resetoptions', newScheme, newFontSet, newScmPrio) else: return self.tk.call('tix', 'resetoptions', newScheme, newFontSet) class Tk(tkinter.Tk, tixCommand): """Toplevel widget of Tix which represents mostly the main window of an application. It has an associated Tcl interpreter.""" def __init__(self, screenName=None, baseName=None, className='Tix'): tkinter.Tk.__init__(self, screenName, baseName, className) tixlib = os.environ.get('TIX_LIBRARY') self.tk.eval('global auto_path; lappend auto_path [file dir [info nameof]]') if tixlib is not None: self.tk.eval('global auto_path; lappend auto_path {%s}' % tixlib) self.tk.eval('global tcl_pkgPath; lappend tcl_pkgPath {%s}' % tixlib) # Load Tix - this should work dynamically or statically # If it's static, tcl/tix8.1/pkgIndex.tcl should have # 'load {} Tix' # If it's dynamic under Unix, tcl/tix8.1/pkgIndex.tcl should have # 'load libtix8.1.8.3.so Tix' self.tk.eval('package require Tix') def destroy(self): # For safety, remove the delete_window binding before destroy self.protocol("WM_DELETE_WINDOW", "") tkinter.Tk.destroy(self) # The Tix 'tixForm' geometry manager class Form: """The Tix Form geometry manager Widgets can be arranged by specifying attachments to other widgets. See Tix documentation for complete details""" def config(self, cnf={}, **kw): self.tk.call('tixForm', self._w, *self._options(cnf, kw)) form = config def __setitem__(self, key, value): Form.form(self, {key: value}) def check(self): return self.tk.call('tixForm', 'check', self._w) def forget(self): self.tk.call('tixForm', 'forget', self._w) def grid(self, xsize=0, ysize=0): if (not xsize) and (not ysize): x = self.tk.call('tixForm', 'grid', self._w) y = self.tk.splitlist(x) z = () for x in y: z = z + (self.tk.getint(x),) return z return self.tk.call('tixForm', 'grid', self._w, xsize, ysize) def info(self, option=None): if not option: return self.tk.call('tixForm', 'info', self._w) if option[0] != '-': option = '-' + option return self.tk.call('tixForm', 'info', self._w, option) def slaves(self): return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call( 'tixForm', 'slaves', self._w))] tkinter.Widget.__bases__ = tkinter.Widget.__bases__ + (Form,) class TixWidget(tkinter.Widget): """A TixWidget class is used to package all (or most) Tix widgets. Widget initialization is extended in two ways: 1) It is possible to give a list of options which must be part of the creation command (so called Tix 'static' options). These cannot be given as a 'config' command later. 2) It is possible to give the name of an existing TK widget. These are child widgets created automatically by a Tix mega-widget. The Tk call to create these widgets is therefore bypassed in TixWidget.__init__ Both options are for use by subclasses only. """ def __init__ (self, master=None, widgetName=None, static_options=None, cnf={}, kw={}): # Merge keywords and dictionary arguments if kw: cnf = _cnfmerge((cnf, kw)) else: cnf = _cnfmerge(cnf) # Move static options into extra. static_options must be # a list of keywords (or None). extra=() # 'options' is always a static option if static_options: static_options.append('options') else: static_options = ['options'] for k,v in list(cnf.items()): if k in static_options: extra = extra + ('-' + k, v) del cnf[k] self.widgetName = widgetName Widget._setup(self, master, cnf) # If widgetName is None, this is a dummy creation call where the # corresponding Tk widget has already been created by Tix if widgetName: self.tk.call(widgetName, self._w, *extra) # Non-static options - to be done via a 'config' command if cnf: Widget.config(self, cnf) # Dictionary to hold subwidget names for easier access. We can't # use the children list because the public Tix names may not be the # same as the pathname component self.subwidget_list = {} # We set up an attribute access function so that it is possible to # do w.ok['text'] = 'Hello' rather than w.subwidget('ok')['text'] = 'Hello' # when w is a StdButtonBox. # We can even do w.ok.invoke() because w.ok is subclassed from the # Button class if you go through the proper constructors def __getattr__(self, name): if name in self.subwidget_list: return self.subwidget_list[name] raise AttributeError(name) def set_silent(self, value): """Set a variable without calling its action routine""" self.tk.call('tixSetSilent', self._w, value) def subwidget(self, name): """Return the named subwidget (which must have been created by the sub-class).""" n = self._subwidget_name(name) if not n: raise TclError("Subwidget " + name + " not child of " + self._name) # Remove header of name and leading dot n = n[len(self._w)+1:] return self._nametowidget(n) def subwidgets_all(self): """Return all subwidgets.""" names = self._subwidget_names() if not names: return [] retlist = [] for name in names: name = name[len(self._w)+1:] try: retlist.append(self._nametowidget(name)) except: # some of the widgets are unknown e.g. border in LabelFrame pass return retlist def _subwidget_name(self,name): """Get a subwidget name (returns a String, not a Widget !)""" try: return self.tk.call(self._w, 'subwidget', name) except TclError: return None def _subwidget_names(self): """Return the name of all subwidgets.""" try: x = self.tk.call(self._w, 'subwidgets', '-all') return self.tk.splitlist(x) except TclError: return None def config_all(self, option, value): """Set configuration options for all subwidgets (and self).""" if option == '': return elif not isinstance(option, str): option = repr(option) if not isinstance(value, str): value = repr(value) names = self._subwidget_names() for name in names: self.tk.call(name, 'configure', '-' + option, value) # These are missing from Tkinter def image_create(self, imgtype, cnf={}, master=None, **kw): if not master: master = tkinter._default_root if not master: raise RuntimeError('Too early to create image') if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw options = () for k, v in cnf.items(): if callable(v): v = self._register(v) options = options + ('-'+k, v) return master.tk.call(('image', 'create', imgtype,) + options) def image_delete(self, imgname): try: self.tk.call('image', 'delete', imgname) except TclError: # May happen if the root was destroyed pass # Subwidgets are child widgets created automatically by mega-widgets. # In python, we have to create these subwidgets manually to mirror their # existence in Tk/Tix. class TixSubWidget(TixWidget): """Subwidget class. This is used to mirror child widgets automatically created by Tix/Tk as part of a mega-widget in Python (which is not informed of this)""" def __init__(self, master, name, destroy_physically=1, check_intermediate=1): if check_intermediate: path = master._subwidget_name(name) try: path = path[len(master._w)+1:] plist = path.split('.') except: plist = [] if not check_intermediate: # immediate descendant TixWidget.__init__(self, master, None, None, {'name' : name}) else: # Ensure that the intermediate widgets exist parent = master for i in range(len(plist) - 1): n = '.'.join(plist[:i+1]) try: w = master._nametowidget(n) parent = w except KeyError: # Create the intermediate widget parent = TixSubWidget(parent, plist[i], destroy_physically=0, check_intermediate=0) # The Tk widget name is in plist, not in name if plist: name = plist[-1] TixWidget.__init__(self, parent, None, None, {'name' : name}) self.destroy_physically = destroy_physically def destroy(self): # For some widgets e.g., a NoteBook, when we call destructors, # we must be careful not to destroy the frame widget since this # also destroys the parent NoteBook thus leading to an exception # in Tkinter when it finally calls Tcl to destroy the NoteBook for c in list(self.children.values()): c.destroy() if self._name in self.master.children: del self.master.children[self._name] if self._name in self.master.subwidget_list: del self.master.subwidget_list[self._name] if self.destroy_physically: # This is bypassed only for a few widgets self.tk.call('destroy', self._w) # Useful class to create a display style - later shared by many items. # Contributed by Steffen Kremser class DisplayStyle: """DisplayStyle - handle configuration options shared by (multiple) Display Items""" def __init__(self, itemtype, cnf={}, *, master=None, **kw): if not master: if 'refwindow' in kw: master = kw['refwindow'] elif 'refwindow' in cnf: master = cnf['refwindow'] else: master = tkinter._default_root if not master: raise RuntimeError("Too early to create display style: " "no root window") self.tk = master.tk self.stylename = self.tk.call('tixDisplayStyle', itemtype, *self._options(cnf,kw) ) def __str__(self): return self.stylename def _options(self, cnf, kw): if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw opts = () for k, v in cnf.items(): opts = opts + ('-'+k, v) return opts def delete(self): self.tk.call(self.stylename, 'delete') def __setitem__(self,key,value): self.tk.call(self.stylename, 'configure', '-%s'%key, value) def config(self, cnf={}, **kw): return self._getconfigure( self.stylename, 'configure', *self._options(cnf,kw)) def __getitem__(self,key): return self.tk.call(self.stylename, 'cget', '-%s'%key) ###################################################### ### The Tix Widget classes - in alphabetical order ### ###################################################### class Balloon(TixWidget): """Balloon help widget. Subwidget Class --------- ----- label Label message Message""" # FIXME: It should inherit -superclass tixShell def __init__(self, master=None, cnf={}, **kw): # static seem to be -installcolormap -initwait -statusbar -cursor static = ['options', 'installcolormap', 'initwait', 'statusbar', 'cursor'] TixWidget.__init__(self, master, 'tixBalloon', static, cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label', destroy_physically=0) self.subwidget_list['message'] = _dummyLabel(self, 'message', destroy_physically=0) def bind_widget(self, widget, cnf={}, **kw): """Bind balloon widget to another. One balloon widget may be bound to several widgets at the same time""" self.tk.call(self._w, 'bind', widget._w, *self._options(cnf, kw)) def unbind_widget(self, widget): self.tk.call(self._w, 'unbind', widget._w) class ButtonBox(TixWidget): """ButtonBox - A container for pushbuttons. Subwidgets are the buttons added with the add method. """ def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixButtonBox', ['orientation', 'options'], cnf, kw) def add(self, name, cnf={}, **kw): """Add a button with given name to box.""" btn = self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = _dummyButton(self, name) return btn def invoke(self, name): if name in self.subwidget_list: self.tk.call(self._w, 'invoke', name) class ComboBox(TixWidget): """ComboBox - an Entry field with a dropdown menu. The user can select a choice by either typing in the entry subwidget or selecting from the listbox subwidget. Subwidget Class --------- ----- entry Entry arrow Button slistbox ScrolledListBox tick Button cross Button : present if created with the fancy option""" # FIXME: It should inherit -superclass tixLabelWidget def __init__ (self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixComboBox', ['editable', 'dropdown', 'fancy', 'options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') self.subwidget_list['arrow'] = _dummyButton(self, 'arrow') self.subwidget_list['slistbox'] = _dummyScrolledListBox(self, 'slistbox') try: self.subwidget_list['tick'] = _dummyButton(self, 'tick') self.subwidget_list['cross'] = _dummyButton(self, 'cross') except TypeError: # unavailable when -fancy not specified pass # align def add_history(self, str): self.tk.call(self._w, 'addhistory', str) def append_history(self, str): self.tk.call(self._w, 'appendhistory', str) def insert(self, index, str): self.tk.call(self._w, 'insert', index, str) def pick(self, index): self.tk.call(self._w, 'pick', index) class Control(TixWidget): """Control - An entry field with value change arrows. The user can adjust the value by pressing the two arrow buttons or by entering the value directly into the entry. The new value will be checked against the user-defined upper and lower limits. Subwidget Class --------- ----- incr Button decr Button entry Entry label Label""" # FIXME: It should inherit -superclass tixLabelWidget def __init__ (self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixControl', ['options'], cnf, kw) self.subwidget_list['incr'] = _dummyButton(self, 'incr') self.subwidget_list['decr'] = _dummyButton(self, 'decr') self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') def decrement(self): self.tk.call(self._w, 'decr') def increment(self): self.tk.call(self._w, 'incr') def invoke(self): self.tk.call(self._w, 'invoke') def update(self): self.tk.call(self._w, 'update') class DirList(TixWidget): """DirList - displays a list view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory. Subwidget Class --------- ----- hlist HList hsb Scrollbar vsb Scrollbar""" # FIXME: It should inherit -superclass tixScrolledHList def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirList', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') def chdir(self, dir): self.tk.call(self._w, 'chdir', dir) class DirTree(TixWidget): """DirTree - Directory Listing in a hierarchical view. Displays a tree view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory. Subwidget Class --------- ----- hlist HList hsb Scrollbar vsb Scrollbar""" # FIXME: It should inherit -superclass tixScrolledHList def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirTree', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') def chdir(self, dir): self.tk.call(self._w, 'chdir', dir) class DirSelectBox(TixWidget): """DirSelectBox - Motif style file select box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly selected again. Subwidget Class --------- ----- selection ComboBox filter ComboBox dirlist ScrolledListBox filelist ScrolledListBox""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirSelectBox', ['options'], cnf, kw) self.subwidget_list['dirlist'] = _dummyDirList(self, 'dirlist') self.subwidget_list['dircbx'] = _dummyFileComboBox(self, 'dircbx') class ExFileSelectBox(TixWidget): """ExFileSelectBox - MS Windows style file select box. It provides a convenient method for the user to select files. Subwidget Class --------- ----- cancel Button ok Button hidden Checkbutton types ComboBox dir ComboBox file ComboBox dirlist ScrolledListBox filelist ScrolledListBox""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixExFileSelectBox', ['options'], cnf, kw) self.subwidget_list['cancel'] = _dummyButton(self, 'cancel') self.subwidget_list['ok'] = _dummyButton(self, 'ok') self.subwidget_list['hidden'] = _dummyCheckbutton(self, 'hidden') self.subwidget_list['types'] = _dummyComboBox(self, 'types') self.subwidget_list['dir'] = _dummyComboBox(self, 'dir') self.subwidget_list['dirlist'] = _dummyDirList(self, 'dirlist') self.subwidget_list['file'] = _dummyComboBox(self, 'file') self.subwidget_list['filelist'] = _dummyScrolledListBox(self, 'filelist') def filter(self): self.tk.call(self._w, 'filter') def invoke(self): self.tk.call(self._w, 'invoke') # Should inherit from a Dialog class class DirSelectDialog(TixWidget): """The DirSelectDialog widget presents the directories in the file system in a dialog window. The user can use this dialog window to navigate through the file system to select the desired directory. Subwidgets Class ---------- ----- dirbox DirSelectDialog""" # FIXME: It should inherit -superclass tixDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirSelectDialog', ['options'], cnf, kw) self.subwidget_list['dirbox'] = _dummyDirSelectBox(self, 'dirbox') # cancel and ok buttons are missing def popup(self): self.tk.call(self._w, 'popup') def popdown(self): self.tk.call(self._w, 'popdown') # Should inherit from a Dialog class class ExFileSelectDialog(TixWidget): """ExFileSelectDialog - MS Windows style file select dialog. It provides a convenient method for the user to select files. Subwidgets Class ---------- ----- fsbox ExFileSelectBox""" # FIXME: It should inherit -superclass tixDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixExFileSelectDialog', ['options'], cnf, kw) self.subwidget_list['fsbox'] = _dummyExFileSelectBox(self, 'fsbox') def popup(self): self.tk.call(self._w, 'popup') def popdown(self): self.tk.call(self._w, 'popdown') class FileSelectBox(TixWidget): """ExFileSelectBox - Motif style file select box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly selected again. Subwidget Class --------- ----- selection ComboBox filter ComboBox dirlist ScrolledListBox filelist ScrolledListBox""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixFileSelectBox', ['options'], cnf, kw) self.subwidget_list['dirlist'] = _dummyScrolledListBox(self, 'dirlist') self.subwidget_list['filelist'] = _dummyScrolledListBox(self, 'filelist') self.subwidget_list['filter'] = _dummyComboBox(self, 'filter') self.subwidget_list['selection'] = _dummyComboBox(self, 'selection') def apply_filter(self): # name of subwidget is same as command self.tk.call(self._w, 'filter') def invoke(self): self.tk.call(self._w, 'invoke') # Should inherit from a Dialog class class FileSelectDialog(TixWidget): """FileSelectDialog - Motif style file select dialog. Subwidgets Class ---------- ----- btns StdButtonBox fsbox FileSelectBox""" # FIXME: It should inherit -superclass tixStdDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixFileSelectDialog', ['options'], cnf, kw) self.subwidget_list['btns'] = _dummyStdButtonBox(self, 'btns') self.subwidget_list['fsbox'] = _dummyFileSelectBox(self, 'fsbox') def popup(self): self.tk.call(self._w, 'popup') def popdown(self): self.tk.call(self._w, 'popdown') class FileEntry(TixWidget): """FileEntry - Entry field with button that invokes a FileSelectDialog. The user can type in the filename manually. Alternatively, the user can press the button widget that sits next to the entry, which will bring up a file selection dialog. Subwidgets Class ---------- ----- button Button entry Entry""" # FIXME: It should inherit -superclass tixLabelWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixFileEntry', ['dialogtype', 'options'], cnf, kw) self.subwidget_list['button'] = _dummyButton(self, 'button') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') def invoke(self): self.tk.call(self._w, 'invoke') def file_dialog(self): # FIXME: return python object pass class HList(TixWidget, XView, YView): """HList - Hierarchy display widget can be used to display any data that have a hierarchical structure, for example, file system directory trees. The list entries are indented and connected by branch lines according to their places in the hierarchy. Subwidgets - None""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixHList', ['columns', 'options'], cnf, kw) def add(self, entry, cnf={}, **kw): return self.tk.call(self._w, 'add', entry, *self._options(cnf, kw)) def add_child(self, parent=None, cnf={}, **kw): if not parent: parent = '' return self.tk.call( self._w, 'addchild', parent, *self._options(cnf, kw)) def anchor_set(self, entry): self.tk.call(self._w, 'anchor', 'set', entry) def anchor_clear(self): self.tk.call(self._w, 'anchor', 'clear') def column_width(self, col=0, width=None, chars=None): if not chars: return self.tk.call(self._w, 'column', 'width', col, width) else: return self.tk.call(self._w, 'column', 'width', col, '-char', chars) def delete_all(self): self.tk.call(self._w, 'delete', 'all') def delete_entry(self, entry): self.tk.call(self._w, 'delete', 'entry', entry) def delete_offsprings(self, entry): self.tk.call(self._w, 'delete', 'offsprings', entry) def delete_siblings(self, entry): self.tk.call(self._w, 'delete', 'siblings', entry) def dragsite_set(self, index): self.tk.call(self._w, 'dragsite', 'set', index) def dragsite_clear(self): self.tk.call(self._w, 'dragsite', 'clear') def dropsite_set(self, index): self.tk.call(self._w, 'dropsite', 'set', index) def dropsite_clear(self): self.tk.call(self._w, 'dropsite', 'clear') def header_create(self, col, cnf={}, **kw): self.tk.call(self._w, 'header', 'create', col, *self._options(cnf, kw)) def header_configure(self, col, cnf={}, **kw): if cnf is None: return self._getconfigure(self._w, 'header', 'configure', col) self.tk.call(self._w, 'header', 'configure', col, *self._options(cnf, kw)) def header_cget(self, col, opt): return self.tk.call(self._w, 'header', 'cget', col, opt) def header_exists(self, col): # A workaround to Tix library bug (issue #25464). # The documented command is "exists", but only erroneous "exist" is # accepted. return self.tk.getboolean(self.tk.call(self._w, 'header', 'exist', col)) header_exist = header_exists def header_delete(self, col): self.tk.call(self._w, 'header', 'delete', col) def header_size(self, col): return self.tk.call(self._w, 'header', 'size', col) def hide_entry(self, entry): self.tk.call(self._w, 'hide', 'entry', entry) def indicator_create(self, entry, cnf={}, **kw): self.tk.call( self._w, 'indicator', 'create', entry, *self._options(cnf, kw)) def indicator_configure(self, entry, cnf={}, **kw): if cnf is None: return self._getconfigure( self._w, 'indicator', 'configure', entry) self.tk.call( self._w, 'indicator', 'configure', entry, *self._options(cnf, kw)) def indicator_cget(self, entry, opt): return self.tk.call(self._w, 'indicator', 'cget', entry, opt) def indicator_exists(self, entry): return self.tk.call (self._w, 'indicator', 'exists', entry) def indicator_delete(self, entry): self.tk.call(self._w, 'indicator', 'delete', entry) def indicator_size(self, entry): return self.tk.call(self._w, 'indicator', 'size', entry) def info_anchor(self): return self.tk.call(self._w, 'info', 'anchor') def info_bbox(self, entry): return self._getints( self.tk.call(self._w, 'info', 'bbox', entry)) or None def info_children(self, entry=None): c = self.tk.call(self._w, 'info', 'children', entry) return self.tk.splitlist(c) def info_data(self, entry): return self.tk.call(self._w, 'info', 'data', entry) def info_dragsite(self): return self.tk.call(self._w, 'info', 'dragsite') def info_dropsite(self): return self.tk.call(self._w, 'info', 'dropsite') def info_exists(self, entry): return self.tk.call(self._w, 'info', 'exists', entry) def info_hidden(self, entry): return self.tk.call(self._w, 'info', 'hidden', entry) def info_next(self, entry): return self.tk.call(self._w, 'info', 'next', entry) def info_parent(self, entry): return self.tk.call(self._w, 'info', 'parent', entry) def info_prev(self, entry): return self.tk.call(self._w, 'info', 'prev', entry) def info_selection(self): c = self.tk.call(self._w, 'info', 'selection') return self.tk.splitlist(c) def item_cget(self, entry, col, opt): return self.tk.call(self._w, 'item', 'cget', entry, col, opt) def item_configure(self, entry, col, cnf={}, **kw): if cnf is None: return self._getconfigure(self._w, 'item', 'configure', entry, col) self.tk.call(self._w, 'item', 'configure', entry, col, *self._options(cnf, kw)) def item_create(self, entry, col, cnf={}, **kw): self.tk.call( self._w, 'item', 'create', entry, col, *self._options(cnf, kw)) def item_exists(self, entry, col): return self.tk.call(self._w, 'item', 'exists', entry, col) def item_delete(self, entry, col): self.tk.call(self._w, 'item', 'delete', entry, col) def entrycget(self, entry, opt): return self.tk.call(self._w, 'entrycget', entry, opt) def entryconfigure(self, entry, cnf={}, **kw): if cnf is None: return self._getconfigure(self._w, 'entryconfigure', entry) self.tk.call(self._w, 'entryconfigure', entry, *self._options(cnf, kw)) def nearest(self, y): return self.tk.call(self._w, 'nearest', y) def see(self, entry): self.tk.call(self._w, 'see', entry) def selection_clear(self, cnf={}, **kw): self.tk.call(self._w, 'selection', 'clear', *self._options(cnf, kw)) def selection_includes(self, entry): return self.tk.call(self._w, 'selection', 'includes', entry) def selection_set(self, first, last=None): self.tk.call(self._w, 'selection', 'set', first, last) def show_entry(self, entry): return self.tk.call(self._w, 'show', 'entry', entry) class InputOnly(TixWidget): """InputOnly - Invisible widget. Unix only. Subwidgets - None""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixInputOnly', None, cnf, kw) class LabelEntry(TixWidget): """LabelEntry - Entry field with label. Packages an entry widget and a label into one mega widget. It can be used to simplify the creation of ``entry-form'' type of interface. Subwidgets Class ---------- ----- label Label entry Entry""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixLabelEntry', ['labelside','options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') class LabelFrame(TixWidget): """LabelFrame - Labelled Frame container. Packages a frame widget and a label into one mega widget. To create widgets inside a LabelFrame widget, one creates the new widgets relative to the frame subwidget and manage them inside the frame subwidget. Subwidgets Class ---------- ----- label Label frame Frame""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixLabelFrame', ['labelside','options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['frame'] = _dummyFrame(self, 'frame') class ListNoteBook(TixWidget): """A ListNoteBook widget is very similar to the TixNoteBook widget: it can be used to display many windows in a limited space using a notebook metaphor. The notebook is divided into a stack of pages (windows). At one time only one of these pages can be shown. The user can navigate through these pages by choosing the name of the desired page in the hlist subwidget.""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixListNoteBook', ['options'], cnf, kw) # Is this necessary? It's not an exposed subwidget in Tix. self.subwidget_list['pane'] = _dummyPanedWindow(self, 'pane', destroy_physically=0) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['shlist'] = _dummyScrolledHList(self, 'shlist') def add(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = TixSubWidget(self, name) return self.subwidget_list[name] def page(self, name): return self.subwidget(name) def pages(self): # Can't call subwidgets_all directly because we don't want .nbframe names = self.tk.splitlist(self.tk.call(self._w, 'pages')) ret = [] for x in names: ret.append(self.subwidget(x)) return ret def raise_page(self, name): # raise is a python keyword self.tk.call(self._w, 'raise', name) class Meter(TixWidget): """The Meter widget can be used to show the progress of a background job which may take a long time to execute. """ def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixMeter', ['options'], cnf, kw) class NoteBook(TixWidget): """NoteBook - Multi-page container widget (tabbed notebook metaphor). Subwidgets Class ---------- ----- nbframe NoteBookFrame <pages> page widgets added dynamically with the add method""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self,master,'tixNoteBook', ['options'], cnf, kw) self.subwidget_list['nbframe'] = TixSubWidget(self, 'nbframe', destroy_physically=0) def add(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = TixSubWidget(self, name) return self.subwidget_list[name] def delete(self, name): self.tk.call(self._w, 'delete', name) self.subwidget_list[name].destroy() del self.subwidget_list[name] def page(self, name): return self.subwidget(name) def pages(self): # Can't call subwidgets_all directly because we don't want .nbframe names = self.tk.splitlist(self.tk.call(self._w, 'pages')) ret = [] for x in names: ret.append(self.subwidget(x)) return ret def raise_page(self, name): # raise is a python keyword self.tk.call(self._w, 'raise', name) def raised(self): return self.tk.call(self._w, 'raised') class NoteBookFrame(TixWidget): # FIXME: This is dangerous to expose to be called on its own. pass class OptionMenu(TixWidget): """OptionMenu - creates a menu button of options. Subwidget Class --------- ----- menubutton Menubutton menu Menu""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixOptionMenu', ['options'], cnf, kw) self.subwidget_list['menubutton'] = _dummyMenubutton(self, 'menubutton') self.subwidget_list['menu'] = _dummyMenu(self, 'menu') def add_command(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', 'command', name, *self._options(cnf, kw)) def add_separator(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', 'separator', name, *self._options(cnf, kw)) def delete(self, name): self.tk.call(self._w, 'delete', name) def disable(self, name): self.tk.call(self._w, 'disable', name) def enable(self, name): self.tk.call(self._w, 'enable', name) class PanedWindow(TixWidget): """PanedWindow - Multi-pane container widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.The user changes the sizes of the panes by dragging the resize handle between two panes. Subwidgets Class ---------- ----- <panes> g/p widgets added dynamically with the add method.""" def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixPanedWindow', ['orientation', 'options'], cnf, kw) # add delete forget panecget paneconfigure panes setsize def add(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = TixSubWidget(self, name, check_intermediate=0) return self.subwidget_list[name] def delete(self, name): self.tk.call(self._w, 'delete', name) self.subwidget_list[name].destroy() del self.subwidget_list[name] def forget(self, name): self.tk.call(self._w, 'forget', name) def panecget(self, entry, opt): return self.tk.call(self._w, 'panecget', entry, opt) def paneconfigure(self, entry, cnf={}, **kw): if cnf is None: return self._getconfigure(self._w, 'paneconfigure', entry) self.tk.call(self._w, 'paneconfigure', entry, *self._options(cnf, kw)) def panes(self): names = self.tk.splitlist(self.tk.call(self._w, 'panes')) return [self.subwidget(x) for x in names] class PopupMenu(TixWidget): """PopupMenu widget can be used as a replacement of the tk_popup command. The advantage of the Tix PopupMenu widget is it requires less application code to manipulate. Subwidgets Class ---------- ----- menubutton Menubutton menu Menu""" # FIXME: It should inherit -superclass tixShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixPopupMenu', ['options'], cnf, kw) self.subwidget_list['menubutton'] = _dummyMenubutton(self, 'menubutton') self.subwidget_list['menu'] = _dummyMenu(self, 'menu') def bind_widget(self, widget): self.tk.call(self._w, 'bind', widget._w) def unbind_widget(self, widget): self.tk.call(self._w, 'unbind', widget._w) def post_widget(self, widget, x, y): self.tk.call(self._w, 'post', widget._w, x, y) class ResizeHandle(TixWidget): """Internal widget to draw resize handles on Scrolled widgets.""" def __init__(self, master, cnf={}, **kw): # There seems to be a Tix bug rejecting the configure method # Let's try making the flags -static flags = ['options', 'command', 'cursorfg', 'cursorbg', 'handlesize', 'hintcolor', 'hintwidth', 'x', 'y'] # In fact, x y height width are configurable TixWidget.__init__(self, master, 'tixResizeHandle', flags, cnf, kw) def attach_widget(self, widget): self.tk.call(self._w, 'attachwidget', widget._w) def detach_widget(self, widget): self.tk.call(self._w, 'detachwidget', widget._w) def hide(self, widget): self.tk.call(self._w, 'hide', widget._w) def show(self, widget): self.tk.call(self._w, 'show', widget._w) class ScrolledHList(TixWidget): """ScrolledHList - HList with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledHList', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class ScrolledListBox(TixWidget): """ScrolledListBox - Listbox with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledListBox', ['options'], cnf, kw) self.subwidget_list['listbox'] = _dummyListbox(self, 'listbox') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class ScrolledText(TixWidget): """ScrolledText - Text with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledText', ['options'], cnf, kw) self.subwidget_list['text'] = _dummyText(self, 'text') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class ScrolledTList(TixWidget): """ScrolledTList - TList with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledTList', ['options'], cnf, kw) self.subwidget_list['tlist'] = _dummyTList(self, 'tlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class ScrolledWindow(TixWidget): """ScrolledWindow - Window with automatic scrollbars.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledWindow', ['options'], cnf, kw) self.subwidget_list['window'] = _dummyFrame(self, 'window') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class Select(TixWidget): """Select - Container of button subwidgets. It can be used to provide radio-box or check-box style of selection options for the user. Subwidgets are buttons added dynamically using the add method.""" # FIXME: It should inherit -superclass tixLabelWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixSelect', ['allowzero', 'radio', 'orientation', 'labelside', 'options'], cnf, kw) self.subwidget_list['label'] = _dummyLabel(self, 'label') def add(self, name, cnf={}, **kw): self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) self.subwidget_list[name] = _dummyButton(self, name) return self.subwidget_list[name] def invoke(self, name): self.tk.call(self._w, 'invoke', name) class Shell(TixWidget): """Toplevel window. Subwidgets - None""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixShell', ['options', 'title'], cnf, kw) class DialogShell(TixWidget): """Toplevel window, with popup popdown and center methods. It tells the window manager that it is a dialog window and should be treated specially. The exact treatment depends on the treatment of the window manager. Subwidgets - None""" # FIXME: It should inherit from Shell def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixDialogShell', ['options', 'title', 'mapped', 'minheight', 'minwidth', 'parent', 'transient'], cnf, kw) def popdown(self): self.tk.call(self._w, 'popdown') def popup(self): self.tk.call(self._w, 'popup') def center(self): self.tk.call(self._w, 'center') class StdButtonBox(TixWidget): """StdButtonBox - Standard Button Box (OK, Apply, Cancel and Help) """ def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixStdButtonBox', ['orientation', 'options'], cnf, kw) self.subwidget_list['ok'] = _dummyButton(self, 'ok') self.subwidget_list['apply'] = _dummyButton(self, 'apply') self.subwidget_list['cancel'] = _dummyButton(self, 'cancel') self.subwidget_list['help'] = _dummyButton(self, 'help') def invoke(self, name): if name in self.subwidget_list: self.tk.call(self._w, 'invoke', name) class TList(TixWidget, XView, YView): """TList - Hierarchy display widget which can be used to display data in a tabular format. The list entries of a TList widget are similar to the entries in the Tk listbox widget. The main differences are (1) the TList widget can display the list entries in a two dimensional format and (2) you can use graphical images as well as multiple colors and fonts for the list entries. Subwidgets - None""" def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, 'tixTList', ['options'], cnf, kw) def active_set(self, index): self.tk.call(self._w, 'active', 'set', index) def active_clear(self): self.tk.call(self._w, 'active', 'clear') def anchor_set(self, index): self.tk.call(self._w, 'anchor', 'set', index) def anchor_clear(self): self.tk.call(self._w, 'anchor', 'clear') def delete(self, from_, to=None): self.tk.call(self._w, 'delete', from_, to) def dragsite_set(self, index): self.tk.call(self._w, 'dragsite', 'set', index) def dragsite_clear(self): self.tk.call(self._w, 'dragsite', 'clear') def dropsite_set(self, index): self.tk.call(self._w, 'dropsite', 'set', index) def dropsite_clear(self): self.tk.call(self._w, 'dropsite', 'clear') def insert(self, index, cnf={}, **kw): self.tk.call(self._w, 'insert', index, *self._options(cnf, kw)) def info_active(self): return self.tk.call(self._w, 'info', 'active') def info_anchor(self): return self.tk.call(self._w, 'info', 'anchor') def info_down(self, index): return self.tk.call(self._w, 'info', 'down', index) def info_left(self, index): return self.tk.call(self._w, 'info', 'left', index) def info_right(self, index): return self.tk.call(self._w, 'info', 'right', index) def info_selection(self): c = self.tk.call(self._w, 'info', 'selection') return self.tk.splitlist(c) def info_size(self): return self.tk.call(self._w, 'info', 'size') def info_up(self, index): return self.tk.call(self._w, 'info', 'up', index) def nearest(self, x, y): return self.tk.call(self._w, 'nearest', x, y) def see(self, index): self.tk.call(self._w, 'see', index) def selection_clear(self, cnf={}, **kw): self.tk.call(self._w, 'selection', 'clear', *self._options(cnf, kw)) def selection_includes(self, index): return self.tk.call(self._w, 'selection', 'includes', index) def selection_set(self, first, last=None): self.tk.call(self._w, 'selection', 'set', first, last) class Tree(TixWidget): """Tree - The tixTree widget can be used to display hierarchical data in a tree form. The user can adjust the view of the tree by opening or closing parts of the tree.""" # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixTree', ['options'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') def autosetmode(self): '''This command calls the setmode method for all the entries in this Tree widget: if an entry has no child entries, its mode is set to none. Otherwise, if the entry has any hidden child entries, its mode is set to open; otherwise its mode is set to close.''' self.tk.call(self._w, 'autosetmode') def close(self, entrypath): '''Close the entry given by entryPath if its mode is close.''' self.tk.call(self._w, 'close', entrypath) def getmode(self, entrypath): '''Returns the current mode of the entry given by entryPath.''' return self.tk.call(self._w, 'getmode', entrypath) def open(self, entrypath): '''Open the entry given by entryPath if its mode is open.''' self.tk.call(self._w, 'open', entrypath) def setmode(self, entrypath, mode='none'): '''This command is used to indicate whether the entry given by entryPath has children entries and whether the children are visible. mode must be one of open, close or none. If mode is set to open, a (+) indicator is drawn next the entry. If mode is set to close, a (-) indicator is drawn next the entry. If mode is set to none, no indicators will be drawn for this entry. The default mode is none. The open mode indicates the entry has hidden children and this entry can be opened by the user. The close mode indicates that all the children of the entry are now visible and the entry can be closed by the user.''' self.tk.call(self._w, 'setmode', entrypath, mode) # Could try subclassing Tree for CheckList - would need another arg to init class CheckList(TixWidget): """The CheckList widget displays a list of items to be selected by the user. CheckList acts similarly to the Tk checkbutton or radiobutton widgets, except it is capable of handling many more items than checkbuttons or radiobuttons. """ # FIXME: It should inherit -superclass tixTree def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixCheckList', ['options', 'radio'], cnf, kw) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') def autosetmode(self): '''This command calls the setmode method for all the entries in this Tree widget: if an entry has no child entries, its mode is set to none. Otherwise, if the entry has any hidden child entries, its mode is set to open; otherwise its mode is set to close.''' self.tk.call(self._w, 'autosetmode') def close(self, entrypath): '''Close the entry given by entryPath if its mode is close.''' self.tk.call(self._w, 'close', entrypath) def getmode(self, entrypath): '''Returns the current mode of the entry given by entryPath.''' return self.tk.call(self._w, 'getmode', entrypath) def open(self, entrypath): '''Open the entry given by entryPath if its mode is open.''' self.tk.call(self._w, 'open', entrypath) def getselection(self, mode='on'): '''Returns a list of items whose status matches status. If status is not specified, the list of items in the "on" status will be returned. Mode can be on, off, default''' return self.tk.splitlist(self.tk.call(self._w, 'getselection', mode)) def getstatus(self, entrypath): '''Returns the current status of entryPath.''' return self.tk.call(self._w, 'getstatus', entrypath) def setstatus(self, entrypath, mode='on'): '''Sets the status of entryPath to be status. A bitmap will be displayed next to the entry its status is on, off or default.''' self.tk.call(self._w, 'setstatus', entrypath, mode) ########################################################################### ### The subclassing below is used to instantiate the subwidgets in each ### ### mega widget. This allows us to access their methods directly. ### ########################################################################### class _dummyButton(Button, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyCheckbutton(Checkbutton, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyEntry(Entry, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyFrame(Frame, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyLabel(Label, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyListbox(Listbox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyMenu(Menu, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyMenubutton(Menubutton, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyScrollbar(Scrollbar, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyText(Text, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyScrolledListBox(ScrolledListBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['listbox'] = _dummyListbox(self, 'listbox') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class _dummyHList(HList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyScrolledHList(ScrolledHList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class _dummyTList(TList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyComboBox(ComboBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, ['fancy',destroy_physically]) self.subwidget_list['label'] = _dummyLabel(self, 'label') self.subwidget_list['entry'] = _dummyEntry(self, 'entry') self.subwidget_list['arrow'] = _dummyButton(self, 'arrow') self.subwidget_list['slistbox'] = _dummyScrolledListBox(self, 'slistbox') try: self.subwidget_list['tick'] = _dummyButton(self, 'tick') #cross Button : present if created with the fancy option self.subwidget_list['cross'] = _dummyButton(self, 'cross') except TypeError: # unavailable when -fancy not specified pass class _dummyDirList(DirList, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['hlist'] = _dummyHList(self, 'hlist') self.subwidget_list['vsb'] = _dummyScrollbar(self, 'vsb') self.subwidget_list['hsb'] = _dummyScrollbar(self, 'hsb') class _dummyDirSelectBox(DirSelectBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['dirlist'] = _dummyDirList(self, 'dirlist') self.subwidget_list['dircbx'] = _dummyFileComboBox(self, 'dircbx') class _dummyExFileSelectBox(ExFileSelectBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['cancel'] = _dummyButton(self, 'cancel') self.subwidget_list['ok'] = _dummyButton(self, 'ok') self.subwidget_list['hidden'] = _dummyCheckbutton(self, 'hidden') self.subwidget_list['types'] = _dummyComboBox(self, 'types') self.subwidget_list['dir'] = _dummyComboBox(self, 'dir') self.subwidget_list['dirlist'] = _dummyScrolledListBox(self, 'dirlist') self.subwidget_list['file'] = _dummyComboBox(self, 'file') self.subwidget_list['filelist'] = _dummyScrolledListBox(self, 'filelist') class _dummyFileSelectBox(FileSelectBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['dirlist'] = _dummyScrolledListBox(self, 'dirlist') self.subwidget_list['filelist'] = _dummyScrolledListBox(self, 'filelist') self.subwidget_list['filter'] = _dummyComboBox(self, 'filter') self.subwidget_list['selection'] = _dummyComboBox(self, 'selection') class _dummyFileComboBox(ComboBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['dircbx'] = _dummyComboBox(self, 'dircbx') class _dummyStdButtonBox(StdButtonBox, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) self.subwidget_list['ok'] = _dummyButton(self, 'ok') self.subwidget_list['apply'] = _dummyButton(self, 'apply') self.subwidget_list['cancel'] = _dummyButton(self, 'cancel') self.subwidget_list['help'] = _dummyButton(self, 'help') class _dummyNoteBookFrame(NoteBookFrame, TixSubWidget): def __init__(self, master, name, destroy_physically=0): TixSubWidget.__init__(self, master, name, destroy_physically) class _dummyPanedWindow(PanedWindow, TixSubWidget): def __init__(self, master, name, destroy_physically=1): TixSubWidget.__init__(self, master, name, destroy_physically) ######################## ### Utility Routines ### ######################## #mike Should tixDestroy be exposed as a wrapper? - but not for widgets. def OptionName(widget): '''Returns the qualified path name for the widget. Normally used to set default options for subwidgets. See tixwidgets.py''' return widget.tk.call('tixOptionName', widget._w) # Called with a dictionary argument of the form # {'*.c':'C source files', '*.txt':'Text Files', '*':'All files'} # returns a string which can be used to configure the fsbox file types # in an ExFileSelectBox. i.e., # '{{*} {* - All files}} {{*.c} {*.c - C source files}} {{*.txt} {*.txt - Text Files}}' def FileTypeList(dict): s = '' for type in dict.keys(): s = s + '{{' + type + '} {' + type + ' - ' + dict[type] + '}} ' return s # Still to be done: # tixIconView class CObjView(TixWidget): """This file implements the Canvas Object View widget. This is a base class of IconView. It implements automatic placement/adjustment of the scrollbars according to the canvas objects inside the canvas subwidget. The scrollbars are adjusted so that the canvas is just large enough to see all the objects. """ # FIXME: It should inherit -superclass tixScrolledWidget pass class Grid(TixWidget, XView, YView): '''The Tix Grid command creates a new window and makes it into a tixGrid widget. Additional options, may be specified on the command line or in the option database to configure aspects such as its cursor and relief. A Grid widget displays its contents in a two dimensional grid of cells. Each cell may contain one Tix display item, which may be in text, graphics or other formats. See the DisplayStyle class for more information about Tix display items. Individual cells, or groups of cells, can be formatted with a wide range of attributes, such as its color, relief and border. Subwidgets - None''' # valid specific resources as of Tk 8.4 # editdonecmd, editnotifycmd, floatingcols, floatingrows, formatcmd, # highlightbackground, highlightcolor, leftmargin, itemtype, selectmode, # selectunit, topmargin, def __init__(self, master=None, cnf={}, **kw): static= [] self.cnf= cnf TixWidget.__init__(self, master, 'tixGrid', static, cnf, kw) # valid options as of Tk 8.4 # anchor, bdtype, cget, configure, delete, dragsite, dropsite, entrycget, # edit, entryconfigure, format, geometryinfo, info, index, move, nearest, # selection, set, size, unset, xview, yview def anchor_clear(self): """Removes the selection anchor.""" self.tk.call(self, 'anchor', 'clear') def anchor_get(self): "Get the (x,y) coordinate of the current anchor cell" return self._getints(self.tk.call(self, 'anchor', 'get')) def anchor_set(self, x, y): """Set the selection anchor to the cell at (x, y).""" self.tk.call(self, 'anchor', 'set', x, y) def delete_row(self, from_, to=None): """Delete rows between from_ and to inclusive. If to is not provided, delete only row at from_""" if to is None: self.tk.call(self, 'delete', 'row', from_) else: self.tk.call(self, 'delete', 'row', from_, to) def delete_column(self, from_, to=None): """Delete columns between from_ and to inclusive. If to is not provided, delete only column at from_""" if to is None: self.tk.call(self, 'delete', 'column', from_) else: self.tk.call(self, 'delete', 'column', from_, to) def edit_apply(self): """If any cell is being edited, de-highlight the cell and applies the changes.""" self.tk.call(self, 'edit', 'apply') def edit_set(self, x, y): """Highlights the cell at (x, y) for editing, if the -editnotify command returns True for this cell.""" self.tk.call(self, 'edit', 'set', x, y) def entrycget(self, x, y, option): "Get the option value for cell at (x,y)" if option and option[0] != '-': option = '-' + option return self.tk.call(self, 'entrycget', x, y, option) def entryconfigure(self, x, y, cnf=None, **kw): return self._configure(('entryconfigure', x, y), cnf, kw) # def format # def index def info_exists(self, x, y): "Return True if display item exists at (x,y)" return self._getboolean(self.tk.call(self, 'info', 'exists', x, y)) def info_bbox(self, x, y): # This seems to always return '', at least for 'text' displayitems return self.tk.call(self, 'info', 'bbox', x, y) def move_column(self, from_, to, offset): """Moves the range of columns from position FROM through TO by the distance indicated by OFFSET. For example, move_column(2, 4, 1) moves the columns 2,3,4 to columns 3,4,5.""" self.tk.call(self, 'move', 'column', from_, to, offset) def move_row(self, from_, to, offset): """Moves the range of rows from position FROM through TO by the distance indicated by OFFSET. For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5.""" self.tk.call(self, 'move', 'row', from_, to, offset) def nearest(self, x, y): "Return coordinate of cell nearest pixel coordinate (x,y)" return self._getints(self.tk.call(self, 'nearest', x, y)) # def selection adjust # def selection clear # def selection includes # def selection set # def selection toggle def set(self, x, y, itemtype=None, **kw): args= self._options(self.cnf, kw) if itemtype is not None: args= ('-itemtype', itemtype) + args self.tk.call(self, 'set', x, y, *args) def size_column(self, index, **kw): """Queries or sets the size of the column given by INDEX. INDEX may be any non-negative integer that gives the position of a given column. INDEX can also be the string "default"; in this case, this command queries or sets the default size of all columns. When no option-value pair is given, this command returns a tuple containing the current size setting of the given column. When option-value pairs are given, the corresponding options of the size setting of the given column are changed. Options may be one of the follwing: pad0 pixels Specifies the paddings to the left of a column. pad1 pixels Specifies the paddings to the right of a column. size val Specifies the width of a column. Val may be: "auto" -- the width of the column is set to the width of the widest cell in the column; a valid Tk screen distance unit; or a real number following by the word chars (e.g. 3.4chars) that sets the width of the column to the given number of characters.""" return self.tk.splitlist(self.tk.call(self._w, 'size', 'column', index, *self._options({}, kw))) def size_row(self, index, **kw): """Queries or sets the size of the row given by INDEX. INDEX may be any non-negative integer that gives the position of a given row . INDEX can also be the string "default"; in this case, this command queries or sets the default size of all rows. When no option-value pair is given, this command returns a list con- taining the current size setting of the given row . When option-value pairs are given, the corresponding options of the size setting of the given row are changed. Options may be one of the follwing: pad0 pixels Specifies the paddings to the top of a row. pad1 pixels Specifies the paddings to the bottom of a row. size val Specifies the height of a row. Val may be: "auto" -- the height of the row is set to the height of the highest cell in the row; a valid Tk screen distance unit; or a real number following by the word chars (e.g. 3.4chars) that sets the height of the row to the given number of characters.""" return self.tk.splitlist(self.tk.call( self, 'size', 'row', index, *self._options({}, kw))) def unset(self, x, y): """Clears the cell at (x, y) by removing its display item.""" self.tk.call(self._w, 'unset', x, y) class ScrolledGrid(Grid): '''Scrolled Grid widgets''' # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master=None, cnf={}, **kw): static= [] self.cnf= cnf TixWidget.__init__(self, master, 'tixScrolledGrid', static, cnf, kw)
77,088
1,947
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/scrolledtext.py
"""A ScrolledText widget feels like a text widget but also has a vertical scroll bar on its right. (Later, options may be added to add a horizontal bar as well, to make the bars disappear automatically when not needed, to move them to the other side of the window, etc.) Configuration options are passed to the Text widget. A Frame widget is inserted between the master and the text, to hold the Scrollbar widget. Most methods calls are inherited from the Text widget; Pack, Grid and Place methods are redirected to the Frame widget however. """ __all__ = ['ScrolledText'] from tkinter import Frame, Text, Scrollbar, Pack, Grid, Place from tkinter.constants import RIGHT, LEFT, Y, BOTH class ScrolledText(Text): def __init__(self, master=None, **kw): self.frame = Frame(master) self.vbar = Scrollbar(self.frame) self.vbar.pack(side=RIGHT, fill=Y) kw.update({'yscrollcommand': self.vbar.set}) Text.__init__(self, self.frame, **kw) self.pack(side=LEFT, fill=BOTH, expand=True) self.vbar['command'] = self.yview # Copy geometry methods of self.frame without overriding Text # methods -- hack! text_meths = vars(Text).keys() methods = vars(Pack).keys() | vars(Grid).keys() | vars(Place).keys() methods = methods.difference(text_meths) for m in methods: if m[0] != '_' and m != 'config' and m != 'configure': setattr(self, m, getattr(self.frame, m)) def __str__(self): return str(self.frame) def example(): from tkinter.constants import END stext = ScrolledText(bg='white', height=10) stext.insert(END, __doc__) stext.pack(fill=BOTH, side=LEFT, expand=True) stext.focus_set() stext.mainloop() if __name__ == "__main__": example()
1,814
55
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/simpledialog.py
# # An Introduction to Tkinter # # Copyright (c) 1997 by Fredrik Lundh # # This copyright applies to Dialog, askinteger, askfloat and asktring # # [email protected] # http://www.pythonware.com # """This modules handles dialog boxes. It contains the following public symbols: SimpleDialog -- A simple but flexible modal dialog box Dialog -- a base class for dialogs askinteger -- get an integer from the user askfloat -- get a float from the user askstring -- get a string from the user """ from tkinter import * from tkinter import messagebox import tkinter # used at _QueryDialog for tkinter._default_root class SimpleDialog: def __init__(self, master, text='', buttons=[], default=None, cancel=None, title=None, class_=None): if class_: self.root = Toplevel(master, class_=class_) else: self.root = Toplevel(master) if title: self.root.title(title) self.root.iconname(title) self.message = Message(self.root, text=text, aspect=400) self.message.pack(expand=1, fill=BOTH) self.frame = Frame(self.root) self.frame.pack() self.num = default self.cancel = cancel self.default = default self.root.bind('<Return>', self.return_event) for num in range(len(buttons)): s = buttons[num] b = Button(self.frame, text=s, command=(lambda self=self, num=num: self.done(num))) if num == default: b.config(relief=RIDGE, borderwidth=8) b.pack(side=LEFT, fill=BOTH, expand=1) self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window) self._set_transient(master) def _set_transient(self, master, relx=0.5, rely=0.3): widget = self.root widget.withdraw() # Remain invisible while we figure out the geometry widget.transient(master) widget.update_idletasks() # Actualize geometry information if master.winfo_ismapped(): m_width = master.winfo_width() m_height = master.winfo_height() m_x = master.winfo_rootx() m_y = master.winfo_rooty() else: m_width = master.winfo_screenwidth() m_height = master.winfo_screenheight() m_x = m_y = 0 w_width = widget.winfo_reqwidth() w_height = widget.winfo_reqheight() x = m_x + (m_width - w_width) * relx y = m_y + (m_height - w_height) * rely if x+w_width > master.winfo_screenwidth(): x = master.winfo_screenwidth() - w_width elif x < 0: x = 0 if y+w_height > master.winfo_screenheight(): y = master.winfo_screenheight() - w_height elif y < 0: y = 0 widget.geometry("+%d+%d" % (x, y)) widget.deiconify() # Become visible at the desired location def go(self): self.root.wait_visibility() self.root.grab_set() self.root.mainloop() self.root.destroy() return self.num def return_event(self, event): if self.default is None: self.root.bell() else: self.done(self.default) def wm_delete_window(self): if self.cancel is None: self.root.bell() else: self.done(self.cancel) def done(self, num): self.num = num self.root.quit() class Dialog(Toplevel): '''Class to open dialogs. This class is intended as a base class for custom dialogs ''' def __init__(self, parent, title = None): '''Initialize a dialog. Arguments: parent -- a parent window (the application window) title -- the dialog title ''' Toplevel.__init__(self, parent) self.withdraw() # remain invisible for now # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn if parent.winfo_viewable(): self.transient(parent) if title: self.title(title) self.parent = parent self.result = None body = Frame(self) self.initial_focus = self.body(body) body.pack(padx=5, pady=5) self.buttonbox() if not self.initial_focus: self.initial_focus = self self.protocol("WM_DELETE_WINDOW", self.cancel) if self.parent is not None: self.geometry("+%d+%d" % (parent.winfo_rootx()+50, parent.winfo_rooty()+50)) self.deiconify() # become visible now self.initial_focus.focus_set() # wait for window to appear on screen before calling grab_set self.wait_visibility() self.grab_set() self.wait_window(self) def destroy(self): '''Destroy the window''' self.initial_focus = None Toplevel.destroy(self) # # construction hooks def body(self, master): '''create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method. ''' pass def buttonbox(self): '''add standard button box. override if you do not want the standard buttons ''' box = Frame(self) w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text="Cancel", width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) self.bind("<Escape>", self.cancel) box.pack() # # standard button semantics def ok(self, event=None): if not self.validate(): self.initial_focus.focus_set() # put focus back return self.withdraw() self.update_idletasks() try: self.apply() finally: self.cancel() def cancel(self, event=None): # put focus back to the parent window if self.parent is not None: self.parent.focus_set() self.destroy() # # command hooks def validate(self): '''validate the data This method is called automatically to validate the data before the dialog is destroyed. By default, it always validates OK. ''' return 1 # override def apply(self): '''process the data This method is called automatically to process the data, *after* the dialog is destroyed. By default, it does nothing. ''' pass # override # -------------------------------------------------------------------- # convenience dialogues class _QueryDialog(Dialog): def __init__(self, title, prompt, initialvalue=None, minvalue = None, maxvalue = None, parent = None): if not parent: parent = tkinter._default_root self.prompt = prompt self.minvalue = minvalue self.maxvalue = maxvalue self.initialvalue = initialvalue Dialog.__init__(self, parent, title) def destroy(self): self.entry = None Dialog.destroy(self) def body(self, master): w = Label(master, text=self.prompt, justify=LEFT) w.grid(row=0, padx=5, sticky=W) self.entry = Entry(master, name="entry") self.entry.grid(row=1, padx=5, sticky=W+E) if self.initialvalue is not None: self.entry.insert(0, self.initialvalue) self.entry.select_range(0, END) return self.entry def validate(self): try: result = self.getresult() except ValueError: messagebox.showwarning( "Illegal value", self.errormessage + "\nPlease try again", parent = self ) return 0 if self.minvalue is not None and result < self.minvalue: messagebox.showwarning( "Too small", "The allowed minimum value is %s. " "Please try again." % self.minvalue, parent = self ) return 0 if self.maxvalue is not None and result > self.maxvalue: messagebox.showwarning( "Too large", "The allowed maximum value is %s. " "Please try again." % self.maxvalue, parent = self ) return 0 self.result = result return 1 class _QueryInteger(_QueryDialog): errormessage = "Not an integer." def getresult(self): return self.getint(self.entry.get()) def askinteger(title, prompt, **kw): '''get an integer from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is an integer ''' d = _QueryInteger(title, prompt, **kw) return d.result class _QueryFloat(_QueryDialog): errormessage = "Not a floating point value." def getresult(self): return self.getdouble(self.entry.get()) def askfloat(title, prompt, **kw): '''get a float from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is a float ''' d = _QueryFloat(title, prompt, **kw) return d.result class _QueryString(_QueryDialog): def __init__(self, *args, **kw): if "show" in kw: self.__show = kw["show"] del kw["show"] else: self.__show = None _QueryDialog.__init__(self, *args, **kw) def body(self, master): entry = _QueryDialog.body(self, master) if self.__show is not None: entry.configure(show=self.__show) return entry def getresult(self): return self.entry.get() def askstring(title, prompt, **kw): '''get a string from the user Arguments: title -- the dialog title prompt -- the label text **kw -- see SimpleDialog class Return value is a string ''' d = _QueryString(title, prompt, **kw) return d.result if __name__ == '__main__': def test(): root = Tk() def doit(root=root): d = SimpleDialog(root, text="This is a test dialog. " "Would this have been an actual dialog, " "the buttons below would have been glowing " "in soft pink light.\n" "Do you believe this?", buttons=["Yes", "No", "Cancel"], default=0, cancel=2, title="Test Dialog") print(d.go()) print(askinteger("Spam", "Egg count", initialvalue=12*12)) print(askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100)) print(askstring("Spam", "Egg label")) t = Button(root, text='Test', command=doit) t.pack() q = Button(root, text='Quit', command=t.quit) q.pack() t.mainloop() test()
11,424
424
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/dialog.py
# dialog.py -- Tkinter interface to the tk_dialog script. from tkinter import * from tkinter import _cnfmerge DIALOG_ICON = 'questhead' class Dialog(Widget): def __init__(self, master=None, cnf={}, **kw): cnf = _cnfmerge((cnf, kw)) self.widgetName = '__dialog__' Widget._setup(self, master, cnf) self.num = self.tk.getint( self.tk.call( 'tk_dialog', self._w, cnf['title'], cnf['text'], cnf['bitmap'], cnf['default'], *cnf['strings'])) try: Widget.destroy(self) except TclError: pass def destroy(self): pass def _test(): d = Dialog(None, {'title': 'File Modified', 'text': 'File "Python.h" has been modified' ' since the last time it was saved.' ' Do you want to save it before' ' exiting the application.', 'bitmap': DIALOG_ICON, 'default': 0, 'strings': ('Save File', 'Discard Changes', 'Return to Editor')}) print(d.num) if __name__ == '__main__': t = Button(None, {'text': 'Test', 'command': _test, Pack: {}}) q = Button(None, {'text': 'Quit', 'command': t.quit, Pack: {}}) t.mainloop()
1,509
47
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/commondialog.py
# base class for tk common dialogues # # this module provides a base class for accessing the common # dialogues available in Tk 4.2 and newer. use filedialog, # colorchooser, and messagebox to access the individual # dialogs. # # written by Fredrik Lundh, May 1997 # from tkinter import * class Dialog: command = None def __init__(self, master=None, **options): self.master = master self.options = options if not master and options.get('parent'): self.master = options['parent'] def _fixoptions(self): pass # hook def _fixresult(self, widget, result): return result # hook def show(self, **options): # update instance options for k, v in options.items(): self.options[k] = v self._fixoptions() # we need a dummy widget to properly process the options # (at least as long as we use Tkinter 1.63) w = Frame(self.master) try: s = w.tk.call(self.command, *w._options(self.options)) s = self._fixresult(w, s) finally: try: # get rid of the widget w.destroy() except: pass return s
1,247
56
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/dnd.py
"""Drag-and-drop support for Tkinter. This is very preliminary. I currently only support dnd *within* one application, between different windows (or within the same window). I am trying to make this as generic as possible -- not dependent on the use of a particular widget or icon type, etc. I also hope that this will work with Pmw. To enable an object to be dragged, you must create an event binding for it that starts the drag-and-drop process. Typically, you should bind <ButtonPress> to a callback function that you write. The function should call Tkdnd.dnd_start(source, event), where 'source' is the object to be dragged, and 'event' is the event that invoked the call (the argument to your callback function). Even though this is a class instantiation, the returned instance should not be stored -- it will be kept alive automatically for the duration of the drag-and-drop. When a drag-and-drop is already in process for the Tk interpreter, the call is *ignored*; this normally averts starting multiple simultaneous dnd processes, e.g. because different button callbacks all dnd_start(). The object is *not* necessarily a widget -- it can be any application-specific object that is meaningful to potential drag-and-drop targets. Potential drag-and-drop targets are discovered as follows. Whenever the mouse moves, and at the start and end of a drag-and-drop move, the Tk widget directly under the mouse is inspected. This is the target widget (not to be confused with the target object, yet to be determined). If there is no target widget, there is no dnd target object. If there is a target widget, and it has an attribute dnd_accept, this should be a function (or any callable object). The function is called as dnd_accept(source, event), where 'source' is the object being dragged (the object passed to dnd_start() above), and 'event' is the most recent event object (generally a <Motion> event; it can also be <ButtonPress> or <ButtonRelease>). If the dnd_accept() function returns something other than None, this is the new dnd target object. If dnd_accept() returns None, or if the target widget has no dnd_accept attribute, the target widget's parent is considered as the target widget, and the search for a target object is repeated from there. If necessary, the search is repeated all the way up to the root widget. If none of the target widgets can produce a target object, there is no target object (the target object is None). The target object thus produced, if any, is called the new target object. It is compared with the old target object (or None, if there was no old target widget). There are several cases ('source' is the source object, and 'event' is the most recent event object): - Both the old and new target objects are None. Nothing happens. - The old and new target objects are the same object. Its method dnd_motion(source, event) is called. - The old target object was None, and the new target object is not None. The new target object's method dnd_enter(source, event) is called. - The new target object is None, and the old target object is not None. The old target object's method dnd_leave(source, event) is called. - The old and new target objects differ and neither is None. The old target object's method dnd_leave(source, event), and then the new target object's method dnd_enter(source, event) is called. Once this is done, the new target object replaces the old one, and the Tk mainloop proceeds. The return value of the methods mentioned above is ignored; if they raise an exception, the normal exception handling mechanisms take over. The drag-and-drop processes can end in two ways: a final target object is selected, or no final target object is selected. When a final target object is selected, it will always have been notified of the potential drop by a call to its dnd_enter() method, as described above, and possibly one or more calls to its dnd_motion() method; its dnd_leave() method has not been called since the last call to dnd_enter(). The target is notified of the drop by a call to its method dnd_commit(source, event). If no final target object is selected, and there was an old target object, its dnd_leave(source, event) method is called to complete the dnd sequence. Finally, the source object is notified that the drag-and-drop process is over, by a call to source.dnd_end(target, event), specifying either the selected target object, or None if no target object was selected. The source object can use this to implement the commit action; this is sometimes simpler than to do it in the target's dnd_commit(). The target's dnd_commit() method could then simply be aliased to dnd_leave(). At any time during a dnd sequence, the application can cancel the sequence by calling the cancel() method on the object returned by dnd_start(). This will call dnd_leave() if a target is currently active; it will never call dnd_commit(). """ import tkinter # The factory function def dnd_start(source, event): h = DndHandler(source, event) if h.root: return h else: return None # The class that does the work class DndHandler: root = None def __init__(self, source, event): if event.num > 5: return root = event.widget._root() try: root.__dnd return # Don't start recursive dnd except AttributeError: root.__dnd = self self.root = root self.source = source self.target = None self.initial_button = button = event.num self.initial_widget = widget = event.widget self.release_pattern = "<B%d-ButtonRelease-%d>" % (button, button) self.save_cursor = widget['cursor'] or "" widget.bind(self.release_pattern, self.on_release) widget.bind("<Motion>", self.on_motion) widget['cursor'] = "hand2" def __del__(self): root = self.root self.root = None if root: try: del root.__dnd except AttributeError: pass def on_motion(self, event): x, y = event.x_root, event.y_root target_widget = self.initial_widget.winfo_containing(x, y) source = self.source new_target = None while target_widget: try: attr = target_widget.dnd_accept except AttributeError: pass else: new_target = attr(source, event) if new_target: break target_widget = target_widget.master old_target = self.target if old_target is new_target: if old_target: old_target.dnd_motion(source, event) else: if old_target: self.target = None old_target.dnd_leave(source, event) if new_target: new_target.dnd_enter(source, event) self.target = new_target def on_release(self, event): self.finish(event, 1) def cancel(self, event=None): self.finish(event, 0) def finish(self, event, commit=0): target = self.target source = self.source widget = self.initial_widget root = self.root try: del root.__dnd self.initial_widget.unbind(self.release_pattern) self.initial_widget.unbind("<Motion>") widget['cursor'] = self.save_cursor self.target = self.source = self.initial_widget = self.root = None if target: if commit: target.dnd_commit(source, event) else: target.dnd_leave(source, event) finally: source.dnd_end(target, event) # ---------------------------------------------------------------------- # The rest is here for testing and demonstration purposes only! class Icon: def __init__(self, name): self.name = name self.canvas = self.label = self.id = None def attach(self, canvas, x=10, y=10): if canvas is self.canvas: self.canvas.coords(self.id, x, y) return if self.canvas: self.detach() if not canvas: return label = tkinter.Label(canvas, text=self.name, borderwidth=2, relief="raised") id = canvas.create_window(x, y, window=label, anchor="nw") self.canvas = canvas self.label = label self.id = id label.bind("<ButtonPress>", self.press) def detach(self): canvas = self.canvas if not canvas: return id = self.id label = self.label self.canvas = self.label = self.id = None canvas.delete(id) label.destroy() def press(self, event): if dnd_start(self, event): # where the pointer is relative to the label widget: self.x_off = event.x self.y_off = event.y # where the widget is relative to the canvas: self.x_orig, self.y_orig = self.canvas.coords(self.id) def move(self, event): x, y = self.where(self.canvas, event) self.canvas.coords(self.id, x, y) def putback(self): self.canvas.coords(self.id, self.x_orig, self.y_orig) def where(self, canvas, event): # where the corner of the canvas is relative to the screen: x_org = canvas.winfo_rootx() y_org = canvas.winfo_rooty() # where the pointer is relative to the canvas widget: x = event.x_root - x_org y = event.y_root - y_org # compensate for initial pointer offset return x - self.x_off, y - self.y_off def dnd_end(self, target, event): pass class Tester: def __init__(self, root): self.top = tkinter.Toplevel(root) self.canvas = tkinter.Canvas(self.top, width=100, height=100) self.canvas.pack(fill="both", expand=1) self.canvas.dnd_accept = self.dnd_accept def dnd_accept(self, source, event): return self def dnd_enter(self, source, event): self.canvas.focus_set() # Show highlight border x, y = source.where(self.canvas, event) x1, y1, x2, y2 = source.canvas.bbox(source.id) dx, dy = x2-x1, y2-y1 self.dndid = self.canvas.create_rectangle(x, y, x+dx, y+dy) self.dnd_motion(source, event) def dnd_motion(self, source, event): x, y = source.where(self.canvas, event) x1, y1, x2, y2 = self.canvas.bbox(self.dndid) self.canvas.move(self.dndid, x-x1, y-y1) def dnd_leave(self, source, event): self.top.focus_set() # Hide highlight border self.canvas.delete(self.dndid) self.dndid = None def dnd_commit(self, source, event): self.dnd_leave(source, event) x, y = source.where(self.canvas, event) source.attach(self.canvas, x, y) def test(): root = tkinter.Tk() root.geometry("+1+1") tkinter.Button(command=root.quit, text="Quit").pack() t1 = Tester(root) t1.top.geometry("+1+60") t2 = Tester(root) t2.top.geometry("+120+60") t3 = Tester(root) t3.top.geometry("+240+60") i1 = Icon("ICON1") i2 = Icon("ICON2") i3 = Icon("ICON3") i1.attach(t1.canvas) i2.attach(t2.canvas) i3.attach(t3.canvas) root.mainloop() if __name__ == '__main__': test()
11,488
322
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/constants.py
# Symbolic constants for Tk # Booleans NO=FALSE=OFF=0 YES=TRUE=ON=1 # -anchor and -sticky N='n' S='s' W='w' E='e' NW='nw' SW='sw' NE='ne' SE='se' NS='ns' EW='ew' NSEW='nsew' CENTER='center' # -fill NONE='none' X='x' Y='y' BOTH='both' # -side LEFT='left' TOP='top' RIGHT='right' BOTTOM='bottom' # -relief RAISED='raised' SUNKEN='sunken' FLAT='flat' RIDGE='ridge' GROOVE='groove' SOLID = 'solid' # -orient HORIZONTAL='horizontal' VERTICAL='vertical' # -tabs NUMERIC='numeric' # -wrap CHAR='char' WORD='word' # -align BASELINE='baseline' # -bordermode INSIDE='inside' OUTSIDE='outside' # Special tags, marks and insert positions SEL='sel' SEL_FIRST='sel.first' SEL_LAST='sel.last' END='end' INSERT='insert' CURRENT='current' ANCHOR='anchor' ALL='all' # e.g. Canvas.delete(ALL) # Text widget and button states NORMAL='normal' DISABLED='disabled' ACTIVE='active' # Canvas state HIDDEN='hidden' # Menu item types CASCADE='cascade' CHECKBUTTON='checkbutton' COMMAND='command' RADIOBUTTON='radiobutton' SEPARATOR='separator' # Selection modes for list boxes SINGLE='single' BROWSE='browse' MULTIPLE='multiple' EXTENDED='extended' # Activestyle for list boxes # NONE='none' is also valid DOTBOX='dotbox' UNDERLINE='underline' # Various canvas styles PIESLICE='pieslice' CHORD='chord' ARC='arc' FIRST='first' LAST='last' BUTT='butt' PROJECTING='projecting' ROUND='round' BEVEL='bevel' MITER='miter' # Arguments to xview/yview MOVETO='moveto' SCROLL='scroll' UNITS='units' PAGES='pages'
1,493
111
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/__main__.py
"""Main entry point""" import sys if sys.argv[0].endswith("__main__.py"): sys.argv[0] = "python -m tkinter" from . import _test as main main()
148
8
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/colorchooser.py
# tk common color chooser dialogue # # this module provides an interface to the native color dialogue # available in Tk 4.2 and newer. # # written by Fredrik Lundh, May 1997 # # fixed initialcolor handling in August 1998 # # # options (all have default values): # # - initialcolor: color to mark as selected when dialog is displayed # (given as an RGB triplet or a Tk color string) # # - parent: which window to place the dialog on top of # # - title: dialog title # from tkinter.commondialog import Dialog # # color chooser class class Chooser(Dialog): "Ask for a color" command = "tk_chooseColor" def _fixoptions(self): try: # make sure initialcolor is a tk color string color = self.options["initialcolor"] if isinstance(color, tuple): # assume an RGB triplet self.options["initialcolor"] = "#%02x%02x%02x" % color except KeyError: pass def _fixresult(self, widget, result): # result can be somethings: an empty tuple, an empty string or # a Tcl_Obj, so this somewhat weird check handles that if not result or not str(result): return None, None # canceled # to simplify application code, the color chooser returns # an RGB tuple together with the Tk color string r, g, b = widget.winfo_rgb(result) return (r/256, g/256, b/256), str(result) # # convenience stuff def askcolor(color = None, **options): "Ask for a color" if color: options = options.copy() options["initialcolor"] = color return Chooser(**options).show() # -------------------------------------------------------------------- # test stuff if __name__ == "__main__": print("color", askcolor())
1,791
73
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/font.py
# Tkinter font wrapper # # written by Fredrik Lundh, February 1998 # __version__ = "0.9" import itertools import tkinter # weight/slant NORMAL = "normal" ROMAN = "roman" BOLD = "bold" ITALIC = "italic" def nametofont(name): """Given the name of a tk named font, returns a Font representation. """ return Font(name=name, exists=True) class Font: """Represents a named font. Constructor options are: font -- font specifier (name, system font, or (family, size, style)-tuple) name -- name to use for this font configuration (defaults to a unique name) exists -- does a named font by this name already exist? Creates a new named font if False, points to the existing font if True. Raises _tkinter.TclError if the assertion is false. the following are ignored if font is specified: family -- font 'family', e.g. Courier, Times, Helvetica size -- font size in points weight -- font thickness: NORMAL, BOLD slant -- font slant: ROMAN, ITALIC underline -- font underlining: false (0), true (1) overstrike -- font strikeout: false (0), true (1) """ counter = itertools.count(1) def _set(self, kw): options = [] for k, v in kw.items(): options.append("-"+k) options.append(str(v)) return tuple(options) def _get(self, args): options = [] for k in args: options.append("-"+k) return tuple(options) def _mkdict(self, args): options = {} for i in range(0, len(args), 2): options[args[i][1:]] = args[i+1] return options def __init__(self, root=None, font=None, name=None, exists=False, **options): if not root: root = tkinter._default_root tk = getattr(root, 'tk', root) if font: # get actual settings corresponding to the given font font = tk.splitlist(tk.call("font", "actual", font)) else: font = self._set(options) if not name: name = "font" + str(next(self.counter)) self.name = name if exists: self.delete_font = False # confirm font exists if self.name not in tk.splitlist(tk.call("font", "names")): raise tkinter._tkinter.TclError( "named font %s does not already exist" % (self.name,)) # if font config info supplied, apply it if font: tk.call("font", "configure", self.name, *font) else: # create new font (raises TclError if the font exists) tk.call("font", "create", self.name, *font) self.delete_font = True self._tk = tk self._split = tk.splitlist self._call = tk.call def __str__(self): return self.name def __eq__(self, other): return isinstance(other, Font) and self.name == other.name def __getitem__(self, key): return self.cget(key) def __setitem__(self, key, value): self.configure(**{key: value}) def __del__(self): try: if self.delete_font: self._call("font", "delete", self.name) except Exception: pass def copy(self): "Return a distinct copy of the current font" return Font(self._tk, **self.actual()) def actual(self, option=None, displayof=None): "Return actual font attributes" args = () if displayof: args = ('-displayof', displayof) if option: args = args + ('-' + option, ) return self._call("font", "actual", self.name, *args) else: return self._mkdict( self._split(self._call("font", "actual", self.name, *args))) def cget(self, option): "Get font attribute" return self._call("font", "config", self.name, "-"+option) def config(self, **options): "Modify font attributes" if options: self._call("font", "config", self.name, *self._set(options)) else: return self._mkdict( self._split(self._call("font", "config", self.name))) configure = config def measure(self, text, displayof=None): "Return text width" args = (text,) if displayof: args = ('-displayof', displayof, text) return self._tk.getint(self._call("font", "measure", self.name, *args)) def metrics(self, *options, **kw): """Return font metrics. For best performance, create a dummy widget using this font before calling this method.""" args = () displayof = kw.pop('displayof', None) if displayof: args = ('-displayof', displayof) if options: args = args + self._get(options) return self._tk.getint( self._call("font", "metrics", self.name, *args)) else: res = self._split(self._call("font", "metrics", self.name, *args)) options = {} for i in range(0, len(res), 2): options[res[i][1:]] = self._tk.getint(res[i+1]) return options def families(root=None, displayof=None): "Get font families (as a tuple)" if not root: root = tkinter._default_root args = () if displayof: args = ('-displayof', displayof) return root.tk.splitlist(root.tk.call("font", "families", *args)) def names(root=None): "Get names of defined fonts (as a tuple)" if not root: root = tkinter._default_root return root.tk.splitlist(root.tk.call("font", "names")) # -------------------------------------------------------------------- # test stuff if __name__ == "__main__": root = tkinter.Tk() # create a font f = Font(family="times", size=30, weight=NORMAL) print(f.actual()) print(f.actual("family")) print(f.actual("weight")) print(f.config()) print(f.cget("family")) print(f.cget("weight")) print(names()) print(f.measure("hello"), f.metrics("linespace")) print(f.metrics(displayof=root)) f = Font(font=("Courier", 20, "bold")) print(f.measure("hello"), f.metrics("linespace", displayof=root)) w = tkinter.Label(root, text="Hello, world", font=f) w.pack() w = tkinter.Button(root, text="Quit!", command=root.destroy) w.pack() fb = Font(font=w["font"]).copy() fb.config(weight=BOLD) w.config(font=fb) tkinter.mainloop()
6,581
233
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/filedialog.py
"""File selection dialog classes. Classes: - FileDialog - LoadFileDialog - SaveFileDialog This module also presents tk common file dialogues, it provides interfaces to the native file dialogues available in Tk 4.2 and newer, and the directory dialogue available in Tk 8.3 and newer. These interfaces were written by Fredrik Lundh, May 1997. """ from tkinter import * from tkinter.dialog import Dialog from tkinter import commondialog import os import fnmatch dialogstates = {} class FileDialog: """Standard file selection dialog -- no checks on selected file. Usage: d = FileDialog(master) fname = d.go(dir_or_file, pattern, default, key) if fname is None: ...canceled... else: ...open file... All arguments to go() are optional. The 'key' argument specifies a key in the global dictionary 'dialogstates', which keeps track of the values for the directory and pattern arguments, overriding the values passed in (it does not keep track of the default argument!). If no key is specified, the dialog keeps no memory of previous state. Note that memory is kept even when the dialog is canceled. (All this emulates the behavior of the Macintosh file selection dialogs.) """ title = "File Selection Dialog" def __init__(self, master, title=None): if title is None: title = self.title self.master = master self.directory = None self.top = Toplevel(master) self.top.title(title) self.top.iconname(title) self.botframe = Frame(self.top) self.botframe.pack(side=BOTTOM, fill=X) self.selection = Entry(self.top) self.selection.pack(side=BOTTOM, fill=X) self.selection.bind('<Return>', self.ok_event) self.filter = Entry(self.top) self.filter.pack(side=TOP, fill=X) self.filter.bind('<Return>', self.filter_command) self.midframe = Frame(self.top) self.midframe.pack(expand=YES, fill=BOTH) self.filesbar = Scrollbar(self.midframe) self.filesbar.pack(side=RIGHT, fill=Y) self.files = Listbox(self.midframe, exportselection=0, yscrollcommand=(self.filesbar, 'set')) self.files.pack(side=RIGHT, expand=YES, fill=BOTH) btags = self.files.bindtags() self.files.bindtags(btags[1:] + btags[:1]) self.files.bind('<ButtonRelease-1>', self.files_select_event) self.files.bind('<Double-ButtonRelease-1>', self.files_double_event) self.filesbar.config(command=(self.files, 'yview')) self.dirsbar = Scrollbar(self.midframe) self.dirsbar.pack(side=LEFT, fill=Y) self.dirs = Listbox(self.midframe, exportselection=0, yscrollcommand=(self.dirsbar, 'set')) self.dirs.pack(side=LEFT, expand=YES, fill=BOTH) self.dirsbar.config(command=(self.dirs, 'yview')) btags = self.dirs.bindtags() self.dirs.bindtags(btags[1:] + btags[:1]) self.dirs.bind('<ButtonRelease-1>', self.dirs_select_event) self.dirs.bind('<Double-ButtonRelease-1>', self.dirs_double_event) self.ok_button = Button(self.botframe, text="OK", command=self.ok_command) self.ok_button.pack(side=LEFT) self.filter_button = Button(self.botframe, text="Filter", command=self.filter_command) self.filter_button.pack(side=LEFT, expand=YES) self.cancel_button = Button(self.botframe, text="Cancel", command=self.cancel_command) self.cancel_button.pack(side=RIGHT) self.top.protocol('WM_DELETE_WINDOW', self.cancel_command) # XXX Are the following okay for a general audience? self.top.bind('<Alt-w>', self.cancel_command) self.top.bind('<Alt-W>', self.cancel_command) def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None): if key and key in dialogstates: self.directory, pattern = dialogstates[key] else: dir_or_file = os.path.expanduser(dir_or_file) if os.path.isdir(dir_or_file): self.directory = dir_or_file else: self.directory, default = os.path.split(dir_or_file) self.set_filter(self.directory, pattern) self.set_selection(default) self.filter_command() self.selection.focus_set() self.top.wait_visibility() # window needs to be visible for the grab self.top.grab_set() self.how = None self.master.mainloop() # Exited by self.quit(how) if key: directory, pattern = self.get_filter() if self.how: directory = os.path.dirname(self.how) dialogstates[key] = directory, pattern self.top.destroy() return self.how def quit(self, how=None): self.how = how self.master.quit() # Exit mainloop() def dirs_double_event(self, event): self.filter_command() def dirs_select_event(self, event): dir, pat = self.get_filter() subdir = self.dirs.get('active') dir = os.path.normpath(os.path.join(self.directory, subdir)) self.set_filter(dir, pat) def files_double_event(self, event): self.ok_command() def files_select_event(self, event): file = self.files.get('active') self.set_selection(file) def ok_event(self, event): self.ok_command() def ok_command(self): self.quit(self.get_selection()) def filter_command(self, event=None): dir, pat = self.get_filter() try: names = os.listdir(dir) except OSError: self.master.bell() return self.directory = dir self.set_filter(dir, pat) names.sort() subdirs = [os.pardir] matchingfiles = [] for name in names: fullname = os.path.join(dir, name) if os.path.isdir(fullname): subdirs.append(name) elif fnmatch.fnmatch(name, pat): matchingfiles.append(name) self.dirs.delete(0, END) for name in subdirs: self.dirs.insert(END, name) self.files.delete(0, END) for name in matchingfiles: self.files.insert(END, name) head, tail = os.path.split(self.get_selection()) if tail == os.curdir: tail = '' self.set_selection(tail) def get_filter(self): filter = self.filter.get() filter = os.path.expanduser(filter) if filter[-1:] == os.sep or os.path.isdir(filter): filter = os.path.join(filter, "*") return os.path.split(filter) def get_selection(self): file = self.selection.get() file = os.path.expanduser(file) return file def cancel_command(self, event=None): self.quit() def set_filter(self, dir, pat): if not os.path.isabs(dir): try: pwd = os.getcwd() except OSError: pwd = None if pwd: dir = os.path.join(pwd, dir) dir = os.path.normpath(dir) self.filter.delete(0, END) self.filter.insert(END, os.path.join(dir or os.curdir, pat or "*")) def set_selection(self, file): self.selection.delete(0, END) self.selection.insert(END, os.path.join(self.directory, file)) class LoadFileDialog(FileDialog): """File selection dialog which checks that the file exists.""" title = "Load File Selection Dialog" def ok_command(self): file = self.get_selection() if not os.path.isfile(file): self.master.bell() else: self.quit(file) class SaveFileDialog(FileDialog): """File selection dialog which checks that the file may be created.""" title = "Save File Selection Dialog" def ok_command(self): file = self.get_selection() if os.path.exists(file): if os.path.isdir(file): self.master.bell() return d = Dialog(self.top, title="Overwrite Existing File Question", text="Overwrite existing file %r?" % (file,), bitmap='questhead', default=1, strings=("Yes", "Cancel")) if d.num != 0: return else: head, tail = os.path.split(file) if not os.path.isdir(head): self.master.bell() return self.quit(file) # For the following classes and modules: # # options (all have default values): # # - defaultextension: added to filename if not explicitly given # # - filetypes: sequence of (label, pattern) tuples. the same pattern # may occur with several patterns. use "*" as pattern to indicate # all files. # # - initialdir: initial directory. preserved by dialog instance. # # - initialfile: initial file (ignored by the open dialog). preserved # by dialog instance. # # - parent: which window to place the dialog on top of # # - title: dialog title # # - multiple: if true user may select more than one file # # options for the directory chooser: # # - initialdir, parent, title: see above # # - mustexist: if true, user must pick an existing directory # class _Dialog(commondialog.Dialog): def _fixoptions(self): try: # make sure "filetypes" is a tuple self.options["filetypes"] = tuple(self.options["filetypes"]) except KeyError: pass def _fixresult(self, widget, result): if result: # keep directory and filename until next time # convert Tcl path objects to strings try: result = result.string except AttributeError: # it already is a string pass path, file = os.path.split(result) self.options["initialdir"] = path self.options["initialfile"] = file self.filename = result # compatibility return result # # file dialogs class Open(_Dialog): "Ask for a filename to open" command = "tk_getOpenFile" def _fixresult(self, widget, result): if isinstance(result, tuple): # multiple results: result = tuple([getattr(r, "string", r) for r in result]) if result: path, file = os.path.split(result[0]) self.options["initialdir"] = path # don't set initialfile or filename, as we have multiple of these return result if not widget.tk.wantobjects() and "multiple" in self.options: # Need to split result explicitly return self._fixresult(widget, widget.tk.splitlist(result)) return _Dialog._fixresult(self, widget, result) class SaveAs(_Dialog): "Ask for a filename to save as" command = "tk_getSaveFile" # the directory dialog has its own _fix routines. class Directory(commondialog.Dialog): "Ask for a directory" command = "tk_chooseDirectory" def _fixresult(self, widget, result): if result: # convert Tcl path objects to strings try: result = result.string except AttributeError: # it already is a string pass # keep directory until next time self.options["initialdir"] = result self.directory = result # compatibility return result # # convenience stuff def askopenfilename(**options): "Ask for a filename to open" return Open(**options).show() def asksaveasfilename(**options): "Ask for a filename to save as" return SaveAs(**options).show() def askopenfilenames(**options): """Ask for multiple filenames to open Returns a list of filenames or empty list if cancel button selected """ options["multiple"]=1 return Open(**options).show() # FIXME: are the following perhaps a bit too convenient? def askopenfile(mode = "r", **options): "Ask for a filename to open, and returned the opened file" filename = Open(**options).show() if filename: return open(filename, mode) return None def askopenfiles(mode = "r", **options): """Ask for multiple filenames and return the open file objects returns a list of open file objects or an empty list if cancel selected """ files = askopenfilenames(**options) if files: ofiles=[] for filename in files: ofiles.append(open(filename, mode)) files=ofiles return files def asksaveasfile(mode = "w", **options): "Ask for a filename to save as, and returned the opened file" filename = SaveAs(**options).show() if filename: return open(filename, mode) return None def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show() # -------------------------------------------------------------------- # test stuff def test(): """Simple test program.""" root = Tk() root.withdraw() fd = LoadFileDialog(root) loadfile = fd.go(key="test") fd = SaveFileDialog(root) savefile = fd.go(key="test") print(loadfile, savefile) # Since the file name may contain non-ASCII characters, we need # to find an encoding that likely supports the file name, and # displays correctly on the terminal. # Start off with UTF-8 enc = "utf-8" import sys # See whether CODESET is defined try: import locale locale.setlocale(locale.LC_ALL,'') enc = locale.nl_langinfo(locale.CODESET) except (ImportError, AttributeError): pass # dialog for openening files openfilename=askopenfilename(filetypes=[("all files", "*")]) try: fp=open(openfilename,"r") fp.close() except: print("Could not open File: ") print(sys.exc_info()[1]) print("open", openfilename.encode(enc)) # dialog for saving files saveasfilename=asksaveasfilename() print("saveas", saveasfilename.encode(enc)) if __name__ == '__main__': test()
14,502
480
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/ttk.py
"""Ttk wrapper. This module provides classes to allow using Tk themed widget set. Ttk is based on a revised and enhanced version of TIP #48 (http://tip.tcl.tk/48) specified style engine. Its basic idea is to separate, to the extent possible, the code implementing a widget's behavior from the code implementing its appearance. Widget class bindings are primarily responsible for maintaining the widget state and invoking callbacks, all aspects of the widgets appearance lies at Themes. """ __version__ = "0.3.1" __author__ = "Guilherme Polo <[email protected]>" __all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label", "Labelframe", "LabelFrame", "Menubutton", "Notebook", "Panedwindow", "PanedWindow", "Progressbar", "Radiobutton", "Scale", "Scrollbar", "Separator", "Sizegrip", "Style", "Treeview", # Extensions "LabeledScale", "OptionMenu", # functions "tclobjs_to_py", "setup_master"] import tkinter from tkinter import _flatten, _join, _stringify, _splitdict _sentinel = object() # Verify if Tk is new enough to not need the Tile package _REQUIRE_TILE = True if tkinter.TkVersion < 8.5 else False def _load_tile(master): if _REQUIRE_TILE: import os tilelib = os.environ.get('TILE_LIBRARY') if tilelib: # append custom tile path to the list of directories that # Tcl uses when attempting to resolve packages with the package # command master.tk.eval( 'global auto_path; ' 'lappend auto_path {%s}' % tilelib) master.tk.eval('package require tile') # TclError may be raised here master._tile_loaded = True def _format_optvalue(value, script=False): """Internal function.""" if script: # if caller passes a Tcl script to tk.call, all the values need to # be grouped into words (arguments to a command in Tcl dialect) value = _stringify(value) elif isinstance(value, (list, tuple)): value = _join(value) return value def _format_optdict(optdict, script=False, ignore=None): """Formats optdict to a tuple to pass it to tk.call. E.g. (script=False): {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns: ('-foreground', 'blue', '-padding', '1 2 3 4')""" opts = [] for opt, value in optdict.items(): if not ignore or opt not in ignore: opts.append("-%s" % opt) if value is not None: opts.append(_format_optvalue(value, script)) return _flatten(opts) def _mapdict_values(items): # each value in mapdict is expected to be a sequence, where each item # is another sequence containing a state (or several) and a value # E.g. (script=False): # [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])] # returns: # ['active selected', 'grey', 'focus', [1, 2, 3, 4]] opt_val = [] for *state, val in items: # hacks for backward compatibility state[0] # raise IndexError if empty if len(state) == 1: # if it is empty (something that evaluates to False), then # format it to Tcl code to denote the "normal" state state = state[0] or '' else: # group multiple states state = ' '.join(state) # raise TypeError if not str opt_val.append(state) if val is not None: opt_val.append(val) return opt_val def _format_mapdict(mapdict, script=False): """Formats mapdict to pass it to tk.call. E.g. (script=False): {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]} returns: ('-expand', '{active selected} grey focus {1, 2, 3, 4}')""" opts = [] for opt, value in mapdict.items(): opts.extend(("-%s" % opt, _format_optvalue(_mapdict_values(value), script))) return _flatten(opts) def _format_elemcreate(etype, script=False, *args, **kw): """Formats args and kw according to the given element factory etype.""" spec = None opts = () if etype in ("image", "vsapi"): if etype == "image": # define an element based on an image # first arg should be the default image name iname = args[0] # next args, if any, are statespec/value pairs which is almost # a mapdict, but we just need the value imagespec = _join(_mapdict_values(args[1:])) spec = "%s %s" % (iname, imagespec) else: # define an element whose visual appearance is drawn using the # Microsoft Visual Styles API which is responsible for the # themed styles on Windows XP and Vista. # Availability: Tk 8.6, Windows XP and Vista. class_name, part_id = args[:2] statemap = _join(_mapdict_values(args[2:])) spec = "%s %s %s" % (class_name, part_id, statemap) opts = _format_optdict(kw, script) elif etype == "from": # clone an element # it expects a themename and optionally an element to clone from, # otherwise it will clone {} (empty element) spec = args[0] # theme name if len(args) > 1: # elementfrom specified opts = (_format_optvalue(args[1], script),) if script: spec = '{%s}' % spec opts = ' '.join(opts) return spec, opts def _format_layoutlist(layout, indent=0, indent_size=2): """Formats a layout list so we can pass the result to ttk::style layout and ttk::style settings. Note that the layout doesn't have to be a list necessarily. E.g.: [("Menubutton.background", None), ("Menubutton.button", {"children": [("Menubutton.focus", {"children": [("Menubutton.padding", {"children": [("Menubutton.label", {"side": "left", "expand": 1})] })] })] }), ("Menubutton.indicator", {"side": "right"}) ] returns: Menubutton.background Menubutton.button -children { Menubutton.focus -children { Menubutton.padding -children { Menubutton.label -side left -expand 1 } } } Menubutton.indicator -side right""" script = [] for layout_elem in layout: elem, opts = layout_elem opts = opts or {} fopts = ' '.join(_format_optdict(opts, True, ("children",))) head = "%s%s%s" % (' ' * indent, elem, (" %s" % fopts) if fopts else '') if "children" in opts: script.append(head + " -children {") indent += indent_size newscript, indent = _format_layoutlist(opts['children'], indent, indent_size) script.append(newscript) indent -= indent_size script.append('%s}' % (' ' * indent)) else: script.append(head) return '\n'.join(script), indent def _script_from_settings(settings): """Returns an appropriate script, based on settings, according to theme_settings definition to be used by theme_settings and theme_create.""" script = [] # a script will be generated according to settings passed, which # will then be evaluated by Tcl for name, opts in settings.items(): # will format specific keys according to Tcl code if opts.get('configure'): # format 'configure' s = ' '.join(_format_optdict(opts['configure'], True)) script.append("ttk::style configure %s %s;" % (name, s)) if opts.get('map'): # format 'map' s = ' '.join(_format_mapdict(opts['map'], True)) script.append("ttk::style map %s %s;" % (name, s)) if 'layout' in opts: # format 'layout' which may be empty if not opts['layout']: s = 'null' # could be any other word, but this one makes sense else: s, _ = _format_layoutlist(opts['layout']) script.append("ttk::style layout %s {\n%s\n}" % (name, s)) if opts.get('element create'): # format 'element create' eopts = opts['element create'] etype = eopts[0] # find where args end, and where kwargs start argc = 1 # etype was the first one while argc < len(eopts) and not hasattr(eopts[argc], 'items'): argc += 1 elemargs = eopts[1:argc] elemkw = eopts[argc] if argc < len(eopts) and eopts[argc] else {} spec, opts = _format_elemcreate(etype, True, *elemargs, **elemkw) script.append("ttk::style element create %s %s %s %s" % ( name, etype, spec, opts)) return '\n'.join(script) def _list_from_statespec(stuple): """Construct a list from the given statespec tuple according to the accepted statespec accepted by _format_mapdict.""" nval = [] for val in stuple: typename = getattr(val, 'typename', None) if typename is None: nval.append(val) else: # this is a Tcl object val = str(val) if typename == 'StateSpec': val = val.split() nval.append(val) it = iter(nval) return [_flatten(spec) for spec in zip(it, it)] def _list_from_layouttuple(tk, ltuple): """Construct a list from the tuple returned by ttk::layout, this is somewhat the reverse of _format_layoutlist.""" ltuple = tk.splitlist(ltuple) res = [] indx = 0 while indx < len(ltuple): name = ltuple[indx] opts = {} res.append((name, opts)) indx += 1 while indx < len(ltuple): # grab name's options opt, val = ltuple[indx:indx + 2] if not opt.startswith('-'): # found next name break opt = opt[1:] # remove the '-' from the option indx += 2 if opt == 'children': val = _list_from_layouttuple(tk, val) opts[opt] = val return res def _val_or_dict(tk, options, *args): """Format options then call Tk command with args and options and return the appropriate result. If no option is specified, a dict is returned. If an option is specified with the None value, the value for that option is returned. Otherwise, the function just sets the passed options and the caller shouldn't be expecting a return value anyway.""" options = _format_optdict(options) res = tk.call(*(args + options)) if len(options) % 2: # option specified without a value, return its value return res return _splitdict(tk, res, conv=_tclobj_to_py) def _convert_stringval(value): """Converts a value to, hopefully, a more appropriate Python object.""" value = str(value) try: value = int(value) except (ValueError, TypeError): pass return value def _to_number(x): if isinstance(x, str): if '.' in x: x = float(x) else: x = int(x) return x def _tclobj_to_py(val): """Return value converted from Tcl object to Python object.""" if val and hasattr(val, '__len__') and not isinstance(val, str): if getattr(val[0], 'typename', None) == 'StateSpec': val = _list_from_statespec(val) else: val = list(map(_convert_stringval, val)) elif hasattr(val, 'typename'): # some other (single) Tcl object val = _convert_stringval(val) return val def tclobjs_to_py(adict): """Returns adict with its values converted from Tcl objects to Python objects.""" for opt, val in adict.items(): adict[opt] = _tclobj_to_py(val) return adict def setup_master(master=None): """If master is not None, itself is returned. If master is None, the default master is returned if there is one, otherwise a new master is created and returned. If it is not allowed to use the default root and master is None, RuntimeError is raised.""" if master is None: if tkinter._support_default_root: master = tkinter._default_root or tkinter.Tk() else: raise RuntimeError( "No master specified and tkinter is " "configured to not support default root") return master class Style(object): """Manipulate style database.""" _name = "ttk::style" def __init__(self, master=None): master = setup_master(master) if not getattr(master, '_tile_loaded', False): # Load tile now, if needed _load_tile(master) self.master = master self.tk = self.master.tk def configure(self, style, query_opt=None, **kw): """Query or sets the default value of the specified option(s) in style. Each key in kw is an option and each value is either a string or a sequence identifying the value for that option.""" if query_opt is not None: kw[query_opt] = None result = _val_or_dict(self.tk, kw, self._name, "configure", style) if result or query_opt: return result def map(self, style, query_opt=None, **kw): """Query or sets dynamic values of the specified option(s) in style. Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, or list, or something else of your preference. A statespec is compound of one or more states and then a value.""" if query_opt is not None: return _list_from_statespec(self.tk.splitlist( self.tk.call(self._name, "map", style, '-%s' % query_opt))) return _splitdict( self.tk, self.tk.call(self._name, "map", style, *_format_mapdict(kw)), conv=_tclobj_to_py) def lookup(self, style, option, state=None, default=None): """Returns the value specified for option in style. If state is specified it is expected to be a sequence of one or more states. If the default argument is set, it is used as a fallback value in case no specification for option is found.""" state = ' '.join(state) if state else '' return self.tk.call(self._name, "lookup", style, '-%s' % option, state, default) def layout(self, style, layoutspec=None): """Define the widget layout for given style. If layoutspec is omitted, return the layout specification for given style. layoutspec is expected to be a list or an object different than None that evaluates to False if you want to "turn off" that style. If it is a list (or tuple, or something else), each item should be a tuple where the first item is the layout name and the second item should have the format described below: LAYOUTS A layout can contain the value None, if takes no options, or a dict of options specifying how to arrange the element. The layout mechanism uses a simplified version of the pack geometry manager: given an initial cavity, each element is allocated a parcel. Valid options/values are: side: whichside Specifies which side of the cavity to place the element; one of top, right, bottom or left. If omitted, the element occupies the entire cavity. sticky: nswe Specifies where the element is placed inside its allocated parcel. children: [sublayout... ] Specifies a list of elements to place inside the element. Each element is a tuple (or other sequence) where the first item is the layout name, and the other is a LAYOUT.""" lspec = None if layoutspec: lspec = _format_layoutlist(layoutspec)[0] elif layoutspec is not None: # will disable the layout ({}, '', etc) lspec = "null" # could be any other word, but this may make sense # when calling layout(style) later return _list_from_layouttuple(self.tk, self.tk.call(self._name, "layout", style, lspec)) def element_create(self, elementname, etype, *args, **kw): """Create a new element in the current theme of given etype.""" spec, opts = _format_elemcreate(etype, False, *args, **kw) self.tk.call(self._name, "element", "create", elementname, etype, spec, *opts) def element_names(self): """Returns the list of elements defined in the current theme.""" return tuple(n.lstrip('-') for n in self.tk.splitlist( self.tk.call(self._name, "element", "names"))) def element_options(self, elementname): """Return the list of elementname's options.""" return tuple(o.lstrip('-') for o in self.tk.splitlist( self.tk.call(self._name, "element", "options", elementname))) def theme_create(self, themename, parent=None, settings=None): """Creates a new theme. It is an error if themename already exists. If parent is specified, the new theme will inherit styles, elements and layouts from the specified parent theme. If settings are present, they are expected to have the same syntax used for theme_settings.""" script = _script_from_settings(settings) if settings else '' if parent: self.tk.call(self._name, "theme", "create", themename, "-parent", parent, "-settings", script) else: self.tk.call(self._name, "theme", "create", themename, "-settings", script) def theme_settings(self, themename, settings): """Temporarily sets the current theme to themename, apply specified settings and then restore the previous theme. Each key in settings is a style and each value may contain the keys 'configure', 'map', 'layout' and 'element create' and they are expected to have the same format as specified by the methods configure, map, layout and element_create respectively.""" script = _script_from_settings(settings) self.tk.call(self._name, "theme", "settings", themename, script) def theme_names(self): """Returns a list of all known themes.""" return self.tk.splitlist(self.tk.call(self._name, "theme", "names")) def theme_use(self, themename=None): """If themename is None, returns the theme in use, otherwise, set the current theme to themename, refreshes all widgets and emits a <<ThemeChanged>> event.""" if themename is None: # Starting on Tk 8.6, checking this global is no longer needed # since it allows doing self.tk.call(self._name, "theme", "use") return self.tk.eval("return $ttk::currentTheme") # using "ttk::setTheme" instead of "ttk::style theme use" causes # the variable currentTheme to be updated, also, ttk::setTheme calls # "ttk::style theme use" in order to change theme. self.tk.call("ttk::setTheme", themename) class Widget(tkinter.Widget): """Base class for Tk themed widgets.""" def __init__(self, master, widgetname, kw=None): """Constructs a Ttk Widget with the parent master. STANDARD OPTIONS class, cursor, takefocus, style SCROLLABLE WIDGET OPTIONS xscrollcommand, yscrollcommand LABEL WIDGET OPTIONS text, textvariable, underline, image, compound, width WIDGET STATES active, disabled, focus, pressed, selected, background, readonly, alternate, invalid """ master = setup_master(master) if not getattr(master, '_tile_loaded', False): # Load tile now, if needed _load_tile(master) tkinter.Widget.__init__(self, master, widgetname, kw=kw) def identify(self, x, y): """Returns the name of the element at position x, y, or the empty string if the point does not lie within any element. x and y are pixel coordinates relative to the widget.""" return self.tk.call(self._w, "identify", x, y) def instate(self, statespec, callback=None, *args, **kw): """Test the widget's state. If callback is not specified, returns True if the widget state matches statespec and False otherwise. If callback is specified, then it will be invoked with *args, **kw if the widget state matches statespec. statespec is expected to be a sequence.""" ret = self.tk.getboolean( self.tk.call(self._w, "instate", ' '.join(statespec))) if ret and callback: return callback(*args, **kw) return ret def state(self, statespec=None): """Modify or inquire widget state. Widget state is returned if statespec is None, otherwise it is set according to the statespec flags and then a new state spec is returned indicating which flags were changed. statespec is expected to be a sequence.""" if statespec is not None: statespec = ' '.join(statespec) return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec))) class Button(Widget): """Ttk Button widget, displays a textual label and/or image, and evaluates a command when pressed.""" def __init__(self, master=None, **kw): """Construct a Ttk Button widget with the parent master. STANDARD OPTIONS class, compound, cursor, image, state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS command, default, width """ Widget.__init__(self, master, "ttk::button", kw) def invoke(self): """Invokes the command associated with the button.""" return self.tk.call(self._w, "invoke") class Checkbutton(Widget): """Ttk Checkbutton widget which is either in on- or off-state.""" def __init__(self, master=None, **kw): """Construct a Ttk Checkbutton widget with the parent master. STANDARD OPTIONS class, compound, cursor, image, state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS command, offvalue, onvalue, variable """ Widget.__init__(self, master, "ttk::checkbutton", kw) def invoke(self): """Toggles between the selected and deselected states and invokes the associated command. If the widget is currently selected, sets the option variable to the offvalue option and deselects the widget; otherwise, sets the option variable to the option onvalue. Returns the result of the associated command.""" return self.tk.call(self._w, "invoke") class Entry(Widget, tkinter.Entry): """Ttk Entry widget displays a one-line text string and allows that string to be edited by the user.""" def __init__(self, master=None, widget=None, **kw): """Constructs a Ttk Entry widget with the parent master. STANDARD OPTIONS class, cursor, style, takefocus, xscrollcommand WIDGET-SPECIFIC OPTIONS exportselection, invalidcommand, justify, show, state, textvariable, validate, validatecommand, width VALIDATION MODES none, key, focus, focusin, focusout, all """ Widget.__init__(self, master, widget or "ttk::entry", kw) def bbox(self, index): """Return a tuple of (x, y, width, height) which describes the bounding box of the character given by index.""" return self._getints(self.tk.call(self._w, "bbox", index)) def identify(self, x, y): """Returns the name of the element at position x, y, or the empty string if the coordinates are outside the window.""" return self.tk.call(self._w, "identify", x, y) def validate(self): """Force revalidation, independent of the conditions specified by the validate option. Returns False if validation fails, True if it succeeds. Sets or clears the invalid state accordingly.""" return self.tk.getboolean(self.tk.call(self._w, "validate")) class Combobox(Entry): """Ttk Combobox widget combines a text field with a pop-down list of values.""" def __init__(self, master=None, **kw): """Construct a Ttk Combobox widget with the parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS exportselection, justify, height, postcommand, state, textvariable, values, width """ Entry.__init__(self, master, "ttk::combobox", **kw) def current(self, newindex=None): """If newindex is supplied, sets the combobox value to the element at position newindex in the list of values. Otherwise, returns the index of the current value in the list of values or -1 if the current value does not appear in the list.""" if newindex is None: return self.tk.getint(self.tk.call(self._w, "current")) return self.tk.call(self._w, "current", newindex) def set(self, value): """Sets the value of the combobox to value.""" self.tk.call(self._w, "set", value) class Frame(Widget): """Ttk Frame widget is a container, used to group other widgets together.""" def __init__(self, master=None, **kw): """Construct a Ttk Frame with parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS borderwidth, relief, padding, width, height """ Widget.__init__(self, master, "ttk::frame", kw) class Label(Widget): """Ttk Label widget displays a textual label and/or image.""" def __init__(self, master=None, **kw): """Construct a Ttk Label with parent master. STANDARD OPTIONS class, compound, cursor, image, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS anchor, background, font, foreground, justify, padding, relief, text, wraplength """ Widget.__init__(self, master, "ttk::label", kw) class Labelframe(Widget): """Ttk Labelframe widget is a container used to group other widgets together. It has an optional label, which may be a plain text string or another widget.""" def __init__(self, master=None, **kw): """Construct a Ttk Labelframe with parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS labelanchor, text, underline, padding, labelwidget, width, height """ Widget.__init__(self, master, "ttk::labelframe", kw) LabelFrame = Labelframe # tkinter name compatibility class Menubutton(Widget): """Ttk Menubutton widget displays a textual label and/or image, and displays a menu when pressed.""" def __init__(self, master=None, **kw): """Construct a Ttk Menubutton with parent master. STANDARD OPTIONS class, compound, cursor, image, state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS direction, menu """ Widget.__init__(self, master, "ttk::menubutton", kw) class Notebook(Widget): """Ttk Notebook widget manages a collection of windows and displays a single one at a time. Each child window is associated with a tab, which the user may select to change the currently-displayed window.""" def __init__(self, master=None, **kw): """Construct a Ttk Notebook with parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS height, padding, width TAB OPTIONS state, sticky, padding, text, image, compound, underline TAB IDENTIFIERS (tab_id) The tab_id argument found in several methods may take any of the following forms: * An integer between zero and the number of tabs * The name of a child window * A positional specification of the form "@x,y", which defines the tab * The string "current", which identifies the currently-selected tab * The string "end", which returns the number of tabs (only valid for method index) """ Widget.__init__(self, master, "ttk::notebook", kw) def add(self, child, **kw): """Adds a new tab to the notebook. If window is currently managed by the notebook but hidden, it is restored to its previous position.""" self.tk.call(self._w, "add", child, *(_format_optdict(kw))) def forget(self, tab_id): """Removes the tab specified by tab_id, unmaps and unmanages the associated window.""" self.tk.call(self._w, "forget", tab_id) def hide(self, tab_id): """Hides the tab specified by tab_id. The tab will not be displayed, but the associated window remains managed by the notebook and its configuration remembered. Hidden tabs may be restored with the add command.""" self.tk.call(self._w, "hide", tab_id) def identify(self, x, y): """Returns the name of the tab element at position x, y, or the empty string if none.""" return self.tk.call(self._w, "identify", x, y) def index(self, tab_id): """Returns the numeric index of the tab specified by tab_id, or the total number of tabs if tab_id is the string "end".""" return self.tk.getint(self.tk.call(self._w, "index", tab_id)) def insert(self, pos, child, **kw): """Inserts a pane at the specified position. pos is either the string end, an integer index, or the name of a managed child. If child is already managed by the notebook, moves it to the specified position.""" self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw))) def select(self, tab_id=None): """Selects the specified tab. The associated child window will be displayed, and the previously-selected window (if different) is unmapped. If tab_id is omitted, returns the widget name of the currently selected pane.""" return self.tk.call(self._w, "select", tab_id) def tab(self, tab_id, option=None, **kw): """Query or modify the options of the specific tab_id. If kw is not given, returns a dict of the tab option values. If option is specified, returns the value of that option. Otherwise, sets the options to the corresponding values.""" if option is not None: kw[option] = None return _val_or_dict(self.tk, kw, self._w, "tab", tab_id) def tabs(self): """Returns a list of windows managed by the notebook.""" return self.tk.splitlist(self.tk.call(self._w, "tabs") or ()) def enable_traversal(self): """Enable keyboard traversal for a toplevel window containing this notebook. This will extend the bindings for the toplevel window containing this notebook as follows: Control-Tab: selects the tab following the currently selected one Shift-Control-Tab: selects the tab preceding the currently selected one Alt-K: where K is the mnemonic (underlined) character of any tab, will select that tab. Multiple notebooks in a single toplevel may be enabled for traversal, including nested notebooks. However, notebook traversal only works properly if all panes are direct children of the notebook.""" # The only, and good, difference I see is about mnemonics, which works # after calling this method. Control-Tab and Shift-Control-Tab always # works (here at least). self.tk.call("ttk::notebook::enableTraversal", self._w) class Panedwindow(Widget, tkinter.PanedWindow): """Ttk Panedwindow widget displays a number of subwindows, stacked either vertically or horizontally.""" def __init__(self, master=None, **kw): """Construct a Ttk Panedwindow with parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS orient, width, height PANE OPTIONS weight """ Widget.__init__(self, master, "ttk::panedwindow", kw) forget = tkinter.PanedWindow.forget # overrides Pack.forget def insert(self, pos, child, **kw): """Inserts a pane at the specified positions. pos is either the string end, and integer index, or the name of a child. If child is already managed by the paned window, moves it to the specified position.""" self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw))) def pane(self, pane, option=None, **kw): """Query or modify the options of the specified pane. pane is either an integer index or the name of a managed subwindow. If kw is not given, returns a dict of the pane option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.""" if option is not None: kw[option] = None return _val_or_dict(self.tk, kw, self._w, "pane", pane) def sashpos(self, index, newpos=None): """If newpos is specified, sets the position of sash number index. May adjust the positions of adjacent sashes to ensure that positions are monotonically increasing. Sash positions are further constrained to be between 0 and the total size of the widget. Returns the new position of sash number index.""" return self.tk.getint(self.tk.call(self._w, "sashpos", index, newpos)) PanedWindow = Panedwindow # tkinter name compatibility class Progressbar(Widget): """Ttk Progressbar widget shows the status of a long-running operation. They can operate in two modes: determinate mode shows the amount completed relative to the total amount of work to be done, and indeterminate mode provides an animated display to let the user know that something is happening.""" def __init__(self, master=None, **kw): """Construct a Ttk Progressbar with parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS orient, length, mode, maximum, value, variable, phase """ Widget.__init__(self, master, "ttk::progressbar", kw) def start(self, interval=None): """Begin autoincrement mode: schedules a recurring timer event that calls method step every interval milliseconds. interval defaults to 50 milliseconds (20 steps/second) if omitted.""" self.tk.call(self._w, "start", interval) def step(self, amount=None): """Increments the value option by amount. amount defaults to 1.0 if omitted.""" self.tk.call(self._w, "step", amount) def stop(self): """Stop autoincrement mode: cancels any recurring timer event initiated by start.""" self.tk.call(self._w, "stop") class Radiobutton(Widget): """Ttk Radiobutton widgets are used in groups to show or change a set of mutually-exclusive options.""" def __init__(self, master=None, **kw): """Construct a Ttk Radiobutton with parent master. STANDARD OPTIONS class, compound, cursor, image, state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS command, value, variable """ Widget.__init__(self, master, "ttk::radiobutton", kw) def invoke(self): """Sets the option variable to the option value, selects the widget, and invokes the associated command. Returns the result of the command, or an empty string if no command is specified.""" return self.tk.call(self._w, "invoke") class Scale(Widget, tkinter.Scale): """Ttk Scale widget is typically used to control the numeric value of a linked variable that varies uniformly over some range.""" def __init__(self, master=None, **kw): """Construct a Ttk Scale with parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS command, from, length, orient, to, value, variable """ Widget.__init__(self, master, "ttk::scale", kw) def configure(self, cnf=None, **kw): """Modify or query scale options. Setting a value for any of the "from", "from_" or "to" options generates a <<RangeChanged>> event.""" if cnf: kw.update(cnf) Widget.configure(self, **kw) if any(['from' in kw, 'from_' in kw, 'to' in kw]): self.event_generate('<<RangeChanged>>') def get(self, x=None, y=None): """Get the current value of the value option, or the value corresponding to the coordinates x, y if they are specified. x and y are pixel coordinates relative to the scale widget origin.""" return self.tk.call(self._w, 'get', x, y) class Scrollbar(Widget, tkinter.Scrollbar): """Ttk Scrollbar controls the viewport of a scrollable widget.""" def __init__(self, master=None, **kw): """Construct a Ttk Scrollbar with parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS command, orient """ Widget.__init__(self, master, "ttk::scrollbar", kw) class Separator(Widget): """Ttk Separator widget displays a horizontal or vertical separator bar.""" def __init__(self, master=None, **kw): """Construct a Ttk Separator with parent master. STANDARD OPTIONS class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS orient """ Widget.__init__(self, master, "ttk::separator", kw) class Sizegrip(Widget): """Ttk Sizegrip allows the user to resize the containing toplevel window by pressing and dragging the grip.""" def __init__(self, master=None, **kw): """Construct a Ttk Sizegrip with parent master. STANDARD OPTIONS class, cursor, state, style, takefocus """ Widget.__init__(self, master, "ttk::sizegrip", kw) class Treeview(Widget, tkinter.XView, tkinter.YView): """Ttk Treeview widget displays a hierarchical collection of items. Each item has a textual label, an optional image, and an optional list of data values. The data values are displayed in successive columns after the tree label.""" def __init__(self, master=None, **kw): """Construct a Ttk Treeview with parent master. STANDARD OPTIONS class, cursor, style, takefocus, xscrollcommand, yscrollcommand WIDGET-SPECIFIC OPTIONS columns, displaycolumns, height, padding, selectmode, show ITEM OPTIONS text, image, values, open, tags TAG OPTIONS foreground, background, font, image """ Widget.__init__(self, master, "ttk::treeview", kw) def bbox(self, item, column=None): """Returns the bounding box (relative to the treeview widget's window) of the specified item in the form x y width height. If column is specified, returns the bounding box of that cell. If the item is not visible (i.e., if it is a descendant of a closed item or is scrolled offscreen), returns an empty string.""" return self._getints(self.tk.call(self._w, "bbox", item, column)) or '' def get_children(self, item=None): """Returns a tuple of children belonging to item. If item is not specified, returns root children.""" return self.tk.splitlist( self.tk.call(self._w, "children", item or '') or ()) def set_children(self, item, *newchildren): """Replaces item's child with newchildren. Children present in item that are not present in newchildren are detached from tree. No items in newchildren may be an ancestor of item.""" self.tk.call(self._w, "children", item, newchildren) def column(self, column, option=None, **kw): """Query or modify the options for the specified column. If kw is not given, returns a dict of the column option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.""" if option is not None: kw[option] = None return _val_or_dict(self.tk, kw, self._w, "column", column) def delete(self, *items): """Delete all specified items and all their descendants. The root item may not be deleted.""" self.tk.call(self._w, "delete", items) def detach(self, *items): """Unlinks all of the specified items from the tree. The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed. The root item may not be detached.""" self.tk.call(self._w, "detach", items) def exists(self, item): """Returns True if the specified item is present in the tree, False otherwise.""" return self.tk.getboolean(self.tk.call(self._w, "exists", item)) def focus(self, item=None): """If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or '' if there is none.""" return self.tk.call(self._w, "focus", item) def heading(self, column, option=None, **kw): """Query or modify the heading options for the specified column. If kw is not given, returns a dict of the heading option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values. Valid options/values are: text: text The text to display in the column heading image: image_name Specifies an image to display to the right of the column heading anchor: anchor Specifies how the heading text should be aligned. One of the standard Tk anchor values command: callback A callback to be invoked when the heading label is pressed. To configure the tree column heading, call this with column = "#0" """ cmd = kw.get('command') if cmd and not isinstance(cmd, str): # callback not registered yet, do it now kw['command'] = self.master.register(cmd, self._substitute) if option is not None: kw[option] = None return _val_or_dict(self.tk, kw, self._w, 'heading', column) def identify(self, component, x, y): """Returns a description of the specified component under the point given by x and y, or the empty string if no such component is present at that position.""" return self.tk.call(self._w, "identify", component, x, y) def identify_row(self, y): """Returns the item ID of the item at position y.""" return self.identify("row", 0, y) def identify_column(self, x): """Returns the data column identifier of the cell at position x. The tree column has ID #0.""" return self.identify("column", x, 0) def identify_region(self, x, y): """Returns one of: heading: Tree heading area. separator: Space between two columns headings; tree: The tree area. cell: A data cell. * Availability: Tk 8.6""" return self.identify("region", x, y) def identify_element(self, x, y): """Returns the element at position x, y. * Availability: Tk 8.6""" return self.identify("element", x, y) def index(self, item): """Returns the integer index of item within its parent's list of children.""" return self.tk.getint(self.tk.call(self._w, "index", item)) def insert(self, parent, index, iid=None, **kw): """Creates a new item and return the item identifier of the newly created item. parent is the item ID of the parent item, or the empty string to create a new top-level item. index is an integer, or the value end, specifying where in the list of parent's children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning, if index is greater than or equal to the current number of children, it is inserted at the end. If iid is specified, it is used as the item identifier, iid must not already exist in the tree. Otherwise, a new unique identifier is generated.""" opts = _format_optdict(kw) if iid is not None: res = self.tk.call(self._w, "insert", parent, index, "-id", iid, *opts) else: res = self.tk.call(self._w, "insert", parent, index, *opts) return res def item(self, item, option=None, **kw): """Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by kw.""" if option is not None: kw[option] = None return _val_or_dict(self.tk, kw, self._w, "item", item) def move(self, item, parent, index): """Moves item to position index in parent's list of children. It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning, if greater than or equal to the number of children, it is moved to the end. If item was detached it is reattached.""" self.tk.call(self._w, "move", item, parent, index) reattach = move # A sensible method name for reattaching detached items def next(self, item): """Returns the identifier of item's next sibling, or '' if item is the last child of its parent.""" return self.tk.call(self._w, "next", item) def parent(self, item): """Returns the ID of the parent of item, or '' if item is at the top level of the hierarchy.""" return self.tk.call(self._w, "parent", item) def prev(self, item): """Returns the identifier of item's previous sibling, or '' if item is the first child of its parent.""" return self.tk.call(self._w, "prev", item) def see(self, item): """Ensure that item is visible. Sets all of item's ancestors open option to True, and scrolls the widget if necessary so that item is within the visible portion of the tree.""" self.tk.call(self._w, "see", item) def selection(self, selop=_sentinel, items=None): """Returns the tuple of selected items.""" if selop is _sentinel: selop = None elif selop is None: import warnings warnings.warn( "The selop=None argument of selection() is deprecated " "and will be removed in Python 3.8", DeprecationWarning, 3) elif selop in ('set', 'add', 'remove', 'toggle'): import warnings warnings.warn( "The selop argument of selection() is deprecated " "and will be removed in Python 3.8, " "use selection_%s() instead" % (selop,), DeprecationWarning, 3) else: raise TypeError('Unsupported operation') return self.tk.splitlist(self.tk.call(self._w, "selection", selop, items)) def _selection(self, selop, items): if len(items) == 1 and isinstance(items[0], (tuple, list)): items = items[0] self.tk.call(self._w, "selection", selop, items) def selection_set(self, *items): """The specified items becomes the new selection.""" self._selection("set", items) def selection_add(self, *items): """Add all of the specified items to the selection.""" self._selection("add", items) def selection_remove(self, *items): """Remove all of the specified items from the selection.""" self._selection("remove", items) def selection_toggle(self, *items): """Toggle the selection state of each specified item.""" self._selection("toggle", items) def set(self, item, column=None, value=None): """Query or set the value of given item. With one argument, return a dictionary of column/value pairs for the specified item. With two arguments, return the current value of the specified column. With three arguments, set the value of given column in given item to the specified value.""" res = self.tk.call(self._w, "set", item, column, value) if column is None and value is None: return _splitdict(self.tk, res, cut_minus=False, conv=_tclobj_to_py) else: return res def tag_bind(self, tagname, sequence=None, callback=None): """Bind a callback for the given event sequence to the tag tagname. When an event is delivered to an item, the callbacks for each of the item's tags option are called.""" self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0) def tag_configure(self, tagname, option=None, **kw): """Query or modify the options for the specified tagname. If kw is not given, returns a dict of the option settings for tagname. If option is specified, returns the value for that option for the specified tagname. Otherwise, sets the options to the corresponding values for the given tagname.""" if option is not None: kw[option] = None return _val_or_dict(self.tk, kw, self._w, "tag", "configure", tagname) def tag_has(self, tagname, item=None): """If item is specified, returns 1 or 0 depending on whether the specified item has the given tagname. Otherwise, returns a list of all items which have the specified tag. * Availability: Tk 8.6""" if item is None: return self.tk.splitlist( self.tk.call(self._w, "tag", "has", tagname)) else: return self.tk.getboolean( self.tk.call(self._w, "tag", "has", tagname, item)) # Extensions class LabeledScale(Frame): """A Ttk Scale widget with a Ttk Label widget indicating its current value. The Ttk Scale can be accessed through instance.scale, and Ttk Label can be accessed through instance.label""" def __init__(self, master=None, variable=None, from_=0, to=10, **kw): """Construct a horizontal LabeledScale with parent master, a variable to be associated with the Ttk Scale widget and its range. If variable is not specified, a tkinter.IntVar is created. WIDGET-SPECIFIC OPTIONS compound: 'top' or 'bottom' Specifies how to display the label relative to the scale. Defaults to 'top'. """ self._label_top = kw.pop('compound', 'top') == 'top' Frame.__init__(self, master, **kw) self._variable = variable or tkinter.IntVar(master) self._variable.set(from_) self._last_valid = from_ self.label = Label(self) self.scale = Scale(self, variable=self._variable, from_=from_, to=to) self.scale.bind('<<RangeChanged>>', self._adjust) # position scale and label according to the compound option scale_side = 'bottom' if self._label_top else 'top' label_side = 'top' if scale_side == 'bottom' else 'bottom' self.scale.pack(side=scale_side, fill='x') tmp = Label(self).pack(side=label_side) # place holder self.label.place(anchor='n' if label_side == 'top' else 's') # update the label as scale or variable changes self.__tracecb = self._variable.trace_variable('w', self._adjust) self.bind('<Configure>', self._adjust) self.bind('<Map>', self._adjust) def destroy(self): """Destroy this widget and possibly its associated variable.""" try: self._variable.trace_vdelete('w', self.__tracecb) except AttributeError: pass else: del self._variable super().destroy() self.label = None self.scale = None def _adjust(self, *args): """Adjust the label position according to the scale.""" def adjust_label(): self.update_idletasks() # "force" scale redraw x, y = self.scale.coords() if self._label_top: y = self.scale.winfo_y() - self.label.winfo_reqheight() else: y = self.scale.winfo_reqheight() + self.label.winfo_reqheight() self.label.place_configure(x=x, y=y) from_ = _to_number(self.scale['from']) to = _to_number(self.scale['to']) if to < from_: from_, to = to, from_ newval = self._variable.get() if not from_ <= newval <= to: # value outside range, set value back to the last valid one self.value = self._last_valid return self._last_valid = newval self.label['text'] = newval self.after_idle(adjust_label) def _get_value(self): """Return current scale value.""" return self._variable.get() def _set_value(self, val): """Set new scale value.""" self._variable.set(val) value = property(_get_value, _set_value) class OptionMenu(Menubutton): """Themed OptionMenu, based after tkinter's OptionMenu, which allows the user to select a value from a menu.""" def __init__(self, master, variable, default=None, *values, **kwargs): """Construct a themed OptionMenu widget with master as the parent, the resource textvariable set to variable, the initially selected value specified by the default parameter, the menu values given by *values and additional keywords. WIDGET-SPECIFIC OPTIONS style: stylename Menubutton style. direction: 'above', 'below', 'left', 'right', or 'flush' Menubutton direction. command: callback A callback that will be invoked after selecting an item. """ kw = {'textvariable': variable, 'style': kwargs.pop('style', None), 'direction': kwargs.pop('direction', None)} Menubutton.__init__(self, master, **kw) self['menu'] = tkinter.Menu(self, tearoff=False) self._variable = variable self._callback = kwargs.pop('command', None) if kwargs: raise tkinter.TclError('unknown option -%s' % ( next(iter(kwargs.keys())))) self.set_menu(default, *values) def __getitem__(self, item): if item == 'menu': return self.nametowidget(Menubutton.__getitem__(self, item)) return Menubutton.__getitem__(self, item) def set_menu(self, default=None, *values): """Build a new menu of radiobuttons with *values and optionally a default value.""" menu = self['menu'] menu.delete(0, 'end') for val in values: menu.add_radiobutton(label=val, command=tkinter._setit(self._variable, val, self._callback), variable=self._variable) if default: self._variable.set(default) def destroy(self): """Destroy this widget and its associated variable.""" try: del self._variable except AttributeError: pass super().destroy()
57,090
1,656
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/messagebox.py
# tk common message boxes # # this module provides an interface to the native message boxes # available in Tk 4.2 and newer. # # written by Fredrik Lundh, May 1997 # # # options (all have default values): # # - default: which button to make default (one of the reply codes) # # - icon: which icon to display (see below) # # - message: the message to display # # - parent: which window to place the dialog on top of # # - title: dialog title # # - type: dialog type; that is, which buttons to display (see below) # from tkinter.commondialog import Dialog # # constants # icons ERROR = "error" INFO = "info" QUESTION = "question" WARNING = "warning" # types ABORTRETRYIGNORE = "abortretryignore" OK = "ok" OKCANCEL = "okcancel" RETRYCANCEL = "retrycancel" YESNO = "yesno" YESNOCANCEL = "yesnocancel" # replies ABORT = "abort" RETRY = "retry" IGNORE = "ignore" OK = "ok" CANCEL = "cancel" YES = "yes" NO = "no" # # message dialog class class Message(Dialog): "A message box" command = "tk_messageBox" # # convenience stuff # Rename _icon and _type options to allow overriding them in options def _show(title=None, message=None, _icon=None, _type=None, **options): if _icon and "icon" not in options: options["icon"] = _icon if _type and "type" not in options: options["type"] = _type if title: options["title"] = title if message: options["message"] = message res = Message(**options).show() # In some Tcl installations, yes/no is converted into a boolean. if isinstance(res, bool): if res: return YES return NO # In others we get a Tcl_Obj. return str(res) def showinfo(title=None, message=None, **options): "Show an info message" return _show(title, message, INFO, OK, **options) def showwarning(title=None, message=None, **options): "Show a warning message" return _show(title, message, WARNING, OK, **options) def showerror(title=None, message=None, **options): "Show an error message" return _show(title, message, ERROR, OK, **options) def askquestion(title=None, message=None, **options): "Ask a question" return _show(title, message, QUESTION, YESNO, **options) def askokcancel(title=None, message=None, **options): "Ask if operation should proceed; return true if the answer is ok" s = _show(title, message, QUESTION, OKCANCEL, **options) return s == OK def askyesno(title=None, message=None, **options): "Ask a question; return true if the answer is yes" s = _show(title, message, QUESTION, YESNO, **options) return s == YES def askyesnocancel(title=None, message=None, **options): "Ask a question; return true if the answer is yes, None if cancelled." s = _show(title, message, QUESTION, YESNOCANCEL, **options) # s might be a Tcl index object, so convert it to a string s = str(s) if s == CANCEL: return None return s == YES def askretrycancel(title=None, message=None, **options): "Ask if operation should be retried; return true if the answer is yes" s = _show(title, message, WARNING, RETRYCANCEL, **options) return s == RETRY # -------------------------------------------------------------------- # test stuff if __name__ == "__main__": print("info", showinfo("Spam", "Egg Information")) print("warning", showwarning("Spam", "Egg Warning")) print("error", showerror("Spam", "Egg Alert")) print("question", askquestion("Spam", "Question?")) print("proceed", askokcancel("Spam", "Proceed?")) print("yes/no", askyesno("Spam", "Got it?")) print("yes/no/cancel", askyesnocancel("Spam", "Want it?")) print("try again", askretrycancel("Spam", "Try again?"))
3,701
135
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/__init__.py
"""Wrapper functions for Tcl/Tk. Tkinter provides classes which allow the display, positioning and control of widgets. Toplevel widgets are Tk and Toplevel. Other widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton, Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox LabelFrame and PanedWindow. Properties of the widgets are specified with keyword arguments. Keyword arguments have the same name as the corresponding resource under Tk. Widgets are positioned with one of the geometry managers Place, Pack or Grid. These managers can be called with methods place, pack, grid available in every Widget. Actions are bound to events by resources (e.g. keyword argument command) or with the method bind. Example (Hello, World): import tkinter from tkinter.constants import * tk = tkinter.Tk() frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2) frame.pack(fill=BOTH,expand=1) label = tkinter.Label(frame, text="Hello, World") label.pack(fill=X, expand=1) button = tkinter.Button(frame,text="Exit",command=tk.destroy) button.pack(side=BOTTOM) tk.mainloop() """ import enum import sys import _tkinter # If this fails your Python may not be configured for Tk TclError = _tkinter.TclError from tkinter.constants import * import re wantobjects = 1 TkVersion = float(_tkinter.TK_VERSION) TclVersion = float(_tkinter.TCL_VERSION) READABLE = _tkinter.READABLE WRITABLE = _tkinter.WRITABLE EXCEPTION = _tkinter.EXCEPTION _magic_re = re.compile(r'([\\{}])') _space_re = re.compile(r'([\s])', re.ASCII) def _join(value): """Internal function.""" return ' '.join(map(_stringify, value)) def _stringify(value): """Internal function.""" if isinstance(value, (list, tuple)): if len(value) == 1: value = _stringify(value[0]) if _magic_re.search(value): value = '{%s}' % value else: value = '{%s}' % _join(value) else: value = str(value) if not value: value = '{}' elif _magic_re.search(value): # add '\' before special characters and spaces value = _magic_re.sub(r'\\\1', value) value = value.replace('\n', r'\n') value = _space_re.sub(r'\\\1', value) if value[0] == '"': value = '\\' + value elif value[0] == '"' or _space_re.search(value): value = '{%s}' % value return value def _flatten(seq): """Internal function.""" res = () for item in seq: if isinstance(item, (tuple, list)): res = res + _flatten(item) elif item is not None: res = res + (item,) return res try: _flatten = _tkinter._flatten except AttributeError: pass def _cnfmerge(cnfs): """Internal function.""" if isinstance(cnfs, dict): return cnfs elif isinstance(cnfs, (type(None), str)): return cnfs else: cnf = {} for c in _flatten(cnfs): try: cnf.update(c) except (AttributeError, TypeError) as msg: print("_cnfmerge: fallback due to:", msg) for k, v in c.items(): cnf[k] = v return cnf try: _cnfmerge = _tkinter._cnfmerge except AttributeError: pass def _splitdict(tk, v, cut_minus=True, conv=None): """Return a properly formatted dict built from Tcl list pairs. If cut_minus is True, the supposed '-' prefix will be removed from keys. If conv is specified, it is used to convert values. Tcl list is expected to contain an even number of elements. """ t = tk.splitlist(v) if len(t) % 2: raise RuntimeError('Tcl list representing a dict is expected ' 'to contain an even number of elements') it = iter(t) dict = {} for key, value in zip(it, it): key = str(key) if cut_minus and key[0] == '-': key = key[1:] if conv: value = conv(value) dict[key] = value return dict class EventType(str, enum.Enum): KeyPress = '2' Key = KeyPress, KeyRelease = '3' ButtonPress = '4' Button = ButtonPress, ButtonRelease = '5' Motion = '6' Enter = '7' Leave = '8' FocusIn = '9' FocusOut = '10' Keymap = '11' # undocumented Expose = '12' GraphicsExpose = '13' # undocumented NoExpose = '14' # undocumented Visibility = '15' Create = '16' Destroy = '17' Unmap = '18' Map = '19' MapRequest = '20' Reparent = '21' Configure = '22' ConfigureRequest = '23' Gravity = '24' ResizeRequest = '25' Circulate = '26' CirculateRequest = '27' Property = '28' SelectionClear = '29' # undocumented SelectionRequest = '30' # undocumented Selection = '31' # undocumented Colormap = '32' ClientMessage = '33' # undocumented Mapping = '34' # undocumented VirtualEvent = '35', # undocumented Activate = '36', Deactivate = '37', MouseWheel = '38', def __str__(self): return self.name class Event: """Container for the properties of an event. Instances of this type are generated if one of the following events occurs: KeyPress, KeyRelease - for keyboard events ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate, Colormap, Gravity, Reparent, Property, Destroy, Activate, Deactivate - for window events. If a callback function for one of these events is registered using bind, bind_all, bind_class, or tag_bind, the callback is called with an Event as first argument. It will have the following attributes (in braces are the event types for which the attribute is valid): serial - serial number of event num - mouse button pressed (ButtonPress, ButtonRelease) focus - whether the window has the focus (Enter, Leave) height - height of the exposed window (Configure, Expose) width - width of the exposed window (Configure, Expose) keycode - keycode of the pressed key (KeyPress, KeyRelease) state - state of the event as a number (ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, Motion) state - state as a string (Visibility) time - when the event occurred x - x-position of the mouse y - y-position of the mouse x_root - x-position of the mouse on the screen (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) y_root - y-position of the mouse on the screen (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) char - pressed character (KeyPress, KeyRelease) send_event - see X/Windows documentation keysym - keysym of the event as a string (KeyPress, KeyRelease) keysym_num - keysym of the event as a number (KeyPress, KeyRelease) type - type of the event as a number widget - widget in which the event occurred delta - delta of wheel movement (MouseWheel) """ def __repr__(self): attrs = {k: v for k, v in self.__dict__.items() if v != '??'} if not self.char: del attrs['char'] elif self.char != '??': attrs['char'] = repr(self.char) if not getattr(self, 'send_event', True): del attrs['send_event'] if self.state == 0: del attrs['state'] elif isinstance(self.state, int): state = self.state mods = ('Shift', 'Lock', 'Control', 'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5', 'Button1', 'Button2', 'Button3', 'Button4', 'Button5') s = [] for i, n in enumerate(mods): if state & (1 << i): s.append(n) state = state & ~((1<< len(mods)) - 1) if state or not s: s.append(hex(state)) attrs['state'] = '|'.join(s) if self.delta == 0: del attrs['delta'] # widget usually is known # serial and time are not very interesting # keysym_num duplicates keysym # x_root and y_root mostly duplicate x and y keys = ('send_event', 'state', 'keysym', 'keycode', 'char', 'num', 'delta', 'focus', 'x', 'y', 'width', 'height') return '<%s event%s>' % ( self.type, ''.join(' %s=%s' % (k, attrs[k]) for k in keys if k in attrs) ) _support_default_root = 1 _default_root = None def NoDefaultRoot(): """Inhibit setting of default root window. Call this function to inhibit that the first instance of Tk is used for windows without an explicit parent window. """ global _support_default_root _support_default_root = 0 global _default_root _default_root = None del _default_root def _tkerror(err): """Internal function.""" pass def _exit(code=0): """Internal function. Calling it will raise the exception SystemExit.""" try: code = int(code) except ValueError: pass raise SystemExit(code) _varnum = 0 class Variable: """Class to define value holders for e.g. buttons. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations that constrain the type of the value returned from get().""" _default = "" _tk = None _tclCommands = None def __init__(self, master=None, value=None, name=None): """Construct a variable MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ # check for type of NAME parameter to override weird error message # raised from Modules/_tkinter.c:SetVar like: # TypeError: setvar() takes exactly 3 arguments (2 given) if name is not None and not isinstance(name, str): raise TypeError("name must be a string") global _varnum if not master: master = _default_root self._root = master._root() self._tk = master.tk if name: self._name = name else: self._name = 'PY_VAR' + repr(_varnum) _varnum += 1 if value is not None: self.initialize(value) elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)): self.initialize(self._default) def __del__(self): """Unset the variable in Tcl.""" if self._tk is None: return if self._tk.getboolean(self._tk.call("info", "exists", self._name)): self._tk.globalunsetvar(self._name) if self._tclCommands is not None: for name in self._tclCommands: #print '- Tkinter: deleted command', name self._tk.deletecommand(name) self._tclCommands = None def __str__(self): """Return the name of the variable in Tcl.""" return self._name def set(self, value): """Set the variable to VALUE.""" return self._tk.globalsetvar(self._name, value) initialize = set def get(self): """Return value of variable.""" return self._tk.globalgetvar(self._name) def _register(self, callback): f = CallWrapper(callback, None, self._root).__call__ cbname = repr(id(f)) try: callback = callback.__func__ except AttributeError: pass try: cbname = cbname + callback.__name__ except AttributeError: pass self._tk.createcommand(cbname, f) if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(cbname) return cbname def trace_add(self, mode, callback): """Define a trace callback for the variable. Mode is one of "read", "write", "unset", or a list or tuple of such strings. Callback must be a function which is called when the variable is read, written or unset. Return the name of the callback. """ cbname = self._register(callback) self._tk.call('trace', 'add', 'variable', self._name, mode, (cbname,)) return cbname def trace_remove(self, mode, cbname): """Delete the trace callback for a variable. Mode is one of "read", "write", "unset" or a list or tuple of such strings. Must be same as were specified in trace_add(). cbname is the name of the callback returned from trace_add(). """ self._tk.call('trace', 'remove', 'variable', self._name, mode, cbname) for m, ca in self.trace_info(): if self._tk.splitlist(ca)[0] == cbname: break else: self._tk.deletecommand(cbname) try: self._tclCommands.remove(cbname) except ValueError: pass def trace_info(self): """Return all trace callback information.""" splitlist = self._tk.splitlist return [(splitlist(k), v) for k, v in map(splitlist, splitlist(self._tk.call('trace', 'info', 'variable', self._name)))] def trace_variable(self, mode, callback): """Define a trace callback for the variable. MODE is one of "r", "w", "u" for read, write, undefine. CALLBACK must be a function which is called when the variable is read, written or undefined. Return the name of the callback. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_add() instead. """ # TODO: Add deprecation warning cbname = self._register(callback) self._tk.call("trace", "variable", self._name, mode, cbname) return cbname trace = trace_variable def trace_vdelete(self, mode, cbname): """Delete the trace callback for a variable. MODE is one of "r", "w", "u" for read, write, undefine. CBNAME is the name of the callback returned from trace_variable or trace. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_remove() instead. """ # TODO: Add deprecation warning self._tk.call("trace", "vdelete", self._name, mode, cbname) cbname = self._tk.splitlist(cbname)[0] for m, ca in self.trace_info(): if self._tk.splitlist(ca)[0] == cbname: break else: self._tk.deletecommand(cbname) try: self._tclCommands.remove(cbname) except ValueError: pass def trace_vinfo(self): """Return all trace callback information. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_info() instead. """ # TODO: Add deprecation warning return [self._tk.splitlist(x) for x in self._tk.splitlist( self._tk.call("trace", "vinfo", self._name))] def __eq__(self, other): """Comparison for equality (==). Note: if the Variable's master matters to behavior also compare self._master == other._master """ return self.__class__.__name__ == other.__class__.__name__ \ and self._name == other._name class StringVar(Variable): """Value holder for strings variables.""" _default = "" def __init__(self, master=None, value=None, name=None): """Construct a string variable. MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return value of variable as string.""" value = self._tk.globalgetvar(self._name) if isinstance(value, str): return value return str(value) class IntVar(Variable): """Value holder for integer variables.""" _default = 0 def __init__(self, master=None, value=None, name=None): """Construct an integer variable. MASTER can be given as master widget. VALUE is an optional value (defaults to 0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return the value of the variable as an integer.""" value = self._tk.globalgetvar(self._name) try: return self._tk.getint(value) except (TypeError, TclError): return int(self._tk.getdouble(value)) class DoubleVar(Variable): """Value holder for float variables.""" _default = 0.0 def __init__(self, master=None, value=None, name=None): """Construct a float variable. MASTER can be given as master widget. VALUE is an optional value (defaults to 0.0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return the value of the variable as a float.""" return self._tk.getdouble(self._tk.globalgetvar(self._name)) class BooleanVar(Variable): """Value holder for boolean variables.""" _default = False def __init__(self, master=None, value=None, name=None): """Construct a boolean variable. MASTER can be given as master widget. VALUE is an optional value (defaults to False) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def set(self, value): """Set the variable to VALUE.""" return self._tk.globalsetvar(self._name, self._tk.getboolean(value)) initialize = set def get(self): """Return the value of the variable as a bool.""" try: return self._tk.getboolean(self._tk.globalgetvar(self._name)) except TclError: raise ValueError("invalid literal for getboolean()") def mainloop(n=0): """Run the main loop of Tcl.""" _default_root.tk.mainloop(n) getint = int getdouble = float def getboolean(s): """Convert true and false to integer values 1 and 0.""" try: return _default_root.tk.getboolean(s) except TclError: raise ValueError("invalid literal for getboolean()") # Methods defined on both toplevel and interior widgets class Misc: """Internal class. Base class which defines methods common for interior widgets.""" # used for generating child widget names _last_child_ids = None # XXX font command? _tclCommands = None def destroy(self): """Internal function. Delete all Tcl commands created for this widget in the Tcl interpreter.""" if self._tclCommands is not None: for name in self._tclCommands: #print '- Tkinter: deleted command', name self.tk.deletecommand(name) self._tclCommands = None def deletecommand(self, name): """Internal function. Delete the Tcl command provided in NAME.""" #print '- Tkinter: deleted command', name self.tk.deletecommand(name) try: self._tclCommands.remove(name) except ValueError: pass def tk_strictMotif(self, boolean=None): """Set Tcl internal variable, whether the look and feel should adhere to Motif. A parameter of 1 means adhere to Motif (e.g. no color change if mouse passes over slider). Returns the set value.""" return self.tk.getboolean(self.tk.call( 'set', 'tk_strictMotif', boolean)) def tk_bisque(self): """Change the color scheme to light brown as used in Tk 3.6 and before.""" self.tk.call('tk_bisque') def tk_setPalette(self, *args, **kw): """Set a new color scheme for all widget elements. A single color as argument will cause that all colors of Tk widget elements are derived from this. Alternatively several keyword parameters and its associated colors can be given. The following keywords are valid: activeBackground, foreground, selectColor, activeForeground, highlightBackground, selectBackground, background, highlightColor, selectForeground, disabledForeground, insertBackground, troughColor.""" self.tk.call(('tk_setPalette',) + _flatten(args) + _flatten(list(kw.items()))) def wait_variable(self, name='PY_VAR'): """Wait until the variable is modified. A parameter of type IntVar, StringVar, DoubleVar or BooleanVar must be given.""" self.tk.call('tkwait', 'variable', name) waitvar = wait_variable # XXX b/w compat def wait_window(self, window=None): """Wait until a WIDGET is destroyed. If no parameter is given self is used.""" if window is None: window = self self.tk.call('tkwait', 'window', window._w) def wait_visibility(self, window=None): """Wait until the visibility of a WIDGET changes (e.g. it appears). If no parameter is given self is used.""" if window is None: window = self self.tk.call('tkwait', 'visibility', window._w) def setvar(self, name='PY_VAR', value='1'): """Set Tcl variable NAME to VALUE.""" self.tk.setvar(name, value) def getvar(self, name='PY_VAR'): """Return value of Tcl variable NAME.""" return self.tk.getvar(name) def getint(self, s): try: return self.tk.getint(s) except TclError as exc: raise ValueError(str(exc)) def getdouble(self, s): try: return self.tk.getdouble(s) except TclError as exc: raise ValueError(str(exc)) def getboolean(self, s): """Return a boolean value for Tcl boolean values true and false given as parameter.""" try: return self.tk.getboolean(s) except TclError: raise ValueError("invalid literal for getboolean()") def focus_set(self): """Direct input focus to this widget. If the application currently does not have the focus this widget will get the focus if the application gets the focus through the window manager.""" self.tk.call('focus', self._w) focus = focus_set # XXX b/w compat? def focus_force(self): """Direct input focus to this widget even if the application does not have the focus. Use with caution!""" self.tk.call('focus', '-force', self._w) def focus_get(self): """Return the widget which has currently the focus in the application. Use focus_displayof to allow working with several displays. Return None if application does not have the focus.""" name = self.tk.call('focus') if name == 'none' or not name: return None return self._nametowidget(name) def focus_displayof(self): """Return the widget which has currently the focus on the display where this widget is located. Return None if the application does not have the focus.""" name = self.tk.call('focus', '-displayof', self._w) if name == 'none' or not name: return None return self._nametowidget(name) def focus_lastfor(self): """Return the widget which would have the focus if top level for this widget gets the focus from the window manager.""" name = self.tk.call('focus', '-lastfor', self._w) if name == 'none' or not name: return None return self._nametowidget(name) def tk_focusFollowsMouse(self): """The widget under mouse will get automatically focus. Can not be disabled easily.""" self.tk.call('tk_focusFollowsMouse') def tk_focusNext(self): """Return the next widget in the focus order which follows widget which has currently the focus. The focus order first goes to the next child, then to the children of the child recursively and then to the next sibling which is higher in the stacking order. A widget is omitted if it has the takefocus resource set to 0.""" name = self.tk.call('tk_focusNext', self._w) if not name: return None return self._nametowidget(name) def tk_focusPrev(self): """Return previous widget in the focus order. See tk_focusNext for details.""" name = self.tk.call('tk_focusPrev', self._w) if not name: return None return self._nametowidget(name) def after(self, ms, func=None, *args): """Call function once after given time. MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel.""" if not func: # I'd rather use time.sleep(ms*0.001) self.tk.call('after', ms) return None else: def callit(): try: func(*args) finally: try: self.deletecommand(name) except TclError: pass callit.__name__ = func.__name__ name = self._register(callit) return self.tk.call('after', ms, name) def after_idle(self, func, *args): """Call FUNC once if the Tcl main loop has no event to process. Return an identifier to cancel the scheduling with after_cancel.""" return self.after('idle', func, *args) def after_cancel(self, id): """Cancel scheduling of function identified with ID. Identifier returned by after or after_idle must be given as first parameter. """ if not id: raise ValueError('id must be a valid identifier returned from ' 'after or after_idle') try: data = self.tk.call('after', 'info', id) script = self.tk.splitlist(data)[0] self.deletecommand(script) except TclError: pass self.tk.call('after', 'cancel', id) def bell(self, displayof=0): """Ring a display's bell.""" self.tk.call(('bell',) + self._displayof(displayof)) # Clipboard handling: def clipboard_get(self, **kw): """Retrieve data from the clipboard on window's display. The window keyword defaults to the root window of the Tkinter application. The type keyword specifies the form in which the data is to be returned and should be an atom name such as STRING or FILE_NAME. Type defaults to STRING, except on X11, where the default is to try UTF8_STRING and fall back to STRING. This command is equivalent to: selection_get(CLIPBOARD) """ if 'type' not in kw and self._windowingsystem == 'x11': try: kw['type'] = 'UTF8_STRING' return self.tk.call(('clipboard', 'get') + self._options(kw)) except TclError: del kw['type'] return self.tk.call(('clipboard', 'get') + self._options(kw)) def clipboard_clear(self, **kw): """Clear the data in the Tk clipboard. A widget specified for the optional displayof keyword argument specifies the target display.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'clear') + self._options(kw)) def clipboard_append(self, string, **kw): """Append STRING to the Tk clipboard. A widget specified at the optional displayof keyword argument specifies the target display. The clipboard can be retrieved with selection_get.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'append') + self._options(kw) + ('--', string)) # XXX grab current w/o window argument def grab_current(self): """Return widget which has currently the grab in this application or None.""" name = self.tk.call('grab', 'current', self._w) if not name: return None return self._nametowidget(name) def grab_release(self): """Release grab for this widget if currently set.""" self.tk.call('grab', 'release', self._w) def grab_set(self): """Set grab for this widget. A grab directs all events to this and descendant widgets in the application.""" self.tk.call('grab', 'set', self._w) def grab_set_global(self): """Set global grab for this widget. A global grab directs all events to this and descendant widgets on the display. Use with caution - other applications do not get events anymore.""" self.tk.call('grab', 'set', '-global', self._w) def grab_status(self): """Return None, "local" or "global" if this widget has no, a local or a global grab.""" status = self.tk.call('grab', 'status', self._w) if status == 'none': status = None return status def option_add(self, pattern, value, priority = None): """Set a VALUE (second parameter) for an option PATTERN (first parameter). An optional third parameter gives the numeric priority (defaults to 80).""" self.tk.call('option', 'add', pattern, value, priority) def option_clear(self): """Clear the option database. It will be reloaded if option_add is called.""" self.tk.call('option', 'clear') def option_get(self, name, className): """Return the value for an option NAME for this widget with CLASSNAME. Values with higher priority override lower values.""" return self.tk.call('option', 'get', self._w, name, className) def option_readfile(self, fileName, priority = None): """Read file FILENAME into the option database. An optional second parameter gives the numeric priority.""" self.tk.call('option', 'readfile', fileName, priority) def selection_clear(self, **kw): """Clear the current X selection.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('selection', 'clear') + self._options(kw)) def selection_get(self, **kw): """Return the contents of the current X selection. A keyword parameter selection specifies the name of the selection and defaults to PRIMARY. A keyword parameter displayof specifies a widget on the display to use. A keyword parameter type specifies the form of data to be fetched, defaulting to STRING except on X11, where UTF8_STRING is tried before STRING.""" if 'displayof' not in kw: kw['displayof'] = self._w if 'type' not in kw and self._windowingsystem == 'x11': try: kw['type'] = 'UTF8_STRING' return self.tk.call(('selection', 'get') + self._options(kw)) except TclError: del kw['type'] return self.tk.call(('selection', 'get') + self._options(kw)) def selection_handle(self, command, **kw): """Specify a function COMMAND to call if the X selection owned by this widget is queried by another application. This function must return the contents of the selection. The function will be called with the arguments OFFSET and LENGTH which allows the chunking of very long selections. The following keyword parameters can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).""" name = self._register(command) self.tk.call(('selection', 'handle') + self._options(kw) + (self._w, name)) def selection_own(self, **kw): """Become owner of X selection. A keyword parameter selection specifies the name of the selection (default PRIMARY).""" self.tk.call(('selection', 'own') + self._options(kw) + (self._w,)) def selection_own_get(self, **kw): """Return owner of X selection. The following keyword parameter can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).""" if 'displayof' not in kw: kw['displayof'] = self._w name = self.tk.call(('selection', 'own') + self._options(kw)) if not name: return None return self._nametowidget(name) def send(self, interp, cmd, *args): """Send Tcl command CMD to different interpreter INTERP to be executed.""" return self.tk.call(('send', interp, cmd) + args) def lower(self, belowThis=None): """Lower this widget in the stacking order.""" self.tk.call('lower', self._w, belowThis) def tkraise(self, aboveThis=None): """Raise this widget in the stacking order.""" self.tk.call('raise', self._w, aboveThis) lift = tkraise def winfo_atom(self, name, displayof=0): """Return integer which represents atom NAME.""" args = ('winfo', 'atom') + self._displayof(displayof) + (name,) return self.tk.getint(self.tk.call(args)) def winfo_atomname(self, id, displayof=0): """Return name of atom with identifier ID.""" args = ('winfo', 'atomname') \ + self._displayof(displayof) + (id,) return self.tk.call(args) def winfo_cells(self): """Return number of cells in the colormap for this widget.""" return self.tk.getint( self.tk.call('winfo', 'cells', self._w)) def winfo_children(self): """Return a list of all widgets which are children of this widget.""" result = [] for child in self.tk.splitlist( self.tk.call('winfo', 'children', self._w)): try: # Tcl sometimes returns extra windows, e.g. for # menus; those need to be skipped result.append(self._nametowidget(child)) except KeyError: pass return result def winfo_class(self): """Return window class name of this widget.""" return self.tk.call('winfo', 'class', self._w) def winfo_colormapfull(self): """Return true if at the last color request the colormap was full.""" return self.tk.getboolean( self.tk.call('winfo', 'colormapfull', self._w)) def winfo_containing(self, rootX, rootY, displayof=0): """Return the widget which is at the root coordinates ROOTX, ROOTY.""" args = ('winfo', 'containing') \ + self._displayof(displayof) + (rootX, rootY) name = self.tk.call(args) if not name: return None return self._nametowidget(name) def winfo_depth(self): """Return the number of bits per pixel.""" return self.tk.getint(self.tk.call('winfo', 'depth', self._w)) def winfo_exists(self): """Return true if this widget exists.""" return self.tk.getint( self.tk.call('winfo', 'exists', self._w)) def winfo_fpixels(self, number): """Return the number of pixels for the given distance NUMBER (e.g. "3c") as float.""" return self.tk.getdouble(self.tk.call( 'winfo', 'fpixels', self._w, number)) def winfo_geometry(self): """Return geometry string for this widget in the form "widthxheight+X+Y".""" return self.tk.call('winfo', 'geometry', self._w) def winfo_height(self): """Return height of this widget.""" return self.tk.getint( self.tk.call('winfo', 'height', self._w)) def winfo_id(self): """Return identifier ID for this widget.""" return int(self.tk.call('winfo', 'id', self._w), 0) def winfo_interps(self, displayof=0): """Return the name of all Tcl interpreters for this display.""" args = ('winfo', 'interps') + self._displayof(displayof) return self.tk.splitlist(self.tk.call(args)) def winfo_ismapped(self): """Return true if this widget is mapped.""" return self.tk.getint( self.tk.call('winfo', 'ismapped', self._w)) def winfo_manager(self): """Return the window manager name for this widget.""" return self.tk.call('winfo', 'manager', self._w) def winfo_name(self): """Return the name of this widget.""" return self.tk.call('winfo', 'name', self._w) def winfo_parent(self): """Return the name of the parent of this widget.""" return self.tk.call('winfo', 'parent', self._w) def winfo_pathname(self, id, displayof=0): """Return the pathname of the widget given by ID.""" args = ('winfo', 'pathname') \ + self._displayof(displayof) + (id,) return self.tk.call(args) def winfo_pixels(self, number): """Rounded integer value of winfo_fpixels.""" return self.tk.getint( self.tk.call('winfo', 'pixels', self._w, number)) def winfo_pointerx(self): """Return the x coordinate of the pointer on the root window.""" return self.tk.getint( self.tk.call('winfo', 'pointerx', self._w)) def winfo_pointerxy(self): """Return a tuple of x and y coordinates of the pointer on the root window.""" return self._getints( self.tk.call('winfo', 'pointerxy', self._w)) def winfo_pointery(self): """Return the y coordinate of the pointer on the root window.""" return self.tk.getint( self.tk.call('winfo', 'pointery', self._w)) def winfo_reqheight(self): """Return requested height of this widget.""" return self.tk.getint( self.tk.call('winfo', 'reqheight', self._w)) def winfo_reqwidth(self): """Return requested width of this widget.""" return self.tk.getint( self.tk.call('winfo', 'reqwidth', self._w)) def winfo_rgb(self, color): """Return tuple of decimal values for red, green, blue for COLOR in this widget.""" return self._getints( self.tk.call('winfo', 'rgb', self._w, color)) def winfo_rootx(self): """Return x coordinate of upper left corner of this widget on the root window.""" return self.tk.getint( self.tk.call('winfo', 'rootx', self._w)) def winfo_rooty(self): """Return y coordinate of upper left corner of this widget on the root window.""" return self.tk.getint( self.tk.call('winfo', 'rooty', self._w)) def winfo_screen(self): """Return the screen name of this widget.""" return self.tk.call('winfo', 'screen', self._w) def winfo_screencells(self): """Return the number of the cells in the colormap of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'screencells', self._w)) def winfo_screendepth(self): """Return the number of bits per pixel of the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'screendepth', self._w)) def winfo_screenheight(self): """Return the number of pixels of the height of the screen of this widget in pixel.""" return self.tk.getint( self.tk.call('winfo', 'screenheight', self._w)) def winfo_screenmmheight(self): """Return the number of pixels of the height of the screen of this widget in mm.""" return self.tk.getint( self.tk.call('winfo', 'screenmmheight', self._w)) def winfo_screenmmwidth(self): """Return the number of pixels of the width of the screen of this widget in mm.""" return self.tk.getint( self.tk.call('winfo', 'screenmmwidth', self._w)) def winfo_screenvisual(self): """Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the default colormodel of this screen.""" return self.tk.call('winfo', 'screenvisual', self._w) def winfo_screenwidth(self): """Return the number of pixels of the width of the screen of this widget in pixel.""" return self.tk.getint( self.tk.call('winfo', 'screenwidth', self._w)) def winfo_server(self): """Return information of the X-Server of the screen of this widget in the form "XmajorRminor vendor vendorVersion".""" return self.tk.call('winfo', 'server', self._w) def winfo_toplevel(self): """Return the toplevel widget of this widget.""" return self._nametowidget(self.tk.call( 'winfo', 'toplevel', self._w)) def winfo_viewable(self): """Return true if the widget and all its higher ancestors are mapped.""" return self.tk.getint( self.tk.call('winfo', 'viewable', self._w)) def winfo_visual(self): """Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the colormodel of this widget.""" return self.tk.call('winfo', 'visual', self._w) def winfo_visualid(self): """Return the X identifier for the visual for this widget.""" return self.tk.call('winfo', 'visualid', self._w) def winfo_visualsavailable(self, includeids=False): """Return a list of all visuals available for the screen of this widget. Each item in the list consists of a visual name (see winfo_visual), a depth and if includeids is true is given also the X identifier.""" data = self.tk.call('winfo', 'visualsavailable', self._w, 'includeids' if includeids else None) data = [self.tk.splitlist(x) for x in self.tk.splitlist(data)] return [self.__winfo_parseitem(x) for x in data] def __winfo_parseitem(self, t): """Internal function.""" return t[:1] + tuple(map(self.__winfo_getint, t[1:])) def __winfo_getint(self, x): """Internal function.""" return int(x, 0) def winfo_vrootheight(self): """Return the height of the virtual root window associated with this widget in pixels. If there is no virtual root window return the height of the screen.""" return self.tk.getint( self.tk.call('winfo', 'vrootheight', self._w)) def winfo_vrootwidth(self): """Return the width of the virtual root window associated with this widget in pixel. If there is no virtual root window return the width of the screen.""" return self.tk.getint( self.tk.call('winfo', 'vrootwidth', self._w)) def winfo_vrootx(self): """Return the x offset of the virtual root relative to the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'vrootx', self._w)) def winfo_vrooty(self): """Return the y offset of the virtual root relative to the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'vrooty', self._w)) def winfo_width(self): """Return the width of this widget.""" return self.tk.getint( self.tk.call('winfo', 'width', self._w)) def winfo_x(self): """Return the x coordinate of the upper left corner of this widget in the parent.""" return self.tk.getint( self.tk.call('winfo', 'x', self._w)) def winfo_y(self): """Return the y coordinate of the upper left corner of this widget in the parent.""" return self.tk.getint( self.tk.call('winfo', 'y', self._w)) def update(self): """Enter event loop until all pending events have been processed by Tcl.""" self.tk.call('update') def update_idletasks(self): """Enter event loop until all idle callbacks have been called. This will update the display of windows but not process events caused by the user.""" self.tk.call('update', 'idletasks') def bindtags(self, tagList=None): """Set or get the list of bindtags for this widget. With no argument return the list of all bindtags associated with this widget. With a list of strings as argument the bindtags are set to this list. The bindtags determine in which order events are processed (see bind).""" if tagList is None: return self.tk.splitlist( self.tk.call('bindtags', self._w)) else: self.tk.call('bindtags', self._w, tagList) def _bind(self, what, sequence, func, add, needcleanup=1): """Internal function.""" if isinstance(func, str): self.tk.call(what + (sequence, func)) elif func: funcid = self._register(func, self._substitute, needcleanup) cmd = ('%sif {"[%s %s]" == "break"} break\n' % (add and '+' or '', funcid, self._subst_format_str)) self.tk.call(what + (sequence, cmd)) return funcid elif sequence: return self.tk.call(what + (sequence,)) else: return self.tk.splitlist(self.tk.call(what)) def bind(self, sequence=None, func=None, add=None): """Bind to this widget at event SEQUENCE a call to function FUNC. SEQUENCE is a string of concatenated event patterns. An event pattern is of the form <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4, Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3, B3, Alt, Button4, B4, Double, Button5, B5 Triple, Mod1, M1. TYPE is one of Activate, Enter, Map, ButtonPress, Button, Expose, Motion, ButtonRelease FocusIn, MouseWheel, Circulate, FocusOut, Property, Colormap, Gravity Reparent, Configure, KeyPress, Key, Unmap, Deactivate, KeyRelease Visibility, Destroy, Leave and DETAIL is the button number for ButtonPress, ButtonRelease and DETAIL is the Keysym for KeyPress and KeyRelease. Examples are <Control-Button-1> for pressing Control and mouse button 1 or <Alt-A> for pressing A and the Alt key (KeyPress can be omitted). An event pattern can also be a virtual event of the form <<AString>> where AString can be arbitrary. This event can be generated by event_generate. If events are concatenated they must appear shortly after each other. FUNC will be called if the event sequence occurs with an instance of Event as argument. If the return value of FUNC is "break" no further bound function is invoked. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. Bind will return an identifier to allow deletion of the bound function with unbind without memory leak. If FUNC or SEQUENCE is omitted the bound function or list of bound events are returned.""" return self._bind(('bind', self._w), sequence, func, add) def unbind(self, sequence, funcid=None): """Unbind for this widget for event SEQUENCE the function identified with FUNCID.""" self.tk.call('bind', self._w, sequence, '') if funcid: self.deletecommand(funcid) def bind_all(self, sequence=None, func=None, add=None): """Bind to all widgets at an event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind(('bind', 'all'), sequence, func, add, 0) def unbind_all(self, sequence): """Unbind for all widgets for event SEQUENCE all functions.""" self.tk.call('bind', 'all' , sequence, '') def bind_class(self, className, sequence=None, func=None, add=None): """Bind to widgets with bindtag CLASSNAME at event SEQUENCE a call of function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind(('bind', className), sequence, func, add, 0) def unbind_class(self, className, sequence): """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE all functions.""" self.tk.call('bind', className , sequence, '') def mainloop(self, n=0): """Call the mainloop of Tk.""" self.tk.mainloop(n) def quit(self): """Quit the Tcl interpreter. All widgets will be destroyed.""" self.tk.quit() def _getints(self, string): """Internal function.""" if string: return tuple(map(self.tk.getint, self.tk.splitlist(string))) def _getdoubles(self, string): """Internal function.""" if string: return tuple(map(self.tk.getdouble, self.tk.splitlist(string))) def _getboolean(self, string): """Internal function.""" if string: return self.tk.getboolean(string) def _displayof(self, displayof): """Internal function.""" if displayof: return ('-displayof', displayof) if displayof is None: return ('-displayof', self._w) return () @property def _windowingsystem(self): """Internal function.""" try: return self._root()._windowingsystem_cached except AttributeError: ws = self._root()._windowingsystem_cached = \ self.tk.call('tk', 'windowingsystem') return ws def _options(self, cnf, kw = None): """Internal function.""" if kw: cnf = _cnfmerge((cnf, kw)) else: cnf = _cnfmerge(cnf) res = () for k, v in cnf.items(): if v is not None: if k[-1] == '_': k = k[:-1] if callable(v): v = self._register(v) elif isinstance(v, (tuple, list)): nv = [] for item in v: if isinstance(item, int): nv.append(str(item)) elif isinstance(item, str): nv.append(_stringify(item)) else: break else: v = ' '.join(nv) res = res + ('-'+k, v) return res def nametowidget(self, name): """Return the Tkinter instance of a widget identified by its Tcl name NAME.""" name = str(name).split('.') w = self if not name[0]: w = w._root() name = name[1:] for n in name: if not n: break w = w.children[n] return w _nametowidget = nametowidget def _register(self, func, subst=None, needcleanup=1): """Return a newly created Tcl function. If this function is called, the Python function FUNC will be executed. An optional function SUBST can be given which will be executed before FUNC.""" f = CallWrapper(func, subst, self).__call__ name = repr(id(f)) try: func = func.__func__ except AttributeError: pass try: name = name + func.__name__ except AttributeError: pass self.tk.createcommand(name, f) if needcleanup: if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(name) return name register = _register def _root(self): """Internal function.""" w = self while w.master: w = w.master return w _subst_format = ('%#', '%b', '%f', '%h', '%k', '%s', '%t', '%w', '%x', '%y', '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D') _subst_format_str = " ".join(_subst_format) def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = self.tk.getint def getint_event(s): """Tk changed behavior in 8.4.2, returning "??" rather more often.""" try: return getint(s) except (ValueError, TclError): return s nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() # serial field: valid for all events # number of button: ButtonPress and ButtonRelease events only # height field: Configure, ConfigureRequest, Create, # ResizeRequest, and Expose events only # keycode field: KeyPress and KeyRelease events only # time field: "valid for events that contain a time field" # width field: Configure, ConfigureRequest, Create, ResizeRequest, # and Expose events only # x field: "valid for events that contain an x field" # y field: "valid for events that contain a y field" # keysym as decimal: KeyPress and KeyRelease events only # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress, # KeyRelease, and Motion events e.serial = getint(nsign) e.num = getint_event(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint_event(h) e.keycode = getint_event(k) e.state = getint_event(s) e.time = getint_event(t) e.width = getint_event(w) e.x = getint_event(x) e.y = getint_event(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint_event(N) try: e.type = EventType(T) except ValueError: e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint_event(X) e.y_root = getint_event(Y) try: e.delta = getint(D) except (ValueError, TclError): e.delta = 0 return (e,) def _report_exception(self): """Internal function.""" exc, val, tb = sys.exc_info() root = self._root() root.report_callback_exception(exc, val, tb) def _getconfigure(self, *args): """Call Tcl configure command and return the result as a dict.""" cnf = {} for x in self.tk.splitlist(self.tk.call(*args)): x = self.tk.splitlist(x) cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf def _getconfigure1(self, *args): x = self.tk.splitlist(self.tk.call(*args)) return (x[0][1:],) + x[1:] def _configure(self, cmd, cnf, kw): """Internal function.""" if kw: cnf = _cnfmerge((cnf, kw)) elif cnf: cnf = _cnfmerge(cnf) if cnf is None: return self._getconfigure(_flatten((self._w, cmd))) if isinstance(cnf, str): return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf))) self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) # These used to be defined in Widget: def configure(self, cnf=None, **kw): """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys. """ return self._configure('configure', cnf, kw) config = configure def cget(self, key): """Return the resource value for a KEY given as string.""" return self.tk.call(self._w, 'cget', '-' + key) __getitem__ = cget def __setitem__(self, key, value): self.configure({key: value}) def keys(self): """Return a list of all resource names of this widget.""" splitlist = self.tk.splitlist return [splitlist(x)[0][1:] for x in splitlist(self.tk.call(self._w, 'configure'))] def __str__(self): """Return the window path name of this widget.""" return self._w def __repr__(self): return '<%s.%s object %s>' % ( self.__class__.__module__, self.__class__.__qualname__, self._w) # Pack methods that apply to the master _noarg_ = ['_noarg_'] def pack_propagate(self, flag=_noarg_): """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given the current setting will be returned. """ if flag is Misc._noarg_: return self._getboolean(self.tk.call( 'pack', 'propagate', self._w)) else: self.tk.call('pack', 'propagate', self._w, flag) propagate = pack_propagate def pack_slaves(self): """Return a list of all slaves of this widget in its packing order.""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call('pack', 'slaves', self._w))] slaves = pack_slaves # Place method that applies to the master def place_slaves(self): """Return a list of all slaves of this widget in its packing order.""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call( 'place', 'slaves', self._w))] # Grid methods that apply to the master def grid_anchor(self, anchor=None): # new in Tk 8.5 """The anchor value controls how to place the grid within the master when no row/column has any weight. The default anchor is nw.""" self.tk.call('grid', 'anchor', self._w, anchor) anchor = grid_anchor def grid_bbox(self, column=None, row=None, col2=None, row2=None): """Return a tuple of integer coordinates for the bounding box of this widget controlled by the geometry manager grid. If COLUMN, ROW is given the bounding box applies from the cell with row and column 0 to the specified cell. If COL2 and ROW2 are given the bounding box starts at that cell. The returned integers specify the offset of the upper left corner in the master widget and the width and height. """ args = ('grid', 'bbox', self._w) if column is not None and row is not None: args = args + (column, row) if col2 is not None and row2 is not None: args = args + (col2, row2) return self._getints(self.tk.call(*args)) or None bbox = grid_bbox def _gridconvvalue(self, value): if isinstance(value, (str, _tkinter.Tcl_Obj)): try: svalue = str(value) if not svalue: return None elif '.' in svalue: return self.tk.getdouble(svalue) else: return self.tk.getint(svalue) except (ValueError, TclError): pass return value def _grid_configure(self, command, index, cnf, kw): """Internal function.""" if isinstance(cnf, str) and not kw: if cnf[-1:] == '_': cnf = cnf[:-1] if cnf[:1] != '-': cnf = '-'+cnf options = (cnf,) else: options = self._options(cnf, kw) if not options: return _splitdict( self.tk, self.tk.call('grid', command, self._w, index), conv=self._gridconvvalue) res = self.tk.call( ('grid', command, self._w, index) + options) if len(options) == 1: return self._gridconvvalue(res) def grid_columnconfigure(self, index, cnf={}, **kw): """Configure column INDEX of a grid. Valid resources are minsize (minimum size of the column), weight (how much does additional space propagate to this column) and pad (how much space to let additionally).""" return self._grid_configure('columnconfigure', index, cnf, kw) columnconfigure = grid_columnconfigure def grid_location(self, x, y): """Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located.""" return self._getints( self.tk.call( 'grid', 'location', self._w, x, y)) or None def grid_propagate(self, flag=_noarg_): """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given, the current setting will be returned. """ if flag is Misc._noarg_: return self._getboolean(self.tk.call( 'grid', 'propagate', self._w)) else: self.tk.call('grid', 'propagate', self._w, flag) def grid_rowconfigure(self, index, cnf={}, **kw): """Configure row INDEX of a grid. Valid resources are minsize (minimum size of the row), weight (how much does additional space propagate to this row) and pad (how much space to let additionally).""" return self._grid_configure('rowconfigure', index, cnf, kw) rowconfigure = grid_rowconfigure def grid_size(self): """Return a tuple of the number of column and rows in the grid.""" return self._getints( self.tk.call('grid', 'size', self._w)) or None size = grid_size def grid_slaves(self, row=None, column=None): """Return a list of all slaves of this widget in its packing order.""" args = () if row is not None: args = args + ('-row', row) if column is not None: args = args + ('-column', column) return [self._nametowidget(x) for x in self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args))] # Support for the "event" command, new in Tk 4.2. # By Case Roole. def event_add(self, virtual, *sequences): """Bind a virtual event VIRTUAL (of the form <<Name>>) to an event SEQUENCE such that the virtual event is triggered whenever SEQUENCE occurs.""" args = ('event', 'add', virtual) + sequences self.tk.call(args) def event_delete(self, virtual, *sequences): """Unbind a virtual event VIRTUAL from SEQUENCE.""" args = ('event', 'delete', virtual) + sequences self.tk.call(args) def event_generate(self, sequence, **kw): """Generate an event SEQUENCE. Additional keyword arguments specify parameter of the event (e.g. x, y, rootx, rooty).""" args = ('event', 'generate', self._w, sequence) for k, v in kw.items(): args = args + ('-%s' % k, str(v)) self.tk.call(args) def event_info(self, virtual=None): """Return a list of all virtual events or the information about the SEQUENCE bound to the virtual event VIRTUAL.""" return self.tk.splitlist( self.tk.call('event', 'info', virtual)) # Image related commands def image_names(self): """Return a list of all existing image names.""" return self.tk.splitlist(self.tk.call('image', 'names')) def image_types(self): """Return a list of all available image types (e.g. photo bitmap).""" return self.tk.splitlist(self.tk.call('image', 'types')) class CallWrapper: """Internal class. Stores function to call when some user defined Tcl function is called e.g. after an event occurred.""" def __init__(self, func, subst, widget): """Store FUNC, SUBST and WIDGET as members.""" self.func = func self.subst = subst self.widget = widget def __call__(self, *args): """Apply first function SUBST to arguments, than FUNC.""" try: if self.subst: args = self.subst(*args) return self.func(*args) except SystemExit: raise except: self.widget._report_exception() class XView: """Mix-in class for querying and changing the horizontal position of a widget's window.""" def xview(self, *args): """Query and change the horizontal position of the view.""" res = self.tk.call(self._w, 'xview', *args) if not args: return self._getdoubles(res) def xview_moveto(self, fraction): """Adjusts the view in the window so that FRACTION of the total width of the canvas is off-screen to the left.""" self.tk.call(self._w, 'xview', 'moveto', fraction) def xview_scroll(self, number, what): """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" self.tk.call(self._w, 'xview', 'scroll', number, what) class YView: """Mix-in class for querying and changing the vertical position of a widget's window.""" def yview(self, *args): """Query and change the vertical position of the view.""" res = self.tk.call(self._w, 'yview', *args) if not args: return self._getdoubles(res) def yview_moveto(self, fraction): """Adjusts the view in the window so that FRACTION of the total height of the canvas is off-screen to the top.""" self.tk.call(self._w, 'yview', 'moveto', fraction) def yview_scroll(self, number, what): """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" self.tk.call(self._w, 'yview', 'scroll', number, what) class Wm: """Provides functions for the communication with the window manager.""" def wm_aspect(self, minNumer=None, minDenom=None, maxNumer=None, maxDenom=None): """Instruct the window manager to set the aspect ratio (width/height) of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple of the actual values if no argument is given.""" return self._getints( self.tk.call('wm', 'aspect', self._w, minNumer, minDenom, maxNumer, maxDenom)) aspect = wm_aspect def wm_attributes(self, *args): """This subcommand returns or sets platform specific attributes The first form returns a list of the platform specific flags and their values. The second form returns the value for the specific option. The third form sets one or more of the values. The values are as follows: On Windows, -disabled gets or sets whether the window is in a disabled state. -toolwindow gets or sets the style of the window to toolwindow (as defined in the MSDN). -topmost gets or sets whether this is a topmost window (displays above all other windows). On Macintosh, XXXXX On Unix, there are currently no special attribute values. """ args = ('wm', 'attributes', self._w) + args return self.tk.call(args) attributes=wm_attributes def wm_client(self, name=None): """Store NAME in WM_CLIENT_MACHINE property of this widget. Return current value.""" return self.tk.call('wm', 'client', self._w, name) client = wm_client def wm_colormapwindows(self, *wlist): """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property of this widget. This list contains windows whose colormaps differ from their parents. Return current list of widgets if WLIST is empty.""" if len(wlist) > 1: wlist = (wlist,) # Tk needs a list of windows here args = ('wm', 'colormapwindows', self._w) + wlist if wlist: self.tk.call(args) else: return [self._nametowidget(x) for x in self.tk.splitlist(self.tk.call(args))] colormapwindows = wm_colormapwindows def wm_command(self, value=None): """Store VALUE in WM_COMMAND property. It is the command which shall be used to invoke the application. Return current command if VALUE is None.""" return self.tk.call('wm', 'command', self._w, value) command = wm_command def wm_deiconify(self): """Deiconify this widget. If it was never mapped it will not be mapped. On Windows it will raise this widget and give it the focus.""" return self.tk.call('wm', 'deiconify', self._w) deiconify = wm_deiconify def wm_focusmodel(self, model=None): """Set focus model to MODEL. "active" means that this widget will claim the focus itself, "passive" means that the window manager shall give the focus. Return current focus model if MODEL is None.""" return self.tk.call('wm', 'focusmodel', self._w, model) focusmodel = wm_focusmodel def wm_forget(self, window): # new in Tk 8.5 """The window will be unmapped from the screen and will no longer be managed by wm. toplevel windows will be treated like frame windows once they are no longer managed by wm, however, the menu option configuration will be remembered and the menus will return once the widget is managed again.""" self.tk.call('wm', 'forget', window) forget = wm_forget def wm_frame(self): """Return identifier for decorative frame of this widget if present.""" return self.tk.call('wm', 'frame', self._w) frame = wm_frame def wm_geometry(self, newGeometry=None): """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return current value if None is given.""" return self.tk.call('wm', 'geometry', self._w, newGeometry) geometry = wm_geometry def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): """Instruct the window manager that this widget shall only be resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the number of grid units requested in Tk_GeometryRequest.""" return self._getints(self.tk.call( 'wm', 'grid', self._w, baseWidth, baseHeight, widthInc, heightInc)) grid = wm_grid def wm_group(self, pathName=None): """Set the group leader widgets for related widgets to PATHNAME. Return the group leader of this widget if None is given.""" return self.tk.call('wm', 'group', self._w, pathName) group = wm_group def wm_iconbitmap(self, bitmap=None, default=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given. Under Windows, the DEFAULT parameter can be used to set the icon for the widget and any descendents that don't have an icon set explicitly. DEFAULT can be the relative path to a .ico file (example: root.iconbitmap(default='myicon.ico') ). See Tk documentation for more information.""" if default: return self.tk.call('wm', 'iconbitmap', self._w, '-default', default) else: return self.tk.call('wm', 'iconbitmap', self._w, bitmap) iconbitmap = wm_iconbitmap def wm_iconify(self): """Display widget as icon.""" return self.tk.call('wm', 'iconify', self._w) iconify = wm_iconify def wm_iconmask(self, bitmap=None): """Set mask for the icon bitmap of this widget. Return the mask if None is given.""" return self.tk.call('wm', 'iconmask', self._w, bitmap) iconmask = wm_iconmask def wm_iconname(self, newName=None): """Set the name of the icon for this widget. Return the name if None is given.""" return self.tk.call('wm', 'iconname', self._w, newName) iconname = wm_iconname def wm_iconphoto(self, default=False, *args): # new in Tk 8.5 """Sets the titlebar icon for this window based on the named photo images passed through args. If default is True, this is applied to all future created toplevels as well. The data in the images is taken as a snapshot at the time of invocation. If the images are later changed, this is not reflected to the titlebar icons. Multiple images are accepted to allow different images sizes to be provided. The window manager may scale provided icons to an appropriate size. On Windows, the images are packed into a Windows icon structure. This will override an icon specified to wm_iconbitmap, and vice versa. On X, the images are arranged into the _NET_WM_ICON X property, which most modern window managers support. An icon specified by wm_iconbitmap may exist simultaneously. On Macintosh, this currently does nothing.""" if default: self.tk.call('wm', 'iconphoto', self._w, "-default", *args) else: self.tk.call('wm', 'iconphoto', self._w, *args) iconphoto = wm_iconphoto def wm_iconposition(self, x=None, y=None): """Set the position of the icon of this widget to X and Y. Return a tuple of the current values of X and X if None is given.""" return self._getints(self.tk.call( 'wm', 'iconposition', self._w, x, y)) iconposition = wm_iconposition def wm_iconwindow(self, pathName=None): """Set widget PATHNAME to be displayed instead of icon. Return the current value if None is given.""" return self.tk.call('wm', 'iconwindow', self._w, pathName) iconwindow = wm_iconwindow def wm_manage(self, widget): # new in Tk 8.5 """The widget specified will become a stand alone top-level window. The window will be decorated with the window managers title bar, etc.""" self.tk.call('wm', 'manage', widget) manage = wm_manage def wm_maxsize(self, width=None, height=None): """Set max WIDTH and HEIGHT for this widget. If the window is gridded the values are given in grid units. Return the current values if None is given.""" return self._getints(self.tk.call( 'wm', 'maxsize', self._w, width, height)) maxsize = wm_maxsize def wm_minsize(self, width=None, height=None): """Set min WIDTH and HEIGHT for this widget. If the window is gridded the values are given in grid units. Return the current values if None is given.""" return self._getints(self.tk.call( 'wm', 'minsize', self._w, width, height)) minsize = wm_minsize def wm_overrideredirect(self, boolean=None): """Instruct the window manager to ignore this widget if BOOLEAN is given with 1. Return the current value if None is given.""" return self._getboolean(self.tk.call( 'wm', 'overrideredirect', self._w, boolean)) overrideredirect = wm_overrideredirect def wm_positionfrom(self, who=None): """Instruct the window manager that the position of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program".""" return self.tk.call('wm', 'positionfrom', self._w, who) positionfrom = wm_positionfrom def wm_protocol(self, name=None, func=None): """Bind function FUNC to command NAME for this widget. Return the function bound to NAME if None is given. NAME could be e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW".""" if callable(func): command = self._register(func) else: command = func return self.tk.call( 'wm', 'protocol', self._w, name, command) protocol = wm_protocol def wm_resizable(self, width=None, height=None): """Instruct the window manager whether this width can be resized in WIDTH or HEIGHT. Both values are boolean values.""" return self.tk.call('wm', 'resizable', self._w, width, height) resizable = wm_resizable def wm_sizefrom(self, who=None): """Instruct the window manager that the size of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program".""" return self.tk.call('wm', 'sizefrom', self._w, who) sizefrom = wm_sizefrom def wm_state(self, newstate=None): """Query or set the state of this widget as one of normal, icon, iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only).""" return self.tk.call('wm', 'state', self._w, newstate) state = wm_state def wm_title(self, string=None): """Set the title of this widget.""" return self.tk.call('wm', 'title', self._w, string) title = wm_title def wm_transient(self, master=None): """Instruct the window manager that this widget is transient with regard to widget MASTER.""" return self.tk.call('wm', 'transient', self._w, master) transient = wm_transient def wm_withdraw(self): """Withdraw this widget from the screen such that it is unmapped and forgotten by the window manager. Re-draw it with wm_deiconify.""" return self.tk.call('wm', 'withdraw', self._w) withdraw = wm_withdraw class Tk(Misc, Wm): """Toplevel widget of Tk which represents mostly the main window of an application. It has an associated Tcl interpreter.""" _w = '.' def __init__(self, screenName=None, baseName=None, className='Tk', useTk=1, sync=0, use=None): """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME is the name of the widget class.""" self.master = None self.children = {} self._tkloaded = 0 # to avoid recursions in the getattr code in case of failure, we # ensure that self.tk is always _something_. self.tk = None if baseName is None: import os baseName = os.path.basename(sys.argv[0]) baseName, ext = os.path.splitext(baseName) if ext not in ('.py', '.pyc'): baseName = baseName + ext interactive = 0 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) if useTk: self._loadtk() if not sys.flags.ignore_environment: # Issue #16248: Honor the -E flag to avoid code injection. self.readprofile(baseName, className) def loadtk(self): if not self._tkloaded: self.tk.loadtk() self._loadtk() def _loadtk(self): self._tkloaded = 1 global _default_root # Version sanity checks tk_version = self.tk.getvar('tk_version') if tk_version != _tkinter.TK_VERSION: raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)" % (_tkinter.TK_VERSION, tk_version)) # Under unknown circumstances, tcl_version gets coerced to float tcl_version = str(self.tk.getvar('tcl_version')) if tcl_version != _tkinter.TCL_VERSION: raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \ % (_tkinter.TCL_VERSION, tcl_version)) # Create and register the tkerror and exit commands # We need to inline parts of _register here, _ register # would register differently-named commands. if self._tclCommands is None: self._tclCommands = [] self.tk.createcommand('tkerror', _tkerror) self.tk.createcommand('exit', _exit) self._tclCommands.append('tkerror') self._tclCommands.append('exit') if _support_default_root and not _default_root: _default_root = self self.protocol("WM_DELETE_WINDOW", self.destroy) def destroy(self): """Destroy this and all descendants widgets. This will end the application of this Tcl interpreter.""" for c in list(self.children.values()): c.destroy() self.tk.call('destroy', self._w) Misc.destroy(self) global _default_root if _support_default_root and _default_root is self: _default_root = None def readprofile(self, baseName, className): """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into the Tcl Interpreter and calls exec on the contents of BASENAME.py and CLASSNAME.py if such a file exists in the home directory.""" import os if 'HOME' in os.environ: home = os.environ['HOME'] else: home = os.curdir class_tcl = os.path.join(home, '.%s.tcl' % className) class_py = os.path.join(home, '.%s.py' % className) base_tcl = os.path.join(home, '.%s.tcl' % baseName) base_py = os.path.join(home, '.%s.py' % baseName) dir = {'self': self} exec('from tkinter import *', dir) if os.path.isfile(class_tcl): self.tk.call('source', class_tcl) if os.path.isfile(class_py): exec(open(class_py).read(), dir) if os.path.isfile(base_tcl): self.tk.call('source', base_tcl) if os.path.isfile(base_py): exec(open(base_py).read(), dir) def report_callback_exception(self, exc, val, tb): """Report callback exception on sys.stderr. Applications may want to override this internal function, and should when sys.stderr is None.""" import traceback print("Exception in Tkinter callback", file=sys.stderr) sys.last_type = exc sys.last_value = val sys.last_traceback = tb traceback.print_exception(exc, val, tb) def __getattr__(self, attr): "Delegate attribute access to the interpreter object" return getattr(self.tk, attr) # Ideally, the classes Pack, Place and Grid disappear, the # pack/place/grid methods are defined on the Widget class, and # everybody uses w.pack_whatever(...) instead of Pack.whatever(w, # ...), with pack(), place() and grid() being short for # pack_configure(), place_configure() and grid_columnconfigure(), and # forget() being short for pack_forget(). As a practical matter, I'm # afraid that there is too much code out there that may be using the # Pack, Place or Grid class, so I leave them intact -- but only as # backwards compatibility features. Also note that those methods that # take a master as argument (e.g. pack_propagate) have been moved to # the Misc class (which now incorporates all methods common between # toplevel and interior widgets). Again, for compatibility, these are # copied into the Pack, Place or Grid class. def Tcl(screenName=None, baseName=None, className='Tk', useTk=0): return Tk(screenName, baseName, className, useTk) class Pack: """Geometry manager Pack. Base class to use the methods pack_* in every widget.""" def pack_configure(self, cnf={}, **kw): """Pack a widget in the parent widget. Use as options: after=widget - pack it after you have packed widget anchor=NSEW (or subset) - position widget according to given direction before=widget - pack it before you will pack widget expand=bool - expand widget if parent size grows fill=NONE or X or Y or BOTH - fill widget if widget grows in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget. """ self.tk.call( ('pack', 'configure', self._w) + self._options(cnf, kw)) pack = configure = config = pack_configure def pack_forget(self): """Unmap this widget and do not use it for the packing order.""" self.tk.call('pack', 'forget', self._w) forget = pack_forget def pack_info(self): """Return information about the packing options for this widget.""" d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = pack_info propagate = pack_propagate = Misc.pack_propagate slaves = pack_slaves = Misc.pack_slaves class Place: """Geometry manager Place. Base class to use the methods place_* in every widget.""" def place_configure(self, cnf={}, **kw): """Place a widget in the parent widget. Use as options: in=master - master relative to which the widget is placed in_=master - see 'in' option description x=amount - locate anchor of this widget at position x of master y=amount - locate anchor of this widget at position y of master relx=amount - locate anchor of this widget between 0.0 and 1.0 relative to width of master (1.0 is right edge) rely=amount - locate anchor of this widget between 0.0 and 1.0 relative to height of master (1.0 is bottom edge) anchor=NSEW (or subset) - position anchor according to given direction width=amount - width of this widget in pixel height=amount - height of this widget in pixel relwidth=amount - width of this widget between 0.0 and 1.0 relative to width of master (1.0 is the same width as the master) relheight=amount - height of this widget between 0.0 and 1.0 relative to height of master (1.0 is the same height as the master) bordermode="inside" or "outside" - whether to take border width of master widget into account """ self.tk.call( ('place', 'configure', self._w) + self._options(cnf, kw)) place = configure = config = place_configure def place_forget(self): """Unmap this widget.""" self.tk.call('place', 'forget', self._w) forget = place_forget def place_info(self): """Return information about the placing options for this widget.""" d = _splitdict(self.tk, self.tk.call('place', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = place_info slaves = place_slaves = Misc.place_slaves class Grid: """Geometry manager Grid. Base class to use the methods grid_* in every widget.""" # Thanks to Masazumi Yoshikawa ([email protected]) def grid_configure(self, cnf={}, **kw): """Position a widget in the parent widget in a grid. Use as options: column=number - use cell identified with given column (starting with 0) columnspan=number - this widget will span several columns in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction row=number - use cell identified with given row (starting with 0) rowspan=number - this widget will span several rows sticky=NSEW - if cell is larger on which sides will this widget stick to the cell boundary """ self.tk.call( ('grid', 'configure', self._w) + self._options(cnf, kw)) grid = configure = config = grid_configure bbox = grid_bbox = Misc.grid_bbox columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure def grid_forget(self): """Unmap this widget.""" self.tk.call('grid', 'forget', self._w) forget = grid_forget def grid_remove(self): """Unmap this widget but remember the grid options.""" self.tk.call('grid', 'remove', self._w) def grid_info(self): """Return information about the options for positioning this widget in a grid.""" d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = grid_info location = grid_location = Misc.grid_location propagate = grid_propagate = Misc.grid_propagate rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure size = grid_size = Misc.grid_size slaves = grid_slaves = Misc.grid_slaves class BaseWidget(Misc): """Internal class.""" def _setup(self, master, cnf): """Internal function. Sets up information about children.""" if _support_default_root: global _default_root if not master: if not _default_root: _default_root = Tk() master = _default_root self.master = master self.tk = master.tk name = None if 'name' in cnf: name = cnf['name'] del cnf['name'] if not name: name = self.__class__.__name__.lower() if master._last_child_ids is None: master._last_child_ids = {} count = master._last_child_ids.get(name, 0) + 1 master._last_child_ids[name] = count if count == 1: name = '!%s' % (name,) else: name = '!%s%d' % (name, count) self._name = name if master._w=='.': self._w = '.' + name else: self._w = master._w + '.' + name self.children = {} if self._name in self.master.children: self.master.children[self._name].destroy() self.master.children[self._name] = self def __init__(self, master, widgetName, cnf={}, kw={}, extra=()): """Construct a widget with the parent widget MASTER, a name WIDGETNAME and appropriate options.""" if kw: cnf = _cnfmerge((cnf, kw)) self.widgetName = widgetName BaseWidget._setup(self, master, cnf) if self._tclCommands is None: self._tclCommands = [] classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)] for k, v in classes: del cnf[k] self.tk.call( (widgetName, self._w) + extra + self._options(cnf)) for k, v in classes: k.configure(self, v) def destroy(self): """Destroy this and all descendants widgets.""" for c in list(self.children.values()): c.destroy() self.tk.call('destroy', self._w) if self._name in self.master.children: del self.master.children[self._name] Misc.destroy(self) def _do(self, name, args=()): # XXX Obsolete -- better use self.tk.call directly! return self.tk.call((self._w, name) + args) class Widget(BaseWidget, Pack, Place, Grid): """Internal class. Base class for a widget which can be positioned with the geometry managers Pack, Place or Grid.""" pass class Toplevel(BaseWidget, Wm): """Toplevel widget, e.g. for dialogs.""" def __init__(self, master=None, cnf={}, **kw): """Construct a toplevel widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.""" if kw: cnf = _cnfmerge((cnf, kw)) extra = () for wmkey in ['screen', 'class_', 'class', 'visual', 'colormap']: if wmkey in cnf: val = cnf[wmkey] # TBD: a hack needed because some keys # are not valid as keyword arguments if wmkey[-1] == '_': opt = '-'+wmkey[:-1] else: opt = '-'+wmkey extra = extra + (opt, val) del cnf[wmkey] BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra) root = self._root() self.iconname(root.iconname()) self.title(root.title()) self.protocol("WM_DELETE_WINDOW", self.destroy) class Button(Widget): """Button widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a button widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, repeatdelay, repeatinterval, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS command, compound, default, height, overrelief, state, width """ Widget.__init__(self, master, 'button', cnf, kw) def flash(self): """Flash the button. This is accomplished by redisplaying the button several times, alternating between active and normal colors. At the end of the flash the button is left in the same normal/active state as when the command was invoked. This command is ignored if the button's state is disabled. """ self.tk.call(self._w, 'flash') def invoke(self): """Invoke the command associated with the button. The return value is the return value from the command, or an empty string if there is no command associated with the button. This command is ignored if the button's state is disabled. """ return self.tk.call(self._w, 'invoke') class Canvas(Widget, XView, YView): """Canvas widget to display graphical elements like lines or text.""" def __init__(self, master=None, cnf={}, **kw): """Construct a canvas widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, closeenough, confine, cursor, height, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, offset, relief, scrollregion, selectbackground, selectborderwidth, selectforeground, state, takefocus, width, xscrollcommand, xscrollincrement, yscrollcommand, yscrollincrement.""" Widget.__init__(self, master, 'canvas', cnf, kw) def addtag(self, *args): """Internal function.""" self.tk.call((self._w, 'addtag') + args) def addtag_above(self, newtag, tagOrId): """Add tag NEWTAG to all items above TAGORID.""" self.addtag(newtag, 'above', tagOrId) def addtag_all(self, newtag): """Add tag NEWTAG to all items.""" self.addtag(newtag, 'all') def addtag_below(self, newtag, tagOrId): """Add tag NEWTAG to all items below TAGORID.""" self.addtag(newtag, 'below', tagOrId) def addtag_closest(self, newtag, x, y, halo=None, start=None): """Add tag NEWTAG to item which is closest to pixel at X, Y. If several match take the top-most. All items closer than HALO are considered overlapping (all are closests). If START is specified the next below this tag is taken.""" self.addtag(newtag, 'closest', x, y, halo, start) def addtag_enclosed(self, newtag, x1, y1, x2, y2): """Add tag NEWTAG to all items in the rectangle defined by X1,Y1,X2,Y2.""" self.addtag(newtag, 'enclosed', x1, y1, x2, y2) def addtag_overlapping(self, newtag, x1, y1, x2, y2): """Add tag NEWTAG to all items which overlap the rectangle defined by X1,Y1,X2,Y2.""" self.addtag(newtag, 'overlapping', x1, y1, x2, y2) def addtag_withtag(self, newtag, tagOrId): """Add tag NEWTAG to all items with TAGORID.""" self.addtag(newtag, 'withtag', tagOrId) def bbox(self, *args): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses all items with tags specified as arguments.""" return self._getints( self.tk.call((self._w, 'bbox') + args)) or None def tag_unbind(self, tagOrId, sequence, funcid=None): """Unbind for all items with TAGORID for event SEQUENCE the function identified with FUNCID.""" self.tk.call(self._w, 'bind', tagOrId, sequence, '') if funcid: self.deletecommand(funcid) def tag_bind(self, tagOrId, sequence=None, func=None, add=None): """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind((self._w, 'bind', tagOrId), sequence, func, add) def canvasx(self, screenx, gridspacing=None): """Return the canvas x coordinate of pixel position SCREENX rounded to nearest multiple of GRIDSPACING units.""" return self.tk.getdouble(self.tk.call( self._w, 'canvasx', screenx, gridspacing)) def canvasy(self, screeny, gridspacing=None): """Return the canvas y coordinate of pixel position SCREENY rounded to nearest multiple of GRIDSPACING units.""" return self.tk.getdouble(self.tk.call( self._w, 'canvasy', screeny, gridspacing)) def coords(self, *args): """Return a list of coordinates for the item given in ARGS.""" # XXX Should use _flatten on args return [self.tk.getdouble(x) for x in self.tk.splitlist( self.tk.call((self._w, 'coords') + args))] def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={}) """Internal function.""" args = _flatten(args) cnf = args[-1] if isinstance(cnf, (dict, tuple)): args = args[:-1] else: cnf = {} return self.tk.getint(self.tk.call( self._w, 'create', itemType, *(args + self._options(cnf, kw)))) def create_arc(self, *args, **kw): """Create arc shaped region with coordinates x1,y1,x2,y2.""" return self._create('arc', args, kw) def create_bitmap(self, *args, **kw): """Create bitmap with coordinates x1,y1.""" return self._create('bitmap', args, kw) def create_image(self, *args, **kw): """Create image item with coordinates x1,y1.""" return self._create('image', args, kw) def create_line(self, *args, **kw): """Create line with coordinates x1,y1,...,xn,yn.""" return self._create('line', args, kw) def create_oval(self, *args, **kw): """Create oval with coordinates x1,y1,x2,y2.""" return self._create('oval', args, kw) def create_polygon(self, *args, **kw): """Create polygon with coordinates x1,y1,...,xn,yn.""" return self._create('polygon', args, kw) def create_rectangle(self, *args, **kw): """Create rectangle with coordinates x1,y1,x2,y2.""" return self._create('rectangle', args, kw) def create_text(self, *args, **kw): """Create text with coordinates x1,y1.""" return self._create('text', args, kw) def create_window(self, *args, **kw): """Create window with coordinates x1,y1,x2,y2.""" return self._create('window', args, kw) def dchars(self, *args): """Delete characters of text items identified by tag or id in ARGS (possibly several times) from FIRST to LAST character (including).""" self.tk.call((self._w, 'dchars') + args) def delete(self, *args): """Delete items identified by all tag or ids contained in ARGS.""" self.tk.call((self._w, 'delete') + args) def dtag(self, *args): """Delete tag or id given as last arguments in ARGS from items identified by first argument in ARGS.""" self.tk.call((self._w, 'dtag') + args) def find(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'find') + args)) or () def find_above(self, tagOrId): """Return items above TAGORID.""" return self.find('above', tagOrId) def find_all(self): """Return all items.""" return self.find('all') def find_below(self, tagOrId): """Return all items below TAGORID.""" return self.find('below', tagOrId) def find_closest(self, x, y, halo=None, start=None): """Return item which is closest to pixel at X, Y. If several match take the top-most. All items closer than HALO are considered overlapping (all are closest). If START is specified the next below this tag is taken.""" return self.find('closest', x, y, halo, start) def find_enclosed(self, x1, y1, x2, y2): """Return all items in rectangle defined by X1,Y1,X2,Y2.""" return self.find('enclosed', x1, y1, x2, y2) def find_overlapping(self, x1, y1, x2, y2): """Return all items which overlap the rectangle defined by X1,Y1,X2,Y2.""" return self.find('overlapping', x1, y1, x2, y2) def find_withtag(self, tagOrId): """Return all items with TAGORID.""" return self.find('withtag', tagOrId) def focus(self, *args): """Set focus to the first item specified in ARGS.""" return self.tk.call((self._w, 'focus') + args) def gettags(self, *args): """Return tags associated with the first item specified in ARGS.""" return self.tk.splitlist( self.tk.call((self._w, 'gettags') + args)) def icursor(self, *args): """Set cursor at position POS in the item identified by TAGORID. In ARGS TAGORID must be first.""" self.tk.call((self._w, 'icursor') + args) def index(self, *args): """Return position of cursor as integer in item specified in ARGS.""" return self.tk.getint(self.tk.call((self._w, 'index') + args)) def insert(self, *args): """Insert TEXT in item TAGORID at position POS. ARGS must be TAGORID POS TEXT.""" self.tk.call((self._w, 'insert') + args) def itemcget(self, tagOrId, option): """Return the resource value for an OPTION for item TAGORID.""" return self.tk.call( (self._w, 'itemcget') + (tagOrId, '-'+option)) def itemconfigure(self, tagOrId, cnf=None, **kw): """Configure resources of an item TAGORID. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method without arguments. """ return self._configure(('itemconfigure', tagOrId), cnf, kw) itemconfig = itemconfigure # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift, # so the preferred name for them is tag_lower, tag_raise # (similar to tag_bind, and similar to the Text widget); # unfortunately can't delete the old ones yet (maybe in 1.6) def tag_lower(self, *args): """Lower an item TAGORID given in ARGS (optional below another item).""" self.tk.call((self._w, 'lower') + args) lower = tag_lower def move(self, *args): """Move an item TAGORID given in ARGS.""" self.tk.call((self._w, 'move') + args) def postscript(self, cnf={}, **kw): """Print the contents of the canvas to a postscript file. Valid options: colormap, colormode, file, fontmap, height, pageanchor, pageheight, pagewidth, pagex, pagey, rotate, width, x, y.""" return self.tk.call((self._w, 'postscript') + self._options(cnf, kw)) def tag_raise(self, *args): """Raise an item TAGORID given in ARGS (optional above another item).""" self.tk.call((self._w, 'raise') + args) lift = tkraise = tag_raise def scale(self, *args): """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE.""" self.tk.call((self._w, 'scale') + args) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y, gain=10): """Adjust the view of the canvas to GAIN times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y, gain) def select_adjust(self, tagOrId, index): """Adjust the end of the selection near the cursor of an item TAGORID to index.""" self.tk.call(self._w, 'select', 'adjust', tagOrId, index) def select_clear(self): """Clear the selection if it is in this widget.""" self.tk.call(self._w, 'select', 'clear') def select_from(self, tagOrId, index): """Set the fixed end of a selection in item TAGORID to INDEX.""" self.tk.call(self._w, 'select', 'from', tagOrId, index) def select_item(self): """Return the item which has the selection.""" return self.tk.call(self._w, 'select', 'item') or None def select_to(self, tagOrId, index): """Set the variable end of a selection in item TAGORID to INDEX.""" self.tk.call(self._w, 'select', 'to', tagOrId, index) def type(self, tagOrId): """Return the type of the item TAGORID.""" return self.tk.call(self._w, 'type', tagOrId) or None class Checkbutton(Widget): """Checkbutton widget which is either in on- or off-state.""" def __init__(self, master=None, cnf={}, **kw): """Construct a checkbutton widget with the parent MASTER. Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, disabledforeground, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, image, indicatoron, justify, offvalue, onvalue, padx, pady, relief, selectcolor, selectimage, state, takefocus, text, textvariable, underline, variable, width, wraplength.""" Widget.__init__(self, master, 'checkbutton', cnf, kw) def deselect(self): """Put the button in off-state.""" self.tk.call(self._w, 'deselect') def flash(self): """Flash the button.""" self.tk.call(self._w, 'flash') def invoke(self): """Toggle the button and invoke a command if given as resource.""" return self.tk.call(self._w, 'invoke') def select(self): """Put the button in on-state.""" self.tk.call(self._w, 'select') def toggle(self): """Toggle the button.""" self.tk.call(self._w, 'toggle') class Entry(Widget, XView): """Entry widget which allows displaying simple text.""" def __init__(self, master=None, cnf={}, **kw): """Construct an entry widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, invalidcommand, invcmd, justify, relief, selectbackground, selectborderwidth, selectforeground, show, state, takefocus, textvariable, validate, validatecommand, vcmd, width, xscrollcommand.""" Widget.__init__(self, master, 'entry', cnf, kw) def delete(self, first, last=None): """Delete text from FIRST to LAST (not included).""" self.tk.call(self._w, 'delete', first, last) def get(self): """Return the text.""" return self.tk.call(self._w, 'get') def icursor(self, index): """Insert cursor at INDEX.""" self.tk.call(self._w, 'icursor', index) def index(self, index): """Return position of cursor.""" return self.tk.getint(self.tk.call( self._w, 'index', index)) def insert(self, index, string): """Insert STRING at INDEX.""" self.tk.call(self._w, 'insert', index, string) def scan_mark(self, x): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x) def scan_dragto(self, x): """Adjust the view of the canvas to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x) def selection_adjust(self, index): """Adjust the end of the selection near the cursor to INDEX.""" self.tk.call(self._w, 'selection', 'adjust', index) select_adjust = selection_adjust def selection_clear(self): """Clear the selection if it is in this widget.""" self.tk.call(self._w, 'selection', 'clear') select_clear = selection_clear def selection_from(self, index): """Set the fixed end of a selection to INDEX.""" self.tk.call(self._w, 'selection', 'from', index) select_from = selection_from def selection_present(self): """Return True if there are characters selected in the entry, False otherwise.""" return self.tk.getboolean( self.tk.call(self._w, 'selection', 'present')) select_present = selection_present def selection_range(self, start, end): """Set the selection from START to END (not included).""" self.tk.call(self._w, 'selection', 'range', start, end) select_range = selection_range def selection_to(self, index): """Set the variable end of a selection to INDEX.""" self.tk.call(self._w, 'selection', 'to', index) select_to = selection_to class Frame(Widget): """Frame widget which may contain other widgets and can have a 3D border.""" def __init__(self, master=None, cnf={}, **kw): """Construct a frame widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, relief, takefocus, visual, width.""" cnf = _cnfmerge((cnf, kw)) extra = () if 'class_' in cnf: extra = ('-class', cnf['class_']) del cnf['class_'] elif 'class' in cnf: extra = ('-class', cnf['class']) del cnf['class'] Widget.__init__(self, master, 'frame', cnf, {}, extra) class Label(Widget): """Label widget which can display text and bitmaps.""" def __init__(self, master=None, cnf={}, **kw): """Construct a label widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground, highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS height, state, width """ Widget.__init__(self, master, 'label', cnf, kw) class Listbox(Widget, XView, YView): """Listbox widget which can display a list of strings.""" def __init__(self, master=None, cnf={}, **kw): """Construct a listbox widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, relief, selectbackground, selectborderwidth, selectforeground, selectmode, setgrid, takefocus, width, xscrollcommand, yscrollcommand, listvariable.""" Widget.__init__(self, master, 'listbox', cnf, kw) def activate(self, index): """Activate item identified by INDEX.""" self.tk.call(self._w, 'activate', index) def bbox(self, index): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the item identified by the given index.""" return self._getints(self.tk.call(self._w, 'bbox', index)) or None def curselection(self): """Return the indices of currently selected item.""" return self._getints(self.tk.call(self._w, 'curselection')) or () def delete(self, first, last=None): """Delete items from FIRST to LAST (included).""" self.tk.call(self._w, 'delete', first, last) def get(self, first, last=None): """Get list of items from FIRST to LAST (included).""" if last is not None: return self.tk.splitlist(self.tk.call( self._w, 'get', first, last)) else: return self.tk.call(self._w, 'get', first) def index(self, index): """Return index of item identified with INDEX.""" i = self.tk.call(self._w, 'index', index) if i == 'none': return None return self.tk.getint(i) def insert(self, index, *elements): """Insert ELEMENTS at INDEX.""" self.tk.call((self._w, 'insert', index) + elements) def nearest(self, y): """Get index of item which is nearest to y coordinate Y.""" return self.tk.getint(self.tk.call( self._w, 'nearest', y)) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): """Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y) def see(self, index): """Scroll such that INDEX is visible.""" self.tk.call(self._w, 'see', index) def selection_anchor(self, index): """Set the fixed end oft the selection to INDEX.""" self.tk.call(self._w, 'selection', 'anchor', index) select_anchor = selection_anchor def selection_clear(self, first, last=None): """Clear the selection from FIRST to LAST (included).""" self.tk.call(self._w, 'selection', 'clear', first, last) select_clear = selection_clear def selection_includes(self, index): """Return 1 if INDEX is part of the selection.""" return self.tk.getboolean(self.tk.call( self._w, 'selection', 'includes', index)) select_includes = selection_includes def selection_set(self, first, last=None): """Set the selection from FIRST to LAST (included) without changing the currently selected elements.""" self.tk.call(self._w, 'selection', 'set', first, last) select_set = selection_set def size(self): """Return the number of elements in the listbox.""" return self.tk.getint(self.tk.call(self._w, 'size')) def itemcget(self, index, option): """Return the resource value for an ITEM and an OPTION.""" return self.tk.call( (self._w, 'itemcget') + (index, '-'+option)) def itemconfigure(self, index, cnf=None, **kw): """Configure resources of an ITEM. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method without arguments. Valid resource names: background, bg, foreground, fg, selectbackground, selectforeground.""" return self._configure(('itemconfigure', index), cnf, kw) itemconfig = itemconfigure class Menu(Widget): """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus.""" def __init__(self, master=None, cnf={}, **kw): """Construct menu widget with the parent MASTER. Valid resource names: activebackground, activeborderwidth, activeforeground, background, bd, bg, borderwidth, cursor, disabledforeground, fg, font, foreground, postcommand, relief, selectcolor, takefocus, tearoff, tearoffcommand, title, type.""" Widget.__init__(self, master, 'menu', cnf, kw) def tk_popup(self, x, y, entry=""): """Post the menu at position X,Y with entry ENTRY.""" self.tk.call('tk_popup', self._w, x, y, entry) def activate(self, index): """Activate entry at INDEX.""" self.tk.call(self._w, 'activate', index) def add(self, itemType, cnf={}, **kw): """Internal function.""" self.tk.call((self._w, 'add', itemType) + self._options(cnf, kw)) def add_cascade(self, cnf={}, **kw): """Add hierarchical menu item.""" self.add('cascade', cnf or kw) def add_checkbutton(self, cnf={}, **kw): """Add checkbutton menu item.""" self.add('checkbutton', cnf or kw) def add_command(self, cnf={}, **kw): """Add command menu item.""" self.add('command', cnf or kw) def add_radiobutton(self, cnf={}, **kw): """Addd radio menu item.""" self.add('radiobutton', cnf or kw) def add_separator(self, cnf={}, **kw): """Add separator.""" self.add('separator', cnf or kw) def insert(self, index, itemType, cnf={}, **kw): """Internal function.""" self.tk.call((self._w, 'insert', index, itemType) + self._options(cnf, kw)) def insert_cascade(self, index, cnf={}, **kw): """Add hierarchical menu item at INDEX.""" self.insert(index, 'cascade', cnf or kw) def insert_checkbutton(self, index, cnf={}, **kw): """Add checkbutton menu item at INDEX.""" self.insert(index, 'checkbutton', cnf or kw) def insert_command(self, index, cnf={}, **kw): """Add command menu item at INDEX.""" self.insert(index, 'command', cnf or kw) def insert_radiobutton(self, index, cnf={}, **kw): """Addd radio menu item at INDEX.""" self.insert(index, 'radiobutton', cnf or kw) def insert_separator(self, index, cnf={}, **kw): """Add separator at INDEX.""" self.insert(index, 'separator', cnf or kw) def delete(self, index1, index2=None): """Delete menu items between INDEX1 and INDEX2 (included).""" if index2 is None: index2 = index1 num_index1, num_index2 = self.index(index1), self.index(index2) if (num_index1 is None) or (num_index2 is None): num_index1, num_index2 = 0, -1 for i in range(num_index1, num_index2 + 1): if 'command' in self.entryconfig(i): c = str(self.entrycget(i, 'command')) if c: self.deletecommand(c) self.tk.call(self._w, 'delete', index1, index2) def entrycget(self, index, option): """Return the resource value of a menu item for OPTION at INDEX.""" return self.tk.call(self._w, 'entrycget', index, '-' + option) def entryconfigure(self, index, cnf=None, **kw): """Configure a menu item at INDEX.""" return self._configure(('entryconfigure', index), cnf, kw) entryconfig = entryconfigure def index(self, index): """Return the index of a menu item identified by INDEX.""" i = self.tk.call(self._w, 'index', index) if i == 'none': return None return self.tk.getint(i) def invoke(self, index): """Invoke a menu item identified by INDEX and execute the associated command.""" return self.tk.call(self._w, 'invoke', index) def post(self, x, y): """Display a menu at position X,Y.""" self.tk.call(self._w, 'post', x, y) def type(self, index): """Return the type of the menu item at INDEX.""" return self.tk.call(self._w, 'type', index) def unpost(self): """Unmap a menu.""" self.tk.call(self._w, 'unpost') def xposition(self, index): # new in Tk 8.5 """Return the x-position of the leftmost pixel of the menu item at INDEX.""" return self.tk.getint(self.tk.call(self._w, 'xposition', index)) def yposition(self, index): """Return the y-position of the topmost pixel of the menu item at INDEX.""" return self.tk.getint(self.tk.call( self._w, 'yposition', index)) class Menubutton(Widget): """Menubutton widget, obsolete since Tk8.0.""" def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'menubutton', cnf, kw) class Message(Widget): """Message widget to display multiline text. Obsolete since Label does it too.""" def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'message', cnf, kw) class Radiobutton(Widget): """Radiobutton widget which shows only one of several buttons in on-state.""" def __init__(self, master=None, cnf={}, **kw): """Construct a radiobutton widget with the parent MASTER. Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, disabledforeground, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, image, indicatoron, justify, padx, pady, relief, selectcolor, selectimage, state, takefocus, text, textvariable, underline, value, variable, width, wraplength.""" Widget.__init__(self, master, 'radiobutton', cnf, kw) def deselect(self): """Put the button in off-state.""" self.tk.call(self._w, 'deselect') def flash(self): """Flash the button.""" self.tk.call(self._w, 'flash') def invoke(self): """Toggle the button and invoke a command if given as resource.""" return self.tk.call(self._w, 'invoke') def select(self): """Put the button in on-state.""" self.tk.call(self._w, 'select') class Scale(Widget): """Scale widget which can display a numerical scale.""" def __init__(self, master=None, cnf={}, **kw): """Construct a scale widget with the parent MASTER. Valid resource names: activebackground, background, bigincrement, bd, bg, borderwidth, command, cursor, digits, fg, font, foreground, from, highlightbackground, highlightcolor, highlightthickness, label, length, orient, relief, repeatdelay, repeatinterval, resolution, showvalue, sliderlength, sliderrelief, state, takefocus, tickinterval, to, troughcolor, variable, width.""" Widget.__init__(self, master, 'scale', cnf, kw) def get(self): """Get the current value as integer or float.""" value = self.tk.call(self._w, 'get') try: return self.tk.getint(value) except (ValueError, TypeError, TclError): return self.tk.getdouble(value) def set(self, value): """Set the value to VALUE.""" self.tk.call(self._w, 'set', value) def coords(self, value=None): """Return a tuple (X,Y) of the point along the centerline of the trough that corresponds to VALUE or the current value if None is given.""" return self._getints(self.tk.call(self._w, 'coords', value)) def identify(self, x, y): """Return where the point X,Y lies. Valid return values are "slider", "though1" and "though2".""" return self.tk.call(self._w, 'identify', x, y) class Scrollbar(Widget): """Scrollbar widget which displays a slider at a certain position.""" def __init__(self, master=None, cnf={}, **kw): """Construct a scrollbar widget with the parent MASTER. Valid resource names: activebackground, activerelief, background, bd, bg, borderwidth, command, cursor, elementborderwidth, highlightbackground, highlightcolor, highlightthickness, jump, orient, relief, repeatdelay, repeatinterval, takefocus, troughcolor, width.""" Widget.__init__(self, master, 'scrollbar', cnf, kw) def activate(self, index=None): """Marks the element indicated by index as active. The only index values understood by this method are "arrow1", "slider", or "arrow2". If any other value is specified then no element of the scrollbar will be active. If index is not specified, the method returns the name of the element that is currently active, or None if no element is active.""" return self.tk.call(self._w, 'activate', index) or None def delta(self, deltax, deltay): """Return the fractional change of the scrollbar setting if it would be moved by DELTAX or DELTAY pixels.""" return self.tk.getdouble( self.tk.call(self._w, 'delta', deltax, deltay)) def fraction(self, x, y): """Return the fractional value which corresponds to a slider position of X,Y.""" return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y)) def identify(self, x, y): """Return the element under position X,Y as one of "arrow1","slider","arrow2" or "".""" return self.tk.call(self._w, 'identify', x, y) def get(self): """Return the current fractional values (upper and lower end) of the slider position.""" return self._getdoubles(self.tk.call(self._w, 'get')) def set(self, first, last): """Set the fractional values of the slider position (upper and lower ends as value between 0 and 1).""" self.tk.call(self._w, 'set', first, last) class Text(Widget, XView, YView): """Text widget which can display text in various forms.""" def __init__(self, master=None, cnf={}, **kw): """Construct a text widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground, setgrid, takefocus, xscrollcommand, yscrollcommand, WIDGET-SPECIFIC OPTIONS autoseparators, height, maxundo, spacing1, spacing2, spacing3, state, tabs, undo, width, wrap, """ Widget.__init__(self, master, 'text', cnf, kw) def bbox(self, index): """Return a tuple of (x,y,width,height) which gives the bounding box of the visible part of the character at the given index.""" return self._getints( self.tk.call(self._w, 'bbox', index)) or None def compare(self, index1, op, index2): """Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.""" return self.tk.getboolean(self.tk.call( self._w, 'compare', index1, op, index2)) def count(self, index1, index2, *args): # new in Tk 8.5 """Counts the number of relevant things between the two indices. If index1 is after index2, the result will be a negative number (and this holds for each of the possible options). The actual items which are counted depends on the options given by args. The result is a list of integers, one for the result of each counting option given. Valid counting options are "chars", "displaychars", "displayindices", "displaylines", "indices", "lines", "xpixels" and "ypixels". There is an additional possible option "update", which if given then all subsequent options ensure that any possible out of date information is recalculated.""" args = ['-%s' % arg for arg in args if not arg.startswith('-')] args += [index1, index2] res = self.tk.call(self._w, 'count', *args) or None if res is not None and len(args) <= 3: return (res, ) else: return res def debug(self, boolean=None): """Turn on the internal consistency checks of the B-Tree inside the text widget according to BOOLEAN.""" if boolean is None: return self.tk.getboolean(self.tk.call(self._w, 'debug')) self.tk.call(self._w, 'debug', boolean) def delete(self, index1, index2=None): """Delete the characters between INDEX1 and INDEX2 (not included).""" self.tk.call(self._w, 'delete', index1, index2) def dlineinfo(self, index): """Return tuple (x,y,width,height,baseline) giving the bounding box and baseline position of the visible part of the line containing the character at INDEX.""" return self._getints(self.tk.call(self._w, 'dlineinfo', index)) def dump(self, index1, index2=None, command=None, **kw): """Return the contents of the widget between index1 and index2. The type of contents returned in filtered based on the keyword parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are given and true, then the corresponding items are returned. The result is a list of triples of the form (key, value, index). If none of the keywords are true then 'all' is used by default. If the 'command' argument is given, it is called once for each element of the list of triples, with the values of each triple serving as the arguments to the function. In this case the list is not returned.""" args = [] func_name = None result = None if not command: # Never call the dump command without the -command flag, since the # output could involve Tcl quoting and would be a pain to parse # right. Instead just set the command to build a list of triples # as if we had done the parsing. result = [] def append_triple(key, value, index, result=result): result.append((key, value, index)) command = append_triple try: if not isinstance(command, str): func_name = command = self._register(command) args += ["-command", command] for key in kw: if kw[key]: args.append("-" + key) args.append(index1) if index2: args.append(index2) self.tk.call(self._w, "dump", *args) return result finally: if func_name: self.deletecommand(func_name) ## new in tk8.4 def edit(self, *args): """Internal method This method controls the undo mechanism and the modified flag. The exact behavior of the command depends on the option argument that follows the edit argument. The following forms of the command are currently supported: edit_modified, edit_redo, edit_reset, edit_separator and edit_undo """ return self.tk.call(self._w, 'edit', *args) def edit_modified(self, arg=None): """Get or Set the modified flag If arg is not specified, returns the modified flag of the widget. The insert, delete, edit undo and edit redo commands or the user can set or clear the modified flag. If boolean is specified, sets the modified flag of the widget to arg. """ return self.edit("modified", arg) def edit_redo(self): """Redo the last undone edit When the undo option is true, reapplies the last undone edits provided no other edits were done since then. Generates an error when the redo stack is empty. Does nothing when the undo option is false. """ return self.edit("redo") def edit_reset(self): """Clears the undo and redo stacks """ return self.edit("reset") def edit_separator(self): """Inserts a separator (boundary) on the undo stack. Does nothing when the undo option is false """ return self.edit("separator") def edit_undo(self): """Undoes the last edit action If the undo option is true. An edit action is defined as all the insert and delete commands that are recorded on the undo stack in between two separators. Generates an error when the undo stack is empty. Does nothing when the undo option is false """ return self.edit("undo") def get(self, index1, index2=None): """Return the text from INDEX1 to INDEX2 (not included).""" return self.tk.call(self._w, 'get', index1, index2) # (Image commands are new in 8.0) def image_cget(self, index, option): """Return the value of OPTION of an embedded image at INDEX.""" if option[:1] != "-": option = "-" + option if option[-1:] == "_": option = option[:-1] return self.tk.call(self._w, "image", "cget", index, option) def image_configure(self, index, cnf=None, **kw): """Configure an embedded image at INDEX.""" return self._configure(('image', 'configure', index), cnf, kw) def image_create(self, index, cnf={}, **kw): """Create an embedded image at INDEX.""" return self.tk.call( self._w, "image", "create", index, *self._options(cnf, kw)) def image_names(self): """Return all names of embedded images in this widget.""" return self.tk.call(self._w, "image", "names") def index(self, index): """Return the index in the form line.char for INDEX.""" return str(self.tk.call(self._w, 'index', index)) def insert(self, index, chars, *args): """Insert CHARS before the characters at INDEX. An additional tag can be given in ARGS. Additional CHARS and tags can follow in ARGS.""" self.tk.call((self._w, 'insert', index, chars) + args) def mark_gravity(self, markName, direction=None): """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT). Return the current value if None is given for DIRECTION.""" return self.tk.call( (self._w, 'mark', 'gravity', markName, direction)) def mark_names(self): """Return all mark names.""" return self.tk.splitlist(self.tk.call( self._w, 'mark', 'names')) def mark_set(self, markName, index): """Set mark MARKNAME before the character at INDEX.""" self.tk.call(self._w, 'mark', 'set', markName, index) def mark_unset(self, *markNames): """Delete all marks in MARKNAMES.""" self.tk.call((self._w, 'mark', 'unset') + markNames) def mark_next(self, index): """Return the name of the next mark after INDEX.""" return self.tk.call(self._w, 'mark', 'next', index) or None def mark_previous(self, index): """Return the name of the previous mark before INDEX.""" return self.tk.call(self._w, 'mark', 'previous', index) or None def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5 """Creates a peer text widget with the given newPathName, and any optional standard configuration options. By default the peer will have the same start and end line as the parent widget, but these can be overridden with the standard configuration options.""" self.tk.call(self._w, 'peer', 'create', newPathName, *self._options(cnf, kw)) def peer_names(self): # new in Tk 8.5 """Returns a list of peers of this widget (this does not include the widget itself).""" return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names')) def replace(self, index1, index2, chars, *args): # new in Tk 8.5 """Replaces the range of characters between index1 and index2 with the given characters and tags specified by args. See the method insert for some more information about args, and the method delete for information about the indices.""" self.tk.call(self._w, 'replace', index1, index2, chars, *args) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): """Adjust the view of the text to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y) def search(self, pattern, index, stopindex=None, forwards=None, backwards=None, exact=None, regexp=None, nocase=None, count=None, elide=None): """Search PATTERN beginning from INDEX until STOPINDEX. Return the index of the first character of a match or an empty string.""" args = [self._w, 'search'] if forwards: args.append('-forwards') if backwards: args.append('-backwards') if exact: args.append('-exact') if regexp: args.append('-regexp') if nocase: args.append('-nocase') if elide: args.append('-elide') if count: args.append('-count'); args.append(count) if pattern and pattern[0] == '-': args.append('--') args.append(pattern) args.append(index) if stopindex: args.append(stopindex) return str(self.tk.call(tuple(args))) def see(self, index): """Scroll such that the character at INDEX is visible.""" self.tk.call(self._w, 'see', index) def tag_add(self, tagName, index1, *args): """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS. Additional pairs of indices may follow in ARGS.""" self.tk.call( (self._w, 'tag', 'add', tagName, index1) + args) def tag_unbind(self, tagName, sequence, funcid=None): """Unbind for all characters with TAGNAME for event SEQUENCE the function identified with FUNCID.""" self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def tag_bind(self, tagName, sequence, func, add=None): """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind((self._w, 'tag', 'bind', tagName), sequence, func, add) def tag_cget(self, tagName, option): """Return the value of OPTION for tag TAGNAME.""" if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'tag', 'cget', tagName, option) def tag_configure(self, tagName, cnf=None, **kw): """Configure a tag TAGNAME.""" return self._configure(('tag', 'configure', tagName), cnf, kw) tag_config = tag_configure def tag_delete(self, *tagNames): """Delete all tags in TAGNAMES.""" self.tk.call((self._w, 'tag', 'delete') + tagNames) def tag_lower(self, tagName, belowThis=None): """Change the priority of tag TAGNAME such that it is lower than the priority of BELOWTHIS.""" self.tk.call(self._w, 'tag', 'lower', tagName, belowThis) def tag_names(self, index=None): """Return a list of all tag names.""" return self.tk.splitlist( self.tk.call(self._w, 'tag', 'names', index)) def tag_nextrange(self, tagName, index1, index2=None): """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched forward from INDEX1.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'nextrange', tagName, index1, index2)) def tag_prevrange(self, tagName, index1, index2=None): """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched backwards from INDEX1.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'prevrange', tagName, index1, index2)) def tag_raise(self, tagName, aboveThis=None): """Change the priority of tag TAGNAME such that it is higher than the priority of ABOVETHIS.""" self.tk.call( self._w, 'tag', 'raise', tagName, aboveThis) def tag_ranges(self, tagName): """Return a list of ranges of text which have tag TAGNAME.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'ranges', tagName)) def tag_remove(self, tagName, index1, index2=None): """Remove tag TAGNAME from all characters between INDEX1 and INDEX2.""" self.tk.call( self._w, 'tag', 'remove', tagName, index1, index2) def window_cget(self, index, option): """Return the value of OPTION of an embedded window at INDEX.""" if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'window', 'cget', index, option) def window_configure(self, index, cnf=None, **kw): """Configure an embedded window at INDEX.""" return self._configure(('window', 'configure', index), cnf, kw) window_config = window_configure def window_create(self, index, cnf={}, **kw): """Create a window at INDEX.""" self.tk.call( (self._w, 'window', 'create', index) + self._options(cnf, kw)) def window_names(self): """Return all names of embedded windows in this widget.""" return self.tk.splitlist( self.tk.call(self._w, 'window', 'names')) def yview_pickplace(self, *what): """Obsolete function, use see.""" self.tk.call((self._w, 'yview', '-pickplace') + what) class _setit: """Internal class. It wraps the command in the widget OptionMenu.""" def __init__(self, var, value, callback=None): self.__value = value self.__var = var self.__callback = callback def __call__(self, *args): self.__var.set(self.__value) if self.__callback: self.__callback(self.__value, *args) class OptionMenu(Menubutton): """OptionMenu which allows the user to select a value from a menu.""" def __init__(self, master, variable, value, *values, **kwargs): """Construct an optionmenu widget with the parent MASTER, with the resource textvariable set to VARIABLE, the initially selected value VALUE, the other menu values VALUES and an additional keyword argument command.""" kw = {"borderwidth": 2, "textvariable": variable, "indicatoron": 1, "relief": RAISED, "anchor": "c", "highlightthickness": 2} Widget.__init__(self, master, "menubutton", kw) self.widgetName = 'tk_optionMenu' menu = self.__menu = Menu(self, name="menu", tearoff=0) self.menuname = menu._w # 'command' is the only supported keyword callback = kwargs.get('command') if 'command' in kwargs: del kwargs['command'] if kwargs: raise TclError('unknown option -'+kwargs.keys()[0]) menu.add_command(label=value, command=_setit(variable, value, callback)) for v in values: menu.add_command(label=v, command=_setit(variable, v, callback)) self["menu"] = menu def __getitem__(self, name): if name == 'menu': return self.__menu return Widget.__getitem__(self, name) def destroy(self): """Destroy this widget and the associated menu.""" Menubutton.destroy(self) self.__menu = None class Image: """Base class for images.""" _last_id = 0 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): self.name = None if not master: master = _default_root if not master: raise RuntimeError('Too early to create image') self.tk = getattr(master, 'tk', master) if not name: Image._last_id += 1 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x> if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw options = () for k, v in cnf.items(): if callable(v): v = self._register(v) options = options + ('-'+k, v) self.tk.call(('image', 'create', imgtype, name,) + options) self.name = name def __str__(self): return self.name def __del__(self): if self.name: try: self.tk.call('image', 'delete', self.name) except TclError: # May happen if the root was destroyed pass def __setitem__(self, key, value): self.tk.call(self.name, 'configure', '-'+key, value) def __getitem__(self, key): return self.tk.call(self.name, 'configure', '-'+key) def configure(self, **kw): """Configure the image.""" res = () for k, v in _cnfmerge(kw).items(): if v is not None: if k[-1] == '_': k = k[:-1] if callable(v): v = self._register(v) res = res + ('-'+k, v) self.tk.call((self.name, 'config') + res) config = configure def height(self): """Return the height of the image.""" return self.tk.getint( self.tk.call('image', 'height', self.name)) def type(self): """Return the type of the image, e.g. "photo" or "bitmap".""" return self.tk.call('image', 'type', self.name) def width(self): """Return the width of the image.""" return self.tk.getint( self.tk.call('image', 'width', self.name)) class PhotoImage(Image): """Widget which can display images in PGM, PPM, GIF, PNG format.""" def __init__(self, name=None, cnf={}, master=None, **kw): """Create an image with NAME. Valid resource names: data, format, file, gamma, height, palette, width.""" Image.__init__(self, 'photo', name, cnf, master, **kw) def blank(self): """Display a transparent image.""" self.tk.call(self.name, 'blank') def cget(self, option): """Return the value of OPTION.""" return self.tk.call(self.name, 'cget', '-' + option) # XXX config def __getitem__(self, key): return self.tk.call(self.name, 'cget', '-' + key) # XXX copy -from, -to, ...? def copy(self): """Return a new PhotoImage with the same image as this widget.""" destImage = PhotoImage(master=self.tk) self.tk.call(destImage, 'copy', self.name) return destImage def zoom(self, x, y=''): """Return a new PhotoImage with the same image as this widget but zoom it with a factor of x in the X direction and y in the Y direction. If y is not given, the default value is the same as x. """ destImage = PhotoImage(master=self.tk) if y=='': y=x self.tk.call(destImage, 'copy', self.name, '-zoom',x,y) return destImage def subsample(self, x, y=''): """Return a new PhotoImage based on the same image as this widget but use only every Xth or Yth pixel. If y is not given, the default value is the same as x. """ destImage = PhotoImage(master=self.tk) if y=='': y=x self.tk.call(destImage, 'copy', self.name, '-subsample',x,y) return destImage def get(self, x, y): """Return the color (red, green, blue) of the pixel at X,Y.""" return self.tk.call(self.name, 'get', x, y) def put(self, data, to=None): """Put row formatted colors to image starting from position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))""" args = (self.name, 'put', data) if to: if to[0] == '-to': to = to[1:] args = args + ('-to',) + tuple(to) self.tk.call(args) # XXX read def write(self, filename, format=None, from_coords=None): """Write image to file FILENAME in FORMAT starting from position FROM_COORDS.""" args = (self.name, 'write', filename) if format: args = args + ('-format', format) if from_coords: args = args + ('-from',) + tuple(from_coords) self.tk.call(args) class BitmapImage(Image): """Widget which can display images in XBM format.""" def __init__(self, name=None, cnf={}, master=None, **kw): """Create a bitmap with NAME. Valid resource names: background, data, file, foreground, maskdata, maskfile.""" Image.__init__(self, 'bitmap', name, cnf, master, **kw) def image_names(): return _default_root.tk.splitlist(_default_root.tk.call('image', 'names')) def image_types(): return _default_root.tk.splitlist(_default_root.tk.call('image', 'types')) class Spinbox(Widget, XView): """spinbox widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a spinbox widget with the parent MASTER. STANDARD OPTIONS activebackground, background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, justify, relief, repeatdelay, repeatinterval, selectbackground, selectborderwidth selectforeground, takefocus, textvariable xscrollcommand. WIDGET-SPECIFIC OPTIONS buttonbackground, buttoncursor, buttondownrelief, buttonuprelief, command, disabledbackground, disabledforeground, format, from, invalidcommand, increment, readonlybackground, state, to, validate, validatecommand values, width, wrap, """ Widget.__init__(self, master, 'spinbox', cnf, kw) def bbox(self, index): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the character given by index. The first two elements of the list give the x and y coordinates of the upper-left corner of the screen area covered by the character (in pixels relative to the widget) and the last two elements give the width and height of the character, in pixels. The bounding box may refer to a region outside the visible area of the window. """ return self._getints(self.tk.call(self._w, 'bbox', index)) or None def delete(self, first, last=None): """Delete one or more elements of the spinbox. First is the index of the first character to delete, and last is the index of the character just after the last one to delete. If last isn't specified it defaults to first+1, i.e. a single character is deleted. This command returns an empty string. """ return self.tk.call(self._w, 'delete', first, last) def get(self): """Returns the spinbox's string""" return self.tk.call(self._w, 'get') def icursor(self, index): """Alter the position of the insertion cursor. The insertion cursor will be displayed just before the character given by index. Returns an empty string """ return self.tk.call(self._w, 'icursor', index) def identify(self, x, y): """Returns the name of the widget at position x, y Return value is one of: none, buttondown, buttonup, entry """ return self.tk.call(self._w, 'identify', x, y) def index(self, index): """Returns the numerical index corresponding to index """ return self.tk.call(self._w, 'index', index) def insert(self, index, s): """Insert string s at index Returns an empty string. """ return self.tk.call(self._w, 'insert', index, s) def invoke(self, element): """Causes the specified element to be invoked The element could be buttondown or buttonup triggering the action associated with it. """ return self.tk.call(self._w, 'invoke', element) def scan(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'scan') + args)) or () def scan_mark(self, x): """Records x and the current view in the spinbox window; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget. It returns an empty string. """ return self.scan("mark", x) def scan_dragto(self, x): """Compute the difference between the given x argument and the x argument to the last scan mark command It then adjusts the view left or right by 10 times the difference in x-coordinates. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the spinbox at high speed through the window. The return value is an empty string. """ return self.scan("dragto", x) def selection(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'selection') + args)) or () def selection_adjust(self, index): """Locate the end of the selection nearest to the character given by index, Then adjust that end of the selection to be at index (i.e including but not going beyond index). The other end of the selection is made the anchor point for future select to commands. If the selection isn't currently in the spinbox, then a new selection is created to include the characters between index and the most recent selection anchor point, inclusive. """ return self.selection("adjust", index) def selection_clear(self): """Clear the selection If the selection isn't in this widget then the command has no effect. """ return self.selection("clear") def selection_element(self, element=None): """Sets or gets the currently selected element. If a spinbutton element is specified, it will be displayed depressed. """ return self.tk.call(self._w, 'selection', 'element', element) ########################################################################### class LabelFrame(Widget): """labelframe widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a labelframe widget with the parent MASTER. STANDARD OPTIONS borderwidth, cursor, font, foreground, highlightbackground, highlightcolor, highlightthickness, padx, pady, relief, takefocus, text WIDGET-SPECIFIC OPTIONS background, class, colormap, container, height, labelanchor, labelwidget, visual, width """ Widget.__init__(self, master, 'labelframe', cnf, kw) ######################################################################## class PanedWindow(Widget): """panedwindow widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a panedwindow widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, height, orient, relief, width WIDGET-SPECIFIC OPTIONS handlepad, handlesize, opaqueresize, sashcursor, sashpad, sashrelief, sashwidth, showhandle, """ Widget.__init__(self, master, 'panedwindow', cnf, kw) def add(self, child, **kw): """Add a child widget to the panedwindow in a new pane. The child argument is the name of the child widget followed by pairs of arguments that specify how to manage the windows. The possible options and values are the ones accepted by the paneconfigure method. """ self.tk.call((self._w, 'add', child) + self._options(kw)) def remove(self, child): """Remove the pane containing child from the panedwindow All geometry management options for child will be forgotten. """ self.tk.call(self._w, 'forget', child) forget=remove def identify(self, x, y): """Identify the panedwindow component at point x, y If the point is over a sash or a sash handle, the result is a two element list containing the index of the sash or handle, and a word indicating whether it is over a sash or a handle, such as {0 sash} or {2 handle}. If the point is over any other part of the panedwindow, the result is an empty list. """ return self.tk.call(self._w, 'identify', x, y) def proxy(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'proxy') + args)) or () def proxy_coord(self): """Return the x and y pair of the most recent proxy location """ return self.proxy("coord") def proxy_forget(self): """Remove the proxy from the display. """ return self.proxy("forget") def proxy_place(self, x, y): """Place the proxy at the given x and y coordinates. """ return self.proxy("place", x, y) def sash(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'sash') + args)) or () def sash_coord(self, index): """Return the current x and y pair for the sash given by index. Index must be an integer between 0 and 1 less than the number of panes in the panedwindow. The coordinates given are those of the top left corner of the region containing the sash. pathName sash dragto index x y This command computes the difference between the given coordinates and the coordinates given to the last sash coord command for the given sash. It then moves that sash the computed difference. The return value is the empty string. """ return self.sash("coord", index) def sash_mark(self, index): """Records x and y for the sash given by index; Used in conjunction with later dragto commands to move the sash. """ return self.sash("mark", index) def sash_place(self, index, x, y): """Place the sash given by index at the given coordinates """ return self.sash("place", index, x, y) def panecget(self, child, option): """Query a management option for window. Option may be any value allowed by the paneconfigure subcommand """ return self.tk.call( (self._w, 'panecget') + (child, '-'+option)) def paneconfigure(self, tagOrId, cnf=None, **kw): """Query or modify the management options for window. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. The following options are supported: after window Insert the window after the window specified. window should be the name of a window already managed by pathName. before window Insert the window before the window specified. window should be the name of a window already managed by pathName. height size Specify a height for the window. The height will be the outer dimension of the window including its border, if any. If size is an empty string, or if -height is not specified, then the height requested internally by the window will be used initially; the height may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. minsize n Specifies that the size of the window cannot be made less than n. This constraint only affects the size of the widget in the paned dimension -- the x dimension for horizontal panedwindows, the y dimension for vertical panedwindows. May be any value accepted by Tk_GetPixels. padx n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the X-direction. The value may have any of the forms accepted by Tk_GetPixels. pady n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the Y-direction. The value may have any of the forms accepted by Tk_GetPixels. sticky style If a window's pane is larger than the requested dimensions of the window, this option may be used to position (or stretch) the window within its pane. Style is a string that contains zero or more of the characters n, s, e or w. The string can optionally contains spaces or commas, but they are ignored. Each letter refers to a side (north, south, east, or west) that the window will "stick" to. If both n and s (or e and w) are specified, the window will be stretched to fill the entire height (or width) of its cavity. width size Specify a width for the window. The width will be the outer dimension of the window including its border, if any. If size is an empty string, or if -width is not specified, then the width requested internally by the window will be used initially; the width may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. """ if cnf is None and not kw: return self._getconfigure(self._w, 'paneconfigure', tagOrId) if isinstance(cnf, str) and not kw: return self._getconfigure1( self._w, 'paneconfigure', tagOrId, '-'+cnf) self.tk.call((self._w, 'paneconfigure', tagOrId) + self._options(cnf, kw)) paneconfig = paneconfigure def panes(self): """Returns an ordered list of the child panes.""" return self.tk.splitlist(self.tk.call(self._w, 'panes')) # Test: def _test(): root = Tk() text = "This is Tcl/Tk version %s" % TclVersion text += "\nThis should be a cedilla: \xe7" label = Label(root, text=text) label.pack() test = Button(root, text="Click me!", command=lambda root=root: root.test.configure( text="[%s]" % root.test['text'])) test.pack() root.test = test quit = Button(root, text="QUIT", command=root.destroy) quit.pack() # The following three commands are needed so the window pops # up on top on Windows... root.iconify() root.update() root.deiconify() root.mainloop() if __name__ == '__main__': _test()
166,971
4,009
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/runtktests.py
""" Use this module to get and run all tk tests. tkinter tests should live in a package inside the directory where this file lives, like test_tkinter. Extensions also should live in packages following the same rule as above. """ import os import importlib import test.support this_dir_path = os.path.abspath(os.path.dirname(__file__)) def is_package(path): for name in os.listdir(path): if name in ('__init__.py', '__init__.pyc'): return True return False def get_tests_modules(basepath=this_dir_path, gui=True, packages=None): """This will import and yield modules whose names start with test_ and are inside packages found in the path starting at basepath. If packages is specified it should contain package names that want their tests collected. """ py_ext = '.py' for dirpath, dirnames, filenames in os.walk(basepath): for dirname in list(dirnames): if dirname[0] == '.': dirnames.remove(dirname) if is_package(dirpath) and filenames: pkg_name = dirpath[len(basepath) + len(os.sep):].replace('/', '.') if packages and pkg_name not in packages: continue filenames = filter( lambda x: x.startswith('test_') and x.endswith(py_ext), filenames) for name in filenames: try: yield importlib.import_module( ".%s.%s" % (pkg_name, name[:-len(py_ext)]), "tkinter.test") except test.support.ResourceDenied: if gui: raise def get_tests(text=True, gui=True, packages=None): """Yield all the tests in the modules found by get_tests_modules. If nogui is True, only tests that do not require a GUI will be returned.""" attrs = [] if text: attrs.append('tests_nogui') if gui: attrs.append('tests_gui') for module in get_tests_modules(gui=gui, packages=packages): for attr in attrs: for test in getattr(module, attr, ()): yield test if __name__ == "__main__": test.support.run_unittest(*get_tests())
2,230
70
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/README
Writing new tests ================= Precaution ---------- New tests should always use only one Tk window at once, like all the current tests do. This means that you have to destroy the current window before creating another one, and clean up after the test. The motivation behind this is that some tests may depend on having its window focused while it is running to work properly, and it may be hard to force focus on your window across platforms (right now only test_traversal at test_ttk.test_widgets.NotebookTest depends on this).
566
15
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/support.py
import functools import re import tkinter import unittest class AbstractTkTest: @classmethod def setUpClass(cls): cls._old_support_default_root = tkinter._support_default_root destroy_default_root() tkinter.NoDefaultRoot() cls.root = tkinter.Tk() cls.wantobjects = cls.root.wantobjects() # De-maximize main window. # Some window managers can maximize new windows. cls.root.wm_state('normal') try: cls.root.wm_attributes('-zoomed', False) except tkinter.TclError: pass @classmethod def tearDownClass(cls): cls.root.update_idletasks() cls.root.destroy() del cls.root tkinter._default_root = None tkinter._support_default_root = cls._old_support_default_root def setUp(self): self.root.deiconify() def tearDown(self): for w in self.root.winfo_children(): w.destroy() self.root.withdraw() def destroy_default_root(): if getattr(tkinter, '_default_root', None): tkinter._default_root.update_idletasks() tkinter._default_root.destroy() tkinter._default_root = None def simulate_mouse_click(widget, x, y): """Generate proper events to click at the x, y position (tries to act like an X server).""" widget.event_generate('<Enter>', x=0, y=0) widget.event_generate('<Motion>', x=x, y=y) widget.event_generate('<ButtonPress-1>', x=x, y=y) widget.event_generate('<ButtonRelease-1>', x=x, y=y) import _tkinter tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.'))) def requires_tcl(*version): if len(version) <= 2: return unittest.skipUnless(tcl_version >= version, 'requires Tcl version >= ' + '.'.join(map(str, version))) def deco(test): @functools.wraps(test) def newtest(self): if get_tk_patchlevel() < version: self.skipTest('requires Tcl version >= ' + '.'.join(map(str, version))) test(self) return newtest return deco _tk_patchlevel = None def get_tk_patchlevel(): global _tk_patchlevel if _tk_patchlevel is None: tcl = tkinter.Tcl() patchlevel = tcl.call('info', 'patchlevel') m = re.fullmatch(r'(\d+)\.(\d+)([ab.])(\d+)', patchlevel) major, minor, releaselevel, serial = m.groups() major, minor, serial = int(major), int(minor), int(serial) releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel] if releaselevel == 'final': _tk_patchlevel = major, minor, serial, releaselevel, 0 else: _tk_patchlevel = major, minor, 0, releaselevel, serial return _tk_patchlevel units = { 'c': 72 / 2.54, # centimeters 'i': 72, # inches 'm': 72 / 25.4, # millimeters 'p': 1, # points } def pixels_conv(value): return float(value[:-1]) * units[value[-1:]] def tcl_obj_eq(actual, expected): if actual == expected: return True if isinstance(actual, _tkinter.Tcl_Obj): if isinstance(expected, str): return str(actual) == expected if isinstance(actual, tuple): if isinstance(expected, tuple): return (len(actual) == len(expected) and all(tcl_obj_eq(act, exp) for act, exp in zip(actual, expected))) return False def widget_eq(actual, expected): if actual == expected: return True if isinstance(actual, (str, tkinter.Widget)): if isinstance(expected, (str, tkinter.Widget)): return str(actual) == str(expected) return False
3,722
118
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/widget_tests.py
# Common tests for test_tkinter/test_widgets.py and test_ttk/test_widgets.py import unittest import sys import tkinter from tkinter.ttk import Scale from tkinter.test.support import (AbstractTkTest, tcl_version, requires_tcl, get_tk_patchlevel, pixels_conv, tcl_obj_eq) import test.support noconv = False if get_tk_patchlevel() < (8, 5, 11): noconv = str pixels_round = round if get_tk_patchlevel()[:3] == (8, 5, 11): # Issue #19085: Workaround a bug in Tk # http://core.tcl.tk/tk/info/3497848 pixels_round = int _sentinel = object() class AbstractWidgetTest(AbstractTkTest): _conv_pixels = staticmethod(pixels_round) _conv_pad_pixels = None _stringify = False @property def scaling(self): try: return self._scaling except AttributeError: self._scaling = float(self.root.call('tk', 'scaling')) return self._scaling def _str(self, value): if not self._stringify and self.wantobjects and tcl_version >= (8, 6): return value if isinstance(value, tuple): return ' '.join(map(self._str, value)) return str(value) def assertEqual2(self, actual, expected, msg=None, eq=object.__eq__): if eq(actual, expected): return self.assertEqual(actual, expected, msg) def checkParam(self, widget, name, value, *, expected=_sentinel, conv=False, eq=None): widget[name] = value if expected is _sentinel: expected = value if conv: expected = conv(expected) if self._stringify or not self.wantobjects: if isinstance(expected, tuple): expected = tkinter._join(expected) else: expected = str(expected) if eq is None: eq = tcl_obj_eq self.assertEqual2(widget[name], expected, eq=eq) self.assertEqual2(widget.cget(name), expected, eq=eq) # XXX if not isinstance(widget, Scale): t = widget.configure(name) self.assertEqual(len(t), 5) self.assertEqual2(t[4], expected, eq=eq) def checkInvalidParam(self, widget, name, value, errmsg=None, *, keep_orig=True): orig = widget[name] if errmsg is not None: errmsg = errmsg.format(value) with self.assertRaises(tkinter.TclError) as cm: widget[name] = value if errmsg is not None: self.assertEqual(str(cm.exception), errmsg) if keep_orig: self.assertEqual(widget[name], orig) else: widget[name] = orig with self.assertRaises(tkinter.TclError) as cm: widget.configure({name: value}) if errmsg is not None: self.assertEqual(str(cm.exception), errmsg) if keep_orig: self.assertEqual(widget[name], orig) else: widget[name] = orig def checkParams(self, widget, name, *values, **kwargs): for value in values: self.checkParam(widget, name, value, **kwargs) def checkIntegerParam(self, widget, name, *values, **kwargs): self.checkParams(widget, name, *values, **kwargs) self.checkInvalidParam(widget, name, '', errmsg='expected integer but got ""') self.checkInvalidParam(widget, name, '10p', errmsg='expected integer but got "10p"') self.checkInvalidParam(widget, name, 3.2, errmsg='expected integer but got "3.2"') def checkFloatParam(self, widget, name, *values, conv=float, **kwargs): for value in values: self.checkParam(widget, name, value, conv=conv, **kwargs) self.checkInvalidParam(widget, name, '', errmsg='expected floating-point number but got ""') self.checkInvalidParam(widget, name, 'spam', errmsg='expected floating-point number but got "spam"') def checkBooleanParam(self, widget, name): for value in (False, 0, 'false', 'no', 'off'): self.checkParam(widget, name, value, expected=0) for value in (True, 1, 'true', 'yes', 'on'): self.checkParam(widget, name, value, expected=1) self.checkInvalidParam(widget, name, '', errmsg='expected boolean value but got ""') self.checkInvalidParam(widget, name, 'spam', errmsg='expected boolean value but got "spam"') def checkColorParam(self, widget, name, *, allow_empty=None, **kwargs): self.checkParams(widget, name, '#ff0000', '#00ff00', '#0000ff', '#123456', 'red', 'green', 'blue', 'white', 'black', 'grey', **kwargs) self.checkInvalidParam(widget, name, 'spam', errmsg='unknown color name "spam"') def checkCursorParam(self, widget, name, **kwargs): self.checkParams(widget, name, 'arrow', 'watch', 'cross', '',**kwargs) if tcl_version >= (8, 5): self.checkParam(widget, name, 'none') self.checkInvalidParam(widget, name, 'spam', errmsg='bad cursor spec "spam"') def checkCommandParam(self, widget, name): def command(*args): pass widget[name] = command self.assertTrue(widget[name]) self.checkParams(widget, name, '') def checkEnumParam(self, widget, name, *values, errmsg=None, **kwargs): self.checkParams(widget, name, *values, **kwargs) if errmsg is None: errmsg2 = ' %s "{}": must be %s%s or %s' % ( name, ', '.join(values[:-1]), ',' if len(values) > 2 else '', values[-1]) self.checkInvalidParam(widget, name, '', errmsg='ambiguous' + errmsg2) errmsg = 'bad' + errmsg2 self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) def checkPixelsParam(self, widget, name, *values, conv=None, keep_orig=True, **kwargs): if conv is None: conv = self._conv_pixels for value in values: expected = _sentinel conv1 = conv if isinstance(value, str): if conv1 and conv1 is not str: expected = pixels_conv(value) * self.scaling conv1 = round self.checkParam(widget, name, value, expected=expected, conv=conv1, **kwargs) self.checkInvalidParam(widget, name, '6x', errmsg='bad screen distance "6x"', keep_orig=keep_orig) self.checkInvalidParam(widget, name, 'spam', errmsg='bad screen distance "spam"', keep_orig=keep_orig) def checkReliefParam(self, widget, name): self.checkParams(widget, name, 'flat', 'groove', 'raised', 'ridge', 'solid', 'sunken') errmsg='bad relief "spam": must be '\ 'flat, groove, raised, ridge, solid, or sunken' if tcl_version < (8, 6): errmsg = None self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) def checkImageParam(self, widget, name): image = tkinter.PhotoImage(master=self.root, name='image1') self.checkParam(widget, name, image, conv=str) self.checkInvalidParam(widget, name, 'spam', errmsg='image "spam" doesn\'t exist') widget[name] = '' def checkVariableParam(self, widget, name, var): self.checkParam(widget, name, var, conv=str) def assertIsBoundingBox(self, bbox): self.assertIsNotNone(bbox) self.assertIsInstance(bbox, tuple) if len(bbox) != 4: self.fail('Invalid bounding box: %r' % (bbox,)) for item in bbox: if not isinstance(item, int): self.fail('Invalid bounding box: %r' % (bbox,)) break def test_keys(self): widget = self.create() keys = widget.keys() # XXX if not isinstance(widget, Scale): self.assertEqual(sorted(keys), sorted(widget.configure())) for k in keys: widget[k] # Test if OPTIONS contains all keys if test.support.verbose: aliases = { 'bd': 'borderwidth', 'bg': 'background', 'fg': 'foreground', 'invcmd': 'invalidcommand', 'vcmd': 'validatecommand', } keys = set(keys) expected = set(self.OPTIONS) for k in sorted(keys - expected): if not (k in aliases and aliases[k] in keys and aliases[k] in expected): print('%s.OPTIONS doesn\'t contain "%s"' % (self.__class__.__name__, k)) class StandardOptionsTests: STANDARD_OPTIONS = ( 'activebackground', 'activeborderwidth', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'compound', 'cursor', 'disabledforeground', 'exportselection', 'font', 'foreground', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'insertbackground', 'insertborderwidth', 'insertofftime', 'insertontime', 'insertwidth', 'jump', 'justify', 'orient', 'padx', 'pady', 'relief', 'repeatdelay', 'repeatinterval', 'selectbackground', 'selectborderwidth', 'selectforeground', 'setgrid', 'takefocus', 'text', 'textvariable', 'troughcolor', 'underline', 'wraplength', 'xscrollcommand', 'yscrollcommand', ) def test_activebackground(self): widget = self.create() self.checkColorParam(widget, 'activebackground') def test_activeborderwidth(self): widget = self.create() self.checkPixelsParam(widget, 'activeborderwidth', 0, 1.3, 2.9, 6, -2, '10p') def test_activeforeground(self): widget = self.create() self.checkColorParam(widget, 'activeforeground') def test_anchor(self): widget = self.create() self.checkEnumParam(widget, 'anchor', 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center') def test_background(self): widget = self.create() self.checkColorParam(widget, 'background') if 'bg' in self.OPTIONS: self.checkColorParam(widget, 'bg') def test_bitmap(self): widget = self.create() self.checkParam(widget, 'bitmap', 'questhead') self.checkParam(widget, 'bitmap', 'gray50') filename = test.support.findfile('python.xbm', subdir='imghdrdata') self.checkParam(widget, 'bitmap', '@' + filename) # Cocoa Tk widgets don't detect invalid -bitmap values # See https://core.tcl.tk/tk/info/31cd33dbf0 if not ('aqua' in self.root.tk.call('tk', 'windowingsystem') and 'AppKit' in self.root.winfo_server()): self.checkInvalidParam(widget, 'bitmap', 'spam', errmsg='bitmap "spam" not defined') def test_borderwidth(self): widget = self.create() self.checkPixelsParam(widget, 'borderwidth', 0, 1.3, 2.6, 6, -2, '10p') if 'bd' in self.OPTIONS: self.checkPixelsParam(widget, 'bd', 0, 1.3, 2.6, 6, -2, '10p') def test_compound(self): widget = self.create() self.checkEnumParam(widget, 'compound', 'bottom', 'center', 'left', 'none', 'right', 'top') def test_cursor(self): widget = self.create() self.checkCursorParam(widget, 'cursor') def test_disabledforeground(self): widget = self.create() self.checkColorParam(widget, 'disabledforeground') def test_exportselection(self): widget = self.create() self.checkBooleanParam(widget, 'exportselection') def test_font(self): widget = self.create() self.checkParam(widget, 'font', '-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*') self.checkInvalidParam(widget, 'font', '', errmsg='font "" doesn\'t exist') def test_foreground(self): widget = self.create() self.checkColorParam(widget, 'foreground') if 'fg' in self.OPTIONS: self.checkColorParam(widget, 'fg') def test_highlightbackground(self): widget = self.create() self.checkColorParam(widget, 'highlightbackground') def test_highlightcolor(self): widget = self.create() self.checkColorParam(widget, 'highlightcolor') def test_highlightthickness(self): widget = self.create() self.checkPixelsParam(widget, 'highlightthickness', 0, 1.3, 2.6, 6, '10p') self.checkParam(widget, 'highlightthickness', -2, expected=0, conv=self._conv_pixels) @unittest.skipIf(sys.platform == 'darwin', 'crashes with Cocoa Tk (issue19733)') def test_image(self): widget = self.create() self.checkImageParam(widget, 'image') def test_insertbackground(self): widget = self.create() self.checkColorParam(widget, 'insertbackground') def test_insertborderwidth(self): widget = self.create() self.checkPixelsParam(widget, 'insertborderwidth', 0, 1.3, 2.6, 6, -2, '10p') def test_insertofftime(self): widget = self.create() self.checkIntegerParam(widget, 'insertofftime', 100) def test_insertontime(self): widget = self.create() self.checkIntegerParam(widget, 'insertontime', 100) def test_insertwidth(self): widget = self.create() self.checkPixelsParam(widget, 'insertwidth', 1.3, 2.6, -2, '10p') def test_jump(self): widget = self.create() self.checkBooleanParam(widget, 'jump') def test_justify(self): widget = self.create() self.checkEnumParam(widget, 'justify', 'left', 'right', 'center', errmsg='bad justification "{}": must be ' 'left, right, or center') self.checkInvalidParam(widget, 'justify', '', errmsg='ambiguous justification "": must be ' 'left, right, or center') def test_orient(self): widget = self.create() self.assertEqual(str(widget['orient']), self.default_orient) self.checkEnumParam(widget, 'orient', 'horizontal', 'vertical') def test_padx(self): widget = self.create() self.checkPixelsParam(widget, 'padx', 3, 4.4, 5.6, -2, '12m', conv=self._conv_pad_pixels) def test_pady(self): widget = self.create() self.checkPixelsParam(widget, 'pady', 3, 4.4, 5.6, -2, '12m', conv=self._conv_pad_pixels) def test_relief(self): widget = self.create() self.checkReliefParam(widget, 'relief') def test_repeatdelay(self): widget = self.create() self.checkIntegerParam(widget, 'repeatdelay', -500, 500) def test_repeatinterval(self): widget = self.create() self.checkIntegerParam(widget, 'repeatinterval', -500, 500) def test_selectbackground(self): widget = self.create() self.checkColorParam(widget, 'selectbackground') def test_selectborderwidth(self): widget = self.create() self.checkPixelsParam(widget, 'selectborderwidth', 1.3, 2.6, -2, '10p') def test_selectforeground(self): widget = self.create() self.checkColorParam(widget, 'selectforeground') def test_setgrid(self): widget = self.create() self.checkBooleanParam(widget, 'setgrid') def test_state(self): widget = self.create() self.checkEnumParam(widget, 'state', 'active', 'disabled', 'normal') def test_takefocus(self): widget = self.create() self.checkParams(widget, 'takefocus', '0', '1', '') def test_text(self): widget = self.create() self.checkParams(widget, 'text', '', 'any string') def test_textvariable(self): widget = self.create() var = tkinter.StringVar(self.root) self.checkVariableParam(widget, 'textvariable', var) def test_troughcolor(self): widget = self.create() self.checkColorParam(widget, 'troughcolor') def test_underline(self): widget = self.create() self.checkIntegerParam(widget, 'underline', 0, 1, 10) def test_wraplength(self): widget = self.create() self.checkPixelsParam(widget, 'wraplength', 100) def test_xscrollcommand(self): widget = self.create() self.checkCommandParam(widget, 'xscrollcommand') def test_yscrollcommand(self): widget = self.create() self.checkCommandParam(widget, 'yscrollcommand') # non-standard but common options def test_command(self): widget = self.create() self.checkCommandParam(widget, 'command') def test_indicatoron(self): widget = self.create() self.checkBooleanParam(widget, 'indicatoron') def test_offrelief(self): widget = self.create() self.checkReliefParam(widget, 'offrelief') def test_overrelief(self): widget = self.create() self.checkReliefParam(widget, 'overrelief') def test_selectcolor(self): widget = self.create() self.checkColorParam(widget, 'selectcolor') def test_selectimage(self): widget = self.create() self.checkImageParam(widget, 'selectimage') @requires_tcl(8, 5) def test_tristateimage(self): widget = self.create() self.checkImageParam(widget, 'tristateimage') @requires_tcl(8, 5) def test_tristatevalue(self): widget = self.create() self.checkParam(widget, 'tristatevalue', 'unknowable') def test_variable(self): widget = self.create() var = tkinter.DoubleVar(self.root) self.checkVariableParam(widget, 'variable', var) class IntegerSizeTests: def test_height(self): widget = self.create() self.checkIntegerParam(widget, 'height', 100, -100, 0) def test_width(self): widget = self.create() self.checkIntegerParam(widget, 'width', 402, -402, 0) class PixelSizeTests: def test_height(self): widget = self.create() self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, -100, 0, '3c') def test_width(self): widget = self.create() self.checkPixelsParam(widget, 'width', 402, 403.4, 404.6, -402, 0, '5i') def add_standard_options(*source_classes): # This decorator adds test_xxx methods from source classes for every xxx # option in the OPTIONS class attribute if they are not defined explicitly. def decorator(cls): for option in cls.OPTIONS: methodname = 'test_' + option if not hasattr(cls, methodname): for source_class in source_classes: if hasattr(source_class, methodname): setattr(cls, methodname, getattr(source_class, methodname)) break else: def test(self, option=option): widget = self.create() widget[option] raise AssertionError('Option "%s" is not tested in %s' % (option, cls.__name__)) test.__name__ = methodname setattr(cls, methodname, test) return cls return decorator def setUpModule(): if test.support.verbose: tcl = tkinter.Tcl() print('patchlevel =', tcl.call('info', 'patchlevel'))
20,069
549
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/__init__.py
0
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_ttk/test_functions.py
# -*- encoding: utf-8 -*- import unittest from tkinter import ttk class MockTkApp: def splitlist(self, arg): if isinstance(arg, tuple): return arg return arg.split(':') def wantobjects(self): return True class MockTclObj(object): typename = 'test' def __init__(self, val): self.val = val def __str__(self): return str(self.val) class MockStateSpec(object): typename = 'StateSpec' def __init__(self, *args): self.val = args def __str__(self): return ' '.join(self.val) class InternalFunctionsTest(unittest.TestCase): def test_format_optdict(self): def check_against(fmt_opts, result): for i in range(0, len(fmt_opts), 2): self.assertEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1]) if result: self.fail("result still got elements: %s" % result) # passing an empty dict should return an empty object (tuple here) self.assertFalse(ttk._format_optdict({})) # check list formatting check_against( ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}), {'-fg': 'blue', '-padding': '1 2 3 4'}) # check tuple formatting (same as list) check_against( ttk._format_optdict({'test': (1, 2, '', 0)}), {'-test': '1 2 {} 0'}) # check untouched values check_against( ttk._format_optdict({'test': {'left': 'as is'}}), {'-test': {'left': 'as is'}}) # check script formatting check_against( ttk._format_optdict( {'test': [1, -1, '', '2m', 0], 'test2': 3, 'test3': '', 'test4': 'abc def', 'test5': '"abc"', 'test6': '{}', 'test7': '} -spam {'}, script=True), {'-test': '{1 -1 {} 2m 0}', '-test2': '3', '-test3': '{}', '-test4': '{abc def}', '-test5': '{"abc"}', '-test6': r'\{\}', '-test7': r'\}\ -spam\ \{'}) opts = {'αβγ': True, 'á': False} orig_opts = opts.copy() # check if giving unicode keys is fine check_against(ttk._format_optdict(opts), {'-αβγ': True, '-á': False}) # opts should remain unchanged self.assertEqual(opts, orig_opts) # passing values with spaces inside a tuple/list check_against( ttk._format_optdict( {'option': ('one two', 'three')}), {'-option': '{one two} three'}) check_against( ttk._format_optdict( {'option': ('one\ttwo', 'three')}), {'-option': '{one\ttwo} three'}) # passing empty strings inside a tuple/list check_against( ttk._format_optdict( {'option': ('', 'one')}), {'-option': '{} one'}) # passing values with braces inside a tuple/list check_against( ttk._format_optdict( {'option': ('one} {two', 'three')}), {'-option': r'one\}\ \{two three'}) # passing quoted strings inside a tuple/list check_against( ttk._format_optdict( {'option': ('"one"', 'two')}), {'-option': '{"one"} two'}) check_against( ttk._format_optdict( {'option': ('{one}', 'two')}), {'-option': r'\{one\} two'}) # ignore an option amount_opts = len(ttk._format_optdict(opts, ignore=('á'))) / 2 self.assertEqual(amount_opts, len(opts) - 1) # ignore non-existing options amount_opts = len(ttk._format_optdict(opts, ignore=('á', 'b'))) / 2 self.assertEqual(amount_opts, len(opts) - 1) # ignore every option self.assertFalse(ttk._format_optdict(opts, ignore=list(opts.keys()))) def test_format_mapdict(self): opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]} result = ttk._format_mapdict(opts) self.assertEqual(len(result), len(list(opts.keys())) * 2) self.assertEqual(result, ('-a', '{b c} val d otherval {} single')) self.assertEqual(ttk._format_mapdict(opts, script=True), ('-a', '{{b c} val d otherval {} single}')) self.assertEqual(ttk._format_mapdict({2: []}), ('-2', '')) opts = {'üñíćódè': [('á', 'vãl')]} result = ttk._format_mapdict(opts) self.assertEqual(result, ('-üñíćódè', 'á vãl')) # empty states valid = {'opt': [('', '', 'hi')]} self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi')) # when passing multiple states, they all must be strings invalid = {'opt': [(1, 2, 'valid val')]} self.assertRaises(TypeError, ttk._format_mapdict, invalid) invalid = {'opt': [([1], '2', 'valid val')]} self.assertRaises(TypeError, ttk._format_mapdict, invalid) # but when passing a single state, it can be anything valid = {'opt': [[1, 'value']]} self.assertEqual(ttk._format_mapdict(valid), ('-opt', '1 value')) # special attention to single states which evaluate to False for stateval in (None, 0, False, '', set()): # just some samples valid = {'opt': [(stateval, 'value')]} self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{} value')) # values must be iterable opts = {'a': None} self.assertRaises(TypeError, ttk._format_mapdict, opts) # items in the value must have size >= 2 self.assertRaises(IndexError, ttk._format_mapdict, {'a': [('invalid', )]}) def test_format_elemcreate(self): self.assertTrue(ttk._format_elemcreate(None), (None, ())) ## Testing type = image # image type expects at least an image name, so this should raise # IndexError since it tries to access the index 0 of an empty tuple self.assertRaises(IndexError, ttk._format_elemcreate, 'image') # don't format returned values as a tcl script # minimum acceptable for image type self.assertEqual(ttk._format_elemcreate('image', False, 'test'), ("test ", ())) # specifying a state spec self.assertEqual(ttk._format_elemcreate('image', False, 'test', ('', 'a')), ("test {} a", ())) # state spec with multiple states self.assertEqual(ttk._format_elemcreate('image', False, 'test', ('a', 'b', 'c')), ("test {a b} c", ())) # state spec and options self.assertEqual(ttk._format_elemcreate('image', False, 'test', ('a', 'b'), a='x'), ("test a b", ("-a", "x"))) # format returned values as a tcl script # state spec with multiple states and an option with a multivalue self.assertEqual(ttk._format_elemcreate('image', True, 'test', ('a', 'b', 'c', 'd'), x=[2, 3]), ("{test {a b c} d}", "-x {2 3}")) ## Testing type = vsapi # vsapi type expects at least a class name and a part_id, so this # should raise a ValueError since it tries to get two elements from # an empty tuple self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi') # don't format returned values as a tcl script # minimum acceptable for vsapi self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'), ("a b ", ())) # now with a state spec with multiple states self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b', ('a', 'b', 'c')), ("a b {a b} c", ())) # state spec and option self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b', ('a', 'b'), opt='x'), ("a b a b", ("-opt", "x"))) # format returned values as a tcl script # state spec with a multivalue and an option self.assertEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b', ('a', 'b', [1, 2]), opt='x'), ("{a b {a b} {1 2}}", "-opt x")) # Testing type = from # from type expects at least a type name self.assertRaises(IndexError, ttk._format_elemcreate, 'from') self.assertEqual(ttk._format_elemcreate('from', False, 'a'), ('a', ())) self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'), ('a', ('b', ))) self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'), ('{a}', 'b')) def test_format_layoutlist(self): def sample(indent=0, indent_size=2): return ttk._format_layoutlist( [('a', {'other': [1, 2, 3], 'children': [('b', {'children': [('c', {'children': [('d', {'nice': 'opt'})], 'something': (1, 2) })] })] })], indent=indent, indent_size=indent_size)[0] def sample_expected(indent=0, indent_size=2): spaces = lambda amount=0: ' ' * (amount + indent) return ( "%sa -other {1 2 3} -children {\n" "%sb -children {\n" "%sc -something {1 2} -children {\n" "%sd -nice opt\n" "%s}\n" "%s}\n" "%s}" % (spaces(), spaces(indent_size), spaces(2 * indent_size), spaces(3 * indent_size), spaces(2 * indent_size), spaces(indent_size), spaces())) # empty layout self.assertEqual(ttk._format_layoutlist([])[0], '') # _format_layoutlist always expects the second item (in every item) # to act like a dict (except when the value evaluates to False). self.assertRaises(AttributeError, ttk._format_layoutlist, [('a', 'b')]) smallest = ttk._format_layoutlist([('a', None)], indent=0) self.assertEqual(smallest, ttk._format_layoutlist([('a', '')], indent=0)) self.assertEqual(smallest[0], 'a') # testing indentation levels self.assertEqual(sample(), sample_expected()) for i in range(4): self.assertEqual(sample(i), sample_expected(i)) self.assertEqual(sample(i, i), sample_expected(i, i)) # invalid layout format, different kind of exceptions will be # raised by internal functions # plain wrong format self.assertRaises(ValueError, ttk._format_layoutlist, ['bad', 'format']) # will try to use iteritems in the 'bad' string self.assertRaises(AttributeError, ttk._format_layoutlist, [('name', 'bad')]) # bad children formatting self.assertRaises(ValueError, ttk._format_layoutlist, [('name', {'children': {'a': None}})]) def test_script_from_settings(self): # empty options self.assertFalse(ttk._script_from_settings({'name': {'configure': None, 'map': None, 'element create': None}})) # empty layout self.assertEqual( ttk._script_from_settings({'name': {'layout': None}}), "ttk::style layout name {\nnull\n}") configdict = {'αβγ': True, 'á': False} self.assertTrue( ttk._script_from_settings({'name': {'configure': configdict}})) mapdict = {'üñíćódè': [('á', 'vãl')]} self.assertTrue( ttk._script_from_settings({'name': {'map': mapdict}})) # invalid image element self.assertRaises(IndexError, ttk._script_from_settings, {'name': {'element create': ['image']}}) # minimal valid image self.assertTrue(ttk._script_from_settings({'name': {'element create': ['image', 'name']}})) image = {'thing': {'element create': ['image', 'name', ('state1', 'state2', 'val')]}} self.assertEqual(ttk._script_from_settings(image), "ttk::style element create thing image {name {state1 state2} val} ") image['thing']['element create'].append({'opt': 30}) self.assertEqual(ttk._script_from_settings(image), "ttk::style element create thing image {name {state1 state2} val} " "-opt 30") image['thing']['element create'][-1]['opt'] = [MockTclObj(3), MockTclObj('2m')] self.assertEqual(ttk._script_from_settings(image), "ttk::style element create thing image {name {state1 state2} val} " "-opt {3 2m}") def test_tclobj_to_py(self): self.assertEqual( ttk._tclobj_to_py((MockStateSpec('a', 'b'), 'val')), [('a', 'b', 'val')]) self.assertEqual( ttk._tclobj_to_py([MockTclObj('1'), 2, MockTclObj('3m')]), [1, 2, '3m']) def test_list_from_statespec(self): def test_it(sspec, value, res_value, states): self.assertEqual(ttk._list_from_statespec( (sspec, value)), [states + (res_value, )]) states_even = tuple('state%d' % i for i in range(6)) statespec = MockStateSpec(*states_even) test_it(statespec, 'val', 'val', states_even) test_it(statespec, MockTclObj('val'), 'val', states_even) states_odd = tuple('state%d' % i for i in range(5)) statespec = MockStateSpec(*states_odd) test_it(statespec, 'val', 'val', states_odd) test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c')) def test_list_from_layouttuple(self): tk = MockTkApp() # empty layout tuple self.assertFalse(ttk._list_from_layouttuple(tk, ())) # shortest layout tuple self.assertEqual(ttk._list_from_layouttuple(tk, ('name', )), [('name', {})]) # not so interesting ltuple sample_ltuple = ('name', '-option', 'value') self.assertEqual(ttk._list_from_layouttuple(tk, sample_ltuple), [('name', {'option': 'value'})]) # empty children self.assertEqual(ttk._list_from_layouttuple(tk, ('something', '-children', ())), [('something', {'children': []})] ) # more interesting ltuple ltuple = ( 'name', '-option', 'niceone', '-children', ( ('otherone', '-children', ( ('child', )), '-otheropt', 'othervalue' ) ) ) self.assertEqual(ttk._list_from_layouttuple(tk, ltuple), [('name', {'option': 'niceone', 'children': [('otherone', {'otheropt': 'othervalue', 'children': [('child', {})] })] })] ) # bad tuples self.assertRaises(ValueError, ttk._list_from_layouttuple, tk, ('name', 'no_minus')) self.assertRaises(ValueError, ttk._list_from_layouttuple, tk, ('name', 'no_minus', 'value')) self.assertRaises(ValueError, ttk._list_from_layouttuple, tk, ('something', '-children')) # no children def test_val_or_dict(self): def func(res, opt=None, val=None): if opt is None: return res if val is None: return "test val" return (opt, val) tk = MockTkApp() tk.call = func self.assertEqual(ttk._val_or_dict(tk, {}, '-test:3'), {'test': '3'}) self.assertEqual(ttk._val_or_dict(tk, {}, ('-test', 3)), {'test': 3}) self.assertEqual(ttk._val_or_dict(tk, {'test': None}, 'x:y'), 'test val') self.assertEqual(ttk._val_or_dict(tk, {'test': 3}, 'x:y'), {'test': 3}) def test_convert_stringval(self): tests = ( (0, 0), ('09', 9), ('a', 'a'), ('áÚ', 'áÚ'), ([], '[]'), (None, 'None') ) for orig, expected in tests: self.assertEqual(ttk._convert_stringval(orig), expected) class TclObjsToPyTest(unittest.TestCase): def test_unicode(self): adict = {'opt': 'välúè'} self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'}) adict['opt'] = MockTclObj(adict['opt']) self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'}) def test_multivalues(self): adict = {'opt': [1, 2, 3, 4]} self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]}) adict['opt'] = [1, 'xm', 3] self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]}) adict['opt'] = (MockStateSpec('a', 'b'), 'válũè') self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [('a', 'b', 'válũè')]}) self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}), {'x': ['y z']}) def test_nosplit(self): self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}), {'text': 'some text'}) tests_nogui = (InternalFunctionsTest, TclObjsToPyTest) if __name__ == "__main__": from test.support import run_unittest run_unittest(*tests_nogui)
17,129
462
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_ttk/test_widgets.py
import unittest import tkinter from tkinter import ttk, TclError from test.support import requires import sys from tkinter.test.test_ttk.test_functions import MockTclObj from tkinter.test.support import (AbstractTkTest, tcl_version, get_tk_patchlevel, simulate_mouse_click) from tkinter.test.widget_tests import (add_standard_options, noconv, AbstractWidgetTest, StandardOptionsTests, IntegerSizeTests, PixelSizeTests, setUpModule) requires('gui') class StandardTtkOptionsTests(StandardOptionsTests): def test_class(self): widget = self.create() self.assertEqual(widget['class'], '') errmsg='attempt to change read-only option' if get_tk_patchlevel() < (8, 6, 0, 'beta', 3): errmsg='Attempt to change read-only option' self.checkInvalidParam(widget, 'class', 'Foo', errmsg=errmsg) widget2 = self.create(class_='Foo') self.assertEqual(widget2['class'], 'Foo') def test_padding(self): widget = self.create() self.checkParam(widget, 'padding', 0, expected=('0',)) self.checkParam(widget, 'padding', 5, expected=('5',)) self.checkParam(widget, 'padding', (5, 6), expected=('5', '6')) self.checkParam(widget, 'padding', (5, 6, 7), expected=('5', '6', '7')) self.checkParam(widget, 'padding', (5, 6, 7, 8), expected=('5', '6', '7', '8')) self.checkParam(widget, 'padding', ('5p', '6p', '7p', '8p')) self.checkParam(widget, 'padding', (), expected='') def test_style(self): widget = self.create() self.assertEqual(widget['style'], '') errmsg = 'Layout Foo not found' if hasattr(self, 'default_orient'): errmsg = ('Layout %s.Foo not found' % getattr(self, 'default_orient').title()) self.checkInvalidParam(widget, 'style', 'Foo', errmsg=errmsg) widget2 = self.create(class_='Foo') self.assertEqual(widget2['class'], 'Foo') # XXX pass class WidgetTest(AbstractTkTest, unittest.TestCase): """Tests methods available in every ttk widget.""" def setUp(self): super().setUp() self.widget = ttk.Button(self.root, width=0, text="Text") self.widget.pack() self.widget.wait_visibility() def test_identify(self): self.widget.update_idletasks() self.assertEqual(self.widget.identify( int(self.widget.winfo_width() / 2), int(self.widget.winfo_height() / 2) ), "label") self.assertEqual(self.widget.identify(-1, -1), "") self.assertRaises(tkinter.TclError, self.widget.identify, None, 5) self.assertRaises(tkinter.TclError, self.widget.identify, 5, None) self.assertRaises(tkinter.TclError, self.widget.identify, 5, '') def test_widget_state(self): # XXX not sure about the portability of all these tests self.assertEqual(self.widget.state(), ()) self.assertEqual(self.widget.instate(['!disabled']), True) # changing from !disabled to disabled self.assertEqual(self.widget.state(['disabled']), ('!disabled', )) # no state change self.assertEqual(self.widget.state(['disabled']), ()) # change back to !disable but also active self.assertEqual(self.widget.state(['!disabled', 'active']), ('!active', 'disabled')) # no state changes, again self.assertEqual(self.widget.state(['!disabled', 'active']), ()) self.assertEqual(self.widget.state(['active', '!disabled']), ()) def test_cb(arg1, **kw): return arg1, kw self.assertEqual(self.widget.instate(['!disabled'], test_cb, "hi", **{"msg": "there"}), ('hi', {'msg': 'there'})) # attempt to set invalid statespec currstate = self.widget.state() self.assertRaises(tkinter.TclError, self.widget.instate, ['badstate']) self.assertRaises(tkinter.TclError, self.widget.instate, ['disabled', 'badstate']) # verify that widget didn't change its state self.assertEqual(currstate, self.widget.state()) # ensuring that passing None as state doesn't modify current state self.widget.state(['active', '!disabled']) self.assertEqual(self.widget.state(), ('active', )) class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests): _conv_pixels = noconv @add_standard_options(StandardTtkOptionsTests) class FrameTest(AbstractToplevelTest, unittest.TestCase): OPTIONS = ( 'borderwidth', 'class', 'cursor', 'height', 'padding', 'relief', 'style', 'takefocus', 'width', ) def create(self, **kwargs): return ttk.Frame(self.root, **kwargs) @add_standard_options(StandardTtkOptionsTests) class LabelFrameTest(AbstractToplevelTest, unittest.TestCase): OPTIONS = ( 'borderwidth', 'class', 'cursor', 'height', 'labelanchor', 'labelwidget', 'padding', 'relief', 'style', 'takefocus', 'text', 'underline', 'width', ) def create(self, **kwargs): return ttk.LabelFrame(self.root, **kwargs) def test_labelanchor(self): widget = self.create() self.checkEnumParam(widget, 'labelanchor', 'e', 'en', 'es', 'n', 'ne', 'nw', 's', 'se', 'sw', 'w', 'wn', 'ws', errmsg='Bad label anchor specification {}') self.checkInvalidParam(widget, 'labelanchor', 'center') def test_labelwidget(self): widget = self.create() label = ttk.Label(self.root, text='Mupp', name='foo') self.checkParam(widget, 'labelwidget', label, expected='.foo') label.destroy() class AbstractLabelTest(AbstractWidgetTest): def checkImageParam(self, widget, name): image = tkinter.PhotoImage(master=self.root, name='image1') image2 = tkinter.PhotoImage(master=self.root, name='image2') self.checkParam(widget, name, image, expected=('image1',)) self.checkParam(widget, name, 'image1', expected=('image1',)) self.checkParam(widget, name, (image,), expected=('image1',)) self.checkParam(widget, name, (image, 'active', image2), expected=('image1', 'active', 'image2')) self.checkParam(widget, name, 'image1 active image2', expected=('image1', 'active', 'image2')) self.checkInvalidParam(widget, name, 'spam', errmsg='image "spam" doesn\'t exist') def test_compound(self): widget = self.create() self.checkEnumParam(widget, 'compound', 'none', 'text', 'image', 'center', 'top', 'bottom', 'left', 'right') def test_state(self): widget = self.create() self.checkParams(widget, 'state', 'active', 'disabled', 'normal') def test_width(self): widget = self.create() self.checkParams(widget, 'width', 402, -402, 0) @add_standard_options(StandardTtkOptionsTests) class LabelTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'anchor', 'background', 'borderwidth', 'class', 'compound', 'cursor', 'font', 'foreground', 'image', 'justify', 'padding', 'relief', 'state', 'style', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength', ) _conv_pixels = noconv def create(self, **kwargs): return ttk.Label(self.root, **kwargs) def test_font(self): widget = self.create() self.checkParam(widget, 'font', '-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*') @add_standard_options(StandardTtkOptionsTests) class ButtonTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'class', 'command', 'compound', 'cursor', 'default', 'image', 'padding', 'state', 'style', 'takefocus', 'text', 'textvariable', 'underline', 'width', ) def create(self, **kwargs): return ttk.Button(self.root, **kwargs) def test_default(self): widget = self.create() self.checkEnumParam(widget, 'default', 'normal', 'active', 'disabled') def test_invoke(self): success = [] btn = ttk.Button(self.root, command=lambda: success.append(1)) btn.invoke() self.assertTrue(success) @add_standard_options(StandardTtkOptionsTests) class CheckbuttonTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'class', 'command', 'compound', 'cursor', 'image', 'offvalue', 'onvalue', 'padding', 'state', 'style', 'takefocus', 'text', 'textvariable', 'underline', 'variable', 'width', ) def create(self, **kwargs): return ttk.Checkbutton(self.root, **kwargs) def test_offvalue(self): widget = self.create() self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string') def test_onvalue(self): widget = self.create() self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string') def test_invoke(self): success = [] def cb_test(): success.append(1) return "cb test called" cbtn = ttk.Checkbutton(self.root, command=cb_test) # the variable automatically created by ttk.Checkbutton is actually # undefined till we invoke the Checkbutton self.assertEqual(cbtn.state(), ('alternate', )) self.assertRaises(tkinter.TclError, cbtn.tk.globalgetvar, cbtn['variable']) res = cbtn.invoke() self.assertEqual(res, "cb test called") self.assertEqual(cbtn['onvalue'], cbtn.tk.globalgetvar(cbtn['variable'])) self.assertTrue(success) cbtn['command'] = '' res = cbtn.invoke() self.assertFalse(str(res)) self.assertLessEqual(len(success), 1) self.assertEqual(cbtn['offvalue'], cbtn.tk.globalgetvar(cbtn['variable'])) @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) class EntryTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'background', 'class', 'cursor', 'exportselection', 'font', 'foreground', 'invalidcommand', 'justify', 'show', 'state', 'style', 'takefocus', 'textvariable', 'validate', 'validatecommand', 'width', 'xscrollcommand', ) def setUp(self): super().setUp() self.entry = self.create() def create(self, **kwargs): return ttk.Entry(self.root, **kwargs) def test_invalidcommand(self): widget = self.create() self.checkCommandParam(widget, 'invalidcommand') def test_show(self): widget = self.create() self.checkParam(widget, 'show', '*') self.checkParam(widget, 'show', '') self.checkParam(widget, 'show', ' ') def test_state(self): widget = self.create() self.checkParams(widget, 'state', 'disabled', 'normal', 'readonly') def test_validate(self): widget = self.create() self.checkEnumParam(widget, 'validate', 'all', 'key', 'focus', 'focusin', 'focusout', 'none') def test_validatecommand(self): widget = self.create() self.checkCommandParam(widget, 'validatecommand') def test_bbox(self): self.assertIsBoundingBox(self.entry.bbox(0)) self.assertRaises(tkinter.TclError, self.entry.bbox, 'noindex') self.assertRaises(tkinter.TclError, self.entry.bbox, None) def test_identify(self): self.entry.pack() self.entry.wait_visibility() self.entry.update_idletasks() # bpo-27313: macOS Cocoa widget differs from X, allow either if sys.platform == 'darwin': self.assertIn(self.entry.identify(5, 5), ("textarea", "Combobox.button") ) else: self.assertEqual(self.entry.identify(5, 5), "textarea") self.assertEqual(self.entry.identify(-1, -1), "") self.assertRaises(tkinter.TclError, self.entry.identify, None, 5) self.assertRaises(tkinter.TclError, self.entry.identify, 5, None) self.assertRaises(tkinter.TclError, self.entry.identify, 5, '') def test_validation_options(self): success = [] test_invalid = lambda: success.append(True) self.entry['validate'] = 'none' self.entry['validatecommand'] = lambda: False self.entry['invalidcommand'] = test_invalid self.entry.validate() self.assertTrue(success) self.entry['invalidcommand'] = '' self.entry.validate() self.assertEqual(len(success), 1) self.entry['invalidcommand'] = test_invalid self.entry['validatecommand'] = lambda: True self.entry.validate() self.assertEqual(len(success), 1) self.entry['validatecommand'] = '' self.entry.validate() self.assertEqual(len(success), 1) self.entry['validatecommand'] = True self.assertRaises(tkinter.TclError, self.entry.validate) def test_validation(self): validation = [] def validate(to_insert): if not 'a' <= to_insert.lower() <= 'z': validation.append(False) return False validation.append(True) return True self.entry['validate'] = 'key' self.entry['validatecommand'] = self.entry.register(validate), '%S' self.entry.insert('end', 1) self.entry.insert('end', 'a') self.assertEqual(validation, [False, True]) self.assertEqual(self.entry.get(), 'a') def test_revalidation(self): def validate(content): for letter in content: if not 'a' <= letter.lower() <= 'z': return False return True self.entry['validatecommand'] = self.entry.register(validate), '%P' self.entry.insert('end', 'avocado') self.assertEqual(self.entry.validate(), True) self.assertEqual(self.entry.state(), ()) self.entry.delete(0, 'end') self.assertEqual(self.entry.get(), '') self.entry.insert('end', 'a1b') self.assertEqual(self.entry.validate(), False) self.assertEqual(self.entry.state(), ('invalid', )) self.entry.delete(1) self.assertEqual(self.entry.validate(), True) self.assertEqual(self.entry.state(), ()) @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) class ComboboxTest(EntryTest, unittest.TestCase): OPTIONS = ( 'background', 'class', 'cursor', 'exportselection', 'font', 'foreground', 'height', 'invalidcommand', 'justify', 'postcommand', 'show', 'state', 'style', 'takefocus', 'textvariable', 'validate', 'validatecommand', 'values', 'width', 'xscrollcommand', ) def setUp(self): super().setUp() self.combo = self.create() def create(self, **kwargs): return ttk.Combobox(self.root, **kwargs) def test_height(self): widget = self.create() self.checkParams(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i') def _show_drop_down_listbox(self): width = self.combo.winfo_width() self.combo.event_generate('<ButtonPress-1>', x=width - 5, y=5) self.combo.event_generate('<ButtonRelease-1>', x=width - 5, y=5) self.combo.update_idletasks() def test_virtual_event(self): success = [] self.combo['values'] = [1] self.combo.bind('<<ComboboxSelected>>', lambda evt: success.append(True)) self.combo.pack() self.combo.wait_visibility() height = self.combo.winfo_height() self._show_drop_down_listbox() self.combo.update() self.combo.event_generate('<Return>') self.combo.update() self.assertTrue(success) def test_postcommand(self): success = [] self.combo['postcommand'] = lambda: success.append(True) self.combo.pack() self.combo.wait_visibility() self._show_drop_down_listbox() self.assertTrue(success) # testing postcommand removal self.combo['postcommand'] = '' self._show_drop_down_listbox() self.assertEqual(len(success), 1) def test_values(self): def check_get_current(getval, currval): self.assertEqual(self.combo.get(), getval) self.assertEqual(self.combo.current(), currval) self.assertEqual(self.combo['values'], () if tcl_version < (8, 5) else '') check_get_current('', -1) self.checkParam(self.combo, 'values', 'mon tue wed thur', expected=('mon', 'tue', 'wed', 'thur')) self.checkParam(self.combo, 'values', ('mon', 'tue', 'wed', 'thur')) self.checkParam(self.combo, 'values', (42, 3.14, '', 'any string')) self.checkParam(self.combo, 'values', '', expected='' if get_tk_patchlevel() < (8, 5, 10) else ()) self.combo['values'] = ['a', 1, 'c'] self.combo.set('c') check_get_current('c', 2) self.combo.current(0) check_get_current('a', 0) self.combo.set('d') check_get_current('d', -1) # testing values with empty string self.combo.set('') self.combo['values'] = (1, 2, '', 3) check_get_current('', 2) # testing values with empty string set through configure self.combo.configure(values=[1, '', 2]) self.assertEqual(self.combo['values'], ('1', '', '2') if self.wantobjects else '1 {} 2') # testing values with spaces self.combo['values'] = ['a b', 'a\tb', 'a\nb'] self.assertEqual(self.combo['values'], ('a b', 'a\tb', 'a\nb') if self.wantobjects else '{a b} {a\tb} {a\nb}') # testing values with special characters self.combo['values'] = [r'a\tb', '"a"', '} {'] self.assertEqual(self.combo['values'], (r'a\tb', '"a"', '} {') if self.wantobjects else r'a\\tb {"a"} \}\ \{') # out of range self.assertRaises(tkinter.TclError, self.combo.current, len(self.combo['values'])) # it expects an integer (or something that can be converted to int) self.assertRaises(tkinter.TclError, self.combo.current, '') # testing creating combobox with empty string in values combo2 = ttk.Combobox(self.root, values=[1, 2, '']) self.assertEqual(combo2['values'], ('1', '2', '') if self.wantobjects else '1 2 {}') combo2.destroy() @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'class', 'cursor', 'height', 'orient', 'style', 'takefocus', 'width', ) def setUp(self): super().setUp() self.paned = self.create() def create(self, **kwargs): return ttk.PanedWindow(self.root, **kwargs) def test_orient(self): widget = self.create() self.assertEqual(str(widget['orient']), 'vertical') errmsg='attempt to change read-only option' if get_tk_patchlevel() < (8, 6, 0, 'beta', 3): errmsg='Attempt to change read-only option' self.checkInvalidParam(widget, 'orient', 'horizontal', errmsg=errmsg) widget2 = self.create(orient='horizontal') self.assertEqual(str(widget2['orient']), 'horizontal') def test_add(self): # attempt to add a child that is not a direct child of the paned window label = ttk.Label(self.paned) child = ttk.Label(label) self.assertRaises(tkinter.TclError, self.paned.add, child) label.destroy() child.destroy() # another attempt label = ttk.Label(self.root) child = ttk.Label(label) self.assertRaises(tkinter.TclError, self.paned.add, child) child.destroy() label.destroy() good_child = ttk.Label(self.root) self.paned.add(good_child) # re-adding a child is not accepted self.assertRaises(tkinter.TclError, self.paned.add, good_child) other_child = ttk.Label(self.paned) self.paned.add(other_child) self.assertEqual(self.paned.pane(0), self.paned.pane(1)) self.assertRaises(tkinter.TclError, self.paned.pane, 2) good_child.destroy() other_child.destroy() self.assertRaises(tkinter.TclError, self.paned.pane, 0) def test_forget(self): self.assertRaises(tkinter.TclError, self.paned.forget, None) self.assertRaises(tkinter.TclError, self.paned.forget, 0) self.paned.add(ttk.Label(self.root)) self.paned.forget(0) self.assertRaises(tkinter.TclError, self.paned.forget, 0) def test_insert(self): self.assertRaises(tkinter.TclError, self.paned.insert, None, 0) self.assertRaises(tkinter.TclError, self.paned.insert, 0, None) self.assertRaises(tkinter.TclError, self.paned.insert, 0, 0) child = ttk.Label(self.root) child2 = ttk.Label(self.root) child3 = ttk.Label(self.root) self.assertRaises(tkinter.TclError, self.paned.insert, 0, child) self.paned.insert('end', child2) self.paned.insert(0, child) self.assertEqual(self.paned.panes(), (str(child), str(child2))) self.paned.insert(0, child2) self.assertEqual(self.paned.panes(), (str(child2), str(child))) self.paned.insert('end', child3) self.assertEqual(self.paned.panes(), (str(child2), str(child), str(child3))) # reinserting a child should move it to its current position panes = self.paned.panes() self.paned.insert('end', child3) self.assertEqual(panes, self.paned.panes()) # moving child3 to child2 position should result in child2 ending up # in previous child position and child ending up in previous child3 # position self.paned.insert(child2, child3) self.assertEqual(self.paned.panes(), (str(child3), str(child2), str(child))) def test_pane(self): self.assertRaises(tkinter.TclError, self.paned.pane, 0) child = ttk.Label(self.root) self.paned.add(child) self.assertIsInstance(self.paned.pane(0), dict) self.assertEqual(self.paned.pane(0, weight=None), 0 if self.wantobjects else '0') # newer form for querying a single option self.assertEqual(self.paned.pane(0, 'weight'), 0 if self.wantobjects else '0') self.assertEqual(self.paned.pane(0), self.paned.pane(str(child))) self.assertRaises(tkinter.TclError, self.paned.pane, 0, badoption='somevalue') def test_sashpos(self): self.assertRaises(tkinter.TclError, self.paned.sashpos, None) self.assertRaises(tkinter.TclError, self.paned.sashpos, '') self.assertRaises(tkinter.TclError, self.paned.sashpos, 0) child = ttk.Label(self.paned, text='a') self.paned.add(child, weight=1) self.assertRaises(tkinter.TclError, self.paned.sashpos, 0) child2 = ttk.Label(self.paned, text='b') self.paned.add(child2) self.assertRaises(tkinter.TclError, self.paned.sashpos, 1) self.paned.pack(expand=True, fill='both') self.paned.wait_visibility() curr_pos = self.paned.sashpos(0) self.paned.sashpos(0, 1000) self.assertNotEqual(curr_pos, self.paned.sashpos(0)) self.assertIsInstance(self.paned.sashpos(0), int) @add_standard_options(StandardTtkOptionsTests) class RadiobuttonTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'class', 'command', 'compound', 'cursor', 'image', 'padding', 'state', 'style', 'takefocus', 'text', 'textvariable', 'underline', 'value', 'variable', 'width', ) def create(self, **kwargs): return ttk.Radiobutton(self.root, **kwargs) def test_value(self): widget = self.create() self.checkParams(widget, 'value', 1, 2.3, '', 'any string') def test_invoke(self): success = [] def cb_test(): success.append(1) return "cb test called" myvar = tkinter.IntVar(self.root) cbtn = ttk.Radiobutton(self.root, command=cb_test, variable=myvar, value=0) cbtn2 = ttk.Radiobutton(self.root, command=cb_test, variable=myvar, value=1) if self.wantobjects: conv = lambda x: x else: conv = int res = cbtn.invoke() self.assertEqual(res, "cb test called") self.assertEqual(conv(cbtn['value']), myvar.get()) self.assertEqual(myvar.get(), conv(cbtn.tk.globalgetvar(cbtn['variable']))) self.assertTrue(success) cbtn2['command'] = '' res = cbtn2.invoke() self.assertEqual(str(res), '') self.assertLessEqual(len(success), 1) self.assertEqual(conv(cbtn2['value']), myvar.get()) self.assertEqual(myvar.get(), conv(cbtn.tk.globalgetvar(cbtn['variable']))) self.assertEqual(str(cbtn['variable']), str(cbtn2['variable'])) class MenubuttonTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'class', 'compound', 'cursor', 'direction', 'image', 'menu', 'padding', 'state', 'style', 'takefocus', 'text', 'textvariable', 'underline', 'width', ) def create(self, **kwargs): return ttk.Menubutton(self.root, **kwargs) def test_direction(self): widget = self.create() self.checkEnumParam(widget, 'direction', 'above', 'below', 'left', 'right', 'flush') def test_menu(self): widget = self.create() menu = tkinter.Menu(widget, name='menu') self.checkParam(widget, 'menu', menu, conv=str) menu.destroy() @add_standard_options(StandardTtkOptionsTests) class ScaleTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'class', 'command', 'cursor', 'from', 'length', 'orient', 'style', 'takefocus', 'to', 'value', 'variable', ) _conv_pixels = noconv default_orient = 'horizontal' def setUp(self): super().setUp() self.scale = self.create() self.scale.pack() self.scale.update() def create(self, **kwargs): return ttk.Scale(self.root, **kwargs) def test_from(self): widget = self.create() self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=False) def test_length(self): widget = self.create() self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i') def test_to(self): widget = self.create() self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, conv=False) def test_value(self): widget = self.create() self.checkFloatParam(widget, 'value', 300, 14.9, 15.1, -10, conv=False) def test_custom_event(self): failure = [1, 1, 1] # will need to be empty funcid = self.scale.bind('<<RangeChanged>>', lambda evt: failure.pop()) self.scale['from'] = 10 self.scale['from_'] = 10 self.scale['to'] = 3 self.assertFalse(failure) failure = [1, 1, 1] self.scale.configure(from_=2, to=5) self.scale.configure(from_=0, to=-2) self.scale.configure(to=10) self.assertFalse(failure) def test_get(self): if self.wantobjects: conv = lambda x: x else: conv = float scale_width = self.scale.winfo_width() self.assertEqual(self.scale.get(scale_width, 0), self.scale['to']) self.assertEqual(conv(self.scale.get(0, 0)), conv(self.scale['from'])) self.assertEqual(self.scale.get(), self.scale['value']) self.scale['value'] = 30 self.assertEqual(self.scale.get(), self.scale['value']) self.assertRaises(tkinter.TclError, self.scale.get, '', 0) self.assertRaises(tkinter.TclError, self.scale.get, 0, '') def test_set(self): if self.wantobjects: conv = lambda x: x else: conv = float # set restricts the max/min values according to the current range max = conv(self.scale['to']) new_max = max + 10 self.scale.set(new_max) self.assertEqual(conv(self.scale.get()), max) min = conv(self.scale['from']) self.scale.set(min - 1) self.assertEqual(conv(self.scale.get()), min) # changing directly the variable doesn't impose this limitation tho var = tkinter.DoubleVar(self.root) self.scale['variable'] = var var.set(max + 5) self.assertEqual(conv(self.scale.get()), var.get()) self.assertEqual(conv(self.scale.get()), max + 5) del var # the same happens with the value option self.scale['value'] = max + 10 self.assertEqual(conv(self.scale.get()), max + 10) self.assertEqual(conv(self.scale.get()), conv(self.scale['value'])) # nevertheless, note that the max/min values we can get specifying # x, y coords are the ones according to the current range self.assertEqual(conv(self.scale.get(0, 0)), min) self.assertEqual(conv(self.scale.get(self.scale.winfo_width(), 0)), max) self.assertRaises(tkinter.TclError, self.scale.set, None) @add_standard_options(StandardTtkOptionsTests) class ProgressbarTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'class', 'cursor', 'orient', 'length', 'mode', 'maximum', 'phase', 'style', 'takefocus', 'value', 'variable', ) _conv_pixels = noconv default_orient = 'horizontal' def create(self, **kwargs): return ttk.Progressbar(self.root, **kwargs) def test_length(self): widget = self.create() self.checkPixelsParam(widget, 'length', 100.1, 56.7, '2i') def test_maximum(self): widget = self.create() self.checkFloatParam(widget, 'maximum', 150.2, 77.7, 0, -10, conv=False) def test_mode(self): widget = self.create() self.checkEnumParam(widget, 'mode', 'determinate', 'indeterminate') def test_phase(self): # XXX pass def test_value(self): widget = self.create() self.checkFloatParam(widget, 'value', 150.2, 77.7, 0, -10, conv=False) @unittest.skipIf(sys.platform == 'darwin', 'ttk.Scrollbar is special on MacOSX') @add_standard_options(StandardTtkOptionsTests) class ScrollbarTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'class', 'command', 'cursor', 'orient', 'style', 'takefocus', ) default_orient = 'vertical' def create(self, **kwargs): return ttk.Scrollbar(self.root, **kwargs) @add_standard_options(IntegerSizeTests, StandardTtkOptionsTests) class NotebookTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'class', 'cursor', 'height', 'padding', 'style', 'takefocus', 'width', ) def setUp(self): super().setUp() self.nb = self.create(padding=0) self.child1 = ttk.Label(self.root) self.child2 = ttk.Label(self.root) self.nb.add(self.child1, text='a') self.nb.add(self.child2, text='b') def create(self, **kwargs): return ttk.Notebook(self.root, **kwargs) def test_tab_identifiers(self): self.nb.forget(0) self.nb.hide(self.child2) self.assertRaises(tkinter.TclError, self.nb.tab, self.child1) self.assertEqual(self.nb.index('end'), 1) self.nb.add(self.child2) self.assertEqual(self.nb.index('end'), 1) self.nb.select(self.child2) self.assertTrue(self.nb.tab('current')) self.nb.add(self.child1, text='a') self.nb.pack() self.nb.wait_visibility() if sys.platform == 'darwin': tb_idx = "@20,5" else: tb_idx = "@5,5" self.assertEqual(self.nb.tab(tb_idx), self.nb.tab('current')) for i in range(5, 100, 5): try: if self.nb.tab('@%d, 5' % i, text=None) == 'a': break except tkinter.TclError: pass else: self.fail("Tab with text 'a' not found") def test_add_and_hidden(self): self.assertRaises(tkinter.TclError, self.nb.hide, -1) self.assertRaises(tkinter.TclError, self.nb.hide, 'hi') self.assertRaises(tkinter.TclError, self.nb.hide, None) self.assertRaises(tkinter.TclError, self.nb.add, None) self.assertRaises(tkinter.TclError, self.nb.add, ttk.Label(self.root), unknown='option') tabs = self.nb.tabs() self.nb.hide(self.child1) self.nb.add(self.child1) self.assertEqual(self.nb.tabs(), tabs) child = ttk.Label(self.root) self.nb.add(child, text='c') tabs = self.nb.tabs() curr = self.nb.index('current') # verify that the tab gets readded at its previous position child2_index = self.nb.index(self.child2) self.nb.hide(self.child2) self.nb.add(self.child2) self.assertEqual(self.nb.tabs(), tabs) self.assertEqual(self.nb.index(self.child2), child2_index) self.assertEqual(str(self.child2), self.nb.tabs()[child2_index]) # but the tab next to it (not hidden) is the one selected now self.assertEqual(self.nb.index('current'), curr + 1) def test_forget(self): self.assertRaises(tkinter.TclError, self.nb.forget, -1) self.assertRaises(tkinter.TclError, self.nb.forget, 'hi') self.assertRaises(tkinter.TclError, self.nb.forget, None) tabs = self.nb.tabs() child1_index = self.nb.index(self.child1) self.nb.forget(self.child1) self.assertNotIn(str(self.child1), self.nb.tabs()) self.assertEqual(len(tabs) - 1, len(self.nb.tabs())) self.nb.add(self.child1) self.assertEqual(self.nb.index(self.child1), 1) self.assertNotEqual(child1_index, self.nb.index(self.child1)) def test_index(self): self.assertRaises(tkinter.TclError, self.nb.index, -1) self.assertRaises(tkinter.TclError, self.nb.index, None) self.assertIsInstance(self.nb.index('end'), int) self.assertEqual(self.nb.index(self.child1), 0) self.assertEqual(self.nb.index(self.child2), 1) self.assertEqual(self.nb.index('end'), 2) def test_insert(self): # moving tabs tabs = self.nb.tabs() self.nb.insert(1, tabs[0]) self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0])) self.nb.insert(self.child1, self.child2) self.assertEqual(self.nb.tabs(), tabs) self.nb.insert('end', self.child1) self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0])) self.nb.insert('end', 0) self.assertEqual(self.nb.tabs(), tabs) # bad moves self.assertRaises(tkinter.TclError, self.nb.insert, 2, tabs[0]) self.assertRaises(tkinter.TclError, self.nb.insert, -1, tabs[0]) # new tab child3 = ttk.Label(self.root) self.nb.insert(1, child3) self.assertEqual(self.nb.tabs(), (tabs[0], str(child3), tabs[1])) self.nb.forget(child3) self.assertEqual(self.nb.tabs(), tabs) self.nb.insert(self.child1, child3) self.assertEqual(self.nb.tabs(), (str(child3), ) + tabs) self.nb.forget(child3) self.assertRaises(tkinter.TclError, self.nb.insert, 2, child3) self.assertRaises(tkinter.TclError, self.nb.insert, -1, child3) # bad inserts self.assertRaises(tkinter.TclError, self.nb.insert, 'end', None) self.assertRaises(tkinter.TclError, self.nb.insert, None, 0) self.assertRaises(tkinter.TclError, self.nb.insert, None, None) def test_select(self): self.nb.pack() self.nb.wait_visibility() success = [] tab_changed = [] self.child1.bind('<Unmap>', lambda evt: success.append(True)) self.nb.bind('<<NotebookTabChanged>>', lambda evt: tab_changed.append(True)) self.assertEqual(self.nb.select(), str(self.child1)) self.nb.select(self.child2) self.assertTrue(success) self.assertEqual(self.nb.select(), str(self.child2)) self.nb.update() self.assertTrue(tab_changed) def test_tab(self): self.assertRaises(tkinter.TclError, self.nb.tab, -1) self.assertRaises(tkinter.TclError, self.nb.tab, 'notab') self.assertRaises(tkinter.TclError, self.nb.tab, None) self.assertIsInstance(self.nb.tab(self.child1), dict) self.assertEqual(self.nb.tab(self.child1, text=None), 'a') # newer form for querying a single option self.assertEqual(self.nb.tab(self.child1, 'text'), 'a') self.nb.tab(self.child1, text='abc') self.assertEqual(self.nb.tab(self.child1, text=None), 'abc') self.assertEqual(self.nb.tab(self.child1, 'text'), 'abc') def test_tabs(self): self.assertEqual(len(self.nb.tabs()), 2) self.nb.forget(self.child1) self.nb.forget(self.child2) self.assertEqual(self.nb.tabs(), ()) def test_traversal(self): self.nb.pack() self.nb.wait_visibility() self.nb.select(0) simulate_mouse_click(self.nb, 5, 5) self.nb.focus_force() self.nb.event_generate('<Control-Tab>') self.assertEqual(self.nb.select(), str(self.child2)) self.nb.focus_force() self.nb.event_generate('<Shift-Control-Tab>') self.assertEqual(self.nb.select(), str(self.child1)) self.nb.focus_force() self.nb.event_generate('<Shift-Control-Tab>') self.assertEqual(self.nb.select(), str(self.child2)) self.nb.tab(self.child1, text='a', underline=0) self.nb.enable_traversal() self.nb.focus_force() simulate_mouse_click(self.nb, 5, 5) if sys.platform == 'darwin': self.nb.event_generate('<Option-a>') else: self.nb.event_generate('<Alt-a>') self.assertEqual(self.nb.select(), str(self.child1)) @add_standard_options(StandardTtkOptionsTests) class TreeviewTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'class', 'columns', 'cursor', 'displaycolumns', 'height', 'padding', 'selectmode', 'show', 'style', 'takefocus', 'xscrollcommand', 'yscrollcommand', ) def setUp(self): super().setUp() self.tv = self.create(padding=0) def create(self, **kwargs): return ttk.Treeview(self.root, **kwargs) def test_columns(self): widget = self.create() self.checkParam(widget, 'columns', 'a b c', expected=('a', 'b', 'c')) self.checkParam(widget, 'columns', ('a', 'b', 'c')) self.checkParam(widget, 'columns', (), expected='' if get_tk_patchlevel() < (8, 5, 10) else ()) def test_displaycolumns(self): widget = self.create() widget['columns'] = ('a', 'b', 'c') self.checkParam(widget, 'displaycolumns', 'b a c', expected=('b', 'a', 'c')) self.checkParam(widget, 'displaycolumns', ('b', 'a', 'c')) self.checkParam(widget, 'displaycolumns', '#all', expected=('#all',)) self.checkParam(widget, 'displaycolumns', (2, 1, 0)) self.checkInvalidParam(widget, 'displaycolumns', ('a', 'b', 'd'), errmsg='Invalid column index d') self.checkInvalidParam(widget, 'displaycolumns', (1, 2, 3), errmsg='Column index 3 out of bounds') self.checkInvalidParam(widget, 'displaycolumns', (1, -2), errmsg='Column index -2 out of bounds') def test_height(self): widget = self.create() self.checkPixelsParam(widget, 'height', 100, -100, 0, '3c', conv=False) self.checkPixelsParam(widget, 'height', 101.2, 102.6, conv=noconv) def test_selectmode(self): widget = self.create() self.checkEnumParam(widget, 'selectmode', 'none', 'browse', 'extended') def test_show(self): widget = self.create() self.checkParam(widget, 'show', 'tree headings', expected=('tree', 'headings')) self.checkParam(widget, 'show', ('tree', 'headings')) self.checkParam(widget, 'show', ('headings', 'tree')) self.checkParam(widget, 'show', 'tree', expected=('tree',)) self.checkParam(widget, 'show', 'headings', expected=('headings',)) def test_bbox(self): self.tv.pack() self.assertEqual(self.tv.bbox(''), '') self.tv.wait_visibility() self.tv.update() item_id = self.tv.insert('', 'end') children = self.tv.get_children() self.assertTrue(children) bbox = self.tv.bbox(children[0]) self.assertIsBoundingBox(bbox) # compare width in bboxes self.tv['columns'] = ['test'] self.tv.column('test', width=50) bbox_column0 = self.tv.bbox(children[0], 0) root_width = self.tv.column('#0', width=None) if not self.wantobjects: root_width = int(root_width) self.assertEqual(bbox_column0[0], bbox[0] + root_width) # verify that bbox of a closed item is the empty string child1 = self.tv.insert(item_id, 'end') self.assertEqual(self.tv.bbox(child1), '') def test_children(self): # no children yet, should get an empty tuple self.assertEqual(self.tv.get_children(), ()) item_id = self.tv.insert('', 'end') self.assertIsInstance(self.tv.get_children(), tuple) self.assertEqual(self.tv.get_children()[0], item_id) # add item_id and child3 as children of child2 child2 = self.tv.insert('', 'end') child3 = self.tv.insert('', 'end') self.tv.set_children(child2, item_id, child3) self.assertEqual(self.tv.get_children(child2), (item_id, child3)) # child3 has child2 as parent, thus trying to set child2 as a children # of child3 should result in an error self.assertRaises(tkinter.TclError, self.tv.set_children, child3, child2) # remove child2 children self.tv.set_children(child2) self.assertEqual(self.tv.get_children(child2), ()) # remove root's children self.tv.set_children('') self.assertEqual(self.tv.get_children(), ()) def test_column(self): # return a dict with all options/values self.assertIsInstance(self.tv.column('#0'), dict) # return a single value of the given option if self.wantobjects: self.assertIsInstance(self.tv.column('#0', width=None), int) # set a new value for an option self.tv.column('#0', width=10) # testing new way to get option value self.assertEqual(self.tv.column('#0', 'width'), 10 if self.wantobjects else '10') self.assertEqual(self.tv.column('#0', width=None), 10 if self.wantobjects else '10') # check read-only option self.assertRaises(tkinter.TclError, self.tv.column, '#0', id='X') self.assertRaises(tkinter.TclError, self.tv.column, 'invalid') invalid_kws = [ {'unknown_option': 'some value'}, {'stretch': 'wrong'}, {'anchor': 'wrong'}, {'width': 'wrong'}, {'minwidth': 'wrong'} ] for kw in invalid_kws: self.assertRaises(tkinter.TclError, self.tv.column, '#0', **kw) def test_delete(self): self.assertRaises(tkinter.TclError, self.tv.delete, '#0') item_id = self.tv.insert('', 'end') item2 = self.tv.insert(item_id, 'end') self.assertEqual(self.tv.get_children(), (item_id, )) self.assertEqual(self.tv.get_children(item_id), (item2, )) self.tv.delete(item_id) self.assertFalse(self.tv.get_children()) # reattach should fail self.assertRaises(tkinter.TclError, self.tv.reattach, item_id, '', 'end') # test multiple item delete item1 = self.tv.insert('', 'end') item2 = self.tv.insert('', 'end') self.assertEqual(self.tv.get_children(), (item1, item2)) self.tv.delete(item1, item2) self.assertFalse(self.tv.get_children()) def test_detach_reattach(self): item_id = self.tv.insert('', 'end') item2 = self.tv.insert(item_id, 'end') # calling detach without items is valid, although it does nothing prev = self.tv.get_children() self.tv.detach() # this should do nothing self.assertEqual(prev, self.tv.get_children()) self.assertEqual(self.tv.get_children(), (item_id, )) self.assertEqual(self.tv.get_children(item_id), (item2, )) # detach item with children self.tv.detach(item_id) self.assertFalse(self.tv.get_children()) # reattach item with children self.tv.reattach(item_id, '', 'end') self.assertEqual(self.tv.get_children(), (item_id, )) self.assertEqual(self.tv.get_children(item_id), (item2, )) # move a children to the root self.tv.move(item2, '', 'end') self.assertEqual(self.tv.get_children(), (item_id, item2)) self.assertEqual(self.tv.get_children(item_id), ()) # bad values self.assertRaises(tkinter.TclError, self.tv.reattach, 'nonexistent', '', 'end') self.assertRaises(tkinter.TclError, self.tv.detach, 'nonexistent') self.assertRaises(tkinter.TclError, self.tv.reattach, item2, 'otherparent', 'end') self.assertRaises(tkinter.TclError, self.tv.reattach, item2, '', 'invalid') # multiple detach self.tv.detach(item_id, item2) self.assertEqual(self.tv.get_children(), ()) self.assertEqual(self.tv.get_children(item_id), ()) def test_exists(self): self.assertEqual(self.tv.exists('something'), False) self.assertEqual(self.tv.exists(''), True) self.assertEqual(self.tv.exists({}), False) # the following will make a tk.call equivalent to # tk.call(treeview, "exists") which should result in an error # in the tcl interpreter since tk requires an item. self.assertRaises(tkinter.TclError, self.tv.exists, None) def test_focus(self): # nothing is focused right now self.assertEqual(self.tv.focus(), '') item1 = self.tv.insert('', 'end') self.tv.focus(item1) self.assertEqual(self.tv.focus(), item1) self.tv.delete(item1) self.assertEqual(self.tv.focus(), '') # try focusing inexistent item self.assertRaises(tkinter.TclError, self.tv.focus, 'hi') def test_heading(self): # check a dict is returned self.assertIsInstance(self.tv.heading('#0'), dict) # check a value is returned self.tv.heading('#0', text='hi') self.assertEqual(self.tv.heading('#0', 'text'), 'hi') self.assertEqual(self.tv.heading('#0', text=None), 'hi') # invalid option self.assertRaises(tkinter.TclError, self.tv.heading, '#0', background=None) # invalid value self.assertRaises(tkinter.TclError, self.tv.heading, '#0', anchor=1) def test_heading_callback(self): def simulate_heading_click(x, y): simulate_mouse_click(self.tv, x, y) self.tv.update() success = [] # no success for now self.tv.pack() self.tv.wait_visibility() self.tv.heading('#0', command=lambda: success.append(True)) self.tv.column('#0', width=100) self.tv.update() # assuming that the coords (5, 5) fall into heading #0 simulate_heading_click(5, 5) if not success: self.fail("The command associated to the treeview heading wasn't " "invoked.") success = [] commands = self.tv.master._tclCommands self.tv.heading('#0', command=str(self.tv.heading('#0', command=None))) self.assertEqual(commands, self.tv.master._tclCommands) simulate_heading_click(5, 5) if not success: self.fail("The command associated to the treeview heading wasn't " "invoked.") # XXX The following raises an error in a tcl interpreter, but not in # Python #self.tv.heading('#0', command='I dont exist') #simulate_heading_click(5, 5) def test_index(self): # item 'what' doesn't exist self.assertRaises(tkinter.TclError, self.tv.index, 'what') self.assertEqual(self.tv.index(''), 0) item1 = self.tv.insert('', 'end') item2 = self.tv.insert('', 'end') c1 = self.tv.insert(item1, 'end') c2 = self.tv.insert(item1, 'end') self.assertEqual(self.tv.index(item1), 0) self.assertEqual(self.tv.index(c1), 0) self.assertEqual(self.tv.index(c2), 1) self.assertEqual(self.tv.index(item2), 1) self.tv.move(item2, '', 0) self.assertEqual(self.tv.index(item2), 0) self.assertEqual(self.tv.index(item1), 1) # check that index still works even after its parent and siblings # have been detached self.tv.detach(item1) self.assertEqual(self.tv.index(c2), 1) self.tv.detach(c1) self.assertEqual(self.tv.index(c2), 0) # but it fails after item has been deleted self.tv.delete(item1) self.assertRaises(tkinter.TclError, self.tv.index, c2) def test_insert_item(self): # parent 'none' doesn't exist self.assertRaises(tkinter.TclError, self.tv.insert, 'none', 'end') # open values self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', open='') self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', open='please') self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=True))) self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=False))) # invalid index self.assertRaises(tkinter.TclError, self.tv.insert, '', 'middle') # trying to duplicate item id is invalid itemid = self.tv.insert('', 'end', 'first-item') self.assertEqual(itemid, 'first-item') self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', 'first-item') self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', MockTclObj('first-item')) # unicode values value = '\xe1ba' item = self.tv.insert('', 'end', values=(value, )) self.assertEqual(self.tv.item(item, 'values'), (value,) if self.wantobjects else value) self.assertEqual(self.tv.item(item, values=None), (value,) if self.wantobjects else value) self.tv.item(item, values=self.root.splitlist(self.tv.item(item, values=None))) self.assertEqual(self.tv.item(item, values=None), (value,) if self.wantobjects else value) self.assertIsInstance(self.tv.item(item), dict) # erase item values self.tv.item(item, values='') self.assertFalse(self.tv.item(item, values=None)) # item tags item = self.tv.insert('', 'end', tags=[1, 2, value]) self.assertEqual(self.tv.item(item, tags=None), ('1', '2', value) if self.wantobjects else '1 2 %s' % value) self.tv.item(item, tags=[]) self.assertFalse(self.tv.item(item, tags=None)) self.tv.item(item, tags=(1, 2)) self.assertEqual(self.tv.item(item, tags=None), ('1', '2') if self.wantobjects else '1 2') # values with spaces item = self.tv.insert('', 'end', values=('a b c', '%s %s' % (value, value))) self.assertEqual(self.tv.item(item, values=None), ('a b c', '%s %s' % (value, value)) if self.wantobjects else '{a b c} {%s %s}' % (value, value)) # text self.assertEqual(self.tv.item( self.tv.insert('', 'end', text="Label here"), text=None), "Label here") self.assertEqual(self.tv.item( self.tv.insert('', 'end', text=value), text=None), value) # test for values which are not None itemid = self.tv.insert('', 'end', 0) self.assertEqual(itemid, '0') itemid = self.tv.insert('', 'end', 0.0) self.assertEqual(itemid, '0.0') # this is because False resolves to 0 and element with 0 iid is already present self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', False) self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', '') def test_selection(self): self.assertRaises(TypeError, self.tv.selection, 'spam') # item 'none' doesn't exist self.assertRaises(tkinter.TclError, self.tv.selection_set, 'none') self.assertRaises(tkinter.TclError, self.tv.selection_add, 'none') self.assertRaises(tkinter.TclError, self.tv.selection_remove, 'none') self.assertRaises(tkinter.TclError, self.tv.selection_toggle, 'none') item1 = self.tv.insert('', 'end') item2 = self.tv.insert('', 'end') c1 = self.tv.insert(item1, 'end') c2 = self.tv.insert(item1, 'end') c3 = self.tv.insert(item1, 'end') self.assertEqual(self.tv.selection(), ()) self.tv.selection_set(c1, item2) self.assertEqual(self.tv.selection(), (c1, item2)) self.tv.selection_set(c2) self.assertEqual(self.tv.selection(), (c2,)) self.tv.selection_add(c1, item2) self.assertEqual(self.tv.selection(), (c1, c2, item2)) self.tv.selection_add(item1) self.assertEqual(self.tv.selection(), (item1, c1, c2, item2)) self.tv.selection_add() self.assertEqual(self.tv.selection(), (item1, c1, c2, item2)) self.tv.selection_remove(item1, c3) self.assertEqual(self.tv.selection(), (c1, c2, item2)) self.tv.selection_remove(c2) self.assertEqual(self.tv.selection(), (c1, item2)) self.tv.selection_remove() self.assertEqual(self.tv.selection(), (c1, item2)) self.tv.selection_toggle(c1, c3) self.assertEqual(self.tv.selection(), (c3, item2)) self.tv.selection_toggle(item2) self.assertEqual(self.tv.selection(), (c3,)) self.tv.selection_toggle() self.assertEqual(self.tv.selection(), (c3,)) self.tv.insert('', 'end', id='with spaces') self.tv.selection_set('with spaces') self.assertEqual(self.tv.selection(), ('with spaces',)) self.tv.insert('', 'end', id='{brace') self.tv.selection_set('{brace') self.assertEqual(self.tv.selection(), ('{brace',)) self.tv.insert('', 'end', id='unicode\u20ac') self.tv.selection_set('unicode\u20ac') self.assertEqual(self.tv.selection(), ('unicode\u20ac',)) self.tv.insert('', 'end', id=b'bytes\xe2\x82\xac') self.tv.selection_set(b'bytes\xe2\x82\xac') self.assertEqual(self.tv.selection(), ('bytes\xe2\x82\xac',)) self.tv.selection_set() self.assertEqual(self.tv.selection(), ()) # Old interface self.tv.selection_set((c1, item2)) self.assertEqual(self.tv.selection(), (c1, item2)) self.tv.selection_add((c1, item1)) self.assertEqual(self.tv.selection(), (item1, c1, item2)) self.tv.selection_remove((item1, c3)) self.assertEqual(self.tv.selection(), (c1, item2)) self.tv.selection_toggle((c1, c3)) self.assertEqual(self.tv.selection(), (c3, item2)) if sys.version_info >= (3, 8): import warnings warnings.warn( 'Deprecated API of Treeview.selection() should be removed') self.tv.selection_set() self.assertEqual(self.tv.selection(), ()) with self.assertWarns(DeprecationWarning): self.tv.selection('set', (c1, item2)) self.assertEqual(self.tv.selection(), (c1, item2)) with self.assertWarns(DeprecationWarning): self.tv.selection('add', (c1, item1)) self.assertEqual(self.tv.selection(), (item1, c1, item2)) with self.assertWarns(DeprecationWarning): self.tv.selection('remove', (item1, c3)) self.assertEqual(self.tv.selection(), (c1, item2)) with self.assertWarns(DeprecationWarning): self.tv.selection('toggle', (c1, c3)) self.assertEqual(self.tv.selection(), (c3, item2)) with self.assertWarns(DeprecationWarning): selection = self.tv.selection(None) self.assertEqual(selection, (c3, item2)) def test_set(self): self.tv['columns'] = ['A', 'B'] item = self.tv.insert('', 'end', values=['a', 'b']) self.assertEqual(self.tv.set(item), {'A': 'a', 'B': 'b'}) self.tv.set(item, 'B', 'a') self.assertEqual(self.tv.item(item, values=None), ('a', 'a') if self.wantobjects else 'a a') self.tv['columns'] = ['B'] self.assertEqual(self.tv.set(item), {'B': 'a'}) self.tv.set(item, 'B', 'b') self.assertEqual(self.tv.set(item, column='B'), 'b') self.assertEqual(self.tv.item(item, values=None), ('b', 'a') if self.wantobjects else 'b a') self.tv.set(item, 'B', 123) self.assertEqual(self.tv.set(item, 'B'), 123 if self.wantobjects else '123') self.assertEqual(self.tv.item(item, values=None), (123, 'a') if self.wantobjects else '123 a') self.assertEqual(self.tv.set(item), {'B': 123} if self.wantobjects else {'B': '123'}) # inexistent column self.assertRaises(tkinter.TclError, self.tv.set, item, 'A') self.assertRaises(tkinter.TclError, self.tv.set, item, 'A', 'b') # inexistent item self.assertRaises(tkinter.TclError, self.tv.set, 'notme') def test_tag_bind(self): events = [] item1 = self.tv.insert('', 'end', tags=['call']) item2 = self.tv.insert('', 'end', tags=['call']) self.tv.tag_bind('call', '<ButtonPress-1>', lambda evt: events.append(1)) self.tv.tag_bind('call', '<ButtonRelease-1>', lambda evt: events.append(2)) self.tv.pack() self.tv.wait_visibility() self.tv.update() pos_y = set() found = set() for i in range(0, 100, 10): if len(found) == 2: # item1 and item2 already found break item_id = self.tv.identify_row(i) if item_id and item_id not in found: pos_y.add(i) found.add(item_id) self.assertEqual(len(pos_y), 2) # item1 and item2 y pos for y in pos_y: simulate_mouse_click(self.tv, 0, y) # by now there should be 4 things in the events list, since each # item had a bind for two events that were simulated above self.assertEqual(len(events), 4) for evt in zip(events[::2], events[1::2]): self.assertEqual(evt, (1, 2)) def test_tag_configure(self): # Just testing parameter passing for now self.assertRaises(TypeError, self.tv.tag_configure) self.assertRaises(tkinter.TclError, self.tv.tag_configure, 'test', sky='blue') self.tv.tag_configure('test', foreground='blue') self.assertEqual(str(self.tv.tag_configure('test', 'foreground')), 'blue') self.assertEqual(str(self.tv.tag_configure('test', foreground=None)), 'blue') self.assertIsInstance(self.tv.tag_configure('test'), dict) def test_tag_has(self): item1 = self.tv.insert('', 'end', text='Item 1', tags=['tag1']) item2 = self.tv.insert('', 'end', text='Item 2', tags=['tag2']) self.assertRaises(TypeError, self.tv.tag_has) self.assertRaises(TclError, self.tv.tag_has, 'tag1', 'non-existing') self.assertTrue(self.tv.tag_has('tag1', item1)) self.assertFalse(self.tv.tag_has('tag1', item2)) self.assertFalse(self.tv.tag_has('tag2', item1)) self.assertTrue(self.tv.tag_has('tag2', item2)) self.assertFalse(self.tv.tag_has('tag3', item1)) self.assertFalse(self.tv.tag_has('tag3', item2)) self.assertEqual(self.tv.tag_has('tag1'), (item1,)) self.assertEqual(self.tv.tag_has('tag2'), (item2,)) self.assertEqual(self.tv.tag_has('tag3'), ()) @add_standard_options(StandardTtkOptionsTests) class SeparatorTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'class', 'cursor', 'orient', 'style', 'takefocus', # 'state'? ) default_orient = 'horizontal' def create(self, **kwargs): return ttk.Separator(self.root, **kwargs) @add_standard_options(StandardTtkOptionsTests) class SizegripTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'class', 'cursor', 'style', 'takefocus', # 'state'? ) def create(self, **kwargs): return ttk.Sizegrip(self.root, **kwargs) tests_gui = ( ButtonTest, CheckbuttonTest, ComboboxTest, EntryTest, FrameTest, LabelFrameTest, LabelTest, MenubuttonTest, NotebookTest, PanedWindowTest, ProgressbarTest, RadiobuttonTest, ScaleTest, ScrollbarTest, SeparatorTest, SizegripTest, TreeviewTest, WidgetTest, ) if __name__ == "__main__": unittest.main()
62,539
1,722
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_ttk/test_extensions.py
import sys import unittest import tkinter from tkinter import ttk from test.support import requires, run_unittest, swap_attr from tkinter.test.support import AbstractTkTest, destroy_default_root requires('gui') class LabeledScaleTest(AbstractTkTest, unittest.TestCase): def tearDown(self): self.root.update_idletasks() super().tearDown() def test_widget_destroy(self): # automatically created variable x = ttk.LabeledScale(self.root) var = x._variable._name x.destroy() self.assertRaises(tkinter.TclError, x.tk.globalgetvar, var) # manually created variable myvar = tkinter.DoubleVar(self.root) name = myvar._name x = ttk.LabeledScale(self.root, variable=myvar) x.destroy() if self.wantobjects: self.assertEqual(x.tk.globalgetvar(name), myvar.get()) else: self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get()) del myvar self.assertRaises(tkinter.TclError, x.tk.globalgetvar, name) # checking that the tracing callback is properly removed myvar = tkinter.IntVar(self.root) # LabeledScale will start tracing myvar x = ttk.LabeledScale(self.root, variable=myvar) x.destroy() # Unless the tracing callback was removed, creating a new # LabeledScale with the same var will cause an error now. This # happens because the variable will be set to (possibly) a new # value which causes the tracing callback to be called and then # it tries calling instance attributes not yet defined. ttk.LabeledScale(self.root, variable=myvar) if hasattr(sys, 'last_type'): self.assertNotEqual(sys.last_type, tkinter.TclError) def test_initialization_no_master(self): # no master passing with swap_attr(tkinter, '_default_root', None), \ swap_attr(tkinter, '_support_default_root', True): try: x = ttk.LabeledScale() self.assertIsNotNone(tkinter._default_root) self.assertEqual(x.master, tkinter._default_root) self.assertEqual(x.tk, tkinter._default_root.tk) x.destroy() finally: destroy_default_root() def test_initialization(self): # master passing master = tkinter.Frame(self.root) x = ttk.LabeledScale(master) self.assertEqual(x.master, master) x.destroy() # variable initialization/passing passed_expected = (('0', 0), (0, 0), (10, 10), (-1, -1), (sys.maxsize + 1, sys.maxsize + 1), (2.5, 2), ('2.5', 2)) for pair in passed_expected: x = ttk.LabeledScale(self.root, from_=pair[0]) self.assertEqual(x.value, pair[1]) x.destroy() x = ttk.LabeledScale(self.root, from_=None) self.assertRaises((ValueError, tkinter.TclError), x._variable.get) x.destroy() # variable should have its default value set to the from_ value myvar = tkinter.DoubleVar(self.root, value=20) x = ttk.LabeledScale(self.root, variable=myvar) self.assertEqual(x.value, 0) x.destroy() # check that it is really using a DoubleVar x = ttk.LabeledScale(self.root, variable=myvar, from_=0.5) self.assertEqual(x.value, 0.5) self.assertEqual(x._variable._name, myvar._name) x.destroy() # widget positionment def check_positions(scale, scale_pos, label, label_pos): self.assertEqual(scale.pack_info()['side'], scale_pos) self.assertEqual(label.place_info()['anchor'], label_pos) x = ttk.LabeledScale(self.root, compound='top') check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() x = ttk.LabeledScale(self.root, compound='bottom') check_positions(x.scale, 'top', x.label, 's') x.destroy() # invert default positions x = ttk.LabeledScale(self.root, compound='unknown') check_positions(x.scale, 'top', x.label, 's') x.destroy() x = ttk.LabeledScale(self.root) # take default positions check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() # extra, and invalid, kwargs self.assertRaises(tkinter.TclError, ttk.LabeledScale, master, a='b') def test_horizontal_range(self): lscale = ttk.LabeledScale(self.root, from_=0, to=10) lscale.pack() lscale.wait_visibility() lscale.update() linfo_1 = lscale.label.place_info() prev_xcoord = lscale.scale.coords()[0] self.assertEqual(prev_xcoord, int(linfo_1['x'])) # change range to: from -5 to 5. This should change the x coord of # the scale widget, since 0 is at the middle of the new # range. lscale.scale.configure(from_=-5, to=5) # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome lscale.update() curr_xcoord = lscale.scale.coords()[0] self.assertNotEqual(prev_xcoord, curr_xcoord) # the label widget should have been repositioned too linfo_2 = lscale.label.place_info() self.assertEqual(lscale.label['text'], 0 if self.wantobjects else '0') self.assertEqual(curr_xcoord, int(linfo_2['x'])) # change the range back lscale.scale.configure(from_=0, to=10) self.assertNotEqual(prev_xcoord, curr_xcoord) self.assertEqual(prev_xcoord, int(linfo_1['x'])) lscale.destroy() def test_variable_change(self): x = ttk.LabeledScale(self.root) x.pack() x.wait_visibility() x.update() curr_xcoord = x.scale.coords()[0] newval = x.value + 1 x.value = newval # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome x.update() self.assertEqual(x.value, newval) self.assertEqual(x.label['text'], newval if self.wantobjects else str(newval)) self.assertEqual(float(x.scale.get()), newval) self.assertGreater(x.scale.coords()[0], curr_xcoord) self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) # value outside range if self.wantobjects: conv = lambda x: x else: conv = int x.value = conv(x.scale['to']) + 1 # no changes shouldn't happen x.update() self.assertEqual(x.value, newval) self.assertEqual(conv(x.label['text']), newval) self.assertEqual(float(x.scale.get()), newval) self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) # non-integer value x.value = newval = newval + 1.5 x.update() self.assertEqual(x.value, int(newval)) self.assertEqual(conv(x.label['text']), int(newval)) self.assertEqual(float(x.scale.get()), newval) x.destroy() def test_resize(self): x = ttk.LabeledScale(self.root) x.pack(expand=True, fill='both') x.wait_visibility() x.update() width, height = x.master.winfo_width(), x.master.winfo_height() width_new, height_new = width * 2, height * 2 x.value = 3 x.update() x.master.wm_geometry("%dx%d" % (width_new, height_new)) self.assertEqual(int(x.label.place_info()['x']), x.scale.coords()[0]) # Reset geometry x.master.wm_geometry("%dx%d" % (width, height)) x.destroy() class OptionMenuTest(AbstractTkTest, unittest.TestCase): def setUp(self): super().setUp() self.textvar = tkinter.StringVar(self.root) def tearDown(self): del self.textvar super().tearDown() def test_widget_destroy(self): var = tkinter.StringVar(self.root) optmenu = ttk.OptionMenu(self.root, var) name = var._name optmenu.update_idletasks() optmenu.destroy() self.assertEqual(optmenu.tk.globalgetvar(name), var.get()) del var self.assertRaises(tkinter.TclError, optmenu.tk.globalgetvar, name) def test_initialization(self): self.assertRaises(tkinter.TclError, ttk.OptionMenu, self.root, self.textvar, invalid='thing') optmenu = ttk.OptionMenu(self.root, self.textvar, 'b', 'a', 'b') self.assertEqual(optmenu._variable.get(), 'b') self.assertTrue(optmenu['menu']) self.assertTrue(optmenu['textvariable']) optmenu.destroy() def test_menu(self): items = ('a', 'b', 'c') default = 'a' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) found_default = False for i in range(len(items)): value = optmenu['menu'].entrycget(i, 'value') self.assertEqual(value, items[i]) if value == default: found_default = True self.assertTrue(found_default) optmenu.destroy() # default shouldn't be in menu if it is not part of values default = 'd' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) curr = None i = 0 while True: last, curr = curr, optmenu['menu'].entryconfigure(i, 'value') if last == curr: # no more menu entries break self.assertNotEqual(curr, default) i += 1 self.assertEqual(i, len(items)) # check that variable is updated correctly optmenu.pack() optmenu.wait_visibility() optmenu['menu'].invoke(0) self.assertEqual(optmenu._variable.get(), items[0]) # changing to an invalid index shouldn't change the variable self.assertRaises(tkinter.TclError, optmenu['menu'].invoke, -1) self.assertEqual(optmenu._variable.get(), items[0]) optmenu.destroy() # specifying a callback success = [] def cb_test(item): self.assertEqual(item, items[1]) success.append(True) optmenu = ttk.OptionMenu(self.root, self.textvar, 'a', command=cb_test, *items) optmenu['menu'].invoke(1) if not success: self.fail("Menu callback not invoked") optmenu.destroy() def test_unique_radiobuttons(self): # check that radiobuttons are unique across instances (bpo25684) items = ('a', 'b', 'c') default = 'a' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) textvar2 = tkinter.StringVar(self.root) optmenu2 = ttk.OptionMenu(self.root, textvar2, default, *items) optmenu.pack() optmenu.wait_visibility() optmenu2.pack() optmenu2.wait_visibility() optmenu['menu'].invoke(1) optmenu2['menu'].invoke(2) optmenu_stringvar_name = optmenu['menu'].entrycget(0, 'variable') optmenu2_stringvar_name = optmenu2['menu'].entrycget(0, 'variable') self.assertNotEqual(optmenu_stringvar_name, optmenu2_stringvar_name) self.assertEqual(self.root.tk.globalgetvar(optmenu_stringvar_name), items[1]) self.assertEqual(self.root.tk.globalgetvar(optmenu2_stringvar_name), items[2]) optmenu.destroy() optmenu2.destroy() tests_gui = (LabeledScaleTest, OptionMenuTest) if __name__ == "__main__": run_unittest(*tests_gui)
11,717
324
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_ttk/test_style.py
import unittest import tkinter from tkinter import ttk from test.support import requires, run_unittest from tkinter.test.support import AbstractTkTest requires('gui') class StyleTest(AbstractTkTest, unittest.TestCase): def setUp(self): super().setUp() self.style = ttk.Style(self.root) def test_configure(self): style = self.style style.configure('TButton', background='yellow') self.assertEqual(style.configure('TButton', 'background'), 'yellow') self.assertIsInstance(style.configure('TButton'), dict) def test_map(self): style = self.style style.map('TButton', background=[('active', 'background', 'blue')]) self.assertEqual(style.map('TButton', 'background'), [('active', 'background', 'blue')] if self.wantobjects else [('active background', 'blue')]) self.assertIsInstance(style.map('TButton'), dict) def test_lookup(self): style = self.style style.configure('TButton', background='yellow') style.map('TButton', background=[('active', 'background', 'blue')]) self.assertEqual(style.lookup('TButton', 'background'), 'yellow') self.assertEqual(style.lookup('TButton', 'background', ['active', 'background']), 'blue') self.assertEqual(style.lookup('TButton', 'optionnotdefined', default='iknewit'), 'iknewit') def test_layout(self): style = self.style self.assertRaises(tkinter.TclError, style.layout, 'NotALayout') tv_style = style.layout('Treeview') # "erase" Treeview layout style.layout('Treeview', '') self.assertEqual(style.layout('Treeview'), [('null', {'sticky': 'nswe'})] ) # restore layout style.layout('Treeview', tv_style) self.assertEqual(style.layout('Treeview'), tv_style) # should return a list self.assertIsInstance(style.layout('TButton'), list) # correct layout, but "option" doesn't exist as option self.assertRaises(tkinter.TclError, style.layout, 'Treeview', [('name', {'option': 'inexistent'})]) def test_theme_use(self): self.assertRaises(tkinter.TclError, self.style.theme_use, 'nonexistingname') curr_theme = self.style.theme_use() new_theme = None for theme in self.style.theme_names(): if theme != curr_theme: new_theme = theme self.style.theme_use(theme) break else: # just one theme available, can't go on with tests return self.assertFalse(curr_theme == new_theme) self.assertFalse(new_theme != self.style.theme_use()) self.style.theme_use(curr_theme) tests_gui = (StyleTest, ) if __name__ == "__main__": run_unittest(*tests_gui)
2,900
93
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_ttk/__init__.py
0
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/test_loadtk.py
import os import sys import unittest import test.support as test_support from tkinter import Tcl, TclError test_support.requires('gui') class TkLoadTest(unittest.TestCase): @unittest.skipIf('DISPLAY' not in os.environ, 'No $DISPLAY set.') def testLoadTk(self): tcl = Tcl() self.assertRaises(TclError,tcl.winfo_geometry) tcl.loadtk() self.assertEqual('1x1+0+0', tcl.winfo_geometry()) tcl.destroy() def testLoadTkFailure(self): old_display = None if sys.platform.startswith(('win', 'darwin', 'cygwin')): # no failure possible on windows? # XXX Maybe on tk older than 8.4.13 it would be possible, # see tkinter.h. return with test_support.EnvironmentVarGuard() as env: if 'DISPLAY' in os.environ: del env['DISPLAY'] # on some platforms, deleting environment variables # doesn't actually carry through to the process level # because they don't support unsetenv # If that's the case, abort. with os.popen('echo $DISPLAY') as pipe: display = pipe.read().strip() if display: return tcl = Tcl() self.assertRaises(TclError, tcl.winfo_geometry) self.assertRaises(TclError, tcl.loadtk) tests_gui = (TkLoadTest, ) if __name__ == "__main__": test_support.run_unittest(*tests_gui)
1,503
47
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/test_font.py
import unittest import tkinter from tkinter import font from test.support import requires, run_unittest from tkinter.test.support import AbstractTkTest requires('gui') fontname = "TkDefaultFont" class FontTest(AbstractTkTest, unittest.TestCase): @classmethod def setUpClass(cls): AbstractTkTest.setUpClass.__func__(cls) try: cls.font = font.Font(root=cls.root, name=fontname, exists=True) except tkinter.TclError: cls.font = font.Font(root=cls.root, name=fontname, exists=False) def test_configure(self): options = self.font.configure() self.assertGreaterEqual(set(options), {'family', 'size', 'weight', 'slant', 'underline', 'overstrike'}) for key in options: self.assertEqual(self.font.cget(key), options[key]) self.assertEqual(self.font[key], options[key]) for key in 'family', 'weight', 'slant': self.assertIsInstance(options[key], str) self.assertIsInstance(self.font.cget(key), str) self.assertIsInstance(self.font[key], str) sizetype = int if self.wantobjects else str for key in 'size', 'underline', 'overstrike': self.assertIsInstance(options[key], sizetype) self.assertIsInstance(self.font.cget(key), sizetype) self.assertIsInstance(self.font[key], sizetype) def test_actual(self): options = self.font.actual() self.assertGreaterEqual(set(options), {'family', 'size', 'weight', 'slant', 'underline', 'overstrike'}) for key in options: self.assertEqual(self.font.actual(key), options[key]) for key in 'family', 'weight', 'slant': self.assertIsInstance(options[key], str) self.assertIsInstance(self.font.actual(key), str) sizetype = int if self.wantobjects else str for key in 'size', 'underline', 'overstrike': self.assertIsInstance(options[key], sizetype) self.assertIsInstance(self.font.actual(key), sizetype) def test_name(self): self.assertEqual(self.font.name, fontname) self.assertEqual(str(self.font), fontname) def test_eq(self): font1 = font.Font(root=self.root, name=fontname, exists=True) font2 = font.Font(root=self.root, name=fontname, exists=True) self.assertIsNot(font1, font2) self.assertEqual(font1, font2) self.assertNotEqual(font1, font1.copy()) self.assertNotEqual(font1, 0) def test_measure(self): self.assertIsInstance(self.font.measure('abc'), int) def test_metrics(self): metrics = self.font.metrics() self.assertGreaterEqual(set(metrics), {'ascent', 'descent', 'linespace', 'fixed'}) for key in metrics: self.assertEqual(self.font.metrics(key), metrics[key]) self.assertIsInstance(metrics[key], int) self.assertIsInstance(self.font.metrics(key), int) def test_families(self): families = font.families(self.root) self.assertIsInstance(families, tuple) self.assertTrue(families) for family in families: self.assertIsInstance(family, str) self.assertTrue(family) def test_names(self): names = font.names(self.root) self.assertIsInstance(names, tuple) self.assertTrue(names) for name in names: self.assertIsInstance(name, str) self.assertTrue(name) self.assertIn(fontname, names) tests_gui = (FontTest, ) if __name__ == "__main__": run_unittest(*tests_gui)
3,633
97
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/test_images.py
import unittest import tkinter from test import support from tkinter.test.support import AbstractTkTest, requires_tcl support.requires('gui') class MiscTest(AbstractTkTest, unittest.TestCase): def test_image_types(self): image_types = self.root.image_types() self.assertIsInstance(image_types, tuple) self.assertIn('photo', image_types) self.assertIn('bitmap', image_types) def test_image_names(self): image_names = self.root.image_names() self.assertIsInstance(image_names, tuple) class BitmapImageTest(AbstractTkTest, unittest.TestCase): @classmethod def setUpClass(cls): AbstractTkTest.setUpClass.__func__(cls) cls.testfile = support.findfile('python.xbm', subdir='imghdrdata') def test_create_from_file(self): image = tkinter.BitmapImage('::img::test', master=self.root, foreground='yellow', background='blue', file=self.testfile) self.assertEqual(str(image), '::img::test') self.assertEqual(image.type(), 'bitmap') self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertIn('::img::test', self.root.image_names()) del image self.assertNotIn('::img::test', self.root.image_names()) def test_create_from_data(self): with open(self.testfile, 'rb') as f: data = f.read() image = tkinter.BitmapImage('::img::test', master=self.root, foreground='yellow', background='blue', data=data) self.assertEqual(str(image), '::img::test') self.assertEqual(image.type(), 'bitmap') self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertIn('::img::test', self.root.image_names()) del image self.assertNotIn('::img::test', self.root.image_names()) def assertEqualStrList(self, actual, expected): self.assertIsInstance(actual, str) self.assertEqual(self.root.splitlist(actual), expected) def test_configure_data(self): image = tkinter.BitmapImage('::img::test', master=self.root) self.assertEqual(image['data'], '-data {} {} {} {}') with open(self.testfile, 'rb') as f: data = f.read() image.configure(data=data) self.assertEqualStrList(image['data'], ('-data', '', '', '', data.decode('ascii'))) self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image['maskdata'], '-maskdata {} {} {} {}') image.configure(maskdata=data) self.assertEqualStrList(image['maskdata'], ('-maskdata', '', '', '', data.decode('ascii'))) def test_configure_file(self): image = tkinter.BitmapImage('::img::test', master=self.root) self.assertEqual(image['file'], '-file {} {} {} {}') image.configure(file=self.testfile) self.assertEqualStrList(image['file'], ('-file', '', '', '',self.testfile)) self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image['maskfile'], '-maskfile {} {} {} {}') image.configure(maskfile=self.testfile) self.assertEqualStrList(image['maskfile'], ('-maskfile', '', '', '', self.testfile)) def test_configure_background(self): image = tkinter.BitmapImage('::img::test', master=self.root) self.assertEqual(image['background'], '-background {} {} {} {}') image.configure(background='blue') self.assertEqual(image['background'], '-background {} {} {} blue') def test_configure_foreground(self): image = tkinter.BitmapImage('::img::test', master=self.root) self.assertEqual(image['foreground'], '-foreground {} {} #000000 #000000') image.configure(foreground='yellow') self.assertEqual(image['foreground'], '-foreground {} {} #000000 yellow') class PhotoImageTest(AbstractTkTest, unittest.TestCase): @classmethod def setUpClass(cls): AbstractTkTest.setUpClass.__func__(cls) cls.testfile = support.findfile('python.gif', subdir='imghdrdata') def create(self): return tkinter.PhotoImage('::img::test', master=self.root, file=self.testfile) def colorlist(self, *args): if tkinter.TkVersion >= 8.6 and self.wantobjects: return args else: return tkinter._join(args) def check_create_from_file(self, ext): testfile = support.findfile('python.' + ext, subdir='imghdrdata') image = tkinter.PhotoImage('::img::test', master=self.root, file=testfile) self.assertEqual(str(image), '::img::test') self.assertEqual(image.type(), 'photo') self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image['data'], '') self.assertEqual(image['file'], testfile) self.assertIn('::img::test', self.root.image_names()) del image self.assertNotIn('::img::test', self.root.image_names()) def check_create_from_data(self, ext): testfile = support.findfile('python.' + ext, subdir='imghdrdata') with open(testfile, 'rb') as f: data = f.read() image = tkinter.PhotoImage('::img::test', master=self.root, data=data) self.assertEqual(str(image), '::img::test') self.assertEqual(image.type(), 'photo') self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image['data'], data if self.wantobjects else data.decode('latin1')) self.assertEqual(image['file'], '') self.assertIn('::img::test', self.root.image_names()) del image self.assertNotIn('::img::test', self.root.image_names()) def test_create_from_ppm_file(self): self.check_create_from_file('ppm') def test_create_from_ppm_data(self): self.check_create_from_data('ppm') def test_create_from_pgm_file(self): self.check_create_from_file('pgm') def test_create_from_pgm_data(self): self.check_create_from_data('pgm') def test_create_from_gif_file(self): self.check_create_from_file('gif') def test_create_from_gif_data(self): self.check_create_from_data('gif') @requires_tcl(8, 6) def test_create_from_png_file(self): self.check_create_from_file('png') @requires_tcl(8, 6) def test_create_from_png_data(self): self.check_create_from_data('png') def test_configure_data(self): image = tkinter.PhotoImage('::img::test', master=self.root) self.assertEqual(image['data'], '') with open(self.testfile, 'rb') as f: data = f.read() image.configure(data=data) self.assertEqual(image['data'], data if self.wantobjects else data.decode('latin1')) self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) def test_configure_format(self): image = tkinter.PhotoImage('::img::test', master=self.root) self.assertEqual(image['format'], '') image.configure(file=self.testfile, format='gif') self.assertEqual(image['format'], ('gif',) if self.wantobjects else 'gif') self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) def test_configure_file(self): image = tkinter.PhotoImage('::img::test', master=self.root) self.assertEqual(image['file'], '') image.configure(file=self.testfile) self.assertEqual(image['file'], self.testfile) self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) def test_configure_gamma(self): image = tkinter.PhotoImage('::img::test', master=self.root) self.assertEqual(image['gamma'], '1.0') image.configure(gamma=2.0) self.assertEqual(image['gamma'], '2.0') def test_configure_width_height(self): image = tkinter.PhotoImage('::img::test', master=self.root) self.assertEqual(image['width'], '0') self.assertEqual(image['height'], '0') image.configure(width=20) image.configure(height=10) self.assertEqual(image['width'], '20') self.assertEqual(image['height'], '10') self.assertEqual(image.width(), 20) self.assertEqual(image.height(), 10) def test_configure_palette(self): image = tkinter.PhotoImage('::img::test', master=self.root) self.assertEqual(image['palette'], '') image.configure(palette=256) self.assertEqual(image['palette'], '256') image.configure(palette='3/4/2') self.assertEqual(image['palette'], '3/4/2') def test_blank(self): image = self.create() image.blank() self.assertEqual(image.width(), 16) self.assertEqual(image.height(), 16) self.assertEqual(image.get(4, 6), self.colorlist(0, 0, 0)) def test_copy(self): image = self.create() image2 = image.copy() self.assertEqual(image2.width(), 16) self.assertEqual(image2.height(), 16) self.assertEqual(image.get(4, 6), image.get(4, 6)) def test_subsample(self): image = self.create() image2 = image.subsample(2, 3) self.assertEqual(image2.width(), 8) self.assertEqual(image2.height(), 6) self.assertEqual(image2.get(2, 2), image.get(4, 6)) image2 = image.subsample(2) self.assertEqual(image2.width(), 8) self.assertEqual(image2.height(), 8) self.assertEqual(image2.get(2, 3), image.get(4, 6)) def test_zoom(self): image = self.create() image2 = image.zoom(2, 3) self.assertEqual(image2.width(), 32) self.assertEqual(image2.height(), 48) self.assertEqual(image2.get(8, 18), image.get(4, 6)) self.assertEqual(image2.get(9, 20), image.get(4, 6)) image2 = image.zoom(2) self.assertEqual(image2.width(), 32) self.assertEqual(image2.height(), 32) self.assertEqual(image2.get(8, 12), image.get(4, 6)) self.assertEqual(image2.get(9, 13), image.get(4, 6)) def test_put(self): image = self.create() image.put('{red green} {blue yellow}', to=(4, 6)) self.assertEqual(image.get(4, 6), self.colorlist(255, 0, 0)) self.assertEqual(image.get(5, 6), self.colorlist(0, 128 if tkinter.TkVersion >= 8.6 else 255, 0)) self.assertEqual(image.get(4, 7), self.colorlist(0, 0, 255)) self.assertEqual(image.get(5, 7), self.colorlist(255, 255, 0)) image.put((('#f00', '#00ff00'), ('#000000fff', '#ffffffff0000'))) self.assertEqual(image.get(0, 0), self.colorlist(255, 0, 0)) self.assertEqual(image.get(1, 0), self.colorlist(0, 255, 0)) self.assertEqual(image.get(0, 1), self.colorlist(0, 0, 255)) self.assertEqual(image.get(1, 1), self.colorlist(255, 255, 0)) def test_get(self): image = self.create() self.assertEqual(image.get(4, 6), self.colorlist(62, 116, 162)) self.assertEqual(image.get(0, 0), self.colorlist(0, 0, 0)) self.assertEqual(image.get(15, 15), self.colorlist(0, 0, 0)) self.assertRaises(tkinter.TclError, image.get, -1, 0) self.assertRaises(tkinter.TclError, image.get, 0, -1) self.assertRaises(tkinter.TclError, image.get, 16, 15) self.assertRaises(tkinter.TclError, image.get, 15, 16) def test_write(self): image = self.create() self.addCleanup(support.unlink, support.TESTFN) image.write(support.TESTFN) image2 = tkinter.PhotoImage('::img::test2', master=self.root, format='ppm', file=support.TESTFN) self.assertEqual(str(image2), '::img::test2') self.assertEqual(image2.type(), 'photo') self.assertEqual(image2.width(), 16) self.assertEqual(image2.height(), 16) self.assertEqual(image2.get(0, 0), image.get(0, 0)) self.assertEqual(image2.get(15, 8), image.get(15, 8)) image.write(support.TESTFN, format='gif', from_coords=(4, 6, 6, 9)) image3 = tkinter.PhotoImage('::img::test3', master=self.root, format='gif', file=support.TESTFN) self.assertEqual(str(image3), '::img::test3') self.assertEqual(image3.type(), 'photo') self.assertEqual(image3.width(), 2) self.assertEqual(image3.height(), 3) self.assertEqual(image3.get(0, 0), image.get(4, 6)) self.assertEqual(image3.get(1, 2), image.get(5, 8)) tests_gui = (MiscTest, BitmapImageTest, PhotoImageTest,) if __name__ == "__main__": support.run_unittest(*tests_gui)
13,355
328
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/test_variables.py
import unittest import gc from tkinter import (Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tcl, TclError) class Var(Variable): _default = "default" side_effect = False def set(self, value): self.side_effect = True super().set(value) class TestBase(unittest.TestCase): def setUp(self): self.root = Tcl() def tearDown(self): del self.root class TestVariable(TestBase): def info_exists(self, *args): return self.root.getboolean(self.root.call("info", "exists", *args)) def test_default(self): v = Variable(self.root) self.assertEqual("", v.get()) self.assertRegex(str(v), r"^PY_VAR(\d+)$") def test_name_and_value(self): v = Variable(self.root, "sample string", "varname") self.assertEqual("sample string", v.get()) self.assertEqual("varname", str(v)) def test___del__(self): self.assertFalse(self.info_exists("varname")) v = Variable(self.root, "sample string", "varname") self.assertTrue(self.info_exists("varname")) del v self.assertFalse(self.info_exists("varname")) def test_dont_unset_not_existing(self): self.assertFalse(self.info_exists("varname")) v1 = Variable(self.root, name="name") v2 = Variable(self.root, name="name") del v1 self.assertFalse(self.info_exists("name")) # shouldn't raise exception del v2 self.assertFalse(self.info_exists("name")) def test___eq__(self): # values doesn't matter, only class and name are checked v1 = Variable(self.root, name="abc") v2 = Variable(self.root, name="abc") self.assertEqual(v1, v2) v3 = Variable(self.root, name="abc") v4 = StringVar(self.root, name="abc") self.assertNotEqual(v3, v4) def test_invalid_name(self): with self.assertRaises(TypeError): Variable(self.root, name=123) def test_null_in_name(self): with self.assertRaises(ValueError): Variable(self.root, name='var\x00name') with self.assertRaises(ValueError): self.root.globalsetvar('var\x00name', "value") with self.assertRaises(ValueError): self.root.globalsetvar(b'var\x00name', "value") with self.assertRaises(ValueError): self.root.setvar('var\x00name', "value") with self.assertRaises(ValueError): self.root.setvar(b'var\x00name', "value") def test_initialize(self): v = Var(self.root) self.assertFalse(v.side_effect) v.set("value") self.assertTrue(v.side_effect) def test_trace_old(self): # Old interface v = Variable(self.root) vname = str(v) trace = [] def read_tracer(*args): trace.append(('read',) + args) def write_tracer(*args): trace.append(('write',) + args) cb1 = v.trace_variable('r', read_tracer) cb2 = v.trace_variable('wu', write_tracer) self.assertEqual(sorted(v.trace_vinfo()), [('r', cb1), ('wu', cb2)]) self.assertEqual(trace, []) v.set('spam') self.assertEqual(trace, [('write', vname, '', 'w')]) trace = [] v.get() self.assertEqual(trace, [('read', vname, '', 'r')]) trace = [] info = sorted(v.trace_vinfo()) v.trace_vdelete('w', cb1) # Wrong mode self.assertEqual(sorted(v.trace_vinfo()), info) with self.assertRaises(TclError): v.trace_vdelete('r', 'spam') # Wrong command name self.assertEqual(sorted(v.trace_vinfo()), info) v.trace_vdelete('r', (cb1, 43)) # Wrong arguments self.assertEqual(sorted(v.trace_vinfo()), info) v.get() self.assertEqual(trace, [('read', vname, '', 'r')]) trace = [] v.trace_vdelete('r', cb1) self.assertEqual(v.trace_vinfo(), [('wu', cb2)]) v.get() self.assertEqual(trace, []) trace = [] del write_tracer gc.collect() v.set('eggs') self.assertEqual(trace, [('write', vname, '', 'w')]) trace = [] del v gc.collect() self.assertEqual(trace, [('write', vname, '', 'u')]) def test_trace(self): v = Variable(self.root) vname = str(v) trace = [] def read_tracer(*args): trace.append(('read',) + args) def write_tracer(*args): trace.append(('write',) + args) tr1 = v.trace_add('read', read_tracer) tr2 = v.trace_add(['write', 'unset'], write_tracer) self.assertEqual(sorted(v.trace_info()), [ (('read',), tr1), (('write', 'unset'), tr2)]) self.assertEqual(trace, []) v.set('spam') self.assertEqual(trace, [('write', vname, '', 'write')]) trace = [] v.get() self.assertEqual(trace, [('read', vname, '', 'read')]) trace = [] info = sorted(v.trace_info()) v.trace_remove('write', tr1) # Wrong mode self.assertEqual(sorted(v.trace_info()), info) with self.assertRaises(TclError): v.trace_remove('read', 'spam') # Wrong command name self.assertEqual(sorted(v.trace_info()), info) v.get() self.assertEqual(trace, [('read', vname, '', 'read')]) trace = [] v.trace_remove('read', tr1) self.assertEqual(v.trace_info(), [(('write', 'unset'), tr2)]) v.get() self.assertEqual(trace, []) trace = [] del write_tracer gc.collect() v.set('eggs') self.assertEqual(trace, [('write', vname, '', 'write')]) trace = [] del v gc.collect() self.assertEqual(trace, [('write', vname, '', 'unset')]) class TestStringVar(TestBase): def test_default(self): v = StringVar(self.root) self.assertEqual("", v.get()) def test_get(self): v = StringVar(self.root, "abc", "name") self.assertEqual("abc", v.get()) self.root.globalsetvar("name", "value") self.assertEqual("value", v.get()) def test_get_null(self): v = StringVar(self.root, "abc\x00def", "name") self.assertEqual("abc\x00def", v.get()) self.root.globalsetvar("name", "val\x00ue") self.assertEqual("val\x00ue", v.get()) class TestIntVar(TestBase): def test_default(self): v = IntVar(self.root) self.assertEqual(0, v.get()) def test_get(self): v = IntVar(self.root, 123, "name") self.assertEqual(123, v.get()) self.root.globalsetvar("name", "345") self.assertEqual(345, v.get()) self.root.globalsetvar("name", "876.5") self.assertEqual(876, v.get()) def test_invalid_value(self): v = IntVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises((ValueError, TclError)): v.get() class TestDoubleVar(TestBase): def test_default(self): v = DoubleVar(self.root) self.assertEqual(0.0, v.get()) def test_get(self): v = DoubleVar(self.root, 1.23, "name") self.assertAlmostEqual(1.23, v.get()) self.root.globalsetvar("name", "3.45") self.assertAlmostEqual(3.45, v.get()) def test_get_from_int(self): v = DoubleVar(self.root, 1.23, "name") self.assertAlmostEqual(1.23, v.get()) self.root.globalsetvar("name", "3.45") self.assertAlmostEqual(3.45, v.get()) self.root.globalsetvar("name", "456") self.assertAlmostEqual(456, v.get()) def test_invalid_value(self): v = DoubleVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises((ValueError, TclError)): v.get() class TestBooleanVar(TestBase): def test_default(self): v = BooleanVar(self.root) self.assertIs(v.get(), False) def test_get(self): v = BooleanVar(self.root, True, "name") self.assertIs(v.get(), True) self.root.globalsetvar("name", "0") self.assertIs(v.get(), False) self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1) self.assertIs(v.get(), True) self.root.globalsetvar("name", 0) self.assertIs(v.get(), False) self.root.globalsetvar("name", "on") self.assertIs(v.get(), True) def test_set(self): true = 1 if self.root.wantobjects() else "1" false = 0 if self.root.wantobjects() else "0" v = BooleanVar(self.root, name="name") v.set(True) self.assertEqual(self.root.globalgetvar("name"), true) v.set("0") self.assertEqual(self.root.globalgetvar("name"), false) v.set(42) self.assertEqual(self.root.globalgetvar("name"), true) v.set(0) self.assertEqual(self.root.globalgetvar("name"), false) v.set("on") self.assertEqual(self.root.globalgetvar("name"), true) def test_invalid_value_domain(self): false = 0 if self.root.wantobjects() else "0" v = BooleanVar(self.root, name="name") with self.assertRaises(TclError): v.set("value") self.assertEqual(self.root.globalgetvar("name"), false) self.root.globalsetvar("name", "value") with self.assertRaises(ValueError): v.get() self.root.globalsetvar("name", "1.0") with self.assertRaises(ValueError): v.get() tests_gui = (TestVariable, TestStringVar, TestIntVar, TestDoubleVar, TestBooleanVar) if __name__ == "__main__": from test.support import run_unittest run_unittest(*tests_gui)
9,821
311
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/test_text.py
import unittest import tkinter from test.support import requires, run_unittest from tkinter.test.support import AbstractTkTest requires('gui') class TextTest(AbstractTkTest, unittest.TestCase): def setUp(self): super().setUp() self.text = tkinter.Text(self.root) def test_debug(self): text = self.text olddebug = text.debug() try: text.debug(0) self.assertEqual(text.debug(), 0) text.debug(1) self.assertEqual(text.debug(), 1) finally: text.debug(olddebug) self.assertEqual(text.debug(), olddebug) def test_search(self): text = self.text # pattern and index are obligatory arguments. self.assertRaises(tkinter.TclError, text.search, None, '1.0') self.assertRaises(tkinter.TclError, text.search, 'a', None) self.assertRaises(tkinter.TclError, text.search, None, None) # Invalid text index. self.assertRaises(tkinter.TclError, text.search, '', 0) # Check if we are getting the indices as strings -- you are likely # to get Tcl_Obj under Tk 8.5 if Tkinter doesn't convert it. text.insert('1.0', 'hi-test') self.assertEqual(text.search('-test', '1.0', 'end'), '1.2') self.assertEqual(text.search('test', '1.0', 'end'), '1.3') tests_gui = (TextTest, ) if __name__ == "__main__": run_unittest(*tests_gui)
1,442
48
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/test_widgets.py
import unittest import tkinter from tkinter import TclError import os import sys from test.support import requires from tkinter.test.support import (tcl_version, requires_tcl, get_tk_patchlevel, widget_eq) from tkinter.test.widget_tests import ( add_standard_options, noconv, pixels_round, AbstractWidgetTest, StandardOptionsTests, IntegerSizeTests, PixelSizeTests, setUpModule) requires('gui') def float_round(x): return float(round(x)) class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests): _conv_pad_pixels = noconv def test_class(self): widget = self.create() self.assertEqual(widget['class'], widget.__class__.__name__.title()) self.checkInvalidParam(widget, 'class', 'Foo', errmsg="can't modify -class option after widget is created") widget2 = self.create(class_='Foo') self.assertEqual(widget2['class'], 'Foo') def test_colormap(self): widget = self.create() self.assertEqual(widget['colormap'], '') self.checkInvalidParam(widget, 'colormap', 'new', errmsg="can't modify -colormap option after widget is created") widget2 = self.create(colormap='new') self.assertEqual(widget2['colormap'], 'new') def test_container(self): widget = self.create() self.assertEqual(widget['container'], 0 if self.wantobjects else '0') self.checkInvalidParam(widget, 'container', 1, errmsg="can't modify -container option after widget is created") widget2 = self.create(container=True) self.assertEqual(widget2['container'], 1 if self.wantobjects else '1') def test_visual(self): widget = self.create() self.assertEqual(widget['visual'], '') self.checkInvalidParam(widget, 'visual', 'default', errmsg="can't modify -visual option after widget is created") widget2 = self.create(visual='default') self.assertEqual(widget2['visual'], 'default') @add_standard_options(StandardOptionsTests) class ToplevelTest(AbstractToplevelTest, unittest.TestCase): OPTIONS = ( 'background', 'borderwidth', 'class', 'colormap', 'container', 'cursor', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'menu', 'padx', 'pady', 'relief', 'screen', 'takefocus', 'use', 'visual', 'width', ) def create(self, **kwargs): return tkinter.Toplevel(self.root, **kwargs) def test_menu(self): widget = self.create() menu = tkinter.Menu(self.root) self.checkParam(widget, 'menu', menu, eq=widget_eq) self.checkParam(widget, 'menu', '') def test_screen(self): widget = self.create() self.assertEqual(widget['screen'], '') try: display = os.environ['DISPLAY'] except KeyError: self.skipTest('No $DISPLAY set.') self.checkInvalidParam(widget, 'screen', display, errmsg="can't modify -screen option after widget is created") widget2 = self.create(screen=display) self.assertEqual(widget2['screen'], display) def test_use(self): widget = self.create() self.assertEqual(widget['use'], '') parent = self.create(container=True) wid = hex(parent.winfo_id()) with self.subTest(wid=wid): widget2 = self.create(use=wid) self.assertEqual(widget2['use'], wid) @add_standard_options(StandardOptionsTests) class FrameTest(AbstractToplevelTest, unittest.TestCase): OPTIONS = ( 'background', 'borderwidth', 'class', 'colormap', 'container', 'cursor', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'padx', 'pady', 'relief', 'takefocus', 'visual', 'width', ) def create(self, **kwargs): return tkinter.Frame(self.root, **kwargs) @add_standard_options(StandardOptionsTests) class LabelFrameTest(AbstractToplevelTest, unittest.TestCase): OPTIONS = ( 'background', 'borderwidth', 'class', 'colormap', 'container', 'cursor', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'labelanchor', 'labelwidget', 'padx', 'pady', 'relief', 'takefocus', 'text', 'visual', 'width', ) def create(self, **kwargs): return tkinter.LabelFrame(self.root, **kwargs) def test_labelanchor(self): widget = self.create() self.checkEnumParam(widget, 'labelanchor', 'e', 'en', 'es', 'n', 'ne', 'nw', 's', 'se', 'sw', 'w', 'wn', 'ws') self.checkInvalidParam(widget, 'labelanchor', 'center') def test_labelwidget(self): widget = self.create() label = tkinter.Label(self.root, text='Mupp', name='foo') self.checkParam(widget, 'labelwidget', label, expected='.foo') label.destroy() class AbstractLabelTest(AbstractWidgetTest, IntegerSizeTests): _conv_pixels = noconv def test_highlightthickness(self): widget = self.create() self.checkPixelsParam(widget, 'highlightthickness', 0, 1.3, 2.6, 6, -2, '10p') @add_standard_options(StandardOptionsTests) class LabelTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'compound', 'cursor', 'disabledforeground', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'padx', 'pady', 'relief', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength', ) def create(self, **kwargs): return tkinter.Label(self.root, **kwargs) @add_standard_options(StandardOptionsTests) class ButtonTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'command', 'compound', 'cursor', 'default', 'disabledforeground', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'overrelief', 'padx', 'pady', 'relief', 'repeatdelay', 'repeatinterval', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength') def create(self, **kwargs): return tkinter.Button(self.root, **kwargs) def test_default(self): widget = self.create() self.checkEnumParam(widget, 'default', 'active', 'disabled', 'normal') @add_standard_options(StandardOptionsTests) class CheckbuttonTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'command', 'compound', 'cursor', 'disabledforeground', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'indicatoron', 'justify', 'offrelief', 'offvalue', 'onvalue', 'overrelief', 'padx', 'pady', 'relief', 'selectcolor', 'selectimage', 'state', 'takefocus', 'text', 'textvariable', 'tristateimage', 'tristatevalue', 'underline', 'variable', 'width', 'wraplength', ) def create(self, **kwargs): return tkinter.Checkbutton(self.root, **kwargs) def test_offvalue(self): widget = self.create() self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string') def test_onvalue(self): widget = self.create() self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string') @add_standard_options(StandardOptionsTests) class RadiobuttonTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'command', 'compound', 'cursor', 'disabledforeground', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'indicatoron', 'justify', 'offrelief', 'overrelief', 'padx', 'pady', 'relief', 'selectcolor', 'selectimage', 'state', 'takefocus', 'text', 'textvariable', 'tristateimage', 'tristatevalue', 'underline', 'value', 'variable', 'width', 'wraplength', ) def create(self, **kwargs): return tkinter.Radiobutton(self.root, **kwargs) def test_value(self): widget = self.create() self.checkParams(widget, 'value', 1, 2.3, '', 'any string') @add_standard_options(StandardOptionsTests) class MenubuttonTest(AbstractLabelTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'compound', 'cursor', 'direction', 'disabledforeground', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'indicatoron', 'justify', 'menu', 'padx', 'pady', 'relief', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength', ) _conv_pixels = staticmethod(pixels_round) def create(self, **kwargs): return tkinter.Menubutton(self.root, **kwargs) def test_direction(self): widget = self.create() self.checkEnumParam(widget, 'direction', 'above', 'below', 'flush', 'left', 'right') def test_height(self): widget = self.create() self.checkIntegerParam(widget, 'height', 100, -100, 0, conv=str) test_highlightthickness = StandardOptionsTests.test_highlightthickness @unittest.skipIf(sys.platform == 'darwin', 'crashes with Cocoa Tk (issue19733)') def test_image(self): widget = self.create() image = tkinter.PhotoImage(master=self.root, name='image1') self.checkParam(widget, 'image', image, conv=str) errmsg = 'image "spam" doesn\'t exist' with self.assertRaises(tkinter.TclError) as cm: widget['image'] = 'spam' if errmsg is not None: self.assertEqual(str(cm.exception), errmsg) with self.assertRaises(tkinter.TclError) as cm: widget.configure({'image': 'spam'}) if errmsg is not None: self.assertEqual(str(cm.exception), errmsg) def test_menu(self): widget = self.create() menu = tkinter.Menu(widget, name='menu') self.checkParam(widget, 'menu', menu, eq=widget_eq) menu.destroy() def test_padx(self): widget = self.create() self.checkPixelsParam(widget, 'padx', 3, 4.4, 5.6, '12m') self.checkParam(widget, 'padx', -2, expected=0) def test_pady(self): widget = self.create() self.checkPixelsParam(widget, 'pady', 3, 4.4, 5.6, '12m') self.checkParam(widget, 'pady', -2, expected=0) def test_width(self): widget = self.create() self.checkIntegerParam(widget, 'width', 402, -402, 0, conv=str) class OptionMenuTest(MenubuttonTest, unittest.TestCase): def create(self, default='b', values=('a', 'b', 'c'), **kwargs): return tkinter.OptionMenu(self.root, None, default, *values, **kwargs) @add_standard_options(IntegerSizeTests, StandardOptionsTests) class EntryTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'background', 'borderwidth', 'cursor', 'disabledbackground', 'disabledforeground', 'exportselection', 'font', 'foreground', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'insertbackground', 'insertborderwidth', 'insertofftime', 'insertontime', 'insertwidth', 'invalidcommand', 'justify', 'readonlybackground', 'relief', 'selectbackground', 'selectborderwidth', 'selectforeground', 'show', 'state', 'takefocus', 'textvariable', 'validate', 'validatecommand', 'width', 'xscrollcommand', ) def create(self, **kwargs): return tkinter.Entry(self.root, **kwargs) def test_disabledbackground(self): widget = self.create() self.checkColorParam(widget, 'disabledbackground') def test_insertborderwidth(self): widget = self.create(insertwidth=100) self.checkPixelsParam(widget, 'insertborderwidth', 0, 1.3, 2.6, 6, -2, '10p') # insertborderwidth is bounded above by a half of insertwidth. self.checkParam(widget, 'insertborderwidth', 60, expected=100//2) def test_insertwidth(self): widget = self.create() self.checkPixelsParam(widget, 'insertwidth', 1.3, 3.6, '10p') self.checkParam(widget, 'insertwidth', 0.1, expected=2) self.checkParam(widget, 'insertwidth', -2, expected=2) if pixels_round(0.9) <= 0: self.checkParam(widget, 'insertwidth', 0.9, expected=2) else: self.checkParam(widget, 'insertwidth', 0.9, expected=1) def test_invalidcommand(self): widget = self.create() self.checkCommandParam(widget, 'invalidcommand') self.checkCommandParam(widget, 'invcmd') def test_readonlybackground(self): widget = self.create() self.checkColorParam(widget, 'readonlybackground') def test_show(self): widget = self.create() self.checkParam(widget, 'show', '*') self.checkParam(widget, 'show', '') self.checkParam(widget, 'show', ' ') def test_state(self): widget = self.create() self.checkEnumParam(widget, 'state', 'disabled', 'normal', 'readonly') def test_validate(self): widget = self.create() self.checkEnumParam(widget, 'validate', 'all', 'key', 'focus', 'focusin', 'focusout', 'none') def test_validatecommand(self): widget = self.create() self.checkCommandParam(widget, 'validatecommand') self.checkCommandParam(widget, 'vcmd') @add_standard_options(StandardOptionsTests) class SpinboxTest(EntryTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'background', 'borderwidth', 'buttonbackground', 'buttoncursor', 'buttondownrelief', 'buttonuprelief', 'command', 'cursor', 'disabledbackground', 'disabledforeground', 'exportselection', 'font', 'foreground', 'format', 'from', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'increment', 'insertbackground', 'insertborderwidth', 'insertofftime', 'insertontime', 'insertwidth', 'invalidcommand', 'justify', 'relief', 'readonlybackground', 'repeatdelay', 'repeatinterval', 'selectbackground', 'selectborderwidth', 'selectforeground', 'state', 'takefocus', 'textvariable', 'to', 'validate', 'validatecommand', 'values', 'width', 'wrap', 'xscrollcommand', ) def create(self, **kwargs): return tkinter.Spinbox(self.root, **kwargs) test_show = None def test_buttonbackground(self): widget = self.create() self.checkColorParam(widget, 'buttonbackground') def test_buttoncursor(self): widget = self.create() self.checkCursorParam(widget, 'buttoncursor') def test_buttondownrelief(self): widget = self.create() self.checkReliefParam(widget, 'buttondownrelief') def test_buttonuprelief(self): widget = self.create() self.checkReliefParam(widget, 'buttonuprelief') def test_format(self): widget = self.create() self.checkParam(widget, 'format', '%2f') self.checkParam(widget, 'format', '%2.2f') self.checkParam(widget, 'format', '%.2f') self.checkParam(widget, 'format', '%2.f') self.checkInvalidParam(widget, 'format', '%2e-1f') self.checkInvalidParam(widget, 'format', '2.2') self.checkInvalidParam(widget, 'format', '%2.-2f') self.checkParam(widget, 'format', '%-2.02f') self.checkParam(widget, 'format', '% 2.02f') self.checkParam(widget, 'format', '% -2.200f') self.checkParam(widget, 'format', '%09.200f') self.checkInvalidParam(widget, 'format', '%d') def test_from(self): widget = self.create() self.checkParam(widget, 'to', 100.0) self.checkFloatParam(widget, 'from', -10, 10.2, 11.7) self.checkInvalidParam(widget, 'from', 200, errmsg='-to value must be greater than -from value') def test_increment(self): widget = self.create() self.checkFloatParam(widget, 'increment', -1, 1, 10.2, 12.8, 0) def test_to(self): widget = self.create() self.checkParam(widget, 'from', -100.0) self.checkFloatParam(widget, 'to', -10, 10.2, 11.7) self.checkInvalidParam(widget, 'to', -200, errmsg='-to value must be greater than -from value') def test_values(self): # XXX widget = self.create() self.assertEqual(widget['values'], '') self.checkParam(widget, 'values', 'mon tue wed thur') self.checkParam(widget, 'values', ('mon', 'tue', 'wed', 'thur'), expected='mon tue wed thur') self.checkParam(widget, 'values', (42, 3.14, '', 'any string'), expected='42 3.14 {} {any string}') self.checkParam(widget, 'values', '') def test_wrap(self): widget = self.create() self.checkBooleanParam(widget, 'wrap') def test_bbox(self): widget = self.create() self.assertIsBoundingBox(widget.bbox(0)) self.assertRaises(tkinter.TclError, widget.bbox, 'noindex') self.assertRaises(tkinter.TclError, widget.bbox, None) self.assertRaises(TypeError, widget.bbox) self.assertRaises(TypeError, widget.bbox, 0, 1) def test_selection_element(self): widget = self.create() self.assertEqual(widget.selection_element(), "none") widget.selection_element("buttonup") self.assertEqual(widget.selection_element(), "buttonup") widget.selection_element("buttondown") self.assertEqual(widget.selection_element(), "buttondown") @add_standard_options(StandardOptionsTests) class TextTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'autoseparators', 'background', 'blockcursor', 'borderwidth', 'cursor', 'endline', 'exportselection', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'inactiveselectbackground', 'insertbackground', 'insertborderwidth', 'insertofftime', 'insertontime', 'insertunfocussed', 'insertwidth', 'maxundo', 'padx', 'pady', 'relief', 'selectbackground', 'selectborderwidth', 'selectforeground', 'setgrid', 'spacing1', 'spacing2', 'spacing3', 'startline', 'state', 'tabs', 'tabstyle', 'takefocus', 'undo', 'width', 'wrap', 'xscrollcommand', 'yscrollcommand', ) if tcl_version < (8, 5): _stringify = True def create(self, **kwargs): return tkinter.Text(self.root, **kwargs) def test_autoseparators(self): widget = self.create() self.checkBooleanParam(widget, 'autoseparators') @requires_tcl(8, 5) def test_blockcursor(self): widget = self.create() self.checkBooleanParam(widget, 'blockcursor') @requires_tcl(8, 5) def test_endline(self): widget = self.create() text = '\n'.join('Line %d' for i in range(100)) widget.insert('end', text) self.checkParam(widget, 'endline', 200, expected='') self.checkParam(widget, 'endline', -10, expected='') self.checkInvalidParam(widget, 'endline', 'spam', errmsg='expected integer but got "spam"') self.checkParam(widget, 'endline', 50) self.checkParam(widget, 'startline', 15) self.checkInvalidParam(widget, 'endline', 10, errmsg='-startline must be less than or equal to -endline') def test_height(self): widget = self.create() self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, '3c') self.checkParam(widget, 'height', -100, expected=1) self.checkParam(widget, 'height', 0, expected=1) def test_maxundo(self): widget = self.create() self.checkIntegerParam(widget, 'maxundo', 0, 5, -1) @requires_tcl(8, 5) def test_inactiveselectbackground(self): widget = self.create() self.checkColorParam(widget, 'inactiveselectbackground') @requires_tcl(8, 6) def test_insertunfocussed(self): widget = self.create() self.checkEnumParam(widget, 'insertunfocussed', 'hollow', 'none', 'solid') def test_selectborderwidth(self): widget = self.create() self.checkPixelsParam(widget, 'selectborderwidth', 1.3, 2.6, -2, '10p', conv=noconv, keep_orig=tcl_version >= (8, 5)) def test_spacing1(self): widget = self.create() self.checkPixelsParam(widget, 'spacing1', 20, 21.4, 22.6, '0.5c') self.checkParam(widget, 'spacing1', -5, expected=0) def test_spacing2(self): widget = self.create() self.checkPixelsParam(widget, 'spacing2', 5, 6.4, 7.6, '0.1c') self.checkParam(widget, 'spacing2', -1, expected=0) def test_spacing3(self): widget = self.create() self.checkPixelsParam(widget, 'spacing3', 20, 21.4, 22.6, '0.5c') self.checkParam(widget, 'spacing3', -10, expected=0) @requires_tcl(8, 5) def test_startline(self): widget = self.create() text = '\n'.join('Line %d' for i in range(100)) widget.insert('end', text) self.checkParam(widget, 'startline', 200, expected='') self.checkParam(widget, 'startline', -10, expected='') self.checkInvalidParam(widget, 'startline', 'spam', errmsg='expected integer but got "spam"') self.checkParam(widget, 'startline', 10) self.checkParam(widget, 'endline', 50) self.checkInvalidParam(widget, 'startline', 70, errmsg='-startline must be less than or equal to -endline') def test_state(self): widget = self.create() if tcl_version < (8, 5): self.checkParams(widget, 'state', 'disabled', 'normal') else: self.checkEnumParam(widget, 'state', 'disabled', 'normal') def test_tabs(self): widget = self.create() if get_tk_patchlevel() < (8, 5, 11): self.checkParam(widget, 'tabs', (10.2, 20.7, '1i', '2i'), expected=('10.2', '20.7', '1i', '2i')) else: self.checkParam(widget, 'tabs', (10.2, 20.7, '1i', '2i')) self.checkParam(widget, 'tabs', '10.2 20.7 1i 2i', expected=('10.2', '20.7', '1i', '2i')) self.checkParam(widget, 'tabs', '2c left 4c 6c center', expected=('2c', 'left', '4c', '6c', 'center')) self.checkInvalidParam(widget, 'tabs', 'spam', errmsg='bad screen distance "spam"', keep_orig=tcl_version >= (8, 5)) @requires_tcl(8, 5) def test_tabstyle(self): widget = self.create() self.checkEnumParam(widget, 'tabstyle', 'tabular', 'wordprocessor') def test_undo(self): widget = self.create() self.checkBooleanParam(widget, 'undo') def test_width(self): widget = self.create() self.checkIntegerParam(widget, 'width', 402) self.checkParam(widget, 'width', -402, expected=1) self.checkParam(widget, 'width', 0, expected=1) def test_wrap(self): widget = self.create() if tcl_version < (8, 5): self.checkParams(widget, 'wrap', 'char', 'none', 'word') else: self.checkEnumParam(widget, 'wrap', 'char', 'none', 'word') def test_bbox(self): widget = self.create() self.assertIsBoundingBox(widget.bbox('1.1')) self.assertIsNone(widget.bbox('end')) self.assertRaises(tkinter.TclError, widget.bbox, 'noindex') self.assertRaises(tkinter.TclError, widget.bbox, None) self.assertRaises(TypeError, widget.bbox) self.assertRaises(TypeError, widget.bbox, '1.1', 'end') @add_standard_options(PixelSizeTests, StandardOptionsTests) class CanvasTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'background', 'borderwidth', 'closeenough', 'confine', 'cursor', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'insertbackground', 'insertborderwidth', 'insertofftime', 'insertontime', 'insertwidth', 'offset', 'relief', 'scrollregion', 'selectbackground', 'selectborderwidth', 'selectforeground', 'state', 'takefocus', 'xscrollcommand', 'xscrollincrement', 'yscrollcommand', 'yscrollincrement', 'width', ) _conv_pixels = round _stringify = True def create(self, **kwargs): return tkinter.Canvas(self.root, **kwargs) def test_closeenough(self): widget = self.create() self.checkFloatParam(widget, 'closeenough', 24, 2.4, 3.6, -3, conv=float) def test_confine(self): widget = self.create() self.checkBooleanParam(widget, 'confine') def test_offset(self): widget = self.create() self.assertEqual(widget['offset'], '0,0') self.checkParams(widget, 'offset', 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center') self.checkParam(widget, 'offset', '10,20') self.checkParam(widget, 'offset', '#5,6') self.checkInvalidParam(widget, 'offset', 'spam') def test_scrollregion(self): widget = self.create() self.checkParam(widget, 'scrollregion', '0 0 200 150') self.checkParam(widget, 'scrollregion', (0, 0, 200, 150), expected='0 0 200 150') self.checkParam(widget, 'scrollregion', '') self.checkInvalidParam(widget, 'scrollregion', 'spam', errmsg='bad scrollRegion "spam"') self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200, 'spam')) self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200)) self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200, 150, 0)) def test_state(self): widget = self.create() self.checkEnumParam(widget, 'state', 'disabled', 'normal', errmsg='bad state value "{}": must be normal or disabled') def test_xscrollincrement(self): widget = self.create() self.checkPixelsParam(widget, 'xscrollincrement', 40, 0, 41.2, 43.6, -40, '0.5i') def test_yscrollincrement(self): widget = self.create() self.checkPixelsParam(widget, 'yscrollincrement', 10, 0, 11.2, 13.6, -10, '0.1i') @add_standard_options(IntegerSizeTests, StandardOptionsTests) class ListboxTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'activestyle', 'background', 'borderwidth', 'cursor', 'disabledforeground', 'exportselection', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'justify', 'listvariable', 'relief', 'selectbackground', 'selectborderwidth', 'selectforeground', 'selectmode', 'setgrid', 'state', 'takefocus', 'width', 'xscrollcommand', 'yscrollcommand', ) def create(self, **kwargs): return tkinter.Listbox(self.root, **kwargs) def test_activestyle(self): widget = self.create() self.checkEnumParam(widget, 'activestyle', 'dotbox', 'none', 'underline') test_justify = requires_tcl(8, 6, 5)(StandardOptionsTests.test_justify) def test_listvariable(self): widget = self.create() var = tkinter.DoubleVar(self.root) self.checkVariableParam(widget, 'listvariable', var) def test_selectmode(self): widget = self.create() self.checkParam(widget, 'selectmode', 'single') self.checkParam(widget, 'selectmode', 'browse') self.checkParam(widget, 'selectmode', 'multiple') self.checkParam(widget, 'selectmode', 'extended') def test_state(self): widget = self.create() self.checkEnumParam(widget, 'state', 'disabled', 'normal') def test_itemconfigure(self): widget = self.create() with self.assertRaisesRegex(TclError, 'item number "0" out of range'): widget.itemconfigure(0) colors = 'red orange yellow green blue white violet'.split() widget.insert('end', *colors) for i, color in enumerate(colors): widget.itemconfigure(i, background=color) with self.assertRaises(TypeError): widget.itemconfigure() with self.assertRaisesRegex(TclError, 'bad listbox index "red"'): widget.itemconfigure('red') self.assertEqual(widget.itemconfigure(0, 'background'), ('background', 'background', 'Background', '', 'red')) self.assertEqual(widget.itemconfigure('end', 'background'), ('background', 'background', 'Background', '', 'violet')) self.assertEqual(widget.itemconfigure('@0,0', 'background'), ('background', 'background', 'Background', '', 'red')) d = widget.itemconfigure(0) self.assertIsInstance(d, dict) for k, v in d.items(): self.assertIn(len(v), (2, 5)) if len(v) == 5: self.assertEqual(v, widget.itemconfigure(0, k)) self.assertEqual(v[4], widget.itemcget(0, k)) def check_itemconfigure(self, name, value): widget = self.create() widget.insert('end', 'a', 'b', 'c', 'd') widget.itemconfigure(0, **{name: value}) self.assertEqual(widget.itemconfigure(0, name)[4], value) self.assertEqual(widget.itemcget(0, name), value) with self.assertRaisesRegex(TclError, 'unknown color name "spam"'): widget.itemconfigure(0, **{name: 'spam'}) def test_itemconfigure_background(self): self.check_itemconfigure('background', '#ff0000') def test_itemconfigure_bg(self): self.check_itemconfigure('bg', '#ff0000') def test_itemconfigure_fg(self): self.check_itemconfigure('fg', '#110022') def test_itemconfigure_foreground(self): self.check_itemconfigure('foreground', '#110022') def test_itemconfigure_selectbackground(self): self.check_itemconfigure('selectbackground', '#110022') def test_itemconfigure_selectforeground(self): self.check_itemconfigure('selectforeground', '#654321') def test_box(self): lb = self.create() lb.insert(0, *('el%d' % i for i in range(8))) lb.pack() self.assertIsBoundingBox(lb.bbox(0)) self.assertIsNone(lb.bbox(-1)) self.assertIsNone(lb.bbox(10)) self.assertRaises(TclError, lb.bbox, 'noindex') self.assertRaises(TclError, lb.bbox, None) self.assertRaises(TypeError, lb.bbox) self.assertRaises(TypeError, lb.bbox, 0, 1) def test_curselection(self): lb = self.create() lb.insert(0, *('el%d' % i for i in range(8))) lb.selection_clear(0, tkinter.END) lb.selection_set(2, 4) lb.selection_set(6) self.assertEqual(lb.curselection(), (2, 3, 4, 6)) self.assertRaises(TypeError, lb.curselection, 0) def test_get(self): lb = self.create() lb.insert(0, *('el%d' % i for i in range(8))) self.assertEqual(lb.get(0), 'el0') self.assertEqual(lb.get(3), 'el3') self.assertEqual(lb.get('end'), 'el7') self.assertEqual(lb.get(8), '') self.assertEqual(lb.get(-1), '') self.assertEqual(lb.get(3, 5), ('el3', 'el4', 'el5')) self.assertEqual(lb.get(5, 'end'), ('el5', 'el6', 'el7')) self.assertEqual(lb.get(5, 0), ()) self.assertEqual(lb.get(0, 0), ('el0',)) self.assertRaises(TclError, lb.get, 'noindex') self.assertRaises(TclError, lb.get, None) self.assertRaises(TypeError, lb.get) self.assertRaises(TclError, lb.get, 'end', 'noindex') self.assertRaises(TypeError, lb.get, 1, 2, 3) self.assertRaises(TclError, lb.get, 2.4) @add_standard_options(PixelSizeTests, StandardOptionsTests) class ScaleTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'background', 'bigincrement', 'borderwidth', 'command', 'cursor', 'digits', 'font', 'foreground', 'from', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'label', 'length', 'orient', 'relief', 'repeatdelay', 'repeatinterval', 'resolution', 'showvalue', 'sliderlength', 'sliderrelief', 'state', 'takefocus', 'tickinterval', 'to', 'troughcolor', 'variable', 'width', ) default_orient = 'vertical' def create(self, **kwargs): return tkinter.Scale(self.root, **kwargs) def test_bigincrement(self): widget = self.create() self.checkFloatParam(widget, 'bigincrement', 12.4, 23.6, -5) def test_digits(self): widget = self.create() self.checkIntegerParam(widget, 'digits', 5, 0) def test_from(self): widget = self.create() self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=float_round) def test_label(self): widget = self.create() self.checkParam(widget, 'label', 'any string') self.checkParam(widget, 'label', '') def test_length(self): widget = self.create() self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i') def test_resolution(self): widget = self.create() self.checkFloatParam(widget, 'resolution', 4.2, 0, 6.7, -2) def test_showvalue(self): widget = self.create() self.checkBooleanParam(widget, 'showvalue') def test_sliderlength(self): widget = self.create() self.checkPixelsParam(widget, 'sliderlength', 10, 11.2, 15.6, -3, '3m') def test_sliderrelief(self): widget = self.create() self.checkReliefParam(widget, 'sliderrelief') def test_tickinterval(self): widget = self.create() self.checkFloatParam(widget, 'tickinterval', 1, 4.3, 7.6, 0, conv=float_round) self.checkParam(widget, 'tickinterval', -2, expected=2, conv=float_round) def test_to(self): widget = self.create() self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, conv=float_round) @add_standard_options(PixelSizeTests, StandardOptionsTests) class ScrollbarTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'activerelief', 'background', 'borderwidth', 'command', 'cursor', 'elementborderwidth', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'jump', 'orient', 'relief', 'repeatdelay', 'repeatinterval', 'takefocus', 'troughcolor', 'width', ) _conv_pixels = round _stringify = True default_orient = 'vertical' def create(self, **kwargs): return tkinter.Scrollbar(self.root, **kwargs) def test_activerelief(self): widget = self.create() self.checkReliefParam(widget, 'activerelief') def test_elementborderwidth(self): widget = self.create() self.checkPixelsParam(widget, 'elementborderwidth', 4.3, 5.6, -2, '1m') def test_orient(self): widget = self.create() self.checkEnumParam(widget, 'orient', 'vertical', 'horizontal', errmsg='bad orientation "{}": must be vertical or horizontal') def test_activate(self): sb = self.create() for e in ('arrow1', 'slider', 'arrow2'): sb.activate(e) self.assertEqual(sb.activate(), e) sb.activate('') self.assertIsNone(sb.activate()) self.assertRaises(TypeError, sb.activate, 'arrow1', 'arrow2') def test_set(self): sb = self.create() sb.set(0.2, 0.4) self.assertEqual(sb.get(), (0.2, 0.4)) self.assertRaises(TclError, sb.set, 'abc', 'def') self.assertRaises(TclError, sb.set, 0.6, 'def') self.assertRaises(TclError, sb.set, 0.6, None) self.assertRaises(TypeError, sb.set, 0.6) self.assertRaises(TypeError, sb.set, 0.6, 0.7, 0.8) @add_standard_options(StandardOptionsTests) class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'background', 'borderwidth', 'cursor', 'handlepad', 'handlesize', 'height', 'opaqueresize', 'orient', 'proxybackground', 'proxyborderwidth', 'proxyrelief', 'relief', 'sashcursor', 'sashpad', 'sashrelief', 'sashwidth', 'showhandle', 'width', ) default_orient = 'horizontal' def create(self, **kwargs): return tkinter.PanedWindow(self.root, **kwargs) def test_handlepad(self): widget = self.create() self.checkPixelsParam(widget, 'handlepad', 5, 6.4, 7.6, -3, '1m') def test_handlesize(self): widget = self.create() self.checkPixelsParam(widget, 'handlesize', 8, 9.4, 10.6, -3, '2m', conv=noconv) def test_height(self): widget = self.create() self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i', conv=noconv) def test_opaqueresize(self): widget = self.create() self.checkBooleanParam(widget, 'opaqueresize') @requires_tcl(8, 6, 5) def test_proxybackground(self): widget = self.create() self.checkColorParam(widget, 'proxybackground') @requires_tcl(8, 6, 5) def test_proxyborderwidth(self): widget = self.create() self.checkPixelsParam(widget, 'proxyborderwidth', 0, 1.3, 2.9, 6, -2, '10p', conv=noconv) @requires_tcl(8, 6, 5) def test_proxyrelief(self): widget = self.create() self.checkReliefParam(widget, 'proxyrelief') def test_sashcursor(self): widget = self.create() self.checkCursorParam(widget, 'sashcursor') def test_sashpad(self): widget = self.create() self.checkPixelsParam(widget, 'sashpad', 8, 1.3, 2.6, -2, '2m') def test_sashrelief(self): widget = self.create() self.checkReliefParam(widget, 'sashrelief') def test_sashwidth(self): widget = self.create() self.checkPixelsParam(widget, 'sashwidth', 10, 11.1, 15.6, -3, '1m', conv=noconv) def test_showhandle(self): widget = self.create() self.checkBooleanParam(widget, 'showhandle') def test_width(self): widget = self.create() self.checkPixelsParam(widget, 'width', 402, 403.4, 404.6, -402, 0, '5i', conv=noconv) def create2(self): p = self.create() b = tkinter.Button(p) c = tkinter.Button(p) p.add(b) p.add(c) return p, b, c def test_paneconfigure(self): p, b, c = self.create2() self.assertRaises(TypeError, p.paneconfigure) d = p.paneconfigure(b) self.assertIsInstance(d, dict) for k, v in d.items(): self.assertEqual(len(v), 5) self.assertEqual(v, p.paneconfigure(b, k)) self.assertEqual(v[4], p.panecget(b, k)) def check_paneconfigure(self, p, b, name, value, expected, stringify=False): conv = lambda x: x if not self.wantobjects or stringify: expected = str(expected) if self.wantobjects and stringify: conv = str p.paneconfigure(b, **{name: value}) self.assertEqual(conv(p.paneconfigure(b, name)[4]), expected) self.assertEqual(conv(p.panecget(b, name)), expected) def check_paneconfigure_bad(self, p, b, name, msg): with self.assertRaisesRegex(TclError, msg): p.paneconfigure(b, **{name: 'badValue'}) def test_paneconfigure_after(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'after', c, str(c)) self.check_paneconfigure_bad(p, b, 'after', 'bad window path name "badValue"') def test_paneconfigure_before(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'before', c, str(c)) self.check_paneconfigure_bad(p, b, 'before', 'bad window path name "badValue"') def test_paneconfigure_height(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'height', 10, 10, stringify=get_tk_patchlevel() < (8, 5, 11)) self.check_paneconfigure_bad(p, b, 'height', 'bad screen distance "badValue"') @requires_tcl(8, 5) def test_paneconfigure_hide(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'hide', False, 0) self.check_paneconfigure_bad(p, b, 'hide', 'expected boolean value but got "badValue"') def test_paneconfigure_minsize(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'minsize', 10, 10) self.check_paneconfigure_bad(p, b, 'minsize', 'bad screen distance "badValue"') def test_paneconfigure_padx(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'padx', 1.3, 1) self.check_paneconfigure_bad(p, b, 'padx', 'bad screen distance "badValue"') def test_paneconfigure_pady(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'pady', 1.3, 1) self.check_paneconfigure_bad(p, b, 'pady', 'bad screen distance "badValue"') def test_paneconfigure_sticky(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'sticky', 'nsew', 'nesw') self.check_paneconfigure_bad(p, b, 'sticky', 'bad stickyness value "badValue": must ' 'be a string containing zero or more of ' 'n, e, s, and w') @requires_tcl(8, 5) def test_paneconfigure_stretch(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'stretch', 'alw', 'always') self.check_paneconfigure_bad(p, b, 'stretch', 'bad stretch "badValue": must be ' 'always, first, last, middle, or never') def test_paneconfigure_width(self): p, b, c = self.create2() self.check_paneconfigure(p, b, 'width', 10, 10, stringify=get_tk_patchlevel() < (8, 5, 11)) self.check_paneconfigure_bad(p, b, 'width', 'bad screen distance "badValue"') @add_standard_options(StandardOptionsTests) class MenuTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'activebackground', 'activeborderwidth', 'activeforeground', 'background', 'borderwidth', 'cursor', 'disabledforeground', 'font', 'foreground', 'postcommand', 'relief', 'selectcolor', 'takefocus', 'tearoff', 'tearoffcommand', 'title', 'type', ) _conv_pixels = noconv def create(self, **kwargs): return tkinter.Menu(self.root, **kwargs) def test_postcommand(self): widget = self.create() self.checkCommandParam(widget, 'postcommand') def test_tearoff(self): widget = self.create() self.checkBooleanParam(widget, 'tearoff') def test_tearoffcommand(self): widget = self.create() self.checkCommandParam(widget, 'tearoffcommand') def test_title(self): widget = self.create() self.checkParam(widget, 'title', 'any string') def test_type(self): widget = self.create() self.checkEnumParam(widget, 'type', 'normal', 'tearoff', 'menubar') def test_entryconfigure(self): m1 = self.create() m1.add_command(label='test') self.assertRaises(TypeError, m1.entryconfigure) with self.assertRaisesRegex(TclError, 'bad menu entry index "foo"'): m1.entryconfigure('foo') d = m1.entryconfigure(1) self.assertIsInstance(d, dict) for k, v in d.items(): self.assertIsInstance(k, str) self.assertIsInstance(v, tuple) self.assertEqual(len(v), 5) self.assertEqual(v[0], k) self.assertEqual(m1.entrycget(1, k), v[4]) m1.destroy() def test_entryconfigure_label(self): m1 = self.create() m1.add_command(label='test') self.assertEqual(m1.entrycget(1, 'label'), 'test') m1.entryconfigure(1, label='changed') self.assertEqual(m1.entrycget(1, 'label'), 'changed') def test_entryconfigure_variable(self): m1 = self.create() v1 = tkinter.BooleanVar(self.root) v2 = tkinter.BooleanVar(self.root) m1.add_checkbutton(variable=v1, onvalue=True, offvalue=False, label='Nonsense') self.assertEqual(str(m1.entrycget(1, 'variable')), str(v1)) m1.entryconfigure(1, variable=v2) self.assertEqual(str(m1.entrycget(1, 'variable')), str(v2)) @add_standard_options(PixelSizeTests, StandardOptionsTests) class MessageTest(AbstractWidgetTest, unittest.TestCase): OPTIONS = ( 'anchor', 'aspect', 'background', 'borderwidth', 'cursor', 'font', 'foreground', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'justify', 'padx', 'pady', 'relief', 'takefocus', 'text', 'textvariable', 'width', ) _conv_pad_pixels = noconv def create(self, **kwargs): return tkinter.Message(self.root, **kwargs) def test_aspect(self): widget = self.create() self.checkIntegerParam(widget, 'aspect', 250, 0, -300) tests_gui = ( ButtonTest, CanvasTest, CheckbuttonTest, EntryTest, FrameTest, LabelFrameTest,LabelTest, ListboxTest, MenubuttonTest, MenuTest, MessageTest, OptionMenuTest, PanedWindowTest, RadiobuttonTest, ScaleTest, ScrollbarTest, SpinboxTest, TextTest, ToplevelTest, ) if __name__ == '__main__': unittest.main()
47,210
1,234
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/test_misc.py
import unittest import tkinter from test import support from tkinter.test.support import AbstractTkTest support.requires('gui') class MiscTest(AbstractTkTest, unittest.TestCase): def test_repr(self): t = tkinter.Toplevel(self.root, name='top') f = tkinter.Frame(t, name='child') self.assertEqual(repr(f), '<tkinter.Frame object .top.child>') def test_generated_names(self): t = tkinter.Toplevel(self.root) f = tkinter.Frame(t) f2 = tkinter.Frame(t) b = tkinter.Button(f2) for name in str(b).split('.'): self.assertFalse(name.isidentifier(), msg=repr(name)) def test_tk_setPalette(self): root = self.root root.tk_setPalette('black') self.assertEqual(root['background'], 'black') root.tk_setPalette('white') self.assertEqual(root['background'], 'white') self.assertRaisesRegex(tkinter.TclError, '^unknown color name "spam"$', root.tk_setPalette, 'spam') root.tk_setPalette(background='black') self.assertEqual(root['background'], 'black') root.tk_setPalette(background='blue', highlightColor='yellow') self.assertEqual(root['background'], 'blue') self.assertEqual(root['highlightcolor'], 'yellow') root.tk_setPalette(background='yellow', highlightColor='blue') self.assertEqual(root['background'], 'yellow') self.assertEqual(root['highlightcolor'], 'blue') self.assertRaisesRegex(tkinter.TclError, '^unknown color name "spam"$', root.tk_setPalette, background='spam') self.assertRaisesRegex(tkinter.TclError, '^must specify a background color$', root.tk_setPalette, spam='white') self.assertRaisesRegex(tkinter.TclError, '^must specify a background color$', root.tk_setPalette, highlightColor='blue') def test_after(self): root = self.root def callback(start=0, step=1): nonlocal count count = start + step # Without function, sleeps for ms. self.assertIsNone(root.after(1)) # Set up with callback with no args. count = 0 timer1 = root.after(0, callback) self.assertIn(timer1, root.tk.call('after', 'info')) (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) root.update() # Process all pending events. self.assertEqual(count, 1) with self.assertRaises(tkinter.TclError): root.tk.call(script) # Set up with callback with args. count = 0 timer1 = root.after(0, callback, 42, 11) root.update() # Process all pending events. self.assertEqual(count, 53) # Cancel before called. timer1 = root.after(1000, callback) self.assertIn(timer1, root.tk.call('after', 'info')) (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) root.after_cancel(timer1) # Cancel this event. self.assertEqual(count, 53) with self.assertRaises(tkinter.TclError): root.tk.call(script) def test_after_idle(self): root = self.root def callback(start=0, step=1): nonlocal count count = start + step # Set up with callback with no args. count = 0 idle1 = root.after_idle(callback) self.assertIn(idle1, root.tk.call('after', 'info')) (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) root.update_idletasks() # Process all pending events. self.assertEqual(count, 1) with self.assertRaises(tkinter.TclError): root.tk.call(script) # Set up with callback with args. count = 0 idle1 = root.after_idle(callback, 42, 11) root.update_idletasks() # Process all pending events. self.assertEqual(count, 53) # Cancel before called. idle1 = root.after_idle(callback) self.assertIn(idle1, root.tk.call('after', 'info')) (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) root.after_cancel(idle1) # Cancel this event. self.assertEqual(count, 53) with self.assertRaises(tkinter.TclError): root.tk.call(script) def test_after_cancel(self): root = self.root def callback(): nonlocal count count += 1 timer1 = root.after(5000, callback) idle1 = root.after_idle(callback) # No value for id raises a ValueError. with self.assertRaises(ValueError): root.after_cancel(None) # Cancel timer event. count = 0 (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) root.tk.call(script) self.assertEqual(count, 1) root.after_cancel(timer1) with self.assertRaises(tkinter.TclError): root.tk.call(script) self.assertEqual(count, 1) with self.assertRaises(tkinter.TclError): root.tk.call('after', 'info', timer1) # Cancel same event - nothing happens. root.after_cancel(timer1) # Cancel idle event. count = 0 (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) root.tk.call(script) self.assertEqual(count, 1) root.after_cancel(idle1) with self.assertRaises(tkinter.TclError): root.tk.call(script) self.assertEqual(count, 1) with self.assertRaises(tkinter.TclError): root.tk.call('after', 'info', idle1) tests_gui = (MiscTest, ) if __name__ == "__main__": support.run_unittest(*tests_gui)
5,787
164
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/test_geometry_managers.py
import unittest import re import tkinter from tkinter import TclError from test.support import requires from tkinter.test.support import pixels_conv, tcl_version, requires_tcl from tkinter.test.widget_tests import AbstractWidgetTest requires('gui') class PackTest(AbstractWidgetTest, unittest.TestCase): test_keys = None def create2(self): pack = tkinter.Toplevel(self.root, name='pack') pack.wm_geometry('300x200+0+0') pack.wm_minsize(1, 1) a = tkinter.Frame(pack, name='a', width=20, height=40, bg='red') b = tkinter.Frame(pack, name='b', width=50, height=30, bg='blue') c = tkinter.Frame(pack, name='c', width=80, height=80, bg='green') d = tkinter.Frame(pack, name='d', width=40, height=30, bg='yellow') return pack, a, b, c, d def test_pack_configure_after(self): pack, a, b, c, d = self.create2() with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b): a.pack_configure(after=b) with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'): a.pack_configure(after='.foo') a.pack_configure(side='top') b.pack_configure(side='top') c.pack_configure(side='top') d.pack_configure(side='top') self.assertEqual(pack.pack_slaves(), [a, b, c, d]) a.pack_configure(after=b) self.assertEqual(pack.pack_slaves(), [b, a, c, d]) a.pack_configure(after=a) self.assertEqual(pack.pack_slaves(), [b, a, c, d]) def test_pack_configure_anchor(self): pack, a, b, c, d = self.create2() def check(anchor, geom): a.pack_configure(side='top', ipadx=5, padx=10, ipady=15, pady=20, expand=True, anchor=anchor) self.root.update() self.assertEqual(a.winfo_geometry(), geom) check('n', '30x70+135+20') check('ne', '30x70+260+20') check('e', '30x70+260+65') check('se', '30x70+260+110') check('s', '30x70+135+110') check('sw', '30x70+10+110') check('w', '30x70+10+65') check('nw', '30x70+10+20') check('center', '30x70+135+65') def test_pack_configure_before(self): pack, a, b, c, d = self.create2() with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b): a.pack_configure(before=b) with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'): a.pack_configure(before='.foo') a.pack_configure(side='top') b.pack_configure(side='top') c.pack_configure(side='top') d.pack_configure(side='top') self.assertEqual(pack.pack_slaves(), [a, b, c, d]) a.pack_configure(before=d) self.assertEqual(pack.pack_slaves(), [b, c, a, d]) a.pack_configure(before=a) self.assertEqual(pack.pack_slaves(), [b, c, a, d]) def test_pack_configure_expand(self): pack, a, b, c, d = self.create2() def check(*geoms): self.root.update() self.assertEqual(a.winfo_geometry(), geoms[0]) self.assertEqual(b.winfo_geometry(), geoms[1]) self.assertEqual(c.winfo_geometry(), geoms[2]) self.assertEqual(d.winfo_geometry(), geoms[3]) a.pack_configure(side='left') b.pack_configure(side='top') c.pack_configure(side='right') d.pack_configure(side='bottom') check('20x40+0+80', '50x30+135+0', '80x80+220+75', '40x30+100+170') a.pack_configure(side='left', expand='yes') b.pack_configure(side='top', expand='on') c.pack_configure(side='right', expand=True) d.pack_configure(side='bottom', expand=1) check('20x40+40+80', '50x30+175+35', '80x80+180+110', '40x30+100+135') a.pack_configure(side='left', expand='yes', fill='both') b.pack_configure(side='top', expand='on', fill='both') c.pack_configure(side='right', expand=True, fill='both') d.pack_configure(side='bottom', expand=1, fill='both') check('100x200+0+0', '200x100+100+0', '160x100+140+100', '40x100+100+100') def test_pack_configure_in(self): pack, a, b, c, d = self.create2() a.pack_configure(side='top') b.pack_configure(side='top') c.pack_configure(side='top') d.pack_configure(side='top') a.pack_configure(in_=pack) self.assertEqual(pack.pack_slaves(), [b, c, d, a]) a.pack_configure(in_=c) self.assertEqual(pack.pack_slaves(), [b, c, d]) self.assertEqual(c.pack_slaves(), [a]) with self.assertRaisesRegex(TclError, 'can\'t pack %s inside itself' % (a,)): a.pack_configure(in_=a) with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'): a.pack_configure(in_='.foo') def test_pack_configure_padx_ipadx_fill(self): pack, a, b, c, d = self.create2() def check(geom1, geom2, **kwargs): a.pack_forget() b.pack_forget() a.pack_configure(**kwargs) b.pack_configure(expand=True, fill='both') self.root.update() self.assertEqual(a.winfo_geometry(), geom1) self.assertEqual(b.winfo_geometry(), geom2) check('20x40+260+80', '240x200+0+0', side='right', padx=20) check('20x40+250+80', '240x200+0+0', side='right', padx=(10, 30)) check('60x40+240+80', '240x200+0+0', side='right', ipadx=20) check('30x40+260+80', '250x200+0+0', side='right', ipadx=5, padx=10) check('20x40+260+80', '240x200+0+0', side='right', padx=20, fill='x') check('20x40+249+80', '240x200+0+0', side='right', padx=(9, 31), fill='x') check('60x40+240+80', '240x200+0+0', side='right', ipadx=20, fill='x') check('30x40+260+80', '250x200+0+0', side='right', ipadx=5, padx=10, fill='x') check('30x40+255+80', '250x200+0+0', side='right', ipadx=5, padx=(5, 15), fill='x') check('20x40+140+0', '300x160+0+40', side='top', padx=20) check('20x40+120+0', '300x160+0+40', side='top', padx=(0, 40)) check('60x40+120+0', '300x160+0+40', side='top', ipadx=20) check('30x40+135+0', '300x160+0+40', side='top', ipadx=5, padx=10) check('30x40+130+0', '300x160+0+40', side='top', ipadx=5, padx=(5, 15)) check('260x40+20+0', '300x160+0+40', side='top', padx=20, fill='x') check('260x40+25+0', '300x160+0+40', side='top', padx=(25, 15), fill='x') check('300x40+0+0', '300x160+0+40', side='top', ipadx=20, fill='x') check('280x40+10+0', '300x160+0+40', side='top', ipadx=5, padx=10, fill='x') check('280x40+5+0', '300x160+0+40', side='top', ipadx=5, padx=(5, 15), fill='x') a.pack_configure(padx='1c') self.assertEqual(a.pack_info()['padx'], self._str(pack.winfo_pixels('1c'))) a.pack_configure(ipadx='1c') self.assertEqual(a.pack_info()['ipadx'], self._str(pack.winfo_pixels('1c'))) def test_pack_configure_pady_ipady_fill(self): pack, a, b, c, d = self.create2() def check(geom1, geom2, **kwargs): a.pack_forget() b.pack_forget() a.pack_configure(**kwargs) b.pack_configure(expand=True, fill='both') self.root.update() self.assertEqual(a.winfo_geometry(), geom1) self.assertEqual(b.winfo_geometry(), geom2) check('20x40+280+80', '280x200+0+0', side='right', pady=20) check('20x40+280+70', '280x200+0+0', side='right', pady=(10, 30)) check('20x80+280+60', '280x200+0+0', side='right', ipady=20) check('20x50+280+75', '280x200+0+0', side='right', ipady=5, pady=10) check('20x40+280+80', '280x200+0+0', side='right', pady=20, fill='x') check('20x40+280+69', '280x200+0+0', side='right', pady=(9, 31), fill='x') check('20x80+280+60', '280x200+0+0', side='right', ipady=20, fill='x') check('20x50+280+75', '280x200+0+0', side='right', ipady=5, pady=10, fill='x') check('20x50+280+70', '280x200+0+0', side='right', ipady=5, pady=(5, 15), fill='x') check('20x40+140+20', '300x120+0+80', side='top', pady=20) check('20x40+140+0', '300x120+0+80', side='top', pady=(0, 40)) check('20x80+140+0', '300x120+0+80', side='top', ipady=20) check('20x50+140+10', '300x130+0+70', side='top', ipady=5, pady=10) check('20x50+140+5', '300x130+0+70', side='top', ipady=5, pady=(5, 15)) check('300x40+0+20', '300x120+0+80', side='top', pady=20, fill='x') check('300x40+0+25', '300x120+0+80', side='top', pady=(25, 15), fill='x') check('300x80+0+0', '300x120+0+80', side='top', ipady=20, fill='x') check('300x50+0+10', '300x130+0+70', side='top', ipady=5, pady=10, fill='x') check('300x50+0+5', '300x130+0+70', side='top', ipady=5, pady=(5, 15), fill='x') a.pack_configure(pady='1c') self.assertEqual(a.pack_info()['pady'], self._str(pack.winfo_pixels('1c'))) a.pack_configure(ipady='1c') self.assertEqual(a.pack_info()['ipady'], self._str(pack.winfo_pixels('1c'))) def test_pack_configure_side(self): pack, a, b, c, d = self.create2() def check(side, geom1, geom2): a.pack_configure(side=side) self.assertEqual(a.pack_info()['side'], side) b.pack_configure(expand=True, fill='both') self.root.update() self.assertEqual(a.winfo_geometry(), geom1) self.assertEqual(b.winfo_geometry(), geom2) check('top', '20x40+140+0', '300x160+0+40') check('bottom', '20x40+140+160', '300x160+0+0') check('left', '20x40+0+80', '280x200+20+0') check('right', '20x40+280+80', '280x200+0+0') def test_pack_forget(self): pack, a, b, c, d = self.create2() a.pack_configure() b.pack_configure() c.pack_configure() self.assertEqual(pack.pack_slaves(), [a, b, c]) b.pack_forget() self.assertEqual(pack.pack_slaves(), [a, c]) b.pack_forget() self.assertEqual(pack.pack_slaves(), [a, c]) d.pack_forget() def test_pack_info(self): pack, a, b, c, d = self.create2() with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % a): a.pack_info() a.pack_configure() b.pack_configure(side='right', in_=a, anchor='s', expand=True, fill='x', ipadx=5, padx=10, ipady=2, pady=(5, 15)) info = a.pack_info() self.assertIsInstance(info, dict) self.assertEqual(info['anchor'], 'center') self.assertEqual(info['expand'], self._str(0)) self.assertEqual(info['fill'], 'none') self.assertEqual(info['in'], pack) self.assertEqual(info['ipadx'], self._str(0)) self.assertEqual(info['ipady'], self._str(0)) self.assertEqual(info['padx'], self._str(0)) self.assertEqual(info['pady'], self._str(0)) self.assertEqual(info['side'], 'top') info = b.pack_info() self.assertIsInstance(info, dict) self.assertEqual(info['anchor'], 's') self.assertEqual(info['expand'], self._str(1)) self.assertEqual(info['fill'], 'x') self.assertEqual(info['in'], a) self.assertEqual(info['ipadx'], self._str(5)) self.assertEqual(info['ipady'], self._str(2)) self.assertEqual(info['padx'], self._str(10)) self.assertEqual(info['pady'], self._str((5, 15))) self.assertEqual(info['side'], 'right') def test_pack_propagate(self): pack, a, b, c, d = self.create2() pack.configure(width=300, height=200) a.pack_configure() pack.pack_propagate(False) self.root.update() self.assertEqual(pack.winfo_reqwidth(), 300) self.assertEqual(pack.winfo_reqheight(), 200) pack.pack_propagate(True) self.root.update() self.assertEqual(pack.winfo_reqwidth(), 20) self.assertEqual(pack.winfo_reqheight(), 40) def test_pack_slaves(self): pack, a, b, c, d = self.create2() self.assertEqual(pack.pack_slaves(), []) a.pack_configure() self.assertEqual(pack.pack_slaves(), [a]) b.pack_configure() self.assertEqual(pack.pack_slaves(), [a, b]) class PlaceTest(AbstractWidgetTest, unittest.TestCase): test_keys = None def create2(self): t = tkinter.Toplevel(self.root, width=300, height=200, bd=0) t.wm_geometry('300x200+0+0') f = tkinter.Frame(t, width=154, height=84, bd=2, relief='raised') f.place_configure(x=48, y=38) f2 = tkinter.Frame(t, width=30, height=60, bd=2, relief='raised') self.root.update() return t, f, f2 def test_place_configure_in(self): t, f, f2 = self.create2() self.assertEqual(f2.winfo_manager(), '') with self.assertRaisesRegex(TclError, "can't place %s relative to " "itself" % re.escape(str(f2))): f2.place_configure(in_=f2) if tcl_version >= (8, 5): self.assertEqual(f2.winfo_manager(), '') with self.assertRaisesRegex(TclError, 'bad window path name'): f2.place_configure(in_='spam') f2.place_configure(in_=f) self.assertEqual(f2.winfo_manager(), 'place') def test_place_configure_x(self): t, f, f2 = self.create2() f2.place_configure(in_=f) self.assertEqual(f2.place_info()['x'], '0') self.root.update() self.assertEqual(f2.winfo_x(), 50) f2.place_configure(x=100) self.assertEqual(f2.place_info()['x'], '100') self.root.update() self.assertEqual(f2.winfo_x(), 150) f2.place_configure(x=-10, relx=1) self.assertEqual(f2.place_info()['x'], '-10') self.root.update() self.assertEqual(f2.winfo_x(), 190) with self.assertRaisesRegex(TclError, 'bad screen distance "spam"'): f2.place_configure(in_=f, x='spam') def test_place_configure_y(self): t, f, f2 = self.create2() f2.place_configure(in_=f) self.assertEqual(f2.place_info()['y'], '0') self.root.update() self.assertEqual(f2.winfo_y(), 40) f2.place_configure(y=50) self.assertEqual(f2.place_info()['y'], '50') self.root.update() self.assertEqual(f2.winfo_y(), 90) f2.place_configure(y=-10, rely=1) self.assertEqual(f2.place_info()['y'], '-10') self.root.update() self.assertEqual(f2.winfo_y(), 110) with self.assertRaisesRegex(TclError, 'bad screen distance "spam"'): f2.place_configure(in_=f, y='spam') def test_place_configure_relx(self): t, f, f2 = self.create2() f2.place_configure(in_=f) self.assertEqual(f2.place_info()['relx'], '0') self.root.update() self.assertEqual(f2.winfo_x(), 50) f2.place_configure(relx=0.5) self.assertEqual(f2.place_info()['relx'], '0.5') self.root.update() self.assertEqual(f2.winfo_x(), 125) f2.place_configure(relx=1) self.assertEqual(f2.place_info()['relx'], '1') self.root.update() self.assertEqual(f2.winfo_x(), 200) with self.assertRaisesRegex(TclError, 'expected floating-point number ' 'but got "spam"'): f2.place_configure(in_=f, relx='spam') def test_place_configure_rely(self): t, f, f2 = self.create2() f2.place_configure(in_=f) self.assertEqual(f2.place_info()['rely'], '0') self.root.update() self.assertEqual(f2.winfo_y(), 40) f2.place_configure(rely=0.5) self.assertEqual(f2.place_info()['rely'], '0.5') self.root.update() self.assertEqual(f2.winfo_y(), 80) f2.place_configure(rely=1) self.assertEqual(f2.place_info()['rely'], '1') self.root.update() self.assertEqual(f2.winfo_y(), 120) with self.assertRaisesRegex(TclError, 'expected floating-point number ' 'but got "spam"'): f2.place_configure(in_=f, rely='spam') def test_place_configure_anchor(self): f = tkinter.Frame(self.root) with self.assertRaisesRegex(TclError, 'bad anchor "j"'): f.place_configure(anchor='j') with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'): f.place_configure(anchor='') for value in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center': f.place_configure(anchor=value) self.assertEqual(f.place_info()['anchor'], value) def test_place_configure_width(self): t, f, f2 = self.create2() f2.place_configure(in_=f, width=120) self.root.update() self.assertEqual(f2.winfo_width(), 120) f2.place_configure(width='') self.root.update() self.assertEqual(f2.winfo_width(), 30) with self.assertRaisesRegex(TclError, 'bad screen distance "abcd"'): f2.place_configure(width='abcd') def test_place_configure_height(self): t, f, f2 = self.create2() f2.place_configure(in_=f, height=120) self.root.update() self.assertEqual(f2.winfo_height(), 120) f2.place_configure(height='') self.root.update() self.assertEqual(f2.winfo_height(), 60) with self.assertRaisesRegex(TclError, 'bad screen distance "abcd"'): f2.place_configure(height='abcd') def test_place_configure_relwidth(self): t, f, f2 = self.create2() f2.place_configure(in_=f, relwidth=0.5) self.root.update() self.assertEqual(f2.winfo_width(), 75) f2.place_configure(relwidth='') self.root.update() self.assertEqual(f2.winfo_width(), 30) with self.assertRaisesRegex(TclError, 'expected floating-point number ' 'but got "abcd"'): f2.place_configure(relwidth='abcd') def test_place_configure_relheight(self): t, f, f2 = self.create2() f2.place_configure(in_=f, relheight=0.5) self.root.update() self.assertEqual(f2.winfo_height(), 40) f2.place_configure(relheight='') self.root.update() self.assertEqual(f2.winfo_height(), 60) with self.assertRaisesRegex(TclError, 'expected floating-point number ' 'but got "abcd"'): f2.place_configure(relheight='abcd') def test_place_configure_bordermode(self): f = tkinter.Frame(self.root) with self.assertRaisesRegex(TclError, 'bad bordermode "j"'): f.place_configure(bordermode='j') with self.assertRaisesRegex(TclError, 'ambiguous bordermode ""'): f.place_configure(bordermode='') for value in 'inside', 'outside', 'ignore': f.place_configure(bordermode=value) self.assertEqual(f.place_info()['bordermode'], value) def test_place_forget(self): foo = tkinter.Frame(self.root) foo.place_configure(width=50, height=50) self.root.update() foo.place_forget() self.root.update() self.assertFalse(foo.winfo_ismapped()) with self.assertRaises(TypeError): foo.place_forget(0) def test_place_info(self): t, f, f2 = self.create2() f2.place_configure(in_=f, x=1, y=2, width=3, height=4, relx=0.1, rely=0.2, relwidth=0.3, relheight=0.4, anchor='se', bordermode='outside') info = f2.place_info() self.assertIsInstance(info, dict) self.assertEqual(info['x'], '1') self.assertEqual(info['y'], '2') self.assertEqual(info['width'], '3') self.assertEqual(info['height'], '4') self.assertEqual(info['relx'], '0.1') self.assertEqual(info['rely'], '0.2') self.assertEqual(info['relwidth'], '0.3') self.assertEqual(info['relheight'], '0.4') self.assertEqual(info['anchor'], 'se') self.assertEqual(info['bordermode'], 'outside') self.assertEqual(info['x'], '1') self.assertEqual(info['x'], '1') with self.assertRaises(TypeError): f2.place_info(0) def test_place_slaves(self): foo = tkinter.Frame(self.root) bar = tkinter.Frame(self.root) self.assertEqual(foo.place_slaves(), []) bar.place_configure(in_=foo) self.assertEqual(foo.place_slaves(), [bar]) with self.assertRaises(TypeError): foo.place_slaves(0) class GridTest(AbstractWidgetTest, unittest.TestCase): test_keys = None def tearDown(self): cols, rows = self.root.grid_size() for i in range(cols + 1): self.root.grid_columnconfigure(i, weight=0, minsize=0, pad=0, uniform='') for i in range(rows + 1): self.root.grid_rowconfigure(i, weight=0, minsize=0, pad=0, uniform='') self.root.grid_propagate(1) if tcl_version >= (8, 5): self.root.grid_anchor('nw') super().tearDown() def test_grid_configure(self): b = tkinter.Button(self.root) self.assertEqual(b.grid_info(), {}) b.grid_configure() self.assertEqual(b.grid_info()['in'], self.root) self.assertEqual(b.grid_info()['column'], self._str(0)) self.assertEqual(b.grid_info()['row'], self._str(0)) b.grid_configure({'column': 1}, row=2) self.assertEqual(b.grid_info()['column'], self._str(1)) self.assertEqual(b.grid_info()['row'], self._str(2)) def test_grid_configure_column(self): b = tkinter.Button(self.root) with self.assertRaisesRegex(TclError, 'bad column value "-1": ' 'must be a non-negative integer'): b.grid_configure(column=-1) b.grid_configure(column=2) self.assertEqual(b.grid_info()['column'], self._str(2)) def test_grid_configure_columnspan(self): b = tkinter.Button(self.root) with self.assertRaisesRegex(TclError, 'bad columnspan value "0": ' 'must be a positive integer'): b.grid_configure(columnspan=0) b.grid_configure(columnspan=2) self.assertEqual(b.grid_info()['columnspan'], self._str(2)) def test_grid_configure_in(self): f = tkinter.Frame(self.root) b = tkinter.Button(self.root) self.assertEqual(b.grid_info(), {}) b.grid_configure() self.assertEqual(b.grid_info()['in'], self.root) b.grid_configure(in_=f) self.assertEqual(b.grid_info()['in'], f) b.grid_configure({'in': self.root}) self.assertEqual(b.grid_info()['in'], self.root) def test_grid_configure_ipadx(self): b = tkinter.Button(self.root) with self.assertRaisesRegex(TclError, 'bad ipadx value "-1": ' 'must be positive screen distance'): b.grid_configure(ipadx=-1) b.grid_configure(ipadx=1) self.assertEqual(b.grid_info()['ipadx'], self._str(1)) b.grid_configure(ipadx='.5c') self.assertEqual(b.grid_info()['ipadx'], self._str(round(pixels_conv('.5c') * self.scaling))) def test_grid_configure_ipady(self): b = tkinter.Button(self.root) with self.assertRaisesRegex(TclError, 'bad ipady value "-1": ' 'must be positive screen distance'): b.grid_configure(ipady=-1) b.grid_configure(ipady=1) self.assertEqual(b.grid_info()['ipady'], self._str(1)) b.grid_configure(ipady='.5c') self.assertEqual(b.grid_info()['ipady'], self._str(round(pixels_conv('.5c') * self.scaling))) def test_grid_configure_padx(self): b = tkinter.Button(self.root) with self.assertRaisesRegex(TclError, 'bad pad value "-1": ' 'must be positive screen distance'): b.grid_configure(padx=-1) b.grid_configure(padx=1) self.assertEqual(b.grid_info()['padx'], self._str(1)) b.grid_configure(padx=(10, 5)) self.assertEqual(b.grid_info()['padx'], self._str((10, 5))) b.grid_configure(padx='.5c') self.assertEqual(b.grid_info()['padx'], self._str(round(pixels_conv('.5c') * self.scaling))) def test_grid_configure_pady(self): b = tkinter.Button(self.root) with self.assertRaisesRegex(TclError, 'bad pad value "-1": ' 'must be positive screen distance'): b.grid_configure(pady=-1) b.grid_configure(pady=1) self.assertEqual(b.grid_info()['pady'], self._str(1)) b.grid_configure(pady=(10, 5)) self.assertEqual(b.grid_info()['pady'], self._str((10, 5))) b.grid_configure(pady='.5c') self.assertEqual(b.grid_info()['pady'], self._str(round(pixels_conv('.5c') * self.scaling))) def test_grid_configure_row(self): b = tkinter.Button(self.root) with self.assertRaisesRegex(TclError, 'bad (row|grid) value "-1": ' 'must be a non-negative integer'): b.grid_configure(row=-1) b.grid_configure(row=2) self.assertEqual(b.grid_info()['row'], self._str(2)) def test_grid_configure_rownspan(self): b = tkinter.Button(self.root) with self.assertRaisesRegex(TclError, 'bad rowspan value "0": ' 'must be a positive integer'): b.grid_configure(rowspan=0) b.grid_configure(rowspan=2) self.assertEqual(b.grid_info()['rowspan'], self._str(2)) def test_grid_configure_sticky(self): f = tkinter.Frame(self.root, bg='red') with self.assertRaisesRegex(TclError, 'bad stickyness value "glue"'): f.grid_configure(sticky='glue') f.grid_configure(sticky='ne') self.assertEqual(f.grid_info()['sticky'], 'ne') f.grid_configure(sticky='n,s,e,w') self.assertEqual(f.grid_info()['sticky'], 'nesw') def test_grid_columnconfigure(self): with self.assertRaises(TypeError): self.root.grid_columnconfigure() self.assertEqual(self.root.grid_columnconfigure(0), {'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0}) with self.assertRaisesRegex(TclError, 'bad option "-foo"'): self.root.grid_columnconfigure(0, 'foo') self.root.grid_columnconfigure((0, 3), weight=2) with self.assertRaisesRegex(TclError, 'must specify a single element on retrieval'): self.root.grid_columnconfigure((0, 3)) b = tkinter.Button(self.root) b.grid_configure(column=0, row=0) if tcl_version >= (8, 5): self.root.grid_columnconfigure('all', weight=3) with self.assertRaisesRegex(TclError, 'expected integer but got "all"'): self.root.grid_columnconfigure('all') self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3) self.assertEqual(self.root.grid_columnconfigure(3, 'weight'), 2) self.assertEqual(self.root.grid_columnconfigure(265, 'weight'), 0) if tcl_version >= (8, 5): self.root.grid_columnconfigure(b, weight=4) self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 4) def test_grid_columnconfigure_minsize(self): with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'): self.root.grid_columnconfigure(0, minsize='foo') self.root.grid_columnconfigure(0, minsize=10) self.assertEqual(self.root.grid_columnconfigure(0, 'minsize'), 10) self.assertEqual(self.root.grid_columnconfigure(0)['minsize'], 10) def test_grid_columnconfigure_weight(self): with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'): self.root.grid_columnconfigure(0, weight='bad') with self.assertRaisesRegex(TclError, 'invalid arg "-weight": ' 'should be non-negative'): self.root.grid_columnconfigure(0, weight=-3) self.root.grid_columnconfigure(0, weight=3) self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3) self.assertEqual(self.root.grid_columnconfigure(0)['weight'], 3) def test_grid_columnconfigure_pad(self): with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'): self.root.grid_columnconfigure(0, pad='foo') with self.assertRaisesRegex(TclError, 'invalid arg "-pad": ' 'should be non-negative'): self.root.grid_columnconfigure(0, pad=-3) self.root.grid_columnconfigure(0, pad=3) self.assertEqual(self.root.grid_columnconfigure(0, 'pad'), 3) self.assertEqual(self.root.grid_columnconfigure(0)['pad'], 3) def test_grid_columnconfigure_uniform(self): self.root.grid_columnconfigure(0, uniform='foo') self.assertEqual(self.root.grid_columnconfigure(0, 'uniform'), 'foo') self.assertEqual(self.root.grid_columnconfigure(0)['uniform'], 'foo') def test_grid_rowconfigure(self): with self.assertRaises(TypeError): self.root.grid_rowconfigure() self.assertEqual(self.root.grid_rowconfigure(0), {'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0}) with self.assertRaisesRegex(TclError, 'bad option "-foo"'): self.root.grid_rowconfigure(0, 'foo') self.root.grid_rowconfigure((0, 3), weight=2) with self.assertRaisesRegex(TclError, 'must specify a single element on retrieval'): self.root.grid_rowconfigure((0, 3)) b = tkinter.Button(self.root) b.grid_configure(column=0, row=0) if tcl_version >= (8, 5): self.root.grid_rowconfigure('all', weight=3) with self.assertRaisesRegex(TclError, 'expected integer but got "all"'): self.root.grid_rowconfigure('all') self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3) self.assertEqual(self.root.grid_rowconfigure(3, 'weight'), 2) self.assertEqual(self.root.grid_rowconfigure(265, 'weight'), 0) if tcl_version >= (8, 5): self.root.grid_rowconfigure(b, weight=4) self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 4) def test_grid_rowconfigure_minsize(self): with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'): self.root.grid_rowconfigure(0, minsize='foo') self.root.grid_rowconfigure(0, minsize=10) self.assertEqual(self.root.grid_rowconfigure(0, 'minsize'), 10) self.assertEqual(self.root.grid_rowconfigure(0)['minsize'], 10) def test_grid_rowconfigure_weight(self): with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'): self.root.grid_rowconfigure(0, weight='bad') with self.assertRaisesRegex(TclError, 'invalid arg "-weight": ' 'should be non-negative'): self.root.grid_rowconfigure(0, weight=-3) self.root.grid_rowconfigure(0, weight=3) self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3) self.assertEqual(self.root.grid_rowconfigure(0)['weight'], 3) def test_grid_rowconfigure_pad(self): with self.assertRaisesRegex(TclError, 'bad screen distance "foo"'): self.root.grid_rowconfigure(0, pad='foo') with self.assertRaisesRegex(TclError, 'invalid arg "-pad": ' 'should be non-negative'): self.root.grid_rowconfigure(0, pad=-3) self.root.grid_rowconfigure(0, pad=3) self.assertEqual(self.root.grid_rowconfigure(0, 'pad'), 3) self.assertEqual(self.root.grid_rowconfigure(0)['pad'], 3) def test_grid_rowconfigure_uniform(self): self.root.grid_rowconfigure(0, uniform='foo') self.assertEqual(self.root.grid_rowconfigure(0, 'uniform'), 'foo') self.assertEqual(self.root.grid_rowconfigure(0)['uniform'], 'foo') def test_grid_forget(self): b = tkinter.Button(self.root) c = tkinter.Button(self.root) b.grid_configure(row=2, column=2, rowspan=2, columnspan=2, padx=3, pady=4, sticky='ns') self.assertEqual(self.root.grid_slaves(), [b]) b.grid_forget() c.grid_forget() self.assertEqual(self.root.grid_slaves(), []) self.assertEqual(b.grid_info(), {}) b.grid_configure(row=0, column=0) info = b.grid_info() self.assertEqual(info['row'], self._str(0)) self.assertEqual(info['column'], self._str(0)) self.assertEqual(info['rowspan'], self._str(1)) self.assertEqual(info['columnspan'], self._str(1)) self.assertEqual(info['padx'], self._str(0)) self.assertEqual(info['pady'], self._str(0)) self.assertEqual(info['sticky'], '') def test_grid_remove(self): b = tkinter.Button(self.root) c = tkinter.Button(self.root) b.grid_configure(row=2, column=2, rowspan=2, columnspan=2, padx=3, pady=4, sticky='ns') self.assertEqual(self.root.grid_slaves(), [b]) b.grid_remove() c.grid_remove() self.assertEqual(self.root.grid_slaves(), []) self.assertEqual(b.grid_info(), {}) b.grid_configure(row=0, column=0) info = b.grid_info() self.assertEqual(info['row'], self._str(0)) self.assertEqual(info['column'], self._str(0)) self.assertEqual(info['rowspan'], self._str(2)) self.assertEqual(info['columnspan'], self._str(2)) self.assertEqual(info['padx'], self._str(3)) self.assertEqual(info['pady'], self._str(4)) self.assertEqual(info['sticky'], 'ns') def test_grid_info(self): b = tkinter.Button(self.root) self.assertEqual(b.grid_info(), {}) b.grid_configure(row=2, column=2, rowspan=2, columnspan=2, padx=3, pady=4, sticky='ns') info = b.grid_info() self.assertIsInstance(info, dict) self.assertEqual(info['in'], self.root) self.assertEqual(info['row'], self._str(2)) self.assertEqual(info['column'], self._str(2)) self.assertEqual(info['rowspan'], self._str(2)) self.assertEqual(info['columnspan'], self._str(2)) self.assertEqual(info['padx'], self._str(3)) self.assertEqual(info['pady'], self._str(4)) self.assertEqual(info['sticky'], 'ns') @requires_tcl(8, 5) def test_grid_anchor(self): with self.assertRaisesRegex(TclError, 'bad anchor "x"'): self.root.grid_anchor('x') with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'): self.root.grid_anchor('') with self.assertRaises(TypeError): self.root.grid_anchor('se', 'nw') self.root.grid_anchor('se') self.assertEqual(self.root.tk.call('grid', 'anchor', self.root), 'se') def test_grid_bbox(self): self.assertEqual(self.root.grid_bbox(), (0, 0, 0, 0)) self.assertEqual(self.root.grid_bbox(0, 0), (0, 0, 0, 0)) self.assertEqual(self.root.grid_bbox(0, 0, 1, 1), (0, 0, 0, 0)) with self.assertRaisesRegex(TclError, 'expected integer but got "x"'): self.root.grid_bbox('x', 0) with self.assertRaisesRegex(TclError, 'expected integer but got "x"'): self.root.grid_bbox(0, 'x') with self.assertRaisesRegex(TclError, 'expected integer but got "x"'): self.root.grid_bbox(0, 0, 'x', 0) with self.assertRaisesRegex(TclError, 'expected integer but got "x"'): self.root.grid_bbox(0, 0, 0, 'x') with self.assertRaises(TypeError): self.root.grid_bbox(0, 0, 0, 0, 0) t = self.root # de-maximize t.wm_geometry('1x1+0+0') t.wm_geometry('') f1 = tkinter.Frame(t, width=75, height=75, bg='red') f2 = tkinter.Frame(t, width=90, height=90, bg='blue') f1.grid_configure(row=0, column=0) f2.grid_configure(row=1, column=1) self.root.update() self.assertEqual(t.grid_bbox(), (0, 0, 165, 165)) self.assertEqual(t.grid_bbox(0, 0), (0, 0, 75, 75)) self.assertEqual(t.grid_bbox(0, 0, 1, 1), (0, 0, 165, 165)) self.assertEqual(t.grid_bbox(1, 1), (75, 75, 90, 90)) self.assertEqual(t.grid_bbox(10, 10, 0, 0), (0, 0, 165, 165)) self.assertEqual(t.grid_bbox(-2, -2, -1, -1), (0, 0, 0, 0)) self.assertEqual(t.grid_bbox(10, 10, 12, 12), (165, 165, 0, 0)) def test_grid_location(self): with self.assertRaises(TypeError): self.root.grid_location() with self.assertRaises(TypeError): self.root.grid_location(0) with self.assertRaises(TypeError): self.root.grid_location(0, 0, 0) with self.assertRaisesRegex(TclError, 'bad screen distance "x"'): self.root.grid_location('x', 'y') with self.assertRaisesRegex(TclError, 'bad screen distance "y"'): self.root.grid_location('1c', 'y') t = self.root # de-maximize t.wm_geometry('1x1+0+0') t.wm_geometry('') f = tkinter.Frame(t, width=200, height=100, highlightthickness=0, bg='red') self.assertEqual(f.grid_location(10, 10), (-1, -1)) f.grid_configure() self.root.update() self.assertEqual(t.grid_location(-10, -10), (-1, -1)) self.assertEqual(t.grid_location(-10, 0), (-1, 0)) self.assertEqual(t.grid_location(-1, 0), (-1, 0)) self.assertEqual(t.grid_location(0, -10), (0, -1)) self.assertEqual(t.grid_location(0, -1), (0, -1)) self.assertEqual(t.grid_location(0, 0), (0, 0)) self.assertEqual(t.grid_location(200, 0), (0, 0)) self.assertEqual(t.grid_location(201, 0), (1, 0)) self.assertEqual(t.grid_location(0, 100), (0, 0)) self.assertEqual(t.grid_location(0, 101), (0, 1)) self.assertEqual(t.grid_location(201, 101), (1, 1)) def test_grid_propagate(self): self.assertEqual(self.root.grid_propagate(), True) with self.assertRaises(TypeError): self.root.grid_propagate(False, False) self.root.grid_propagate(False) self.assertFalse(self.root.grid_propagate()) f = tkinter.Frame(self.root, width=100, height=100, bg='red') f.grid_configure(row=0, column=0) self.root.update() self.assertEqual(f.winfo_width(), 100) self.assertEqual(f.winfo_height(), 100) f.grid_propagate(False) g = tkinter.Frame(self.root, width=75, height=85, bg='green') g.grid_configure(in_=f, row=0, column=0) self.root.update() self.assertEqual(f.winfo_width(), 100) self.assertEqual(f.winfo_height(), 100) f.grid_propagate(True) self.root.update() self.assertEqual(f.winfo_width(), 75) self.assertEqual(f.winfo_height(), 85) def test_grid_size(self): with self.assertRaises(TypeError): self.root.grid_size(0) self.assertEqual(self.root.grid_size(), (0, 0)) f = tkinter.Scale(self.root) f.grid_configure(row=0, column=0) self.assertEqual(self.root.grid_size(), (1, 1)) f.grid_configure(row=4, column=5) self.assertEqual(self.root.grid_size(), (6, 5)) def test_grid_slaves(self): self.assertEqual(self.root.grid_slaves(), []) a = tkinter.Label(self.root) a.grid_configure(row=0, column=1) b = tkinter.Label(self.root) b.grid_configure(row=1, column=0) c = tkinter.Label(self.root) c.grid_configure(row=1, column=1) d = tkinter.Label(self.root) d.grid_configure(row=1, column=1) self.assertEqual(self.root.grid_slaves(), [d, c, b, a]) self.assertEqual(self.root.grid_slaves(row=0), [a]) self.assertEqual(self.root.grid_slaves(row=1), [d, c, b]) self.assertEqual(self.root.grid_slaves(column=0), [b]) self.assertEqual(self.root.grid_slaves(column=1), [d, c, a]) self.assertEqual(self.root.grid_slaves(row=1, column=1), [d, c]) tests_gui = ( PackTest, PlaceTest, GridTest, ) if __name__ == '__main__': unittest.main()
41,015
907
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/tkinter/test/test_tkinter/__init__.py
0
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/logging/handlers.py
# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ Additional handlers for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python. Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved. To use, simply 'import logging.handlers' and log away! """ import logging, socket, os, pickle, struct, time, re from _stat import ST_DEV, ST_INO, ST_MTIME import queue try: import threading except ImportError: #pragma: no cover threading = None # # Some constants... # DEFAULT_TCP_LOGGING_PORT = 9020 DEFAULT_UDP_LOGGING_PORT = 9021 DEFAULT_HTTP_LOGGING_PORT = 9022 DEFAULT_SOAP_LOGGING_PORT = 9023 SYSLOG_UDP_PORT = 514 SYSLOG_TCP_PORT = 514 _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day class BaseRotatingHandler(logging.FileHandler): """ Base class for handlers that rotate log files at a certain point. Not meant to be instantiated directly. Instead, use RotatingFileHandler or TimedRotatingFileHandler. """ def __init__(self, filename, mode, encoding=None, delay=False): """ Use the specified filename for streamed logging """ logging.FileHandler.__init__(self, filename, mode, encoding, delay) self.mode = mode self.encoding = encoding self.namer = None self.rotator = None def emit(self, record): """ Emit a record. Output the record to the file, catering for rollover as described in doRollover(). """ try: if self.shouldRollover(record): self.doRollover() logging.FileHandler.emit(self, record) except Exception: self.handleError(record) def rotation_filename(self, default_name): """ Modify the filename of a log file when rotating. This is provided so that a custom filename can be provided. The default implementation calls the 'namer' attribute of the handler, if it's callable, passing the default name to it. If the attribute isn't callable (the default is None), the name is returned unchanged. :param default_name: The default name for the log file. """ if not callable(self.namer): result = default_name else: result = self.namer(default_name) return result def rotate(self, source, dest): """ When rotating, rotate the current log. The default implementation calls the 'rotator' attribute of the handler, if it's callable, passing the source and dest arguments to it. If the attribute isn't callable (the default is None), the source is simply renamed to the destination. :param source: The source filename. This is normally the base filename, e.g. 'test.log' :param dest: The destination filename. This is normally what the source is rotated to, e.g. 'test.log.1'. """ if not callable(self.rotator): # Issue 18940: A file may not have been created if delay is True. if os.path.exists(source): os.rename(source, dest) else: self.rotator(source, dest) class RotatingFileHandler(BaseRotatingHandler): """ Handler for logging to a set of files, which switches from one file to the next when the current file reaches a certain size. """ def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size. Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. appended to it. For example, with a backupCount of 5 and a base file name of "app.log", you would get "app.log", "app.log.1", "app.log.2", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, it is closed and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. exist, then they are renamed to "app.log.2", "app.log.3" etc. respectively. If maxBytes is zero, rollover never occurs. """ # If rotation/rollover is wanted, it doesn't make sense to use another # mode. If for example 'w' were specified, then if there were multiple # runs of the calling application, the logs from previous runs would be # lost if the 'w' is respected, because the log file would be truncated # on each run. if maxBytes > 0: mode = 'a' BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) self.maxBytes = maxBytes self.backupCount = backupCount def doRollover(self): """ Do a rollover, as described in __init__(). """ if self.stream: self.stream.close() self.stream = None if self.backupCount > 0: for i in range(self.backupCount - 1, 0, -1): sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i)) dfn = self.rotation_filename("%s.%d" % (self.baseFilename, i + 1)) if os.path.exists(sfn): if os.path.exists(dfn): os.remove(dfn) os.rename(sfn, dfn) dfn = self.rotation_filename(self.baseFilename + ".1") if os.path.exists(dfn): os.remove(dfn) self.rotate(self.baseFilename, dfn) if not self.delay: self.stream = self._open() def shouldRollover(self, record): """ Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have. """ if self.stream is None: # delay was set... self.stream = self._open() if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) self.stream.seek(0, 2) #due to non-posix-compliant Windows feature if self.stream.tell() + len(msg) >= self.maxBytes: return 1 return 0 class TimedRotatingFileHandler(BaseRotatingHandler): """ Handler for logging to a file, rotating the log file at certain timed intervals. If backupCount is > 0, when rollover is done, no more than backupCount files are kept - the oldest ones are deleted. """ def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None): BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay) self.when = when.upper() self.backupCount = backupCount self.utc = utc self.atTime = atTime # Calculate the real rollover interval, which is just the number of # seconds between rollovers. Also set the filename suffix used when # a rollover occurs. Current 'when' events supported: # S - Seconds # M - Minutes # H - Hours # D - Days # midnight - roll over at midnight # W{0-6} - roll over on a certain day; 0 - Monday # # Case of the 'when' specifier is not important; lower or upper case # will work. if self.when == 'S': self.interval = 1 # one second self.suffix = "%Y-%m-%d_%H-%M-%S" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$" elif self.when == 'M': self.interval = 60 # one minute self.suffix = "%Y-%m-%d_%H-%M" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$" elif self.when == 'H': self.interval = 60 * 60 # one hour self.suffix = "%Y-%m-%d_%H" self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$" elif self.when == 'D' or self.when == 'MIDNIGHT': self.interval = 60 * 60 * 24 # one day self.suffix = "%Y-%m-%d" self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$" elif self.when.startswith('W'): self.interval = 60 * 60 * 24 * 7 # one week if len(self.when) != 2: raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when) if self.when[1] < '0' or self.when[1] > '6': raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) self.dayOfWeek = int(self.when[1]) self.suffix = "%Y-%m-%d" self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$" else: raise ValueError("Invalid rollover interval specified: %s" % self.when) self.extMatch = re.compile(self.extMatch, re.ASCII) self.interval = self.interval * interval # multiply by units requested # The following line added because the filename passed in could be a # path object (see Issue #27493), but self.baseFilename will be a string filename = self.baseFilename if os.path.exists(filename): t = os.stat(filename)[ST_MTIME] else: t = int(time.time()) self.rolloverAt = self.computeRollover(t) def computeRollover(self, currentTime): """ Work out the rollover time based on the specified time. """ result = currentTime + self.interval # If we are rolling over at midnight or weekly, then the interval is already known. # What we need to figure out is WHEN the next interval is. In other words, # if you are rolling over at midnight, then your base interval is 1 day, # but you want to start that one day clock at midnight, not now. So, we # have to fudge the rolloverAt value in order to trigger the first rollover # at the right time. After that, the regular interval will take care of # the rest. Note that this code doesn't care about leap seconds. :) if self.when == 'MIDNIGHT' or self.when.startswith('W'): # This could be done with less code, but I wanted it to be clear if self.utc: t = time.gmtime(currentTime) else: t = time.localtime(currentTime) currentHour = t[3] currentMinute = t[4] currentSecond = t[5] currentDay = t[6] # r is the number of seconds left between now and the next rotation if self.atTime is None: rotate_ts = _MIDNIGHT else: rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 + self.atTime.second) r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 + currentSecond) if r < 0: # Rotate time is before the current time (for example when # self.rotateAt is 13:45 and it now 14:15), rotation is # tomorrow. r += _MIDNIGHT currentDay = (currentDay + 1) % 7 result = currentTime + r # If we are rolling over on a certain day, add in the number of days until # the next rollover, but offset by 1 since we just calculated the time # until the next day starts. There are three cases: # Case 1) The day to rollover is today; in this case, do nothing # Case 2) The day to rollover is further in the interval (i.e., today is # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to # next rollover is simply 6 - 2 - 1, or 3. # Case 3) The day to rollover is behind us in the interval (i.e., today # is day 5 (Saturday) and rollover is on day 3 (Thursday). # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the # number of days left in the current week (1) plus the number # of days in the next week until the rollover day (3). # The calculations described in 2) and 3) above need to have a day added. # This is because the above time calculation takes us to midnight on this # day, i.e. the start of the next day. if self.when.startswith('W'): day = currentDay # 0 is Monday if day != self.dayOfWeek: if day < self.dayOfWeek: daysToWait = self.dayOfWeek - day else: daysToWait = 6 - day + self.dayOfWeek + 1 newRolloverAt = result + (daysToWait * (60 * 60 * 24)) if not self.utc: dstNow = t[-1] dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend result = newRolloverAt return result def shouldRollover(self, record): """ Determine if rollover should occur. record is not used, as we are just comparing times, but it is needed so the method signatures are the same """ t = int(time.time()) if t >= self.rolloverAt: return 1 return 0 def getFilesToDelete(self): """ Determine the files to delete when rolling over. More specific than the earlier method, which just used glob.glob(). """ dirName, baseName = os.path.split(self.baseFilename) fileNames = os.listdir(dirName) result = [] prefix = baseName + "." plen = len(prefix) for fileName in fileNames: if fileName[:plen] == prefix: suffix = fileName[plen:] if self.extMatch.match(suffix): result.append(os.path.join(dirName, fileName)) if len(result) < self.backupCount: result = [] else: result.sort() result = result[:len(result) - self.backupCount] return result def doRollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix. """ if self.stream: self.stream.close() self.stream = None # get the time that this sequence started at and make it a TimeTuple currentTime = int(time.time()) dstNow = time.localtime(currentTime)[-1] t = self.rolloverAt - self.interval if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) dstThen = timeTuple[-1] if dstNow != dstThen: if dstNow: addend = 3600 else: addend = -3600 timeTuple = time.localtime(t + addend) dfn = self.rotation_filename(self.baseFilename + "." + time.strftime(self.suffix, timeTuple)) if os.path.exists(dfn): os.remove(dfn) self.rotate(self.baseFilename, dfn) if self.backupCount > 0: for s in self.getFilesToDelete(): os.remove(s) if not self.delay: self.stream = self._open() newRolloverAt = self.computeRollover(currentTime) while newRolloverAt <= currentTime: newRolloverAt = newRolloverAt + self.interval #If DST changes and midnight or weekly rollover, adjust for this. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour addend = -3600 else: # DST bows out before next rollover, so we need to add an hour addend = 3600 newRolloverAt += addend self.rolloverAt = newRolloverAt class WatchedFileHandler(logging.FileHandler): """ A handler for logging to a file, which watches the file to see if it has changed while in use. This can happen because of usage of programs such as newsyslog and logrotate which perform log file rotation. This handler, intended for use under Unix, watches the file to see if it has changed since the last emit. (A file has changed if its device or inode have changed.) If it has changed, the old file stream is closed, and the file opened to get a new stream. This handler is not appropriate for use under Windows, because under Windows open files cannot be moved or renamed - logging opens the files with exclusive locks - and so there is no need for such a handler. Furthermore, ST_INO is not supported under Windows; stat always returns zero for this value. This handler is based on a suggestion and patch by Chad J. Schroeder. """ def __init__(self, filename, mode='a', encoding=None, delay=False): logging.FileHandler.__init__(self, filename, mode, encoding, delay) self.dev, self.ino = -1, -1 self._statstream() def _statstream(self): if self.stream: sres = os.fstat(self.stream.fileno()) self.dev, self.ino = sres[ST_DEV], sres[ST_INO] def reopenIfNeeded(self): """ Reopen log file if needed. Checks if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream. """ # Reduce the chance of race conditions by stat'ing by path only # once and then fstat'ing our new fd if we opened a new log stream. # See issue #14632: Thanks to John Mulligan for the problem report # and patch. try: # stat the file by path, checking for existence sres = os.stat(self.baseFilename) except FileNotFoundError: sres = None # compare file system stat with that of our stream file handle if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino: if self.stream is not None: # we have an open file handle, clean it up self.stream.flush() self.stream.close() self.stream = None # See Issue #21742: _open () might fail. # open a new file handle and get new stat info from that fd self.stream = self._open() self._statstream() def emit(self, record): """ Emit a record. If underlying file has changed, reopen the file before emitting the record to it. """ self.reopenIfNeeded() logging.FileHandler.emit(self, record) class SocketHandler(logging.Handler): """ A handler class which writes logging records, in pickle format, to a streaming socket. The socket is kept open across logging calls. If the peer resets it, an attempt is made to reconnect on the next call. The pickle which is sent is that of the LogRecord's attribute dictionary (__dict__), so that the receiver does not need to have the logging module installed in order to process the logging event. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord function. """ def __init__(self, host, port): """ Initializes the handler with a specific host address and port. When the attribute *closeOnError* is set to True - if a socket error occurs, the socket is silently closed and then reopened on the next logging call. """ logging.Handler.__init__(self) self.host = host self.port = port if port is None: self.address = host else: self.address = (host, port) self.sock = None self.closeOnError = False self.retryTime = None # # Exponential backoff parameters. # self.retryStart = 1.0 self.retryMax = 30.0 self.retryFactor = 2.0 def makeSocket(self, timeout=1): """ A factory method which allows subclasses to define the precise type of socket they want. """ if self.port is not None: result = socket.create_connection(self.address, timeout=timeout) else: result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) result.settimeout(timeout) try: result.connect(self.address) except OSError: result.close() # Issue 19182 raise return result def createSocket(self): """ Try to create a socket, using an exponential backoff with a max retry time. Thanks to Robert Olson for the original patch (SF #815911) which has been slightly refactored. """ now = time.time() # Either retryTime is None, in which case this # is the first time back after a disconnect, or # we've waited long enough. if self.retryTime is None: attempt = True else: attempt = (now >= self.retryTime) if attempt: try: self.sock = self.makeSocket() self.retryTime = None # next time, no delay before trying except OSError: #Creation failed, so set the retry time and return. if self.retryTime is None: self.retryPeriod = self.retryStart else: self.retryPeriod = self.retryPeriod * self.retryFactor if self.retryPeriod > self.retryMax: self.retryPeriod = self.retryMax self.retryTime = now + self.retryPeriod def send(self, s): """ Send a pickled string to the socket. This function allows for partial sends which can happen when the network is busy. """ if self.sock is None: self.createSocket() #self.sock can be None either because we haven't reached the retry #time yet, or because we have reached the retry time and retried, #but are still unable to connect. if self.sock: try: self.sock.sendall(s) except OSError: #pragma: no cover self.sock.close() self.sock = None # so we can call createSocket next time def makePickle(self, record): """ Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket. """ ei = record.exc_info if ei: # just to get traceback text into record.exc_text ... dummy = self.format(record) # See issue #14436: If msg or args are objects, they may not be # available on the receiving end. So we convert the msg % args # to a string, save it as msg and zap the args. d = dict(record.__dict__) d['msg'] = record.getMessage() d['args'] = None d['exc_info'] = None # Issue #25685: delete 'message' if present: redundant with 'msg' d.pop('message', None) s = pickle.dumps(d, 1) slen = struct.pack(">L", len(s)) return slen + s def handleError(self, record): """ Handle an error during logging. An error has occurred during logging. Most likely cause - connection lost. Close the socket so that we can retry on the next event. """ if self.closeOnError and self.sock: self.sock.close() self.sock = None #try to reconnect next time else: logging.Handler.handleError(self, record) def emit(self, record): """ Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket. """ try: s = self.makePickle(record) self.send(s) except Exception: self.handleError(record) def close(self): """ Closes the socket. """ self.acquire() try: sock = self.sock if sock: self.sock = None sock.close() logging.Handler.close(self) finally: self.release() class DatagramHandler(SocketHandler): """ A handler class which writes logging records, in pickle format, to a datagram socket. The pickle which is sent is that of the LogRecord's attribute dictionary (__dict__), so that the receiver does not need to have the logging module installed in order to process the logging event. To unpickle the record at the receiving end into a LogRecord, use the makeLogRecord function. """ def __init__(self, host, port): """ Initializes the handler with a specific host address and port. """ SocketHandler.__init__(self, host, port) self.closeOnError = False def makeSocket(self): """ The factory method of SocketHandler is here overridden to create a UDP socket (SOCK_DGRAM). """ if self.port is None: family = socket.AF_UNIX else: family = socket.AF_INET s = socket.socket(family, socket.SOCK_DGRAM) return s def send(self, s): """ Send a pickled string to a socket. This function no longer allows for partial sends which can happen when the network is busy - UDP does not guarantee delivery and can deliver packets out of sequence. """ if self.sock is None: self.createSocket() self.sock.sendto(s, self.address) class SysLogHandler(logging.Handler): """ A handler class which sends formatted logging records to a syslog server. Based on Sam Rushing's syslog module: http://www.nightmare.com/squirl/python-ext/misc/syslog.py Contributed by Nicolas Untz (after which minor refactoring changes have been made). """ # from <linux/sys/syslog.h>: # ====================================================================== # priorities/facilities are encoded into a single 32-bit quantity, where # the bottom 3 bits are the priority (0-7) and the top 28 bits are the # facility (0-big number). Both the priorities and the facilities map # roughly one-to-one to strings in the syslogd(8) source code. This # mapping is included in this file. # # priorities (these are ordered) LOG_EMERG = 0 # system is unusable LOG_ALERT = 1 # action must be taken immediately LOG_CRIT = 2 # critical conditions LOG_ERR = 3 # error conditions LOG_WARNING = 4 # warning conditions LOG_NOTICE = 5 # normal but significant condition LOG_INFO = 6 # informational LOG_DEBUG = 7 # debug-level messages # facility codes LOG_KERN = 0 # kernel messages LOG_USER = 1 # random user-level messages LOG_MAIL = 2 # mail system LOG_DAEMON = 3 # system daemons LOG_AUTH = 4 # security/authorization messages LOG_SYSLOG = 5 # messages generated internally by syslogd LOG_LPR = 6 # line printer subsystem LOG_NEWS = 7 # network news subsystem LOG_UUCP = 8 # UUCP subsystem LOG_CRON = 9 # clock daemon LOG_AUTHPRIV = 10 # security/authorization messages (private) LOG_FTP = 11 # FTP daemon # other codes through 15 reserved for system use LOG_LOCAL0 = 16 # reserved for local use LOG_LOCAL1 = 17 # reserved for local use LOG_LOCAL2 = 18 # reserved for local use LOG_LOCAL3 = 19 # reserved for local use LOG_LOCAL4 = 20 # reserved for local use LOG_LOCAL5 = 21 # reserved for local use LOG_LOCAL6 = 22 # reserved for local use LOG_LOCAL7 = 23 # reserved for local use priority_names = { "alert": LOG_ALERT, "crit": LOG_CRIT, "critical": LOG_CRIT, "debug": LOG_DEBUG, "emerg": LOG_EMERG, "err": LOG_ERR, "error": LOG_ERR, # DEPRECATED "info": LOG_INFO, "notice": LOG_NOTICE, "panic": LOG_EMERG, # DEPRECATED "warn": LOG_WARNING, # DEPRECATED "warning": LOG_WARNING, } facility_names = { "auth": LOG_AUTH, "authpriv": LOG_AUTHPRIV, "cron": LOG_CRON, "daemon": LOG_DAEMON, "ftp": LOG_FTP, "kern": LOG_KERN, "lpr": LOG_LPR, "mail": LOG_MAIL, "news": LOG_NEWS, "security": LOG_AUTH, # DEPRECATED "syslog": LOG_SYSLOG, "user": LOG_USER, "uucp": LOG_UUCP, "local0": LOG_LOCAL0, "local1": LOG_LOCAL1, "local2": LOG_LOCAL2, "local3": LOG_LOCAL3, "local4": LOG_LOCAL4, "local5": LOG_LOCAL5, "local6": LOG_LOCAL6, "local7": LOG_LOCAL7, } #The map below appears to be trivially lowercasing the key. However, #there's more to it than meets the eye - in some locales, lowercasing #gives unexpected results. See SF #1524081: in the Turkish locale, #"INFO".lower() != "info" priority_map = { "DEBUG" : "debug", "INFO" : "info", "WARNING" : "warning", "ERROR" : "error", "CRITICAL" : "critical" } def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=None): """ Initialize a handler. If address is specified as a string, a UNIX socket is used. To log to a local syslogd, "SysLogHandler(address="/dev/log")" can be used. If facility is not specified, LOG_USER is used. If socktype is specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific socket type will be used. For Unix sockets, you can also specify a socktype of None, in which case socket.SOCK_DGRAM will be used, falling back to socket.SOCK_STREAM. """ logging.Handler.__init__(self) self.address = address self.facility = facility self.socktype = socktype if isinstance(address, str): self.unixsocket = True # Syslog server may be unavailable during handler initialisation. # C's openlog() function also ignores connection errors. # Moreover, we ignore these errors while logging, so it not worse # to ignore it also here. try: self._connect_unixsocket(address) except OSError: pass else: self.unixsocket = False if socktype is None: socktype = socket.SOCK_DGRAM host, port = address ress = socket.getaddrinfo(host, port, 0, socktype) if not ress: raise OSError("getaddrinfo returns an empty list") for res in ress: af, socktype, proto, _, sa = res err = sock = None try: sock = socket.socket(af, socktype, proto) if socktype == socket.SOCK_STREAM: sock.connect(sa) break except OSError as exc: err = exc if sock is not None: sock.close() if err is not None: raise err self.socket = sock self.socktype = socktype def _connect_unixsocket(self, address): use_socktype = self.socktype if use_socktype is None: use_socktype = socket.SOCK_DGRAM self.socket = socket.socket(socket.AF_UNIX, use_socktype) try: self.socket.connect(address) # it worked, so set self.socktype to the used type self.socktype = use_socktype except OSError: self.socket.close() if self.socktype is not None: # user didn't specify falling back, so fail raise use_socktype = socket.SOCK_STREAM self.socket = socket.socket(socket.AF_UNIX, use_socktype) try: self.socket.connect(address) # it worked, so set self.socktype to the used type self.socktype = use_socktype except OSError: self.socket.close() raise def encodePriority(self, facility, priority): """ Encode the facility and priority. You can pass in strings or integers - if strings are passed, the facility_names and priority_names mapping dictionaries are used to convert them to integers. """ if isinstance(facility, str): facility = self.facility_names[facility] if isinstance(priority, str): priority = self.priority_names[priority] return (facility << 3) | priority def close(self): """ Closes the socket. """ self.acquire() try: self.socket.close() logging.Handler.close(self) finally: self.release() def mapPriority(self, levelName): """ Map a logging level name to a key in the priority_names map. This is useful in two scenarios: when custom levels are being used, and in the case where you can't do a straightforward mapping by lowercasing the logging level name because of locale- specific issues (see SF #1524081). """ return self.priority_map.get(levelName, "warning") ident = '' # prepended to all messages append_nul = True # some old syslog daemons expect a NUL terminator def emit(self, record): """ Emit a record. The record is formatted, and then sent to the syslog server. If exception information is present, it is NOT sent to the server. """ try: msg = self.format(record) if self.ident: msg = self.ident + msg if self.append_nul: msg += '\000' # We need to convert record level to lowercase, maybe this will # change in the future. prio = '<%d>' % self.encodePriority(self.facility, self.mapPriority(record.levelname)) prio = prio.encode('utf-8') # Message is a string. Convert to bytes as required by RFC 5424 msg = msg.encode('utf-8') msg = prio + msg if self.unixsocket: try: self.socket.send(msg) except OSError: self.socket.close() self._connect_unixsocket(self.address) self.socket.send(msg) elif self.socktype == socket.SOCK_DGRAM: self.socket.sendto(msg, self.address) else: self.socket.sendall(msg) except Exception: self.handleError(record) class SMTPHandler(logging.Handler): """ A handler class which sends an SMTP email for each logging event. """ def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=5.0): """ Initialize the handler. Initialize the instance with the from and to addresses and subject line of the email. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. To specify authentication credentials, supply a (username, password) tuple for the credentials argument. To specify the use of a secure protocol (TLS), pass in a tuple for the secure argument. This will only be used when authentication credentials are supplied. The tuple will be either an empty tuple, or a single-value tuple with the name of a keyfile, or a 2-value tuple with the names of the keyfile and certificate file. (This tuple is passed to the `starttls` method). A timeout in seconds can be specified for the SMTP connection (the default is one second). """ logging.Handler.__init__(self) if isinstance(mailhost, (list, tuple)): self.mailhost, self.mailport = mailhost else: self.mailhost, self.mailport = mailhost, None if isinstance(credentials, (list, tuple)): self.username, self.password = credentials else: self.username = None self.fromaddr = fromaddr if isinstance(toaddrs, str): toaddrs = [toaddrs] self.toaddrs = toaddrs self.subject = subject self.secure = secure self.timeout = timeout def getSubject(self, record): """ Determine the subject for the email. If you want to specify a subject line which is record-dependent, override this method. """ return self.subject def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: import smtplib from email.message import EmailMessage import email.utils port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout) msg = EmailMessage() msg['From'] = self.fromaddr msg['To'] = ','.join(self.toaddrs) msg['Subject'] = self.getSubject(record) msg['Date'] = email.utils.localtime() msg.set_content(self.format(record)) if self.username: if self.secure is not None: smtp.ehlo() smtp.starttls(*self.secure) smtp.ehlo() smtp.login(self.username, self.password) smtp.send_message(msg) smtp.quit() except Exception: self.handleError(record) class NTEventLogHandler(logging.Handler): """ A handler class which sends events to the NT Event Log. Adds a registry entry for the specified application name. If no dllname is provided, win32service.pyd (which contains some basic message placeholders) is used. Note that use of these placeholders will make your event logs big, as the entire message source is held in the log. If you want slimmer logs, you have to pass in the name of your own DLL which contains the message definitions you want to use in the event log. """ def __init__(self, appname, dllname=None, logtype="Application"): logging.Handler.__init__(self) try: import win32evtlogutil, win32evtlog self.appname = appname self._welu = win32evtlogutil if not dllname: dllname = os.path.split(self._welu.__file__) dllname = os.path.split(dllname[0]) dllname = os.path.join(dllname[0], r'win32service.pyd') self.dllname = dllname self.logtype = logtype self._welu.AddSourceToRegistry(appname, dllname, logtype) self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE self.typemap = { logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE, logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, } except ImportError: print("The Python Win32 extensions for NT (service, event "\ "logging) appear not to be available.") self._welu = None def getMessageID(self, record): """ Return the message ID for the event record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a formatting string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in win32service.pyd. """ return 1 def getEventCategory(self, record): """ Return the event category for the record. Override this if you want to specify your own categories. This version returns 0. """ return 0 def getEventType(self, record): """ Return the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler's typemap attribute, which is set up in __init__() to a dictionary which contains mappings for DEBUG, INFO, WARNING, ERROR and CRITICAL. If you are using your own levels you will either need to override this method or place a suitable dictionary in the handler's typemap attribute. """ return self.typemap.get(record.levelno, self.deftype) def emit(self, record): """ Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log. """ if self._welu: try: id = self.getMessageID(record) cat = self.getEventCategory(record) type = self.getEventType(record) msg = self.format(record) self._welu.ReportEvent(self.appname, id, cat, type, [msg]) except Exception: self.handleError(record) def close(self): """ Clean up this handler. You can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the DLL name. """ #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype) logging.Handler.close(self) class HTTPHandler(logging.Handler): """ A class which sends records to a Web server, using either GET or POST semantics. """ def __init__(self, host, url, method="GET", secure=False, credentials=None, context=None): """ Initialize the instance with the host, the request URL, and the method ("GET" or "POST") """ logging.Handler.__init__(self) method = method.upper() if method not in ["GET", "POST"]: raise ValueError("method must be GET or POST") if not secure and context is not None: raise ValueError("context parameter only makes sense " "with secure=True") self.host = host self.url = url self.method = method self.secure = secure self.credentials = credentials self.context = context def mapLogRecord(self, record): """ Default implementation of mapping the log record into a dict that is sent as the CGI data. Overwrite in your class. Contributed by Franz Glasner. """ return record.__dict__ def emit(self, record): """ Emit a record. Send the record to the Web server as a percent-encoded dictionary """ try: import http.client, urllib.parse host = self.host if self.secure: h = http.client.HTTPSConnection(host, context=self.context) else: h = http.client.HTTPConnection(host) url = self.url data = urllib.parse.urlencode(self.mapLogRecord(record)) if self.method == "GET": if (url.find('?') >= 0): sep = '&' else: sep = '?' url = url + "%c%s" % (sep, data) h.putrequest(self.method, url) # support multiple hosts on one IP address... # need to strip optional :port from host, if present i = host.find(":") if i >= 0: host = host[:i] # See issue #30904: putrequest call above already adds this header # on Python 3.x. # h.putheader("Host", host) if self.method == "POST": h.putheader("Content-type", "application/x-www-form-urlencoded") h.putheader("Content-length", str(len(data))) if self.credentials: import base64 s = ('%s:%s' % self.credentials).encode('utf-8') s = 'Basic ' + base64.b64encode(s).strip().decode('ascii') h.putheader('Authorization', s) h.endheaders() if self.method == "POST": h.send(data.encode('utf-8')) h.getresponse() #can't do anything with the result except Exception: self.handleError(record) class BufferingHandler(logging.Handler): """ A handler class which buffers logging records in memory. Whenever each record is added to the buffer, a check is made to see if the buffer should be flushed. If it should, then flush() is expected to do what's needed. """ def __init__(self, capacity): """ Initialize the handler with the buffer size. """ logging.Handler.__init__(self) self.capacity = capacity self.buffer = [] def shouldFlush(self, record): """ Should the handler flush its buffer? Returns true if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies. """ return (len(self.buffer) >= self.capacity) def emit(self, record): """ Emit a record. Append the record. If shouldFlush() tells us to, call flush() to process the buffer. """ self.buffer.append(record) if self.shouldFlush(record): self.flush() def flush(self): """ Override to implement custom flushing behaviour. This version just zaps the buffer to empty. """ self.acquire() try: self.buffer = [] finally: self.release() def close(self): """ Close the handler. This version just flushes and chains to the parent class' close(). """ try: self.flush() finally: logging.Handler.close(self) class MemoryHandler(BufferingHandler): """ A handler class which buffers logging records in memory, periodically flushing them to a target handler. Flushing occurs whenever the buffer is full, or when an event of a certain severity or greater is seen. """ def __init__(self, capacity, flushLevel=logging.ERROR, target=None, flushOnClose=True): """ Initialize the handler with the buffer size, the level at which flushing should occur and an optional target. Note that without a target being set either here or via setTarget(), a MemoryHandler is no use to anyone! The ``flushOnClose`` argument is ``True`` for backward compatibility reasons - the old behaviour is that when the handler is closed, the buffer is flushed, even if the flush level hasn't been exceeded nor the capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``. """ BufferingHandler.__init__(self, capacity) self.flushLevel = flushLevel self.target = target # See Issue #26559 for why this has been added self.flushOnClose = flushOnClose def shouldFlush(self, record): """ Check for buffer full or a record at the flushLevel or higher. """ return (len(self.buffer) >= self.capacity) or \ (record.levelno >= self.flushLevel) def setTarget(self, target): """ Set the target handler for this handler. """ self.target = target def flush(self): """ For a MemoryHandler, flushing means just sending the buffered records to the target, if there is one. Override if you want different behaviour. The record buffer is also cleared by this operation. """ self.acquire() try: if self.target: for record in self.buffer: self.target.handle(record) self.buffer = [] finally: self.release() def close(self): """ Flush, if appropriately configured, set the target to None and lose the buffer. """ try: if self.flushOnClose: self.flush() finally: self.acquire() try: self.target = None BufferingHandler.close(self) finally: self.release() class QueueHandler(logging.Handler): """ This handler sends events to a queue. Typically, it would be used together with a multiprocessing Queue to centralise logging to file in one process (in a multi-process application), so as to avoid file write contention between processes. This code is new in Python 3.2, but this class can be copy pasted into user code for use with earlier Python versions. """ def __init__(self, queue): """ Initialise an instance, using the passed queue. """ logging.Handler.__init__(self) self.queue = queue def enqueue(self, record): """ Enqueue a record. The base implementation uses put_nowait. You may want to override this method if you want to use blocking, timeouts or custom queue implementations. """ self.queue.put_nowait(record) def prepare(self, record): """ Prepares a record for queuing. The object returned by this method is enqueued. The base implementation formats the record to merge the message and arguments, and removes unpickleable items from the record in-place. You might want to override this method if you want to convert the record to a dict or JSON string, or send a modified copy of the record while leaving the original intact. """ # The format operation gets traceback text into record.exc_text # (if there's exception data), and also puts the message into # record.message. We can then use this to replace the original # msg + args, as these might be unpickleable. We also zap the # exc_info attribute, as it's no longer needed and, if not None, # will typically not be pickleable. self.format(record) record.msg = record.message record.args = None record.exc_info = None return record def emit(self, record): """ Emit a record. Writes the LogRecord to the queue, preparing it for pickling first. """ try: self.enqueue(self.prepare(record)) except Exception: self.handleError(record) if threading: class QueueListener(object): """ This class implements an internal threaded listener which watches for LogRecords being added to a queue, removes them and passes them to a list of handlers for processing. """ _sentinel = None def __init__(self, queue, *handlers, respect_handler_level=False): """ Initialise an instance with the specified queue and handlers. """ self.queue = queue self.handlers = handlers self._thread = None self.respect_handler_level = respect_handler_level def dequeue(self, block): """ Dequeue a record and return it, optionally blocking. The base implementation uses get. You may want to override this method if you want to use timeouts or work with custom queue implementations. """ return self.queue.get(block) def start(self): """ Start the listener. This starts up a background thread to monitor the queue for LogRecords to process. """ self._thread = t = threading.Thread(target=self._monitor) t.daemon = True t.start() def prepare(self , record): """ Prepare a record for handling. This method just returns the passed-in record. You may want to override this method if you need to do any custom marshalling or manipulation of the record before passing it to the handlers. """ return record def handle(self, record): """ Handle a record. This just loops through the handlers offering them the record to handle. """ record = self.prepare(record) for handler in self.handlers: if not self.respect_handler_level: process = True else: process = record.levelno >= handler.level if process: handler.handle(record) def _monitor(self): """ Monitor the queue for records, and ask the handler to deal with them. This method runs on a separate, internal thread. The thread will terminate if it sees a sentinel object in the queue. """ q = self.queue has_task_done = hasattr(q, 'task_done') while True: try: record = self.dequeue(True) if record is self._sentinel: break self.handle(record) if has_task_done: q.task_done() except queue.Empty: break def enqueue_sentinel(self): """ This is used to enqueue the sentinel record. The base implementation uses put_nowait. You may want to override this method if you want to use timeouts or work with custom queue implementations. """ self.queue.put_nowait(self._sentinel) def stop(self): """ Stop the listener. This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed. """ self.enqueue_sentinel() self._thread.join() self._thread = None
58,054
1,506
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/logging/config.py
# Copyright 2001-2014 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ Configuration functions for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system. Copyright (C) 2001-2014 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ import errno import io import logging import logging.handlers import re import struct import sys import traceback try: import _thread as thread import threading except ImportError: #pragma: no cover thread = None from socketserver import ThreadingTCPServer, StreamRequestHandler DEFAULT_LOGGING_CONFIG_PORT = 9030 RESET_ERROR = errno.ECONNRESET # # The following code implements a socket listener for on-the-fly # reconfiguration of logging. # # _listener holds the server object doing the listening _listener = None def fileConfig(fname, defaults=None, disable_existing_loggers=True): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). """ import configparser if isinstance(fname, configparser.RawConfigParser): cp = fname else: cp = configparser.ConfigParser(defaults) if hasattr(fname, 'readline'): cp.read_file(fname) else: cp.read(fname) formatters = _create_formatters(cp) # critical section logging._acquireLock() try: _clearExistingHandlers() # Handlers add themselves to logging._handlers handlers = _install_handlers(cp, formatters) _install_loggers(cp, handlers, disable_existing_loggers) finally: logging._releaseLock() def _resolve(name): """Resolve a dotted name to a global object.""" name = name.split('.') used = name.pop(0) found = __import__(used) for n in name: used = used + '.' + n try: found = getattr(found, n) except AttributeError: __import__(used) found = getattr(found, n) return found def _strip_spaces(alist): return map(lambda x: x.strip(), alist) def _create_formatters(cp): """Create and return formatters""" flist = cp["formatters"]["keys"] if not len(flist): return {} flist = flist.split(",") flist = _strip_spaces(flist) formatters = {} for form in flist: sectname = "formatter_%s" % form fs = cp.get(sectname, "format", raw=True, fallback=None) dfs = cp.get(sectname, "datefmt", raw=True, fallback=None) stl = cp.get(sectname, "style", raw=True, fallback='%') c = logging.Formatter class_name = cp[sectname].get("class") if class_name: c = _resolve(class_name) f = c(fs, dfs, stl) formatters[form] = f return formatters def _install_handlers(cp, formatters): """Install and return handlers""" hlist = cp["handlers"]["keys"] if not len(hlist): return {} hlist = hlist.split(",") hlist = _strip_spaces(hlist) handlers = {} fixups = [] #for inter-handler references for hand in hlist: section = cp["handler_%s" % hand] klass = section["class"] fmt = section.get("formatter", "") try: klass = eval(klass, vars(logging)) except (AttributeError, NameError): klass = _resolve(klass) args = section["args"] args = eval(args, vars(logging)) h = klass(*args) if "level" in section: level = section["level"] h.setLevel(level) if len(fmt): h.setFormatter(formatters[fmt]) if issubclass(klass, logging.handlers.MemoryHandler): target = section.get("target", "") if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for h, t in fixups: h.setTarget(handlers[t]) return handlers def _handle_existing_loggers(existing, child_loggers, disable_existing): """ When (re)configuring logging, handle loggers which were in the previous configuration but are not in the new configuration. There's no point deleting them as other threads may continue to hold references to them; and by disabling them, you stop them doing any logging. However, don't disable children of named loggers, as that's probably not what was intended by the user. Also, allow existing loggers to NOT be disabled if disable_existing is false. """ root = logging.root for log in existing: logger = root.manager.loggerDict[log] if log in child_loggers: logger.level = logging.NOTSET logger.handlers = [] logger.propagate = True else: logger.disabled = disable_existing def _install_loggers(cp, handlers, disable_existing): """Create and install loggers""" # configure the root first llist = cp["loggers"]["keys"] llist = llist.split(",") llist = list(map(lambda x: x.strip(), llist)) llist.remove("root") section = cp["logger_root"] root = logging.root log = root if "level" in section: level = section["level"] log.setLevel(level) for h in root.handlers[:]: root.removeHandler(h) hlist = section["handlers"] if len(hlist): hlist = hlist.split(",") hlist = _strip_spaces(hlist) for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = list(root.manager.loggerDict.keys()) #The list needs to be sorted so that we can #avoid disabling child loggers of explicitly #named loggers. With a sorted list it is easier #to find the child loggers. existing.sort() #We'll keep the list of existing loggers #which are children of named loggers here... child_loggers = [] #now set up the new ones... for log in llist: section = cp["logger_%s" % log] qn = section["qualname"] propagate = section.getint("propagate", fallback=1) logger = logging.getLogger(qn) if qn in existing: i = existing.index(qn) + 1 # start with the entry after qn prefixed = qn + "." pflen = len(prefixed) num_existing = len(existing) while i < num_existing: if existing[i][:pflen] == prefixed: child_loggers.append(existing[i]) i += 1 existing.remove(qn) if "level" in section: level = section["level"] logger.setLevel(level) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = section["handlers"] if len(hlist): hlist = hlist.split(",") hlist = _strip_spaces(hlist) for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. #However, don't disable children of named loggers, as that's #probably not what was intended by the user. #for log in existing: # logger = root.manager.loggerDict[log] # if log in child_loggers: # logger.level = logging.NOTSET # logger.handlers = [] # logger.propagate = 1 # elif disable_existing_loggers: # logger.disabled = 1 _handle_existing_loggers(existing, child_loggers, disable_existing) def _clearExistingHandlers(): """Clear and close existing handlers""" logging._handlers.clear() logging.shutdown(logging._handlerList[:]) del logging._handlerList[:] IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I) def valid_ident(s): m = IDENTIFIER.match(s) if not m: raise ValueError('Not a valid Python identifier: %r' % s) return True class ConvertingMixin(object): """For ConvertingXXX's, this mixin class provides common functions""" def convert_with_key(self, key, value, replace=True): result = self.configurator.convert(value) #If the converted value is different, save for next time if value is not result: if replace: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def convert(self, value): result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self return result # The ConvertingXXX classes are wrappers around standard Python containers, # and they serve to convert any suitable values in the container. The # conversion converts base dicts, lists and tuples to their wrapped # equivalents, whereas strings which match a conversion format are converted # appropriately. # # Each wrapper should have a configurator attribute holding the actual # configurator to use for conversion. class ConvertingDict(dict, ConvertingMixin): """A converting dictionary wrapper.""" def __getitem__(self, key): value = dict.__getitem__(self, key) return self.convert_with_key(key, value) def get(self, key, default=None): value = dict.get(self, key, default) return self.convert_with_key(key, value) def pop(self, key, default=None): value = dict.pop(self, key, default) return self.convert_with_key(key, value, replace=False) class ConvertingList(list, ConvertingMixin): """A converting list wrapper.""" def __getitem__(self, key): value = list.__getitem__(self, key) return self.convert_with_key(key, value) def pop(self, idx=-1): value = list.pop(self, idx) return self.convert(value) class ConvertingTuple(tuple, ConvertingMixin): """A converting tuple wrapper.""" def __getitem__(self, key): value = tuple.__getitem__(self, key) # Can't replace a tuple entry. return self.convert_with_key(key, value, replace=False) class BaseConfigurator(object): """ The configurator base class which defines some useful defaults. """ CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$') WORD_PATTERN = re.compile(r'^\s*(\w+)\s*') DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*') INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*') DIGIT_PATTERN = re.compile(r'^\d+$') value_converters = { 'ext' : 'ext_convert', 'cfg' : 'cfg_convert', } # We might want to use a different one, e.g. importlib importer = staticmethod(__import__) def __init__(self, config): self.config = ConvertingDict(config) self.config.configurator = self def resolve(self, s): """ Resolve strings to objects using standard import and attribute syntax. """ name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag try: found = getattr(found, frag) except AttributeError: self.importer(used) found = getattr(found, frag) return found except ImportError: e, tb = sys.exc_info()[1:] v = ValueError('Cannot resolve %r: %s' % (s, e)) v.__cause__, v.__traceback__ = e, tb raise v def ext_convert(self, value): """Default converter for the ext:// protocol.""" return self.resolve(value) def cfg_convert(self, value): """Default converter for the cfg:// protocol.""" rest = value m = self.WORD_PATTERN.match(rest) if m is None: raise ValueError("Unable to convert %r" % value) else: rest = rest[m.end():] d = self.config[m.groups()[0]] #print d, rest while rest: m = self.DOT_PATTERN.match(rest) if m: d = d[m.groups()[0]] else: m = self.INDEX_PATTERN.match(rest) if m: idx = m.groups()[0] if not self.DIGIT_PATTERN.match(idx): d = d[idx] else: try: n = int(idx) # try as number first (most likely) d = d[n] except TypeError: d = d[idx] if m: rest = rest[m.end():] else: raise ValueError('Unable to convert ' '%r at %r' % (value, rest)) #rest should be empty return d def convert(self, value): """ Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. """ if not isinstance(value, ConvertingDict) and isinstance(value, dict): value = ConvertingDict(value) value.configurator = self elif not isinstance(value, ConvertingList) and isinstance(value, list): value = ConvertingList(value) value.configurator = self elif not isinstance(value, ConvertingTuple) and\ isinstance(value, tuple): value = ConvertingTuple(value) value.configurator = self elif isinstance(value, str): # str for py3k m = self.CONVERT_PATTERN.match(value) if m: d = m.groupdict() prefix = d['prefix'] converter = self.value_converters.get(prefix, None) if converter: suffix = d['suffix'] converter = getattr(self, converter) value = converter(suffix) return value def configure_custom(self, config): """Configure an object with a user-supplied factory.""" c = config.pop('()') if not callable(c): c = self.resolve(c) props = config.pop('.', None) # Check for valid identifiers kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) result = c(**kwargs) if props: for name, value in props.items(): setattr(result, name, value) return result def as_tuple(self, value): """Utility function which converts lists to tuples.""" if isinstance(value, list): value = tuple(value) return value class DictConfigurator(BaseConfigurator): """ Configure logging using a dictionary-like object to describe the configuration. """ def configure(self): """Do the configuration.""" config = self.config if 'version' not in config: raise ValueError("dictionary doesn't specify a version") if config['version'] != 1: raise ValueError("Unsupported version: %s" % config['version']) incremental = config.pop('incremental', False) EMPTY_DICT = {} logging._acquireLock() try: if incremental: handlers = config.get('handlers', EMPTY_DICT) for name in handlers: if name not in logging._handlers: raise ValueError('No handler found with ' 'name %r' % name) else: try: handler = logging._handlers[name] handler_config = handlers[name] level = handler_config.get('level', None) if level: handler.setLevel(logging._checkLevel(level)) except Exception as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) loggers = config.get('loggers', EMPTY_DICT) for name in loggers: try: self.configure_logger(name, loggers[name], True) except Exception as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) root = config.get('root', None) if root: try: self.configure_root(root, True) except Exception as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) else: disable_existing = config.pop('disable_existing_loggers', True) _clearExistingHandlers() # Do formatters first - they don't refer to anything else formatters = config.get('formatters', EMPTY_DICT) for name in formatters: try: formatters[name] = self.configure_formatter( formatters[name]) except Exception as e: raise ValueError('Unable to configure ' 'formatter %r: %s' % (name, e)) # Next, do filters - they don't refer to anything else, either filters = config.get('filters', EMPTY_DICT) for name in filters: try: filters[name] = self.configure_filter(filters[name]) except Exception as e: raise ValueError('Unable to configure ' 'filter %r: %s' % (name, e)) # Next, do handlers - they refer to formatters and filters # As handlers can refer to other handlers, sort the keys # to allow a deterministic order of configuration handlers = config.get('handlers', EMPTY_DICT) deferred = [] for name in sorted(handlers): try: handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler except Exception as e: if 'target not configured yet' in str(e): deferred.append(name) else: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Now do any that were deferred for name in deferred: try: handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler except Exception as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Next, do loggers - they refer to handlers and filters #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. root = logging.root existing = list(root.manager.loggerDict.keys()) #The list needs to be sorted so that we can #avoid disabling child loggers of explicitly #named loggers. With a sorted list it is easier #to find the child loggers. existing.sort() #We'll keep the list of existing loggers #which are children of named loggers here... child_loggers = [] #now set up the new ones... loggers = config.get('loggers', EMPTY_DICT) for name in loggers: if name in existing: i = existing.index(name) + 1 # look after name prefixed = name + "." pflen = len(prefixed) num_existing = len(existing) while i < num_existing: if existing[i][:pflen] == prefixed: child_loggers.append(existing[i]) i += 1 existing.remove(name) try: self.configure_logger(name, loggers[name]) except Exception as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. #However, don't disable children of named loggers, as that's #probably not what was intended by the user. #for log in existing: # logger = root.manager.loggerDict[log] # if log in child_loggers: # logger.level = logging.NOTSET # logger.handlers = [] # logger.propagate = True # elif disable_existing: # logger.disabled = True _handle_existing_loggers(existing, child_loggers, disable_existing) # And finally, do the root logger root = config.get('root', None) if root: try: self.configure_root(root) except Exception as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) finally: logging._releaseLock() def configure_formatter(self, config): """Configure a formatter from a dictionary.""" if '()' in config: factory = config['()'] # for use in exception handler try: result = self.configure_custom(config) except TypeError as te: if "'format'" not in str(te): raise #Name of parameter changed from fmt to format. #Retry with old name. #This is so that code can be used with older Python versions #(e.g. by Django) config['fmt'] = config.pop('format') config['()'] = factory result = self.configure_custom(config) else: fmt = config.get('format', None) dfmt = config.get('datefmt', None) style = config.get('style', '%') cname = config.get('class', None) if not cname: c = logging.Formatter else: c = _resolve(cname) result = c(fmt, dfmt, style) return result def configure_filter(self, config): """Configure a filter from a dictionary.""" if '()' in config: result = self.configure_custom(config) else: name = config.get('name', '') result = logging.Filter(name) return result def add_filters(self, filterer, filters): """Add filters to a filterer from a list of names.""" for f in filters: try: filterer.addFilter(self.config['filters'][f]) except Exception as e: raise ValueError('Unable to add filter %r: %s' % (f, e)) def configure_handler(self, config): """Configure a handler from a dictionary.""" config_copy = dict(config) # for restoring in case of error formatter = config.pop('formatter', None) if formatter: try: formatter = self.config['formatters'][formatter] except Exception as e: raise ValueError('Unable to set formatter ' '%r: %s' % (formatter, e)) level = config.pop('level', None) filters = config.pop('filters', None) if '()' in config: c = config.pop('()') if not callable(c): c = self.resolve(c) factory = c else: cname = config.pop('class') klass = self.resolve(cname) #Special case for handler which refers to another handler if issubclass(klass, logging.handlers.MemoryHandler) and\ 'target' in config: try: th = self.config['handlers'][config['target']] if not isinstance(th, logging.Handler): config.update(config_copy) # restore for deferred cfg raise TypeError('target not configured yet') config['target'] = th except Exception as e: raise ValueError('Unable to set target handler ' '%r: %s' % (config['target'], e)) elif issubclass(klass, logging.handlers.SMTPHandler) and\ 'mailhost' in config: config['mailhost'] = self.as_tuple(config['mailhost']) elif issubclass(klass, logging.handlers.SysLogHandler) and\ 'address' in config: config['address'] = self.as_tuple(config['address']) factory = klass props = config.pop('.', None) kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) try: result = factory(**kwargs) except TypeError as te: if "'stream'" not in str(te): raise #The argument name changed from strm to stream #Retry with old name. #This is so that code can be used with older Python versions #(e.g. by Django) kwargs['strm'] = kwargs.pop('stream') result = factory(**kwargs) if formatter: result.setFormatter(formatter) if level is not None: result.setLevel(logging._checkLevel(level)) if filters: self.add_filters(result, filters) if props: for name, value in props.items(): setattr(result, name, value) return result def add_handlers(self, logger, handlers): """Add handlers to a logger from a list of names.""" for h in handlers: try: logger.addHandler(self.config['handlers'][h]) except Exception as e: raise ValueError('Unable to add handler %r: %s' % (h, e)) def common_logger_config(self, logger, config, incremental=False): """ Perform configuration which is common to root and non-root loggers. """ level = config.get('level', None) if level is not None: logger.setLevel(logging._checkLevel(level)) if not incremental: #Remove any existing handlers for h in logger.handlers[:]: logger.removeHandler(h) handlers = config.get('handlers', None) if handlers: self.add_handlers(logger, handlers) filters = config.get('filters', None) if filters: self.add_filters(logger, filters) def configure_logger(self, name, config, incremental=False): """Configure a non-root logger from a dictionary.""" logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if propagate is not None: logger.propagate = propagate def configure_root(self, config, incremental=False): """Configure a root logger from a dictionary.""" root = logging.getLogger() self.common_logger_config(root, config, incremental) dictConfigClass = DictConfigurator def dictConfig(config): """Configure logging using a dictionary.""" dictConfigClass(config).configure() def listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None): """ Start up a socket server on the specified port, and listen for new configurations. These will be sent as a file suitable for processing by fileConfig(). Returns a Thread object on which you can call start() to start the server, and which you can join() when appropriate. To stop the server, call stopListening(). Use the ``verify`` argument to verify any bytes received across the wire from a client. If specified, it should be a callable which receives a single argument - the bytes of configuration data received across the network - and it should return either ``None``, to indicate that the passed in bytes could not be verified and should be discarded, or a byte string which is then passed to the configuration machinery as normal. Note that you can return transformed bytes, e.g. by decrypting the bytes passed in. """ if not thread: #pragma: no cover raise NotImplementedError("listen() needs threading to work") class ConfigStreamHandler(StreamRequestHandler): """ Handler for a logging configuration request. It expects a completely new logging configuration and uses fileConfig to install it. """ def handle(self): """ Handle a request. Each request is expected to be a 4-byte length, packed using struct.pack(">L", n), followed by the config file. Uses fileConfig() to do the grunt work. """ try: conn = self.connection chunk = conn.recv(4) if len(chunk) == 4: slen = struct.unpack(">L", chunk)[0] chunk = self.connection.recv(slen) while len(chunk) < slen: chunk = chunk + conn.recv(slen - len(chunk)) if self.server.verify is not None: chunk = self.server.verify(chunk) if chunk is not None: # verified, can process chunk = chunk.decode("utf-8") try: import json d =json.loads(chunk) assert isinstance(d, dict) dictConfig(d) except Exception: #Apply new configuration. file = io.StringIO(chunk) try: fileConfig(file) except Exception: traceback.print_exc() if self.server.ready: self.server.ready.set() except OSError as e: if e.errno != RESET_ERROR: raise class ConfigSocketReceiver(ThreadingTCPServer): """ A simple TCP socket-based logging config receiver. """ allow_reuse_address = 1 def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT, handler=None, ready=None, verify=None): ThreadingTCPServer.__init__(self, (host, port), handler) logging._acquireLock() self.abort = 0 logging._releaseLock() self.timeout = 1 self.ready = ready self.verify = verify def serve_until_stopped(self): import select abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() logging._acquireLock() abort = self.abort logging._releaseLock() self.socket.close() class Server(threading.Thread): def __init__(self, rcvr, hdlr, port, verify): super(Server, self).__init__() self.rcvr = rcvr self.hdlr = hdlr self.port = port self.verify = verify self.ready = threading.Event() def run(self): server = self.rcvr(port=self.port, handler=self.hdlr, ready=self.ready, verify=self.verify) if self.port == 0: self.port = server.server_address[1] self.ready.set() global _listener logging._acquireLock() _listener = server logging._releaseLock() server.serve_until_stopped() return Server(ConfigSocketReceiver, ConfigStreamHandler, port, verify) def stopListening(): """ Stop the listening server which was created with a call to listen(). """ global _listener logging._acquireLock() try: if _listener: _listener.abort = 1 _listener = None finally: logging._releaseLock()
36,048
941
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/logging/__init__.py
# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ Logging package for Python. Based on PEP 282 and comments thereto in comp.lang.python. Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ import sys, os, time, io, traceback, warnings, weakref, collections from string import Template __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR', 'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO', 'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler', 'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig', 'captureWarnings', 'critical', 'debug', 'disable', 'error', 'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass', 'info', 'log', 'makeLogRecord', 'setLoggerClass', 'shutdown', 'warn', 'warning', 'getLogRecordFactory', 'setLogRecordFactory', 'lastResort', 'raiseExceptions'] try: import threading except ImportError: #pragma: no cover threading = None __author__ = "Vinay Sajip <[email protected]>" __status__ = "production" # The following module attributes are no longer updated. __version__ = "0.5.1.2" __date__ = "07 February 2010" #--------------------------------------------------------------------------- # Miscellaneous module data #--------------------------------------------------------------------------- # #_startTime is used as the base when calculating the relative time of events # _startTime = time.time() # #raiseExceptions is used to see if exceptions during handling should be #propagated # raiseExceptions = True # # If you don't want threading information in the log, set this to zero # logThreads = True # # If you don't want multiprocessing information in the log, set this to zero # logMultiprocessing = True # # If you don't want process information in the log, set this to zero # logProcesses = True #--------------------------------------------------------------------------- # Level related stuff #--------------------------------------------------------------------------- # # Default levels and level names, these can be replaced with any positive set # of values having corresponding names. There is a pseudo-level, NOTSET, which # is only really there as a lower limit for user-defined levels. Handlers and # loggers are initialized with NOTSET so that they will log all messages, even # at user-defined levels. # CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 _levelToName = { CRITICAL: 'CRITICAL', ERROR: 'ERROR', WARNING: 'WARNING', INFO: 'INFO', DEBUG: 'DEBUG', NOTSET: 'NOTSET', } _nameToLevel = { 'CRITICAL': CRITICAL, 'FATAL': FATAL, 'ERROR': ERROR, 'WARN': WARNING, 'WARNING': WARNING, 'INFO': INFO, 'DEBUG': DEBUG, 'NOTSET': NOTSET, } def getLevelName(level): """ Return the textual representation of logging level 'level'. If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, INFO, DEBUG) then you get the corresponding string. If you have associated levels with names using addLevelName then the name you have associated with 'level' is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. Otherwise, the string "Level %s" % level is returned. """ # See Issues #22386, #27937 and #29220 for why it's this way result = _levelToName.get(level) if result is not None: return result result = _nameToLevel.get(level) if result is not None: return result return "Level %s" % level def addLevelName(level, levelName): """ Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting. """ _acquireLock() try: #unlikely to cause an exception, but you never know... _levelToName[level] = levelName _nameToLevel[levelName] = level finally: _releaseLock() if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) else: #pragma: no cover def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except Exception: return sys.exc_info()[2].tb_frame.f_back # # _srcfile is used when walking the stack to check when we've got the first # caller stack frame, by skipping frames whose filename is that of this # module's source. It therefore should contain the filename of this module's # source file. # # Ordinarily we would use __file__ for this, but frozen modules don't always # have __file__ set, for some reason (see Issue #21736). Thus, we get the # filename from a handy code object from a function defined in this module. # (There's no particular reason for picking addLevelName.) # _srcfile = os.path.normcase(addLevelName.__code__.co_filename) # _srcfile is only used in conjunction with sys._getframe(). # To provide compatibility with older versions of Python, set _srcfile # to None if _getframe() is not available; this value will prevent # findCaller() from being called. You can also do this if you want to avoid # the overhead of fetching caller information, even when _getframe() is # available. #if not hasattr(sys, '_getframe'): # _srcfile = None def _checkLevel(level): if isinstance(level, int): rv = level elif str(level) == level: if level not in _nameToLevel: raise ValueError("Unknown level: %r" % level) rv = _nameToLevel[level] else: raise TypeError("Level not an integer or a valid string: %r" % level) return rv #--------------------------------------------------------------------------- # Thread-related stuff #--------------------------------------------------------------------------- # #_lock is used to serialize access to shared data structures in this module. #This needs to be an RLock because fileConfig() creates and configures #Handlers, and so might arbitrary user threads. Since Handler code updates the #shared dictionary _handlers, it needs to acquire the lock. But if configuring, #the lock would already have been acquired - so we need an RLock. #The same argument applies to Loggers and Manager.loggerDict. # if threading: _lock = threading.RLock() else: #pragma: no cover _lock = None def _acquireLock(): """ Acquire the module-level lock for serializing access to shared data. This should be released with _releaseLock(). """ if _lock: _lock.acquire() def _releaseLock(): """ Release the module-level lock acquired by calling _acquireLock(). """ if _lock: _lock.release() #--------------------------------------------------------------------------- # The logging record #--------------------------------------------------------------------------- class LogRecord(object): """ A LogRecord instance represents an event being logged. LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in msg and args, which are combined using str(msg) % args to create the message field of the record. The record also includes information such as when the record was created, the source line where the logging call was made, and any exception information to be logged. """ def __init__(self, name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs): """ Initialize a logging record with interesting information. """ ct = time.time() self.name = name self.msg = msg # # The following statement allows passing of a dictionary as a sole # argument, so that you can do something like # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) # Suggested by Stefan Behnel. # Note that without the test for args[0], we get a problem because # during formatting, we test to see if the arg is present using # 'if self.args:'. If the event being logged is e.g. 'Value is %d' # and if the passed arg fails 'if self.args:' then no formatting # is done. For example, logger.warning('Value is %d', 0) would log # 'Value is %d' instead of 'Value is 0'. # For the use case of passing a dictionary, this should not be a # problem. # Issue #21172: a request was made to relax the isinstance check # to hasattr(args[0], '__getitem__'). However, the docs on string # formatting still seem to suggest a mapping object is required. # Thus, while not removing the isinstance check, it does now look # for collections.Mapping rather than, as before, dict. if (args and len(args) == 1 and isinstance(args[0], collections.Mapping) and args[0]): args = args[0] self.args = args self.levelname = getLevelName(level) self.levelno = level self.pathname = pathname try: self.filename = os.path.basename(pathname) self.module = os.path.splitext(self.filename)[0] except (TypeError, ValueError, AttributeError): self.filename = pathname self.module = "Unknown module" self.exc_info = exc_info self.exc_text = None # used to cache the traceback text self.stack_info = sinfo self.lineno = lineno self.funcName = func self.created = ct self.msecs = (ct - int(ct)) * 1000 self.relativeCreated = (self.created - _startTime) * 1000 if logThreads and threading: self.thread = threading.get_ident() self.threadName = threading.current_thread().name else: # pragma: no cover self.thread = None self.threadName = None if not logMultiprocessing: # pragma: no cover self.processName = None else: self.processName = 'MainProcess' mp = sys.modules.get('multiprocessing') if mp is not None: # Errors may occur if multiprocessing has not finished loading # yet - e.g. if a custom import hook causes third-party code # to run when multiprocessing calls import. See issue 8200 # for an example try: self.processName = mp.current_process().name except Exception: #pragma: no cover pass if logProcesses and hasattr(os, 'getpid'): self.process = os.getpid() else: self.process = None def __str__(self): return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno, self.pathname, self.lineno, self.msg) __repr__ = __str__ def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ msg = str(self.msg) if self.args: msg = msg % self.args return msg # # Determine which class to use when instantiating log records. # _logRecordFactory = LogRecord def setLogRecordFactory(factory): """ Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. """ global _logRecordFactory _logRecordFactory = factory def getLogRecordFactory(): """ Return the factory to be used when instantiating a log record. """ return _logRecordFactory def makeLogRecord(dict): """ Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord instance. """ rv = _logRecordFactory(None, None, "", 0, "", (), None, None) rv.__dict__.update(dict) return rv #--------------------------------------------------------------------------- # Formatter classes and functions #--------------------------------------------------------------------------- class PercentStyle(object): default_format = '%(message)s' asctime_format = '%(asctime)s' asctime_search = '%(asctime)' def __init__(self, fmt): self._fmt = fmt or self.default_format def usesTime(self): return self._fmt.find(self.asctime_search) >= 0 def format(self, record): return self._fmt % record.__dict__ class StrFormatStyle(PercentStyle): default_format = '{message}' asctime_format = '{asctime}' asctime_search = '{asctime' def format(self, record): return self._fmt.format(**record.__dict__) class StringTemplateStyle(PercentStyle): default_format = '${message}' asctime_format = '${asctime}' asctime_search = '${asctime}' def __init__(self, fmt): self._fmt = fmt or self.default_format self._tpl = Template(self._fmt) def usesTime(self): fmt = self._fmt return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_format) >= 0 def format(self, record): return self._tpl.substitute(**record.__dict__) BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s" _STYLES = { '%': (PercentStyle, BASIC_FORMAT), '{': (StrFormatStyle, '{levelname}:{name}:{message}'), '$': (StringTemplateStyle, '${levelname}:${name}:${message}'), } class Formatter(object): """ Formatter instances are used to convert a LogRecord to text. Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system. The base Formatter allows a formatting string to be specified. If none is supplied, the the style-dependent default value, "%(message)s", "{message}", or "${message}", is used. The Formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are pre- formatted into a LogRecord's message attribute. Currently, the useful attributes in a LogRecord are described by: %(name)s Name of the logger (logging channel) %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL) %(levelname)s Text logging level for the message ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") %(pathname)s Full pathname of the source file where the logging call was issued (if available) %(filename)s Filename portion of pathname %(module)s Module (name portion of filename) %(lineno)d Source line number where the logging call was issued (if available) %(funcName)s Function name %(created)f Time when the LogRecord was created (time.time() return value) %(asctime)s Textual time when the LogRecord was created %(msecs)d Millisecond portion of the creation time %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded (typically at application startup time) %(thread)d Thread ID (if available) %(threadName)s Thread name (if available) %(process)d Process ID (if available) %(message)s The result of record.getMessage(), computed just as the record is emitted """ converter = time.localtime def __init__(self, fmt=None, datefmt=None, style='%'): """ Initialize the formatter with specified format strings. Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format. Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:`str.format` (``{}``) formatting or :class:`string.Template` formatting in your format string. .. versionchanged:: 3.2 Added the ``style`` parameter. """ if style not in _STYLES: raise ValueError('Style must be one of: %s' % ','.join( _STYLES.keys())) self._style = _STYLES[style][0](fmt) self._fmt = self._style._fmt self.datefmt = datefmt default_time_format = '%Y-%m-%d %H:%M:%S' default_msec_format = '%s,%03d' def formatTime(self, record, datefmt=None): """ Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class. """ ct = self.converter(record.created) if datefmt: s = time.strftime(datefmt, ct) else: t = time.strftime(self.default_time_format, ct) s = self.default_msec_format % (t, record.msecs) return s def formatException(self, ei): """ Format and return the specified exception information as a string. This default implementation just uses traceback.print_exception() """ sio = io.StringIO() tb = ei[2] # See issues #9427, #1553375. Commented out for now. #if getattr(self, 'fullstack', False): # traceback.print_stack(tb.tb_frame.f_back, file=sio) traceback.print_exception(ei[0], ei[1], tb, None, sio) s = sio.getvalue() sio.close() if s[-1:] == "\n": s = s[:-1] return s def usesTime(self): """ Check if the format uses the creation time of the record. """ return self._style.usesTime() def formatMessage(self, record): return self._style.format(record) def formatStack(self, stack_info): """ This method is provided as an extension point for specialized formatting of stack information. The input data is a string as returned from a call to :func:`traceback.print_stack`, but with the last trailing newline removed. The base implementation just returns the value passed in. """ return stack_info def format(self, record): """ Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message. """ record.message = record.getMessage() if self.usesTime(): record.asctime = self.formatTime(record, self.datefmt) s = self.formatMessage(record) if record.exc_info: # Cache the traceback text to avoid converting it multiple times # (it's constant anyway) if not record.exc_text: record.exc_text = self.formatException(record.exc_info) if record.exc_text: if s[-1:] != "\n": s = s + "\n" s = s + record.exc_text if record.stack_info: if s[-1:] != "\n": s = s + "\n" s = s + self.formatStack(record.stack_info) return s # # The default formatter to use when no other is specified # _defaultFormatter = Formatter() class BufferingFormatter(object): """ A formatter suitable for formatting a number of records. """ def __init__(self, linefmt=None): """ Optionally specify a formatter which will be used to format each individual record. """ if linefmt: self.linefmt = linefmt else: self.linefmt = _defaultFormatter def formatHeader(self, records): """ Return the header string for the specified records. """ return "" def formatFooter(self, records): """ Return the footer string for the specified records. """ return "" def format(self, records): """ Format the specified records and return the result as a string. """ rv = "" if len(records) > 0: rv = rv + self.formatHeader(records) for record in records: rv = rv + self.linefmt.format(record) rv = rv + self.formatFooter(records) return rv #--------------------------------------------------------------------------- # Filter classes and functions #--------------------------------------------------------------------------- class Filter(object): """ Filter instances are used to perform arbitrary filtering of LogRecords. Loggers and Handlers can optionally use Filter instances to filter records as desired. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the empty string, all events are passed. """ def __init__(self, name=''): """ Initialize a filter. Initialize with the name of the logger which, together with its children, will have its events allowed through the filter. If no name is specified, allow every event. """ self.name = name self.nlen = len(name) def filter(self, record): """ Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place. """ if self.nlen == 0: return True elif self.name == record.name: return True elif record.name.find(self.name, 0, self.nlen) != 0: return False return (record.name[self.nlen] == ".") class Filterer(object): """ A base class for loggers and handlers which allows them to share common code. """ def __init__(self): """ Initialize the list of filters to be an empty list. """ self.filters = [] def addFilter(self, filter): """ Add the specified filter to this handler. """ if not (filter in self.filters): self.filters.append(filter) def removeFilter(self, filter): """ Remove the specified filter from this handler. """ if filter in self.filters: self.filters.remove(filter) def filter(self, record): """ Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero. .. versionchanged:: 3.2 Allow filters to be just callables. """ rv = True for f in self.filters: if hasattr(f, 'filter'): result = f.filter(record) else: result = f(record) # assume callable - will raise if not if not result: rv = False break return rv #--------------------------------------------------------------------------- # Handler classes and functions #--------------------------------------------------------------------------- _handlers = weakref.WeakValueDictionary() #map of handler names to handlers _handlerList = [] # added to allow handlers to be removed in reverse of order initialized def _removeHandlerRef(wr): """ Remove a handler reference from the internal cleanup list. """ # This function can be called during module teardown, when globals are # set to None. It can also be called from another thread. So we need to # pre-emptively grab the necessary globals and check if they're None, # to prevent race conditions and failures during interpreter shutdown. acquire, release, handlers = _acquireLock, _releaseLock, _handlerList if acquire and release and handlers: acquire() try: if wr in handlers: handlers.remove(wr) finally: release() def _addHandlerRef(handler): """ Add a handler to the internal cleanup list using a weak reference. """ _acquireLock() try: _handlerList.append(weakref.ref(handler, _removeHandlerRef)) finally: _releaseLock() class Handler(Filterer): """ Handler instances dispatch logging events to specific destinations. The base handler class. Acts as a placeholder which defines the Handler interface. Handlers can optionally use Formatter instances to format records as desired. By default, no formatter is specified; in this case, the 'raw' message as determined by record.message is logged. """ def __init__(self, level=NOTSET): """ Initializes the instance - basically setting the formatter to None and the filter list to empty. """ Filterer.__init__(self) self._name = None self.level = _checkLevel(level) self.formatter = None # Add the handler to the global _handlerList (for cleanup on shutdown) _addHandlerRef(self) self.createLock() def get_name(self): return self._name def set_name(self, name): _acquireLock() try: if self._name in _handlers: del _handlers[self._name] self._name = name if name: _handlers[name] = self finally: _releaseLock() name = property(get_name, set_name) def createLock(self): """ Acquire a thread lock for serializing access to the underlying I/O. """ if threading: self.lock = threading.RLock() else: #pragma: no cover self.lock = None def acquire(self): """ Acquire the I/O thread lock. """ if self.lock: self.lock.acquire() def release(self): """ Release the I/O thread lock. """ if self.lock: self.lock.release() def setLevel(self, level): """ Set the logging level of this handler. level must be an int or a str. """ self.level = _checkLevel(level) def format(self, record): """ Format the specified record. If a formatter is set, use it. Otherwise, use the default formatter for the module. """ if self.formatter: fmt = self.formatter else: fmt = _defaultFormatter return fmt.format(record) def emit(self, record): """ Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError. """ raise NotImplementedError('emit must be implemented ' 'by Handler subclasses') def handle(self, record): """ Conditionally emit the specified logging record. Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission. """ rv = self.filter(record) if rv: self.acquire() try: self.emit(record) finally: self.release() return rv def setFormatter(self, fmt): """ Set the formatter for this handler. """ self.formatter = fmt def flush(self): """ Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses. """ pass def close(self): """ Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods. """ #get the module data lock, as we're updating a shared structure. _acquireLock() try: #unlikely to raise an exception, but you never know... if self._name and self._name in _handlers: del _handlers[self._name] finally: _releaseLock() def handleError(self, record): """ Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method. """ if raiseExceptions and sys.stderr: # see issue 13807 t, v, tb = sys.exc_info() try: sys.stderr.write('--- Logging error ---\n') traceback.print_exception(t, v, tb, None, sys.stderr) sys.stderr.write('Call stack:\n') # Walk the stack frame up until we're out of logging, # so as to print the calling context. frame = tb.tb_frame while (frame and os.path.dirname(frame.f_code.co_filename) == __path__[0]): frame = frame.f_back if frame: traceback.print_stack(frame, file=sys.stderr) else: # couldn't find the right stack frame, for some reason sys.stderr.write('Logged from file %s, line %s\n' % ( record.filename, record.lineno)) # Issue 18671: output logging message and arguments try: sys.stderr.write('Message: %r\n' 'Arguments: %s\n' % (record.msg, record.args)) except Exception: sys.stderr.write('Unable to print the message and arguments' ' - possible formatting error.\nUse the' ' traceback above to help find the error.\n' ) except OSError: #pragma: no cover pass # see issue 5971 finally: del t, v, tb def __repr__(self): level = getLevelName(self.level) return '<%s (%s)>' % (self.__class__.__name__, level) class StreamHandler(Handler): """ A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used. """ terminator = '\n' def __init__(self, stream=None): """ Initialize the handler. If stream is not specified, sys.stderr is used. """ Handler.__init__(self) if stream is None: stream = sys.stderr self.stream = stream def flush(self): """ Flushes the stream. """ self.acquire() try: if self.stream and hasattr(self.stream, "flush"): self.stream.flush() finally: self.release() def emit(self, record): """ Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an 'encoding' attribute, it is used to determine how to do the output to the stream. """ try: msg = self.format(record) stream = self.stream stream.write(msg) stream.write(self.terminator) self.flush() except Exception: self.handleError(record) def __repr__(self): level = getLevelName(self.level) name = getattr(self.stream, 'name', '') if name: name += ' ' return '<%s %s(%s)>' % (self.__class__.__name__, name, level) class FileHandler(StreamHandler): """ A handler class which writes formatted logging records to disk files. """ def __init__(self, filename, mode='a', encoding=None, delay=False): """ Open the specified file and use it as the stream for logging. """ # Issue #27493: add support for Path objects to be passed in filename = os.fspath(filename) #keep the absolute path, otherwise derived classes which use this #may come a cropper when the current directory changes self.baseFilename = os.path.abspath(filename) self.mode = mode self.encoding = encoding self.delay = delay if delay: #We don't open the stream, but we still need to call the #Handler constructor to set level, formatter, lock etc. Handler.__init__(self) self.stream = None else: StreamHandler.__init__(self, self._open()) def close(self): """ Closes the stream. """ self.acquire() try: try: if self.stream: try: self.flush() finally: stream = self.stream self.stream = None if hasattr(stream, "close"): stream.close() finally: # Issue #19523: call unconditionally to # prevent a handler leak when delay is set StreamHandler.close(self) finally: self.release() def _open(self): """ Open the current base file with the (original) mode and encoding. Return the resulting stream. """ return open(self.baseFilename, self.mode, encoding=self.encoding) def emit(self, record): """ Emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit. """ if self.stream is None: self.stream = self._open() StreamHandler.emit(self, record) def __repr__(self): level = getLevelName(self.level) return '<%s %s (%s)>' % (self.__class__.__name__, self.baseFilename, level) class _StderrHandler(StreamHandler): """ This class is like a StreamHandler using sys.stderr, but always uses whatever sys.stderr is currently set to rather than the value of sys.stderr at handler construction time. """ def __init__(self, level=NOTSET): """ Initialize the handler. """ Handler.__init__(self, level) @property def stream(self): return sys.stderr _defaultLastResort = _StderrHandler(WARNING) lastResort = _defaultLastResort #--------------------------------------------------------------------------- # Manager classes and functions #--------------------------------------------------------------------------- class PlaceHolder(object): """ PlaceHolder instances are used in the Manager logger hierarchy to take the place of nodes for which no loggers have been defined. This class is intended for internal use only and not as part of the public API. """ def __init__(self, alogger): """ Initialize with the specified logger being a child of this placeholder. """ self.loggerMap = { alogger : None } def append(self, alogger): """ Add the specified logger as a child of this placeholder. """ if alogger not in self.loggerMap: self.loggerMap[alogger] = None # # Determine which class to use when instantiating loggers. # def setLoggerClass(klass): """ Set the class to be used when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__() """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) global _loggerClass _loggerClass = klass def getLoggerClass(): """ Return the class to be used when instantiating a logger. """ return _loggerClass class Manager(object): """ There is [under normal circumstances] just one Manager instance, which holds the hierarchy of loggers. """ def __init__(self, rootnode): """ Initialize the manager with the root node of the logger hierarchy. """ self.root = rootnode self.disable = 0 self.emittedNoHandlerWarning = False self.loggerDict = {} self.loggerClass = None self.logRecordFactory = None def getLogger(self, name): """ Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. """ rv = None if not isinstance(name, str): raise TypeError('A logger name must be a string') _acquireLock() try: if name in self.loggerDict: rv = self.loggerDict[name] if isinstance(rv, PlaceHolder): ph = rv rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupChildren(ph, rv) self._fixupParents(rv) else: rv = (self.loggerClass or _loggerClass)(name) rv.manager = self self.loggerDict[name] = rv self._fixupParents(rv) finally: _releaseLock() return rv def setLoggerClass(self, klass): """ Set the class to be used when instantiating a logger with this Manager. """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) self.loggerClass = klass def setLogRecordFactory(self, factory): """ Set the factory to be used when instantiating a log record with this Manager. """ self.logRecordFactory = factory def _fixupParents(self, alogger): """ Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy. """ name = alogger.name i = name.rfind(".") rv = None while (i > 0) and not rv: substr = name[:i] if substr not in self.loggerDict: self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] if isinstance(obj, Logger): rv = obj else: assert isinstance(obj, PlaceHolder) obj.append(alogger) i = name.rfind(".", 0, i - 1) if not rv: rv = self.root alogger.parent = rv def _fixupChildren(self, ph, alogger): """ Ensure that children of the placeholder ph are connected to the specified logger. """ name = alogger.name namelen = len(name) for c in ph.loggerMap.keys(): #The if means ... if not c.parent.name.startswith(nm) if c.parent.name[:namelen] != name: alogger.parent = c.parent c.parent = alogger #--------------------------------------------------------------------------- # Logger classes and functions #--------------------------------------------------------------------------- class Logger(Filterer): """ Instances of the Logger class represent a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of "input processing" might include sub-areas "read CSV files", "read XLS files" and "read Gnumeric files"). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be "input" for the upper level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. There is no arbitrary limit to the depth of nesting. """ def __init__(self, name, level=NOTSET): """ Initialize the logger with a name and an optional level. """ Filterer.__init__(self) self.name = name self.level = _checkLevel(level) self.parent = None self.propagate = True self.handlers = [] self.disabled = False def setLevel(self, level): """ Set the logging level of this logger. level must be an int or a str. """ self.level = _checkLevel(level) def debug(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'DEBUG'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) """ if self.isEnabledFor(DEBUG): self._log(DEBUG, msg, args, **kwargs) def info(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'INFO'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1) """ if self.isEnabledFor(INFO): self._log(INFO, msg, args, **kwargs) def warning(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'WARNING'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1) """ if self.isEnabledFor(WARNING): self._log(WARNING, msg, args, **kwargs) def warn(self, msg, *args, **kwargs): warnings.warn("The 'warn' method is deprecated, " "use 'warning' instead", DeprecationWarning, 2) self.warning(msg, *args, **kwargs) def error(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'ERROR'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1) """ if self.isEnabledFor(ERROR): self._log(ERROR, msg, args, **kwargs) def exception(self, msg, *args, exc_info=True, **kwargs): """ Convenience method for logging an ERROR with exception information. """ self.error(msg, *args, exc_info=exc_info, **kwargs) def critical(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'CRITICAL'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1) """ if self.isEnabledFor(CRITICAL): self._log(CRITICAL, msg, args, **kwargs) fatal = critical def log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) """ if not isinstance(level, int): if raiseExceptions: raise TypeError("level must be an integer") else: return if self.isEnabledFor(level): self._log(level, msg, args, **kwargs) def findCaller(self, stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() #On some versions of IronPython, currentframe() returns None if #IronPython isn't run with -X:Frames. if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)", None while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename == _srcfile: f = f.f_back continue sinfo = None if stack_info: sio = io.StringIO() sio.write('Stack (most recent call last):\n') traceback.print_stack(f, file=sio) sinfo = sio.getvalue() if sinfo[-1] == '\n': sinfo = sinfo[:-1] sio.close() rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) break return rv def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func, sinfo) if extra is not None: for key in extra: if (key in ["message", "asctime"]) or (key in rv.__dict__): raise KeyError("Attempt to overwrite %r in LogRecord" % key) rv.__dict__[key] = extra[key] return rv def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): """ Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record. """ sinfo = None if _srcfile: #IronPython doesn't track Python frames, so findCaller raises an #exception on some versions of IronPython. We trap it here so that #IronPython can use logging. try: fn, lno, func, sinfo = self.findCaller(stack_info) except ValueError: # pragma: no cover fn, lno, func = "(unknown file)", 0, "(unknown function)" else: # pragma: no cover fn, lno, func = "(unknown file)", 0, "(unknown function)" if exc_info: if isinstance(exc_info, BaseException): exc_info = (type(exc_info), exc_info, exc_info.__traceback__) elif not isinstance(exc_info, tuple): exc_info = sys.exc_info() record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra, sinfo) self.handle(record) def handle(self, record): """ Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied. """ if (not self.disabled) and self.filter(record): self.callHandlers(record) def addHandler(self, hdlr): """ Add the specified handler to this logger. """ _acquireLock() try: if not (hdlr in self.handlers): self.handlers.append(hdlr) finally: _releaseLock() def removeHandler(self, hdlr): """ Remove the specified handler from this logger. """ _acquireLock() try: if hdlr in self.handlers: self.handlers.remove(hdlr) finally: _releaseLock() def hasHandlers(self): """ See if this logger has any handlers configured. Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger which is checked for the existence of handlers. """ c = self rv = False while c: if c.handlers: rv = True break if not c.propagate: break else: c = c.parent return rv def callHandlers(self, record): """ Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger whose handlers are called. """ c = self found = 0 while c: for hdlr in c.handlers: found = found + 1 if record.levelno >= hdlr.level: hdlr.handle(record) if not c.propagate: c = None #break out else: c = c.parent if (found == 0): if lastResort: if record.levelno >= lastResort.level: lastResort.handle(record) elif raiseExceptions and not self.manager.emittedNoHandlerWarning: sys.stderr.write("No handlers could be found for logger" " \"%s\"\n" % self.name) self.manager.emittedNoHandlerWarning = True def getEffectiveLevel(self): """ Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found. """ logger = self while logger: if logger.level: return logger.level logger = logger.parent return NOTSET def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ if self.manager.disable >= level: return False return level >= self.getEffectiveLevel() def getChild(self, suffix): """ Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. """ if self.root is not self: suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix) def __repr__(self): level = getLevelName(self.getEffectiveLevel()) return '<%s %s (%s)>' % (self.__class__.__name__, self.name, level) class RootLogger(Logger): """ A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy. """ def __init__(self, level): """ Initialize the logger with the name "root". """ Logger.__init__(self, "root", level) _loggerClass = Logger class LoggerAdapter(object): """ An adapter for loggers which makes it easier to specify contextual information in logging output. """ def __init__(self, logger, extra): """ Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2")) """ self.logger = logger self.extra = extra def process(self, msg, kwargs): """ Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. Normally, you'll only need to override this one method in a LoggerAdapter subclass for your specific needs. """ kwargs["extra"] = self.extra return msg, kwargs # # Boilerplate convenience methods # def debug(self, msg, *args, **kwargs): """ Delegate a debug call to the underlying logger. """ self.log(DEBUG, msg, *args, **kwargs) def info(self, msg, *args, **kwargs): """ Delegate an info call to the underlying logger. """ self.log(INFO, msg, *args, **kwargs) def warning(self, msg, *args, **kwargs): """ Delegate a warning call to the underlying logger. """ self.log(WARNING, msg, *args, **kwargs) def warn(self, msg, *args, **kwargs): warnings.warn("The 'warn' method is deprecated, " "use 'warning' instead", DeprecationWarning, 2) self.warning(msg, *args, **kwargs) def error(self, msg, *args, **kwargs): """ Delegate an error call to the underlying logger. """ self.log(ERROR, msg, *args, **kwargs) def exception(self, msg, *args, exc_info=True, **kwargs): """ Delegate an exception call to the underlying logger. """ self.log(ERROR, msg, *args, exc_info=exc_info, **kwargs) def critical(self, msg, *args, **kwargs): """ Delegate a critical call to the underlying logger. """ self.log(CRITICAL, msg, *args, **kwargs) def log(self, level, msg, *args, **kwargs): """ Delegate a log call to the underlying logger, after adding contextual information from this adapter instance. """ if self.isEnabledFor(level): msg, kwargs = self.process(msg, kwargs) self.logger.log(level, msg, *args, **kwargs) def isEnabledFor(self, level): """ Is this logger enabled for level 'level'? """ if self.logger.manager.disable >= level: return False return level >= self.getEffectiveLevel() def setLevel(self, level): """ Set the specified level on the underlying logger. """ self.logger.setLevel(level) def getEffectiveLevel(self): """ Get the effective level for the underlying logger. """ return self.logger.getEffectiveLevel() def hasHandlers(self): """ See if the underlying logger has any handlers. """ return self.logger.hasHandlers() def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): """ Low-level log implementation, proxied to allow nested logger adapters. """ return self.logger._log( level, msg, args, exc_info=exc_info, extra=extra, stack_info=stack_info, ) @property def manager(self): return self.logger.manager @manager.setter def manager(self, value): self.logger.manager = value @property def name(self): return self.logger.name def __repr__(self): logger = self.logger level = getLevelName(logger.getEffectiveLevel()) return '<%s %s (%s)>' % (self.__class__.__name__, logger.name, level) root = RootLogger(WARNING) Logger.root = root Logger.manager = Manager(Logger.root) #--------------------------------------------------------------------------- # Configuration classes and functions #--------------------------------------------------------------------------- def basicConfig(**kwargs): """ Do basic configuration for the logging system. This function does nothing if the root logger already has handlers configured. It is a convenience method intended for use by simple scripts to do one-shot configuration of the logging package. The default behaviour is to create a StreamHandler which writes to sys.stderr, set a formatter using the BASIC_FORMAT format string, and add the handler to the root logger. A number of optional keyword arguments may be specified, which can alter the default behaviour. filename Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler. filemode Specifies the mode to open the file, if filename is specified (if filemode is unspecified, it defaults to 'a'). format Use the specified format string for the handler. datefmt Use the specified date/time format. style If a format string is specified, use this to specify the type of format string (possible values '%', '{', '$', for %-formatting, :meth:`str.format` and :class:`string.Template` - defaults to '%'). level Set the root logger level to the specified level. stream Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with 'filename' - if both are present, 'stream' is ignored. handlers If specified, this should be an iterable of already created handlers, which will be added to the root handler. Any handler in the list which does not have a formatter assigned will be assigned the formatter created in this function. Note that you could specify a stream created using open(filename, mode) rather than passing the filename and mode in. However, it should be remembered that StreamHandler does not close its stream (since it may be using sys.stdout or sys.stderr), whereas FileHandler closes its stream when the handler is closed. .. versionchanged:: 3.2 Added the ``style`` parameter. .. versionchanged:: 3.3 Added the ``handlers`` parameter. A ``ValueError`` is now thrown for incompatible arguments (e.g. ``handlers`` specified together with ``filename``/``filemode``, or ``filename``/``filemode`` specified together with ``stream``, or ``handlers`` specified together with ``stream``. """ # Add thread safety in case someone mistakenly calls # basicConfig() from multiple threads _acquireLock() try: if len(root.handlers) == 0: handlers = kwargs.pop("handlers", None) if handlers is None: if "stream" in kwargs and "filename" in kwargs: raise ValueError("'stream' and 'filename' should not be " "specified together") else: if "stream" in kwargs or "filename" in kwargs: raise ValueError("'stream' or 'filename' should not be " "specified together with 'handlers'") if handlers is None: filename = kwargs.pop("filename", None) mode = kwargs.pop("filemode", 'a') if filename: h = FileHandler(filename, mode) else: stream = kwargs.pop("stream", None) h = StreamHandler(stream) handlers = [h] dfs = kwargs.pop("datefmt", None) style = kwargs.pop("style", '%') if style not in _STYLES: raise ValueError('Style must be one of: %s' % ','.join( _STYLES.keys())) fs = kwargs.pop("format", _STYLES[style][1]) fmt = Formatter(fs, dfs, style) for h in handlers: if h.formatter is None: h.setFormatter(fmt) root.addHandler(h) level = kwargs.pop("level", None) if level is not None: root.setLevel(level) if kwargs: keys = ', '.join(kwargs.keys()) raise ValueError('Unrecognised argument(s): %s' % keys) finally: _releaseLock() #--------------------------------------------------------------------------- # Utility functions at module level. # Basically delegate everything to the root logger. #--------------------------------------------------------------------------- def getLogger(name=None): """ Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger. """ if name: return Logger.manager.getLogger(name) else: return root def critical(msg, *args, **kwargs): """ Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.critical(msg, *args, **kwargs) fatal = critical def error(msg, *args, **kwargs): """ Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.error(msg, *args, **kwargs) def exception(msg, *args, exc_info=True, **kwargs): """ Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format. """ error(msg, *args, exc_info=exc_info, **kwargs) def warning(msg, *args, **kwargs): """ Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.warning(msg, *args, **kwargs) def warn(msg, *args, **kwargs): warnings.warn("The 'warn' function is deprecated, " "use 'warning' instead", DeprecationWarning, 2) warning(msg, *args, **kwargs) def info(msg, *args, **kwargs): """ Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.info(msg, *args, **kwargs) def debug(msg, *args, **kwargs): """ Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.debug(msg, *args, **kwargs) def log(level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.log(level, msg, *args, **kwargs) def disable(level): """ Disable all logging calls of severity 'level' and below. """ root.manager.disable = level def shutdown(handlerList=_handlerList): """ Perform any cleanup actions in the logging system (e.g. flushing buffers). Should be called at application exit. """ for wr in reversed(handlerList[:]): #errors might occur, for example, if files are locked #we just ignore them if raiseExceptions is not set try: h = wr() if h: try: h.acquire() h.flush() h.close() except (OSError, ValueError): # Ignore errors which might be caused # because handlers have been closed but # references to them are still around at # application exit. pass finally: h.release() except: # ignore everything, as we're shutting down if raiseExceptions: raise #else, swallow #Let's try and shutdown automatically on application exit... import atexit atexit.register(shutdown) # Null handler class NullHandler(Handler): """ This handler does nothing. It's intended to be used to avoid the "No handlers could be found for logger XXX" one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be produced; to avoid this, the library developer simply needs to instantiate a NullHandler and add it to the top-level logger of the library module or package. """ def handle(self, record): """Stub.""" def emit(self, record): """Stub.""" def createLock(self): self.lock = None # Warnings integration _warnings_showwarning = None def _showwarning(message, category, filename, lineno, file=None, line=None): """ Implementation of showwarnings which redirects to logging, which will first check to see if the file parameter is None. If a file is specified, it will delegate to the original warnings implementation of showwarning. Otherwise, it will call warnings.formatwarning and will log the resulting string to a warnings logger named "py.warnings" with level logging.WARNING. """ if file is not None: if _warnings_showwarning is not None: _warnings_showwarning(message, category, filename, lineno, file, line) else: s = warnings.formatwarning(message, category, filename, lineno, line) logger = getLogger("py.warnings") if not logger.handlers: logger.addHandler(NullHandler()) logger.warning("%s", s) def captureWarnings(capture): """ If capture is true, redirect all warnings to the logging package. If capture is False, ensure that warnings are not redirected to logging but to their original destinations. """ global _warnings_showwarning if capture: if _warnings_showwarning is None: _warnings_showwarning = warnings.showwarning warnings.showwarning = _showwarning else: if _warnings_showwarning is not None: warnings.showwarning = _warnings_showwarning _warnings_showwarning = None
71,269
2,022
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/cellobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/cellobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" /* clang-format off */ PyObject * PyCell_New(PyObject *obj) { PyCellObject *op; op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type); if (op == NULL) return NULL; op->ob_ref = obj; Py_XINCREF(obj); _PyObject_GC_TRACK(op); return (PyObject *)op; } PyObject * PyCell_Get(PyObject *op) { if (!PyCell_Check(op)) { PyErr_BadInternalCall(); return NULL; } Py_XINCREF(((PyCellObject*)op)->ob_ref); return PyCell_GET(op); } int PyCell_Set(PyObject *op, PyObject *obj) { PyObject* oldobj; if (!PyCell_Check(op)) { PyErr_BadInternalCall(); return -1; } oldobj = PyCell_GET(op); Py_XINCREF(obj); PyCell_SET(op, obj); Py_XDECREF(oldobj); return 0; } static void cell_dealloc(PyCellObject *op) { _PyObject_GC_UNTRACK(op); Py_XDECREF(op->ob_ref); PyObject_GC_Del(op); } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) static PyObject * cell_richcompare(PyObject *a, PyObject *b, int op) { int result; PyObject *v; /* neither argument should be NULL, unless something's gone wrong */ assert(a != NULL && b != NULL); /* both arguments should be instances of PyCellObject */ if (!PyCell_Check(a) || !PyCell_Check(b)) { v = Py_NotImplemented; Py_INCREF(v); return v; } /* compare cells by contents; empty cells come before anything else */ a = ((PyCellObject *)a)->ob_ref; b = ((PyCellObject *)b)->ob_ref; if (a != NULL && b != NULL) return PyObject_RichCompare(a, b, op); result = (b == NULL) - (a == NULL); switch (op) { case Py_EQ: v = TEST_COND(result == 0); break; case Py_NE: v = TEST_COND(result != 0); break; case Py_LE: v = TEST_COND(result <= 0); break; case Py_GE: v = TEST_COND(result >= 0); break; case Py_LT: v = TEST_COND(result < 0); break; case Py_GT: v = TEST_COND(result > 0); break; default: PyErr_BadArgument(); return NULL; } Py_INCREF(v); return v; } static PyObject * cell_repr(PyCellObject *op) { if (op->ob_ref == NULL) return PyUnicode_FromFormat("<cell at %p: empty>", op); return PyUnicode_FromFormat("<cell at %p: %.80s object at %p>", op, op->ob_ref->ob_type->tp_name, op->ob_ref); } static int cell_traverse(PyCellObject *op, visitproc visit, void *arg) { Py_VISIT(op->ob_ref); return 0; } static int cell_clear(PyCellObject *op) { Py_CLEAR(op->ob_ref); return 0; } static PyObject * cell_get_contents(PyCellObject *op, void *closure) { if (op->ob_ref == NULL) { PyErr_SetString(PyExc_ValueError, "Cell is empty"); return NULL; } Py_INCREF(op->ob_ref); return op->ob_ref; } static PyGetSetDef cell_getsetlist[] = { {"cell_contents", (getter)cell_get_contents, NULL}, {NULL} /* sentinel */ }; PyTypeObject PyCell_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "cell", sizeof(PyCellObject), 0, (destructor)cell_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)cell_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)cell_traverse, /* tp_traverse */ (inquiry)cell_clear, /* tp_clear */ cell_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ cell_getsetlist, /* tp_getset */ };
5,920
189
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/capsule.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/import.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pycapsule.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" /* clang-format off */ /* Wrap void * pointers to be passed between C modules */ /* Internal structure of PyCapsule */ typedef struct { PyObject_HEAD void *pointer; const char *name; void *context; PyCapsule_Destructor destructor; } PyCapsule; static int _is_legal_capsule(PyCapsule *capsule, const char *invalid_capsule) { if (!capsule || !PyCapsule_CheckExact(capsule) || capsule->pointer == NULL) { PyErr_SetString(PyExc_ValueError, invalid_capsule); return 0; } return 1; } #define is_legal_capsule(capsule, name) \ (_is_legal_capsule(capsule, \ name " called with invalid PyCapsule object")) static int name_matches(const char *name1, const char *name2) { /* if either is NULL, */ if (!name1 || !name2) { /* they're only the same if they're both NULL. */ return name1 == name2; } return !strcmp(name1, name2); } PyObject * PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor) { PyCapsule *capsule; if (!pointer) { PyErr_SetString(PyExc_ValueError, "PyCapsule_New called with null pointer"); return NULL; } capsule = PyObject_NEW(PyCapsule, &PyCapsule_Type); if (capsule == NULL) { return NULL; } capsule->pointer = pointer; capsule->name = name; capsule->context = NULL; capsule->destructor = destructor; return (PyObject *)capsule; } int PyCapsule_IsValid(PyObject *o, const char *name) { PyCapsule *capsule = (PyCapsule *)o; return (capsule != NULL && PyCapsule_CheckExact(capsule) && capsule->pointer != NULL && name_matches(capsule->name, name)); } void * PyCapsule_GetPointer(PyObject *o, const char *name) { PyCapsule *capsule = (PyCapsule *)o; if (!is_legal_capsule(capsule, "PyCapsule_GetPointer")) { return NULL; } if (!name_matches(name, capsule->name)) { PyErr_SetString(PyExc_ValueError, "PyCapsule_GetPointer called with incorrect name"); return NULL; } return capsule->pointer; } const char * PyCapsule_GetName(PyObject *o) { PyCapsule *capsule = (PyCapsule *)o; if (!is_legal_capsule(capsule, "PyCapsule_GetName")) { return NULL; } return capsule->name; } PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *o) { PyCapsule *capsule = (PyCapsule *)o; if (!is_legal_capsule(capsule, "PyCapsule_GetDestructor")) { return NULL; } return capsule->destructor; } void * PyCapsule_GetContext(PyObject *o) { PyCapsule *capsule = (PyCapsule *)o; if (!is_legal_capsule(capsule, "PyCapsule_GetContext")) { return NULL; } return capsule->context; } int PyCapsule_SetPointer(PyObject *o, void *pointer) { PyCapsule *capsule = (PyCapsule *)o; if (!pointer) { PyErr_SetString(PyExc_ValueError, "PyCapsule_SetPointer called with null pointer"); return -1; } if (!is_legal_capsule(capsule, "PyCapsule_SetPointer")) { return -1; } capsule->pointer = pointer; return 0; } int PyCapsule_SetName(PyObject *o, const char *name) { PyCapsule *capsule = (PyCapsule *)o; if (!is_legal_capsule(capsule, "PyCapsule_SetName")) { return -1; } capsule->name = name; return 0; } int PyCapsule_SetDestructor(PyObject *o, PyCapsule_Destructor destructor) { PyCapsule *capsule = (PyCapsule *)o; if (!is_legal_capsule(capsule, "PyCapsule_SetDestructor")) { return -1; } capsule->destructor = destructor; return 0; } int PyCapsule_SetContext(PyObject *o, void *context) { PyCapsule *capsule = (PyCapsule *)o; if (!is_legal_capsule(capsule, "PyCapsule_SetContext")) { return -1; } capsule->context = context; return 0; } void * PyCapsule_Import(const char *name, int no_block) { PyObject *object = NULL; void *return_value = NULL; char *trace; size_t name_length = (strlen(name) + 1) * sizeof(char); char *name_dup = (char *)PyMem_MALLOC(name_length); if (!name_dup) { return PyErr_NoMemory(); } memcpy(name_dup, name, name_length); trace = name_dup; while (trace) { char *dot = strchr(trace, '.'); if (dot) { *dot++ = '\0'; } if (object == NULL) { if (no_block) { object = PyImport_ImportModuleNoBlock(trace); } else { object = PyImport_ImportModule(trace); if (!object) { PyErr_Format(PyExc_ImportError, "PyCapsule_Import could not import module \"%s\"", trace); } } } else { PyObject *object2 = PyObject_GetAttrString(object, trace); Py_DECREF(object); object = object2; } if (!object) { goto EXIT; } trace = dot; } /* compare attribute name to module.name by hand */ if (PyCapsule_IsValid(object, name)) { PyCapsule *capsule = (PyCapsule *)object; return_value = capsule->pointer; } else { PyErr_Format(PyExc_AttributeError, "PyCapsule_Import \"%s\" is not valid", name); } EXIT: Py_XDECREF(object); if (name_dup) { PyMem_FREE(name_dup); } return return_value; } static void capsule_dealloc(PyObject *o) { PyCapsule *capsule = (PyCapsule *)o; if (capsule->destructor) { capsule->destructor(o); } PyObject_DEL(o); } static PyObject * capsule_repr(PyObject *o) { PyCapsule *capsule = (PyCapsule *)o; const char *name; const char *quote; if (capsule->name) { quote = "\""; name = capsule->name; } else { quote = ""; name = "NULL"; } return PyUnicode_FromFormat("<capsule object %s%s%s at %p>", quote, name, quote, capsule); } PyDoc_STRVAR(PyCapsule_Type__doc__, "Capsule objects let you wrap a C \"void *\" pointer in a Python\n\ object. They're a way of passing data through the Python interpreter\n\ without creating your own custom type.\n\ \n\ Capsules are used for communication between extension modules.\n\ They provide a way for an extension module to export a C interface\n\ to other extension modules, so that extension modules can use the\n\ Python import mechanism to link to one another.\n\ "); PyTypeObject PyCapsule_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "PyCapsule", /*tp_name*/ sizeof(PyCapsule), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ capsule_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ capsule_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ 0, /*tp_flags*/ PyCapsule_Type__doc__ /*tp_doc*/ };
8,541
337
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/sliceobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ /* Written by Jim Hugunin and Chris Chase. This includes both the singular ellipsis object and slice objects. Guido, feel free to do whatever you want in the way of copyrights for this file. */ /* Py_Ellipsis encodes the '...' rubber index token. It is similar to the Py_NoneStruct in that there is no way to create other objects of this type and there is exactly one in existence. */ static PyObject * ellipsis_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) { PyErr_SetString(PyExc_TypeError, "EllipsisType takes no arguments"); return NULL; } Py_INCREF(Py_Ellipsis); return Py_Ellipsis; } static PyObject * ellipsis_repr(PyObject *op) { return PyUnicode_FromString("Ellipsis"); } static PyObject * ellipsis_reduce(PyObject *op) { return PyUnicode_FromString("Ellipsis"); } static PyMethodDef ellipsis_methods[] = { {"__reduce__", (PyCFunction)ellipsis_reduce, METH_NOARGS, NULL}, {NULL, NULL} }; PyTypeObject PyEllipsis_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "ellipsis", /* tp_name */ 0, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /*never called*/ /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ ellipsis_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ellipsis_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ ellipsis_new, /* tp_new */ }; PyObject _Py_EllipsisObject = { _PyObject_EXTRA_INIT 1, &PyEllipsis_Type }; /* Slice object implementation */ /* Using a cache is very effective since typically only a single slice is * created and then deleted again */ static PySliceObject *slice_cache = NULL; void PySlice_Fini(void) { PySliceObject *obj = slice_cache; if (obj != NULL) { slice_cache = NULL; PyObject_GC_Del(obj); } } /* start, stop, and step are python objects with None indicating no index is present. */ PyObject * PySlice_New(PyObject *start, PyObject *stop, PyObject *step) { PySliceObject *obj; if (slice_cache != NULL) { obj = slice_cache; slice_cache = NULL; _Py_NewReference((PyObject *)obj); } else { obj = PyObject_GC_New(PySliceObject, &PySlice_Type); if (obj == NULL) return NULL; } if (step == NULL) step = Py_None; Py_INCREF(step); if (start == NULL) start = Py_None; Py_INCREF(start); if (stop == NULL) stop = Py_None; Py_INCREF(stop); obj->step = step; obj->start = start; obj->stop = stop; _PyObject_GC_TRACK(obj); return (PyObject *) obj; } PyObject * _PySlice_FromIndices(Py_ssize_t istart, Py_ssize_t istop) { PyObject *start, *end, *slice; start = PyLong_FromSsize_t(istart); if (!start) return NULL; end = PyLong_FromSsize_t(istop); if (!end) { Py_DECREF(start); return NULL; } slice = PySlice_New(start, end, NULL); Py_DECREF(start); Py_DECREF(end); return slice; } int PySlice_GetIndices(PyObject *_r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) { PySliceObject *r = (PySliceObject*)_r; /* XXX support long ints */ if (r->step == Py_None) { *step = 1; } else { if (!PyLong_Check(r->step)) return -1; *step = PyLong_AsSsize_t(r->step); } if (r->start == Py_None) { *start = *step < 0 ? length-1 : 0; } else { if (!PyLong_Check(r->start)) return -1; *start = PyLong_AsSsize_t(r->start); if (*start < 0) *start += length; } if (r->stop == Py_None) { *stop = *step < 0 ? -1 : length; } else { if (!PyLong_Check(r->stop)) return -1; *stop = PyLong_AsSsize_t(r->stop); if (*stop < 0) *stop += length; } if (*stop > length) return -1; if (*start >= length) return -1; if (*step == 0) return -1; return 0; } int PySlice_Unpack(PyObject *_r, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step) { PySliceObject *r = (PySliceObject*)_r; /* this is harder to get right than you might think */ Py_BUILD_ASSERT(PY_SSIZE_T_MIN + 1 <= -PY_SSIZE_T_MAX); if (r->step == Py_None) { *step = 1; } else { if (!_PyEval_SliceIndex(r->step, step)) return -1; if (*step == 0) { PyErr_SetString(PyExc_ValueError, "slice step cannot be zero"); return -1; } /* Here *step might be -PY_SSIZE_T_MAX-1; in this case we replace it * with -PY_SSIZE_T_MAX. This doesn't affect the semantics, and it * guards against later undefined behaviour resulting from code that * does "step = -step" as part of a slice reversal. */ if (*step < -PY_SSIZE_T_MAX) *step = -PY_SSIZE_T_MAX; } if (r->start == Py_None) { *start = *step < 0 ? PY_SSIZE_T_MAX : 0; } else { if (!_PyEval_SliceIndex(r->start, start)) return -1; } if (r->stop == Py_None) { *stop = *step < 0 ? PY_SSIZE_T_MIN : PY_SSIZE_T_MAX; } else { if (!_PyEval_SliceIndex(r->stop, stop)) return -1; } return 0; } Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step) { /* this is harder to get right than you might think */ assert(step != 0); assert(step >= -PY_SSIZE_T_MAX); if (*start < 0) { *start += length; if (*start < 0) { *start = (step < 0) ? -1 : 0; } } else if (*start >= length) { *start = (step < 0) ? length - 1 : length; } if (*stop < 0) { *stop += length; if (*stop < 0) { *stop = (step < 0) ? -1 : 0; } } else if (*stop >= length) { *stop = (step < 0) ? length - 1 : length; } if (step < 0) { if (*stop < *start) { return (*start - *stop - 1) / (-step) + 1; } } else { if (*start < *stop) { return (*stop - *start - 1) / step + 1; } } return 0; } #undef PySlice_GetIndicesEx int PySlice_GetIndicesEx(PyObject *_r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength) { if (PySlice_Unpack(_r, start, stop, step) < 0) return -1; *slicelength = PySlice_AdjustIndices(length, start, stop, *step); return 0; } static PyObject * slice_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *start, *stop, *step; start = stop = step = NULL; if (!_PyArg_NoKeywords("slice()", kw)) return NULL; if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step)) return NULL; /* This swapping of stop and start is to maintain similarity with range(). */ if (stop == NULL) { stop = start; start = NULL; } return PySlice_New(start, stop, step); } PyDoc_STRVAR(slice_doc, "slice(stop)\n\ slice(start, stop[, step])\n\ \n\ Create a slice object. This is used for extended slicing (e.g. a[0:10:2])."); static void slice_dealloc(PySliceObject *r) { _PyObject_GC_UNTRACK(r); Py_DECREF(r->step); Py_DECREF(r->start); Py_DECREF(r->stop); if (slice_cache == NULL) slice_cache = r; else PyObject_GC_Del(r); } static PyObject * slice_repr(PySliceObject *r) { return PyUnicode_FromFormat("slice(%R, %R, %R)", r->start, r->stop, r->step); } static PyMemberDef slice_members[] = { {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY}, {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY}, {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY}, {0} }; /* Helper function to convert a slice argument to a PyLong, and raise TypeError with a suitable message on failure. */ static PyObject* evaluate_slice_index(PyObject *v) { if (PyIndex_Check(v)) { return PyNumber_Index(v); } else { PyErr_SetString(PyExc_TypeError, "slice indices must be integers or " "None or have an __index__ method"); return NULL; } } /* Compute slice indices given a slice and length. Return -1 on failure. Used by slice.indices and rangeobject slicing. Assumes that `len` is a nonnegative instance of PyLong. */ int _PySlice_GetLongIndices(PySliceObject *self, PyObject *length, PyObject **start_ptr, PyObject **stop_ptr, PyObject **step_ptr) { PyObject *start=NULL, *stop=NULL, *step=NULL; PyObject *upper=NULL, *lower=NULL; int step_is_negative, cmp_result; /* Convert step to an integer; raise for zero step. */ if (self->step == Py_None) { step = PyLong_FromLong(1L); if (step == NULL) goto error; step_is_negative = 0; } else { int step_sign; step = evaluate_slice_index(self->step); if (step == NULL) goto error; step_sign = _PyLong_Sign(step); if (step_sign == 0) { PyErr_SetString(PyExc_ValueError, "slice step cannot be zero"); goto error; } step_is_negative = step_sign < 0; } /* Find lower and upper bounds for start and stop. */ if (step_is_negative) { lower = PyLong_FromLong(-1L); if (lower == NULL) goto error; upper = PyNumber_Add(length, lower); if (upper == NULL) goto error; } else { lower = PyLong_FromLong(0L); if (lower == NULL) goto error; upper = length; Py_INCREF(upper); } /* Compute start. */ if (self->start == Py_None) { start = step_is_negative ? upper : lower; Py_INCREF(start); } else { start = evaluate_slice_index(self->start); if (start == NULL) goto error; if (_PyLong_Sign(start) < 0) { /* start += length */ PyObject *tmp = PyNumber_Add(start, length); Py_DECREF(start); start = tmp; if (start == NULL) goto error; cmp_result = PyObject_RichCompareBool(start, lower, Py_LT); if (cmp_result < 0) goto error; if (cmp_result) { Py_INCREF(lower); Py_DECREF(start); start = lower; } } else { cmp_result = PyObject_RichCompareBool(start, upper, Py_GT); if (cmp_result < 0) goto error; if (cmp_result) { Py_INCREF(upper); Py_DECREF(start); start = upper; } } } /* Compute stop. */ if (self->stop == Py_None) { stop = step_is_negative ? lower : upper; Py_INCREF(stop); } else { stop = evaluate_slice_index(self->stop); if (stop == NULL) goto error; if (_PyLong_Sign(stop) < 0) { /* stop += length */ PyObject *tmp = PyNumber_Add(stop, length); Py_DECREF(stop); stop = tmp; if (stop == NULL) goto error; cmp_result = PyObject_RichCompareBool(stop, lower, Py_LT); if (cmp_result < 0) goto error; if (cmp_result) { Py_INCREF(lower); Py_DECREF(stop); stop = lower; } } else { cmp_result = PyObject_RichCompareBool(stop, upper, Py_GT); if (cmp_result < 0) goto error; if (cmp_result) { Py_INCREF(upper); Py_DECREF(stop); stop = upper; } } } *start_ptr = start; *stop_ptr = stop; *step_ptr = step; Py_DECREF(upper); Py_DECREF(lower); return 0; error: *start_ptr = *stop_ptr = *step_ptr = NULL; Py_XDECREF(start); Py_XDECREF(stop); Py_XDECREF(step); Py_XDECREF(upper); Py_XDECREF(lower); return -1; } /* Implementation of slice.indices. */ static PyObject* slice_indices(PySliceObject* self, PyObject* len) { PyObject *start, *stop, *step; PyObject *length; int error; /* Convert length to an integer if necessary; raise for negative length. */ length = PyNumber_Index(len); if (length == NULL) return NULL; if (_PyLong_Sign(length) < 0) { PyErr_SetString(PyExc_ValueError, "length should not be negative"); Py_DECREF(length); return NULL; } error = _PySlice_GetLongIndices(self, length, &start, &stop, &step); Py_DECREF(length); if (error == -1) return NULL; else return Py_BuildValue("(NNN)", start, stop, step); } PyDoc_STRVAR(slice_indices_doc, "S.indices(len) -> (start, stop, stride)\n\ \n\ Assuming a sequence of length len, calculate the start and stop\n\ indices, and the stride length of the extended slice described by\n\ S. Out of bounds indices are clipped in a manner consistent with the\n\ handling of normal slices."); static PyObject * slice_reduce(PySliceObject* self) { return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef slice_methods[] = { {"indices", (PyCFunction)slice_indices, METH_O, slice_indices_doc}, {"__reduce__", (PyCFunction)slice_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} }; static PyObject * slice_richcompare(PyObject *v, PyObject *w, int op) { PyObject *t1; PyObject *t2; PyObject *res; if (!PySlice_Check(v) || !PySlice_Check(w)) Py_RETURN_NOTIMPLEMENTED; if (v == w) { /* XXX Do we really need this shortcut? There's a unit test for it, but is that fair? */ switch (op) { case Py_EQ: case Py_LE: case Py_GE: res = Py_True; break; default: res = Py_False; break; } Py_INCREF(res); return res; } t1 = PyTuple_New(3); if (t1 == NULL) return NULL; t2 = PyTuple_New(3); if (t2 == NULL) { Py_DECREF(t1); return NULL; } PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step); PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start); PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop); PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step); res = PyObject_RichCompare(t1, t2, op); PyTuple_SET_ITEM(t1, 0, NULL); PyTuple_SET_ITEM(t1, 1, NULL); PyTuple_SET_ITEM(t1, 2, NULL); PyTuple_SET_ITEM(t2, 0, NULL); PyTuple_SET_ITEM(t2, 1, NULL); PyTuple_SET_ITEM(t2, 2, NULL); Py_DECREF(t1); Py_DECREF(t2); return res; } static int slice_traverse(PySliceObject *v, visitproc visit, void *arg) { Py_VISIT(v->start); Py_VISIT(v->stop); Py_VISIT(v->step); return 0; } PyTypeObject PySlice_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "slice", /* Name of this type */ sizeof(PySliceObject), /* Basic object size */ 0, /* Item size for varobject */ (destructor)slice_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)slice_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ PyObject_HashNotImplemented, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ slice_doc, /* tp_doc */ (traverseproc)slice_traverse, /* tp_traverse */ 0, /* tp_clear */ slice_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ slice_methods, /* tp_methods */ slice_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ slice_new, /* tp_new */ };
21,135
690
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/typeslots.py
#!/usr/bin/python # Usage: typeslots.py < Include/typeslots.h typeslots.inc import sys, re def generate_typeslots(out=sys.stdout): out.write("/* Generated by typeslots.py */\n") res = {} for line in sys.stdin: m = re.match("#define Py_([a-z_]+) ([0-9]+)", line) if not m: continue member = m.group(1) if member.startswith("tp_"): member = "ht_type."+member elif member.startswith("am_"): member = "as_async."+member elif member.startswith("nb_"): member = "as_number."+member elif member.startswith("mp_"): member = "as_mapping."+member elif member.startswith("sq_"): member = "as_sequence."+member elif member.startswith("bf_"): member = "as_buffer."+member res[int(m.group(2))] = member M = max(res.keys())+1 for i in range(1,M): if i in res: out.write("offsetof(PyHeapTypeObject, %s),\n" % res[i]) else: out.write("0,\n") def main(): if len(sys.argv) == 2: with open(sys.argv[1], "w") as f: generate_typeslots(f) else: generate_typeslots() if __name__ == "__main__": main()
1,246
44
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/structseq.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/structseq.h" /* clang-format off */ /* Implementation helper: a struct that looks like a tuple. See timemodule and posixmodule for example uses. */ static const char visible_length_key[] = "n_sequence_fields"; static const char real_length_key[] = "n_fields"; static const char unnamed_fields_key[] = "n_unnamed_fields"; /* Fields with this name have only a field index, not a field name. They are only allowed for indices < n_visible_fields. */ char *PyStructSequence_UnnamedField = "unnamed field"; _Py_IDENTIFIER(n_sequence_fields); _Py_IDENTIFIER(n_fields); _Py_IDENTIFIER(n_unnamed_fields); #define VISIBLE_SIZE(op) Py_SIZE(op) #define VISIBLE_SIZE_TP(tp) PyLong_AsSsize_t( \ _PyDict_GetItemId((tp)->tp_dict, &PyId_n_sequence_fields)) #define REAL_SIZE_TP(tp) PyLong_AsSsize_t( \ _PyDict_GetItemId((tp)->tp_dict, &PyId_n_fields)) #define REAL_SIZE(op) REAL_SIZE_TP(Py_TYPE(op)) #define UNNAMED_FIELDS_TP(tp) PyLong_AsSsize_t( \ _PyDict_GetItemId((tp)->tp_dict, &PyId_n_unnamed_fields)) #define UNNAMED_FIELDS(op) UNNAMED_FIELDS_TP(Py_TYPE(op)) PyObject * PyStructSequence_New(PyTypeObject *type) { PyStructSequence *obj; Py_ssize_t size = REAL_SIZE_TP(type), i; obj = PyObject_GC_NewVar(PyStructSequence, type, size); if (obj == NULL) return NULL; /* Hack the size of the variable object, so invisible fields don't appear to Python code. */ Py_SIZE(obj) = VISIBLE_SIZE_TP(type); for (i = 0; i < size; i++) obj->ob_item[i] = NULL; return (PyObject*)obj; } void PyStructSequence_SetItem(PyObject* op, Py_ssize_t i, PyObject* v) { PyStructSequence_SET_ITEM(op, i, v); } PyObject* PyStructSequence_GetItem(PyObject* op, Py_ssize_t i) { return PyStructSequence_GET_ITEM(op, i); } static void structseq_dealloc(PyStructSequence *obj) { Py_ssize_t i, size; size = REAL_SIZE(obj); for (i = 0; i < size; ++i) { Py_XDECREF(obj->ob_item[i]); } PyObject_GC_Del(obj); } static PyObject * structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg = NULL; PyObject *dict = NULL; PyObject *ob; PyStructSequence *res = NULL; Py_ssize_t len, min_len, max_len, i, n_unnamed_fields; static char *kwlist[] = {"sequence", "dict", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", kwlist, &arg, &dict)) return NULL; arg = PySequence_Fast(arg, "constructor requires a sequence"); if (!arg) { return NULL; } if (dict && !PyDict_Check(dict)) { PyErr_Format(PyExc_TypeError, "%.500s() takes a dict as second arg, if any", type->tp_name); Py_DECREF(arg); return NULL; } len = PySequence_Fast_GET_SIZE(arg); min_len = VISIBLE_SIZE_TP(type); max_len = REAL_SIZE_TP(type); n_unnamed_fields = UNNAMED_FIELDS_TP(type); if (min_len != max_len) { if (len < min_len) { PyErr_Format(PyExc_TypeError, "%.500s() takes an at least %zd-sequence (%zd-sequence given)", type->tp_name, min_len, len); Py_DECREF(arg); return NULL; } if (len > max_len) { PyErr_Format(PyExc_TypeError, "%.500s() takes an at most %zd-sequence (%zd-sequence given)", type->tp_name, max_len, len); Py_DECREF(arg); return NULL; } } else { if (len != min_len) { PyErr_Format(PyExc_TypeError, "%.500s() takes a %zd-sequence (%zd-sequence given)", type->tp_name, min_len, len); Py_DECREF(arg); return NULL; } } res = (PyStructSequence*) PyStructSequence_New(type); if (res == NULL) { Py_DECREF(arg); return NULL; } for (i = 0; i < len; ++i) { PyObject *v = PySequence_Fast_GET_ITEM(arg, i); Py_INCREF(v); res->ob_item[i] = v; } for (; i < max_len; ++i) { if (dict && (ob = PyDict_GetItemString( dict, type->tp_members[i-n_unnamed_fields].name))) { } else { ob = Py_None; } Py_INCREF(ob); res->ob_item[i] = ob; } Py_DECREF(arg); return (PyObject*) res; } static PyObject * structseq_repr(PyStructSequence *obj) { /* buffer and type size were chosen well considered. */ #define REPR_BUFFER_SIZE 512 #define TYPE_MAXSIZE 100 PyTypeObject *typ = Py_TYPE(obj); Py_ssize_t i; int removelast = 0; Py_ssize_t len; char buf[REPR_BUFFER_SIZE]; char *endofbuf, *pbuf = buf; /* pointer to end of writeable buffer; safes space for "...)\0" */ endofbuf= &buf[REPR_BUFFER_SIZE-5]; /* "typename(", limited to TYPE_MAXSIZE */ len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE : strlen(typ->tp_name); strncpy(pbuf, typ->tp_name, len); pbuf += len; *pbuf++ = '('; for (i=0; i < VISIBLE_SIZE(obj); i++) { PyObject *val, *repr; char *cname, *crepr; cname = typ->tp_members[i].name; if (cname == NULL) { PyErr_Format(PyExc_SystemError, "In structseq_repr(), member %d name is NULL" " for type %.500s", i, typ->tp_name); return NULL; } val = PyStructSequence_GET_ITEM(obj, i); repr = PyObject_Repr(val); if (repr == NULL) return NULL; crepr = PyUnicode_AsUTF8(repr); if (crepr == NULL) { Py_DECREF(repr); return NULL; } /* + 3: keep space for "=" and ", " */ len = strlen(cname) + strlen(crepr) + 3; if ((pbuf+len) <= endofbuf) { strcpy(pbuf, cname); pbuf += strlen(cname); *pbuf++ = '='; strcpy(pbuf, crepr); pbuf += strlen(crepr); *pbuf++ = ','; *pbuf++ = ' '; removelast = 1; Py_DECREF(repr); } else { strcpy(pbuf, "..."); pbuf += 3; removelast = 0; Py_DECREF(repr); break; } } if (removelast) { /* overwrite last ", " */ pbuf-=2; } *pbuf++ = ')'; *pbuf = '\0'; return PyUnicode_FromString(buf); } static PyObject * structseq_reduce(PyStructSequence* self) { PyObject* tup = NULL; PyObject* dict = NULL; PyObject* result; Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields, i; n_fields = REAL_SIZE(self); n_visible_fields = VISIBLE_SIZE(self); n_unnamed_fields = UNNAMED_FIELDS(self); tup = PyTuple_New(n_visible_fields); if (!tup) goto error; dict = PyDict_New(); if (!dict) goto error; for (i = 0; i < n_visible_fields; i++) { Py_INCREF(self->ob_item[i]); PyTuple_SET_ITEM(tup, i, self->ob_item[i]); } for (; i < n_fields; i++) { char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name; if (PyDict_SetItemString(dict, n, self->ob_item[i]) < 0) goto error; } result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict); Py_DECREF(tup); Py_DECREF(dict); return result; error: Py_XDECREF(tup); Py_XDECREF(dict); return NULL; } static PyMethodDef structseq_methods[] = { {"__reduce__", (PyCFunction)structseq_reduce, METH_NOARGS, NULL}, {NULL, NULL} }; static PyTypeObject _struct_sequence_template = { PyVarObject_HEAD_INIT(&PyType_Type, 0) NULL, /* tp_name */ sizeof(PyStructSequence) - sizeof(PyObject *), /* tp_basicsize */ sizeof(PyObject *), /* tp_itemsize */ (destructor)structseq_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)structseq_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ NULL, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ structseq_methods, /* tp_methods */ NULL, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ structseq_new, /* tp_new */ }; int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc) { PyObject *dict; PyMemberDef* members; Py_ssize_t n_members, n_unnamed_members, i, k; PyObject *v; #ifdef Py_TRACE_REFS /* if the type object was chained, unchain it first before overwriting its storage */ if (type->ob_base.ob_base._ob_next) { _Py_ForgetReference((PyObject*)type); } #endif n_unnamed_members = 0; for (i = 0; desc->fields[i].name != NULL; ++i) if (desc->fields[i].name == PyStructSequence_UnnamedField) n_unnamed_members++; n_members = i; memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject)); type->tp_base = &PyTuple_Type; type->tp_name = desc->name; type->tp_doc = desc->doc; members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1); if (members == NULL) { PyErr_NoMemory(); return -1; } for (i = k = 0; i < n_members; ++i) { if (desc->fields[i].name == PyStructSequence_UnnamedField) continue; members[k].name = desc->fields[i].name; members[k].type = T_OBJECT; members[k].offset = offsetof(PyStructSequence, ob_item) + i * sizeof(PyObject*); members[k].flags = READONLY; members[k].doc = desc->fields[i].doc; k++; } members[k].name = NULL; type->tp_members = members; if (PyType_Ready(type) < 0) return -1; Py_INCREF(type); dict = type->tp_dict; #define SET_DICT_FROM_SIZE(key, value) \ do { \ v = PyLong_FromSsize_t(value); \ if (v == NULL) \ return -1; \ if (PyDict_SetItemString(dict, key, v) < 0) { \ Py_DECREF(v); \ return -1; \ } \ Py_DECREF(v); \ } while (0) SET_DICT_FROM_SIZE(visible_length_key, desc->n_in_sequence); SET_DICT_FROM_SIZE(real_length_key, n_members); SET_DICT_FROM_SIZE(unnamed_fields_key, n_unnamed_members); return 0; } void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc) { (void)PyStructSequence_InitType2(type, desc); } PyTypeObject* PyStructSequence_NewType(PyStructSequence_Desc *desc) { PyTypeObject *result; result = (PyTypeObject*)PyType_GenericAlloc(&PyType_Type, 0); if (result == NULL) return NULL; if (PyStructSequence_InitType2(result, desc) < 0) { Py_DECREF(result); return NULL; } return result; } int _PyStructSequence_Init(void) { if (_PyUnicode_FromId(&PyId_n_sequence_fields) == NULL || _PyUnicode_FromId(&PyId_n_fields) == NULL || _PyUnicode_FromId(&PyId_n_unnamed_fields) == NULL) return -1; return 0; }
14,374
437
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/funcobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/cellobject.h" #include "third_party/python/Include/classobject.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/eval.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ PyObject * PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname) { PyFunctionObject *op; PyObject *doc, *consts, *module; static PyObject *__name__ = NULL; if (__name__ == NULL) { __name__ = PyUnicode_InternFromString("__name__"); if (__name__ == NULL) return NULL; } op = PyObject_GC_New(PyFunctionObject, &PyFunction_Type); if (op == NULL) return NULL; op->func_weakreflist = NULL; Py_INCREF(code); op->func_code = code; Py_INCREF(globals); op->func_globals = globals; op->func_name = ((PyCodeObject *)code)->co_name; Py_INCREF(op->func_name); op->func_defaults = NULL; /* No default arguments */ op->func_kwdefaults = NULL; /* No keyword only defaults */ op->func_closure = NULL; consts = ((PyCodeObject *)code)->co_consts; if (PyTuple_Size(consts) >= 1) { doc = PyTuple_GetItem(consts, 0); if (!PyUnicode_Check(doc)) doc = Py_None; } else doc = Py_None; Py_INCREF(doc); op->func_doc = doc; op->func_dict = NULL; op->func_module = NULL; op->func_annotations = NULL; /* __module__: If module name is in globals, use it. Otherwise, use None. */ module = PyDict_GetItem(globals, __name__); if (module) { Py_INCREF(module); op->func_module = module; } if (qualname) op->func_qualname = qualname; else op->func_qualname = op->func_name; Py_INCREF(op->func_qualname); _PyObject_GC_TRACK(op); return (PyObject *)op; } PyObject * PyFunction_New(PyObject *code, PyObject *globals) { return PyFunction_NewWithQualName(code, globals, NULL); } PyObject * PyFunction_GetCode(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_code; } PyObject * PyFunction_GetGlobals(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_globals; } PyObject * PyFunction_GetModule(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_module; } PyObject * PyFunction_GetDefaults(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_defaults; } int PyFunction_SetDefaults(PyObject *op, PyObject *defaults) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (defaults == Py_None) defaults = NULL; else if (defaults && PyTuple_Check(defaults)) { Py_INCREF(defaults); } else { PyErr_SetString(PyExc_SystemError, "non-tuple default args"); return -1; } Py_XSETREF(((PyFunctionObject *)op)->func_defaults, defaults); return 0; } PyObject * PyFunction_GetKwDefaults(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_kwdefaults; } int PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (defaults == Py_None) defaults = NULL; else if (defaults && PyDict_Check(defaults)) { Py_INCREF(defaults); } else { PyErr_SetString(PyExc_SystemError, "non-dict keyword only default args"); return -1; } Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults); return 0; } PyObject * PyFunction_GetClosure(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_closure; } int PyFunction_SetClosure(PyObject *op, PyObject *closure) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (closure == Py_None) closure = NULL; else if (PyTuple_Check(closure)) { Py_INCREF(closure); } else { PyErr_Format(PyExc_SystemError, "expected tuple for closure, got '%.100s'", closure->ob_type->tp_name); return -1; } Py_XSETREF(((PyFunctionObject *)op)->func_closure, closure); return 0; } PyObject * PyFunction_GetAnnotations(PyObject *op) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return ((PyFunctionObject *) op) -> func_annotations; } int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations) { if (!PyFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } if (annotations == Py_None) annotations = NULL; else if (annotations && PyDict_Check(annotations)) { Py_INCREF(annotations); } else { PyErr_SetString(PyExc_SystemError, "non-dict annotations"); return -1; } Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations); return 0; } /* Methods */ #define OFF(x) offsetof(PyFunctionObject, x) static PyMemberDef func_memberlist[] = { {"__closure__", T_OBJECT, OFF(func_closure), RESTRICTED|READONLY}, {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED}, {"__globals__", T_OBJECT, OFF(func_globals), RESTRICTED|READONLY}, {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED}, {NULL} /* Sentinel */ }; static PyObject * func_get_code(PyFunctionObject *op, void *Py_UNUSED(ignored)) { Py_INCREF(op->func_code); return op->func_code; } static int func_set_code(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { Py_ssize_t nfree, nclosure; /* Not legal to del f.func_code or to set it to anything * other than a code object. */ if (value == NULL || !PyCode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__code__ must be set to a code object"); return -1; } nfree = PyCode_GetNumFree((PyCodeObject *)value); nclosure = (op->func_closure == NULL ? 0 : PyTuple_GET_SIZE(op->func_closure)); if (nclosure != nfree) { PyErr_Format(PyExc_ValueError, "%U() requires a code object with %zd free vars," " not %zd", op->func_name, nclosure, nfree); return -1; } Py_INCREF(value); Py_XSETREF(op->func_code, value); return 0; } static PyObject * func_get_name(PyFunctionObject *op, void *Py_UNUSED(ignored)) { Py_INCREF(op->func_name); return op->func_name; } static int func_set_name(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { /* Not legal to del f.func_name or to set it to anything * other than a string object. */ if (value == NULL || !PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } Py_INCREF(value); Py_XSETREF(op->func_name, value); return 0; } static PyObject * func_get_qualname(PyFunctionObject *op, void *Py_UNUSED(ignored)) { Py_INCREF(op->func_qualname); return op->func_qualname; } static int func_set_qualname(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { /* Not legal to del f.__qualname__ or to set it to anything * other than a string object. */ if (value == NULL || !PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } Py_INCREF(value); Py_XSETREF(op->func_qualname, value); return 0; } static PyObject * func_get_defaults(PyFunctionObject *op, void *Py_UNUSED(ignored)) { if (op->func_defaults == NULL) { Py_INCREF(Py_None); return Py_None; } Py_INCREF(op->func_defaults); return op->func_defaults; } static int func_set_defaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { /* Legal to del f.func_defaults. * Can only set func_defaults to NULL or a tuple. */ if (value == Py_None) value = NULL; if (value != NULL && !PyTuple_Check(value)) { PyErr_SetString(PyExc_TypeError, "__defaults__ must be set to a tuple object"); return -1; } Py_XINCREF(value); Py_XSETREF(op->func_defaults, value); return 0; } static PyObject * func_get_kwdefaults(PyFunctionObject *op, void *Py_UNUSED(ignored)) { if (op->func_kwdefaults == NULL) { Py_INCREF(Py_None); return Py_None; } Py_INCREF(op->func_kwdefaults); return op->func_kwdefaults; } static int func_set_kwdefaults(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { if (value == Py_None) value = NULL; /* Legal to del f.func_kwdefaults. * Can only set func_kwdefaults to NULL or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__kwdefaults__ must be set to a dict object"); return -1; } Py_XINCREF(value); Py_XSETREF(op->func_kwdefaults, value); return 0; } static PyObject * func_get_annotations(PyFunctionObject *op, void *Py_UNUSED(ignored)) { if (op->func_annotations == NULL) { op->func_annotations = PyDict_New(); if (op->func_annotations == NULL) return NULL; } Py_INCREF(op->func_annotations); return op->func_annotations; } static int func_set_annotations(PyFunctionObject *op, PyObject *value, void *Py_UNUSED(ignored)) { if (value == Py_None) value = NULL; /* Legal to del f.func_annotations. * Can only set func_annotations to NULL (through C api) * or a dict. */ if (value != NULL && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__annotations__ must be set to a dict object"); return -1; } Py_XINCREF(value); Py_XSETREF(op->func_annotations, value); return 0; } static PyGetSetDef func_getsetlist[] = { {"__code__", (getter)func_get_code, (setter)func_set_code}, {"__defaults__", (getter)func_get_defaults, (setter)func_set_defaults}, {"__kwdefaults__", (getter)func_get_kwdefaults, (setter)func_set_kwdefaults}, {"__annotations__", (getter)func_get_annotations, (setter)func_set_annotations}, {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, {"__name__", (getter)func_get_name, (setter)func_set_name}, {"__qualname__", (getter)func_get_qualname, (setter)func_set_qualname}, {NULL} /* Sentinel */ }; PyDoc_STRVAR(func_doc, "function(code, globals[, name[, argdefs[, closure]]])\n\ \n\ Create a function object from a code object and a dictionary.\n\ The optional name string overrides the name from the code object.\n\ The optional argdefs tuple specifies the default argument values.\n\ The optional closure tuple supplies the bindings for free variables."); /* func_new() maintains the following invariants for closures. The closure must correspond to the free variables of the code object. if len(code.co_freevars) == 0: closure = NULL else: len(closure) == len(code.co_freevars) for every elt in closure, type(elt) == cell */ static PyObject * func_new(PyTypeObject* type, PyObject* args, PyObject* kw) { PyCodeObject *code; PyObject *globals; PyObject *name = Py_None; PyObject *defaults = Py_None; PyObject *closure = Py_None; PyFunctionObject *newfunc; Py_ssize_t nfree, nclosure; static char *kwlist[] = {"code", "globals", "name", "argdefs", "closure", 0}; if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function", kwlist, &PyCode_Type, &code, &PyDict_Type, &globals, &name, &defaults, &closure)) return NULL; if (name != Py_None && !PyUnicode_Check(name)) { PyErr_SetString(PyExc_TypeError, "arg 3 (name) must be None or string"); return NULL; } if (defaults != Py_None && !PyTuple_Check(defaults)) { PyErr_SetString(PyExc_TypeError, "arg 4 (defaults) must be None or tuple"); return NULL; } nfree = PyTuple_GET_SIZE(code->co_freevars); if (!PyTuple_Check(closure)) { if (nfree && closure == Py_None) { PyErr_SetString(PyExc_TypeError, "arg 5 (closure) must be tuple"); return NULL; } else if (closure != Py_None) { PyErr_SetString(PyExc_TypeError, "arg 5 (closure) must be None or tuple"); return NULL; } } /* check that the closure is well-formed */ nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure); if (nfree != nclosure) return PyErr_Format(PyExc_ValueError, "%U requires closure of length %zd, not %zd", code->co_name, nfree, nclosure); if (nclosure) { Py_ssize_t i; for (i = 0; i < nclosure; i++) { PyObject *o = PyTuple_GET_ITEM(closure, i); if (!PyCell_Check(o)) { return PyErr_Format(PyExc_TypeError, "arg 5 (closure) expected cell, found %s", o->ob_type->tp_name); } } } newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code, globals); if (newfunc == NULL) return NULL; if (name != Py_None) { Py_INCREF(name); Py_SETREF(newfunc->func_name, name); } if (defaults != Py_None) { Py_INCREF(defaults); newfunc->func_defaults = defaults; } if (closure != Py_None) { Py_INCREF(closure); newfunc->func_closure = closure; } return (PyObject *)newfunc; } static void func_dealloc(PyFunctionObject *op) { _PyObject_GC_UNTRACK(op); if (op->func_weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *) op); Py_DECREF(op->func_code); Py_DECREF(op->func_globals); Py_XDECREF(op->func_module); Py_DECREF(op->func_name); Py_XDECREF(op->func_defaults); Py_XDECREF(op->func_kwdefaults); Py_XDECREF(op->func_doc); Py_XDECREF(op->func_dict); Py_XDECREF(op->func_closure); Py_XDECREF(op->func_annotations); Py_XDECREF(op->func_qualname); PyObject_GC_Del(op); } static PyObject* func_repr(PyFunctionObject *op) { return PyUnicode_FromFormat("<function %U at %p>", op->func_qualname, op); } static int func_traverse(PyFunctionObject *f, visitproc visit, void *arg) { Py_VISIT(f->func_code); Py_VISIT(f->func_globals); Py_VISIT(f->func_module); Py_VISIT(f->func_defaults); Py_VISIT(f->func_kwdefaults); Py_VISIT(f->func_doc); Py_VISIT(f->func_name); Py_VISIT(f->func_dict); Py_VISIT(f->func_closure); Py_VISIT(f->func_annotations); Py_VISIT(f->func_qualname); return 0; } static PyObject * function_call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; PyObject *argdefs; PyObject *kwtuple = NULL; PyObject **d, **k; Py_ssize_t nk, nd; argdefs = PyFunction_GET_DEFAULTS(func); if (argdefs != NULL && PyTuple_Check(argdefs)) { d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0); nd = PyTuple_GET_SIZE(argdefs); } else { d = NULL; nd = 0; } if (kw != NULL && PyDict_Check(kw)) { Py_ssize_t pos, i; nk = PyDict_Size(kw); kwtuple = PyTuple_New(2*nk); if (kwtuple == NULL) return NULL; k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i/2; } else { k = NULL; nk = 0; } result = PyEval_EvalCodeEx( PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), (PyObject *)NULL, &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg), k, nk, d, nd, PyFunction_GET_KW_DEFAULTS(func), PyFunction_GET_CLOSURE(func)); Py_XDECREF(kwtuple); return result; } /* Bind a function to an object */ static PyObject * func_descr_get(PyObject *func, PyObject *obj, PyObject *type) { if (obj == Py_None || obj == NULL) { Py_INCREF(func); return func; } return PyMethod_New(func, obj); } PyTypeObject PyFunction_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "function", sizeof(PyFunctionObject), 0, (destructor)func_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)func_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ function_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ func_doc, /* tp_doc */ (traverseproc)func_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ func_memberlist, /* tp_members */ func_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ func_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ func_new, /* tp_new */ }; /* Class method object */ /* A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C: @classmethod def f(cls, arg1, arg2, ...): ... It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see static methods below. */ typedef struct { PyObject_HEAD PyObject *cm_callable; PyObject *cm_dict; } classmethod; static void cm_dealloc(classmethod *cm) { _PyObject_GC_UNTRACK((PyObject *)cm); Py_XDECREF(cm->cm_callable); Py_XDECREF(cm->cm_dict); Py_TYPE(cm)->tp_free((PyObject *)cm); } static int cm_traverse(classmethod *cm, visitproc visit, void *arg) { Py_VISIT(cm->cm_callable); Py_VISIT(cm->cm_dict); return 0; } static int cm_clear(classmethod *cm) { Py_CLEAR(cm->cm_callable); Py_CLEAR(cm->cm_dict); return 0; } static PyObject * cm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { classmethod *cm = (classmethod *)self; if (cm->cm_callable == NULL) { PyErr_SetString(PyExc_RuntimeError, "uninitialized classmethod object"); return NULL; } if (type == NULL) type = (PyObject *)(Py_TYPE(obj)); return PyMethod_New(cm->cm_callable, type); } static int cm_init(PyObject *self, PyObject *args, PyObject *kwds) { classmethod *cm = (classmethod *)self; PyObject *callable; if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable)) return -1; if (!_PyArg_NoKeywords("classmethod", kwds)) return -1; Py_INCREF(callable); Py_XSETREF(cm->cm_callable, callable); return 0; } static PyMemberDef cm_memberlist[] = { {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY}, {NULL} /* Sentinel */ }; static PyObject * cm_get___isabstractmethod__(classmethod *cm, void *closure) { int res = _PyObject_IsAbstract(cm->cm_callable); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyGetSetDef cm_getsetlist[] = { {"__isabstractmethod__", (getter)cm_get___isabstractmethod__, NULL, NULL, NULL}, {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL}, {NULL} /* Sentinel */ }; PyDoc_STRVAR(classmethod_doc, "classmethod(function) -> method\n\ \n\ Convert a function to be a class method.\n\ \n\ A class method receives the class as implicit first argument,\n\ just like an instance method receives the instance.\n\ To declare a class method, use this idiom:\n\ \n\ class C:\n\ @classmethod\n\ def f(cls, arg1, arg2, ...):\n\ ...\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). The instance is ignored except for its class.\n\ If a class method is called for a derived class, the derived class\n\ object is passed as the implied first argument.\n\ \n\ Class methods are different than C++ or Java static methods.\n\ If you want those, see the staticmethod builtin."); PyTypeObject PyClassMethod_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "classmethod", sizeof(classmethod), 0, (destructor)cm_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, classmethod_doc, /* tp_doc */ (traverseproc)cm_traverse, /* tp_traverse */ (inquiry)cm_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ cm_memberlist, /* tp_members */ cm_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ cm_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(classmethod, cm_dict), /* tp_dictoffset */ cm_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * PyClassMethod_New(PyObject *callable) { classmethod *cm = (classmethod *) PyType_GenericAlloc(&PyClassMethod_Type, 0); if (cm != NULL) { Py_INCREF(callable); cm->cm_callable = callable; } return (PyObject *)cm; } /* Static method object */ /* A static method does not receive an implicit first argument. To declare a static method, use this idiom: class C: @staticmethod def f(arg1, arg2, ...): ... It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class. Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see class methods above. */ typedef struct { PyObject_HEAD PyObject *sm_callable; PyObject *sm_dict; } staticmethod; static void sm_dealloc(staticmethod *sm) { _PyObject_GC_UNTRACK((PyObject *)sm); Py_XDECREF(sm->sm_callable); Py_XDECREF(sm->sm_dict); Py_TYPE(sm)->tp_free((PyObject *)sm); } static int sm_traverse(staticmethod *sm, visitproc visit, void *arg) { Py_VISIT(sm->sm_callable); Py_VISIT(sm->sm_dict); return 0; } static int sm_clear(staticmethod *sm) { Py_CLEAR(sm->sm_callable); Py_CLEAR(sm->sm_dict); return 0; } static PyObject * sm_descr_get(PyObject *self, PyObject *obj, PyObject *type) { staticmethod *sm = (staticmethod *)self; if (sm->sm_callable == NULL) { PyErr_SetString(PyExc_RuntimeError, "uninitialized staticmethod object"); return NULL; } Py_INCREF(sm->sm_callable); return sm->sm_callable; } static int sm_init(PyObject *self, PyObject *args, PyObject *kwds) { staticmethod *sm = (staticmethod *)self; PyObject *callable; if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable)) return -1; if (!_PyArg_NoKeywords("staticmethod", kwds)) return -1; Py_INCREF(callable); Py_XSETREF(sm->sm_callable, callable); return 0; } static PyMemberDef sm_memberlist[] = { {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY}, {NULL} /* Sentinel */ }; static PyObject * sm_get___isabstractmethod__(staticmethod *sm, void *closure) { int res = _PyObject_IsAbstract(sm->sm_callable); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyGetSetDef sm_getsetlist[] = { {"__isabstractmethod__", (getter)sm_get___isabstractmethod__, NULL, NULL, NULL}, {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, NULL, NULL}, {NULL} /* Sentinel */ }; PyDoc_STRVAR(staticmethod_doc, "staticmethod(function) -> method\n\ \n\ Convert a function to be a static method.\n\ \n\ A static method does not receive an implicit first argument.\n\ To declare a static method, use this idiom:\n\ \n\ class C:\n\ @staticmethod\n\ def f(arg1, arg2, ...):\n\ ...\n\ \n\ It can be called either on the class (e.g. C.f()) or on an instance\n\ (e.g. C().f()). The instance is ignored except for its class.\n\ \n\ Static methods in Python are similar to those found in Java or C++.\n\ For a more advanced concept, see the classmethod builtin."); PyTypeObject PyStaticMethod_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "staticmethod", sizeof(staticmethod), 0, (destructor)sm_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, staticmethod_doc, /* tp_doc */ (traverseproc)sm_traverse, /* tp_traverse */ (inquiry)sm_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ sm_memberlist, /* tp_members */ sm_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ sm_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(staticmethod, sm_dict), /* tp_dictoffset */ sm_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * PyStaticMethod_New(PyObject *callable) { staticmethod *sm = (staticmethod *) PyType_GenericAlloc(&PyStaticMethod_Type, 0); if (sm != NULL) { Py_INCREF(callable); sm->sm_callable = callable; } return (PyObject *)sm; }
32,589
1,047
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/typeobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/intrin/likely.h" #include "libc/fmt/fmt.h" #include "libc/log/countbranch.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/cellobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/compile.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/iterobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/typeslots.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Include/weakrefobject.h" /* clang-format off */ static const short slotoffsets[] = { -1, /* invalid slot */ #include "third_party/python/Objects/typeslots.inc" }; /* Type object implementation */ /* Support type attribute cache */ /* The cache can keep references to the names alive for longer than they normally would. This is why the maximum size is limited to MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large strings are used as attribute names. */ #define MCACHE_MAX_ATTR_SIZE 100 #define MCACHE_SIZE_EXP 12 #define MCACHE_HASH(version, name_hash) \ (((unsigned int)(version) ^ (unsigned int)(name_hash)) \ & ((1 << MCACHE_SIZE_EXP) - 1)) #define MCACHE_HASH_METHOD(type, name) \ MCACHE_HASH((type)->tp_version_tag, \ ((PyASCIIObject *)(name))->hash) #define MCACHE_CACHEABLE_NAME(name) \ PyUnicode_CheckExact(name) && \ PyUnicode_READY(name) != -1 && \ PyUnicode_GET_LENGTH(name) <= MCACHE_MAX_ATTR_SIZE struct method_cache_entry { unsigned int version; PyObject *name; /* reference to exactly a str or None */ PyObject *value; /* borrowed */ }; static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP]; static unsigned int next_version_tag = 0; #define MCACHE_STATS 0 #if MCACHE_STATS static size_t method_cache_hits = 0; static size_t method_cache_misses = 0; static size_t method_cache_collisions = 0; #endif /* alphabetical order */ _Py_IDENTIFIER(__abstractmethods__); _Py_IDENTIFIER(__class__); _Py_IDENTIFIER(__delitem__); _Py_IDENTIFIER(__dict__); _Py_IDENTIFIER(__doc__); _Py_IDENTIFIER(__getattribute__); _Py_IDENTIFIER(__getitem__); _Py_IDENTIFIER(__hash__); _Py_IDENTIFIER(__init_subclass__); _Py_IDENTIFIER(__len__); _Py_IDENTIFIER(__module__); _Py_IDENTIFIER(__name__); _Py_IDENTIFIER(__new__); _Py_IDENTIFIER(__set_name__); _Py_IDENTIFIER(__setitem__); _Py_IDENTIFIER(builtins); static PyObject * slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static void clear_slotdefs(void); /* * finds the beginning of the docstring's introspection signature. * if present, returns a pointer pointing to the first '('. * otherwise returns NULL. * * doesn't guarantee that the signature is valid, only that it * has a valid prefix. (the signature must also pass skip_signature.) */ static const char * find_signature(const char *name, const char *doc) { const char *dot; size_t length; if (!doc) return NULL; assert(name != NULL); /* for dotted names like classes, only use the last component */ dot = strrchr(name, '.'); if (dot) name = dot + 1; length = strlen(name); if (strncmp(doc, name, length)) return NULL; doc += length; if (*doc != '(') return NULL; return doc; } #define SIGNATURE_END_MARKER ")\n--\n\n" #define SIGNATURE_END_MARKER_LENGTH 6 /* * skips past the end of the docstring's instrospection signature. * (assumes doc starts with a valid signature prefix.) */ static const char * skip_signature(const char *doc) { while (*doc) { if ((*doc == *SIGNATURE_END_MARKER) && !strncmp(doc, SIGNATURE_END_MARKER, SIGNATURE_END_MARKER_LENGTH)) return doc + SIGNATURE_END_MARKER_LENGTH; if ((*doc == '\n') && (doc[1] == '\n')) return NULL; doc++; } return NULL; } #ifdef Py_DEBUG static int _PyType_CheckConsistency(PyTypeObject *type) { if (!(type->tp_flags & Py_TPFLAGS_READY)) { /* don't check types before PyType_Ready() */ return 1; } assert(!(type->tp_flags & Py_TPFLAGS_READYING)); assert(type->tp_mro != NULL && PyTuple_Check(type->tp_mro)); assert(type->tp_dict != NULL); return 1; } #endif static const char * _PyType_DocWithoutSignature(const char *name, const char *internal_doc) { const char *doc = find_signature(name, internal_doc); if (doc) { doc = skip_signature(doc); if (doc) return doc; } return internal_doc; } PyObject * _PyType_GetDocFromInternalDoc(const char *name, const char *internal_doc) { const char *doc = _PyType_DocWithoutSignature(name, internal_doc); if (!doc || *doc == '\0') { Py_RETURN_NONE; } return PyUnicode_FromString(doc); } PyObject * _PyType_GetTextSignatureFromInternalDoc(const char *name, const char *internal_doc) { const char *start = find_signature(name, internal_doc); const char *end; if (start) end = skip_signature(start); else end = NULL; if (!end) { Py_RETURN_NONE; } /* back "end" up until it points just past the final ')' */ end -= SIGNATURE_END_MARKER_LENGTH - 1; assert((end - start) >= 2); /* should be "()" at least */ assert(end[-1] == ')'); assert(end[0] == '\n'); return PyUnicode_FromStringAndSize(start, end - start); } unsigned int PyType_ClearCache(void) { Py_ssize_t i; unsigned int cur_version_tag = next_version_tag - 1; #if MCACHE_STATS size_t total = method_cache_hits + method_cache_collisions + method_cache_misses; fprintf(stderr, "-- Method cache hits = %zd (%d%%)\n", method_cache_hits, (int) (100.0 * method_cache_hits / total)); fprintf(stderr, "-- Method cache true misses = %zd (%d%%)\n", method_cache_misses, (int) (100.0 * method_cache_misses / total)); fprintf(stderr, "-- Method cache collisions = %zd (%d%%)\n", method_cache_collisions, (int) (100.0 * method_cache_collisions / total)); fprintf(stderr, "-- Method cache size = %zd KB\n", sizeof(method_cache) / 1024); #endif for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { method_cache[i].version = 0; Py_CLEAR(method_cache[i].name); method_cache[i].value = NULL; } next_version_tag = 0; /* mark all version tags as invalid */ PyType_Modified(&PyBaseObject_Type); return cur_version_tag; } void _PyType_Fini(void) { PyType_ClearCache(); clear_slotdefs(); } void PyType_Modified(PyTypeObject *type) { /* Invalidate any cached data for the specified type and all subclasses. This function is called after the base classes, mro, or attributes of the type are altered. Invariants: - Py_TPFLAGS_VALID_VERSION_TAG is never set if Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type objects coming from non-recompiled extension modules) - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type, it must first be set on all super types. This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a type (so it must first clear it on all subclasses). The tp_version_tag value is meaningless unless this flag is set. We don't assign new version tags eagerly, but only as needed. */ PyObject *raw, *ref; Py_ssize_t i; if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) return; raw = type->tp_subclasses; if (raw != NULL) { assert(PyDict_CheckExact(raw)); i = 0; while (PyDict_Next(raw, &i, NULL, &ref)) { assert(PyWeakref_CheckRef(ref)); ref = PyWeakref_GET_OBJECT(ref); if (ref != Py_None) { PyType_Modified((PyTypeObject *)ref); } } } type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG; } static void type_mro_modified(PyTypeObject *type, PyObject *bases) { /* Check that all base classes or elements of the MRO of type are able to be cached. This function is called after the base classes or mro of the type are altered. Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type has a custom MRO that includes a type which is not officially super type. Called from mro_internal, which will subsequently be called on each subclass when their mro is recursively updated. */ Py_ssize_t i, n; int clear = 0; if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) return; n = PyTuple_GET_SIZE(bases); for (i = 0; i < n; i++) { PyObject *b = PyTuple_GET_ITEM(bases, i); PyTypeObject *cls; assert(PyType_Check(b)); cls = (PyTypeObject *)b; if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) || !PyType_IsSubtype(type, cls)) { clear = 1; break; } } if (clear) type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG| Py_TPFLAGS_VALID_VERSION_TAG); } static int assign_version_tag(PyTypeObject *type) { /* Ensure that the tp_version_tag is valid and set Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this must first be done on all super classes. Return 0 if this cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG. */ Py_ssize_t i, n; PyObject *bases; if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) return 1; if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) return 0; if (!PyType_HasFeature(type, Py_TPFLAGS_READY)) return 0; type->tp_version_tag = next_version_tag++; /* for stress-testing: next_version_tag &= 0xFF; */ if (type->tp_version_tag == 0) { /* wrap-around or just starting Python - clear the whole cache by filling names with references to Py_None. Values are also set to NULL for added protection, as they are borrowed reference */ for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) { method_cache[i].value = NULL; Py_INCREF(Py_None); Py_XSETREF(method_cache[i].name, Py_None); } /* mark all version tags as invalid */ PyType_Modified(&PyBaseObject_Type); return 1; } bases = type->tp_bases; n = PyTuple_GET_SIZE(bases); for (i = 0; i < n; i++) { PyObject *b = PyTuple_GET_ITEM(bases, i); assert(PyType_Check(b)); if (!assign_version_tag((PyTypeObject *)b)) return 0; } type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG; return 1; } static PyMemberDef type_members[] = { {"__basicsize__", T_PYSSIZET, offsetof(PyTypeObject,tp_basicsize),READONLY}, {"__itemsize__", T_PYSSIZET, offsetof(PyTypeObject, tp_itemsize), READONLY}, {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY}, {"__weakrefoffset__", T_LONG, offsetof(PyTypeObject, tp_weaklistoffset), READONLY}, {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY}, {"__dictoffset__", T_LONG, offsetof(PyTypeObject, tp_dictoffset), READONLY}, {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY}, {0} }; static int check_set_special_type_attr(PyTypeObject *type, PyObject *value, const char *name) { if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { PyErr_Format(PyExc_TypeError, "can't set %s.%s", type->tp_name, name); return 0; } if (!value) { PyErr_Format(PyExc_TypeError, "can't delete %s.%s", type->tp_name, name); return 0; } return 1; } static PyObject * type_name(PyTypeObject *type, void *context) { const char *s; if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { PyHeapTypeObject* et = (PyHeapTypeObject*)type; Py_INCREF(et->ht_name); return et->ht_name; } else { s = strrchr(type->tp_name, '.'); if (s == NULL) s = type->tp_name; else s++; return PyUnicode_FromString(s); } } static PyObject * type_qualname(PyTypeObject *type, void *context) { if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { PyHeapTypeObject* et = (PyHeapTypeObject*)type; Py_INCREF(et->ht_qualname); return et->ht_qualname; } else { return type_name(type, context); } } static int type_set_name(PyTypeObject *type, PyObject *value, void *context) { const char *tp_name; Py_ssize_t name_size; if (!check_set_special_type_attr(type, value, "__name__")) return -1; if (!PyUnicode_Check(value)) { PyErr_Format(PyExc_TypeError, "can only assign string to %s.__name__, not '%s'", type->tp_name, Py_TYPE(value)->tp_name); return -1; } tp_name = PyUnicode_AsUTF8AndSize(value, &name_size); if (tp_name == NULL) return -1; if (strlen(tp_name) != (size_t)name_size) { PyErr_SetString(PyExc_ValueError, "type name must not contain null characters"); return -1; } type->tp_name = tp_name; Py_INCREF(value); Py_SETREF(((PyHeapTypeObject*)type)->ht_name, value); return 0; } static int type_set_qualname(PyTypeObject *type, PyObject *value, void *context) { PyHeapTypeObject* et; if (!check_set_special_type_attr(type, value, "__qualname__")) return -1; if (!PyUnicode_Check(value)) { PyErr_Format(PyExc_TypeError, "can only assign string to %s.__qualname__, not '%s'", type->tp_name, Py_TYPE(value)->tp_name); return -1; } et = (PyHeapTypeObject*)type; Py_INCREF(value); Py_SETREF(et->ht_qualname, value); return 0; } static PyObject * type_module(PyTypeObject *type, void *context) { PyObject *mod; if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { mod = _PyDict_GetItemId(type->tp_dict, &PyId___module__); if (mod == NULL) { PyErr_Format(PyExc_AttributeError, "__module__"); return NULL; } Py_INCREF(mod); } else { const char *s = strrchr(type->tp_name, '.'); if (s != NULL) { mod = PyUnicode_FromStringAndSize( type->tp_name, (Py_ssize_t)(s - type->tp_name)); if (mod != NULL) PyUnicode_InternInPlace(&mod); } else { mod = _PyUnicode_FromId(&PyId_builtins); Py_XINCREF(mod); } } return mod; } static int type_set_module(PyTypeObject *type, PyObject *value, void *context) { if (!check_set_special_type_attr(type, value, "__module__")) return -1; PyType_Modified(type); return _PyDict_SetItemId(type->tp_dict, &PyId___module__, value); } static PyObject * type_abstractmethods(PyTypeObject *type, void *context) { PyObject *mod = NULL; /* type itself has an __abstractmethods__ descriptor (this). Don't return that. */ if (type != &PyType_Type) mod = _PyDict_GetItemId(type->tp_dict, &PyId___abstractmethods__); if (!mod) { PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__); if (message) PyErr_SetObject(PyExc_AttributeError, message); return NULL; } Py_INCREF(mod); return mod; } static int type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context) { /* __abstractmethods__ should only be set once on a type, in abc.ABCMeta.__new__, so this function doesn't do anything special to update subclasses. */ int abstract, res; if (value != NULL) { abstract = PyObject_IsTrue(value); if (abstract < 0) return -1; res = _PyDict_SetItemId(type->tp_dict, &PyId___abstractmethods__, value); } else { abstract = 0; res = _PyDict_DelItemId(type->tp_dict, &PyId___abstractmethods__); if (res && PyErr_ExceptionMatches(PyExc_KeyError)) { PyObject *message = _PyUnicode_FromId(&PyId___abstractmethods__); if (message) PyErr_SetObject(PyExc_AttributeError, message); return -1; } } if (res == 0) { PyType_Modified(type); if (abstract) type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT; else type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT; } return res; } static PyObject * type_get_bases(PyTypeObject *type, void *context) { Py_INCREF(type->tp_bases); return type->tp_bases; } static PyTypeObject *best_base(PyObject *); static int mro_internal(PyTypeObject *, PyObject **); static int type_is_subtype_base_chain(PyTypeObject *, PyTypeObject *); static int compatible_for_assignment(PyTypeObject *, PyTypeObject *, const char *); static int add_subclass(PyTypeObject*, PyTypeObject*); static int add_all_subclasses(PyTypeObject *type, PyObject *bases); static void remove_subclass(PyTypeObject *, PyTypeObject *); static void remove_all_subclasses(PyTypeObject *type, PyObject *bases); static void update_all_slots(PyTypeObject *); typedef int (*update_callback)(PyTypeObject *, void *); static int update_subclasses(PyTypeObject *type, PyObject *name, update_callback callback, void *data); static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, update_callback callback, void *data); static PyObject *type_subclasses(PyTypeObject *type, PyObject *ignored); static int mro_hierarchy(PyTypeObject *type, PyObject *temp) { int res; PyObject *new_mro, *old_mro; PyObject *tuple; PyObject *subclasses; Py_ssize_t i, n; res = mro_internal(type, &old_mro); if (res <= 0) /* error / reentrance */ return res; new_mro = type->tp_mro; if (old_mro != NULL) tuple = PyTuple_Pack(3, type, new_mro, old_mro); else tuple = PyTuple_Pack(2, type, new_mro); if (tuple != NULL) res = PyList_Append(temp, tuple); else res = -1; Py_XDECREF(tuple); if (res < 0) { type->tp_mro = old_mro; Py_DECREF(new_mro); return -1; } Py_XDECREF(old_mro); /* Obtain a copy of subclasses list to iterate over. Otherwise type->tp_subclasses might be altered in the middle of the loop, for example, through a custom mro(), by invoking type_set_bases on some subclass of the type which in turn calls remove_subclass/add_subclass on this type. Finally, this makes things simple avoiding the need to deal with dictionary iterators and weak references. */ subclasses = type_subclasses(type, NULL); if (subclasses == NULL) return -1; n = PyList_GET_SIZE(subclasses); for (i = 0; i < n; i++) { PyTypeObject *subclass; subclass = (PyTypeObject *)PyList_GET_ITEM(subclasses, i); res = mro_hierarchy(subclass, temp); if (res < 0) break; } Py_DECREF(subclasses); return res; } static int type_set_bases(PyTypeObject *type, PyObject *new_bases, void *context) { int res = 0; PyObject *temp; PyObject *old_bases; PyTypeObject *new_base, *old_base; Py_ssize_t i; if (!check_set_special_type_attr(type, new_bases, "__bases__")) return -1; if (!PyTuple_Check(new_bases)) { PyErr_Format(PyExc_TypeError, "can only assign tuple to %s.__bases__, not %s", type->tp_name, Py_TYPE(new_bases)->tp_name); return -1; } if (PyTuple_GET_SIZE(new_bases) == 0) { PyErr_Format(PyExc_TypeError, "can only assign non-empty tuple to %s.__bases__, not ()", type->tp_name); return -1; } for (i = 0; i < PyTuple_GET_SIZE(new_bases); i++) { PyObject *ob; PyTypeObject *base; ob = PyTuple_GET_ITEM(new_bases, i); if (!PyType_Check(ob)) { PyErr_Format(PyExc_TypeError, "%s.__bases__ must be tuple of classes, not '%s'", type->tp_name, Py_TYPE(ob)->tp_name); return -1; } base = (PyTypeObject*)ob; if (PyType_IsSubtype(base, type) || /* In case of reentering here again through a custom mro() the above check is not enough since it relies on base->tp_mro which would gonna be updated inside mro_internal only upon returning from the mro(). However, base->tp_base has already been assigned (see below), which in turn may cause an inheritance cycle through tp_base chain. And this is definitely not what you want to ever happen. */ (base->tp_mro != NULL && type_is_subtype_base_chain(base, type))) { PyErr_SetString(PyExc_TypeError, "a __bases__ item causes an inheritance cycle"); return -1; } } new_base = best_base(new_bases); if (new_base == NULL) return -1; if (!compatible_for_assignment(type->tp_base, new_base, "__bases__")) return -1; Py_INCREF(new_bases); Py_INCREF(new_base); old_bases = type->tp_bases; old_base = type->tp_base; type->tp_bases = new_bases; type->tp_base = new_base; temp = PyList_New(0); if (temp == NULL) goto bail; if (mro_hierarchy(type, temp) < 0) goto undo; Py_DECREF(temp); /* Take no action in case if type->tp_bases has been replaced through reentrance. */ if (type->tp_bases == new_bases) { /* any base that was in __bases__ but now isn't, we need to remove |type| from its tp_subclasses. conversely, any class now in __bases__ that wasn't needs to have |type| added to its subclasses. */ /* for now, sod that: just remove from all old_bases, add to all new_bases */ remove_all_subclasses(type, old_bases); res = add_all_subclasses(type, new_bases); update_all_slots(type); } Py_DECREF(old_bases); Py_DECREF(old_base); assert(_PyType_CheckConsistency(type)); return res; undo: for (i = PyList_GET_SIZE(temp) - 1; i >= 0; i--) { PyTypeObject *cls; PyObject *new_mro, *old_mro = NULL; PyArg_UnpackTuple(PyList_GET_ITEM(temp, i), "", 2, 3, &cls, &new_mro, &old_mro); /* Do not rollback if cls has a newer version of MRO. */ if (cls->tp_mro == new_mro) { Py_XINCREF(old_mro); cls->tp_mro = old_mro; Py_DECREF(new_mro); } } Py_DECREF(temp); bail: if (type->tp_bases == new_bases) { assert(type->tp_base == new_base); type->tp_bases = old_bases; type->tp_base = old_base; Py_DECREF(new_bases); Py_DECREF(new_base); } else { Py_DECREF(old_bases); Py_DECREF(old_base); } assert(_PyType_CheckConsistency(type)); return -1; } static PyObject * type_dict(PyTypeObject *type, void *context) { if (type->tp_dict == NULL) { Py_RETURN_NONE; } return PyDictProxy_New(type->tp_dict); } static PyObject * type_get_doc(PyTypeObject *type, void *context) { PyObject *result; if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL) { return _PyType_GetDocFromInternalDoc(type->tp_name, type->tp_doc); } result = _PyDict_GetItemId(type->tp_dict, &PyId___doc__); if (result == NULL) { result = Py_None; Py_INCREF(result); } else if (Py_TYPE(result)->tp_descr_get) { result = Py_TYPE(result)->tp_descr_get(result, NULL, (PyObject *)type); } else { Py_INCREF(result); } return result; } static PyObject * type_get_text_signature(PyTypeObject *type, void *context) { return _PyType_GetTextSignatureFromInternalDoc(type->tp_name, type->tp_doc); } static int type_set_doc(PyTypeObject *type, PyObject *value, void *context) { if (!check_set_special_type_attr(type, value, "__doc__")) return -1; PyType_Modified(type); return _PyDict_SetItemId(type->tp_dict, &PyId___doc__, value); } static PyObject * type___instancecheck__(PyObject *type, PyObject *inst) { switch (_PyObject_RealIsInstance(inst, type)) { case -1: return NULL; case 0: Py_RETURN_FALSE; default: Py_RETURN_TRUE; } } static PyObject * type___subclasscheck__(PyObject *type, PyObject *inst) { switch (_PyObject_RealIsSubclass(inst, type)) { case -1: return NULL; case 0: Py_RETURN_FALSE; default: Py_RETURN_TRUE; } } static PyGetSetDef type_getsets[] = { {"__name__", (getter)type_name, (setter)type_set_name, NULL}, {"__qualname__", (getter)type_qualname, (setter)type_set_qualname, NULL}, {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL}, {"__module__", (getter)type_module, (setter)type_set_module, NULL}, {"__abstractmethods__", (getter)type_abstractmethods, (setter)type_set_abstractmethods, NULL}, {"__dict__", (getter)type_dict, NULL, NULL}, {"__doc__", (getter)type_get_doc, (setter)type_set_doc, NULL}, {"__text_signature__", (getter)type_get_text_signature, NULL, NULL}, {0} }; static PyObject * type_repr(PyTypeObject *type) { PyObject *mod, *name, *rtn; mod = type_module(type, NULL); if (mod == NULL) PyErr_Clear(); else if (!PyUnicode_Check(mod)) { Py_DECREF(mod); mod = NULL; } name = type_qualname(type, NULL); if (name == NULL) { Py_XDECREF(mod); return NULL; } if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins)) rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name); else rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name); Py_XDECREF(mod); Py_DECREF(name); return rtn; } static PyObject * type_call(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *obj; if (type->tp_new == NULL) { PyErr_Format(PyExc_TypeError, "cannot create '%.100s' instances", type->tp_name); return NULL; } #ifdef Py_DEBUG /* type_call() must not be called with an exception set, because it can clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); #endif obj = type->tp_new(type, args, kwds); obj = _Py_CheckFunctionResult((PyObject*)type, obj, NULL); if (obj == NULL) return NULL; /* Ugly exception: when the call was type(something), don't call tp_init on the result. */ if (type == &PyType_Type && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && (kwds == NULL || (PyDict_Check(kwds) && PyDict_GET_SIZE(kwds) == 0))) return obj; /* If the returned object is not an instance of type, it won't be initialized. */ if (!PyType_IsSubtype(Py_TYPE(obj), type)) return obj; type = Py_TYPE(obj); if (type->tp_init != NULL) { int res = type->tp_init(obj, args, kwds); if (res < 0) { assert(PyErr_Occurred()); Py_DECREF(obj); obj = NULL; } else { assert(!PyErr_Occurred()); } } return obj; } PyObject * PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) { PyObject *obj; const size_t size = _PyObject_VAR_SIZE(type, nitems+1); /* note that we need to add one, for the sentinel */ if (PyType_IS_GC(type)) obj = _PyObject_GC_Malloc(size); else obj = (PyObject *)PyObject_MALLOC(size); if (obj == NULL) return PyErr_NoMemory(); bzero(obj, size); if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) Py_INCREF(type); if (type->tp_itemsize == 0) (void)PyObject_INIT(obj, type); else (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems); if (PyType_IS_GC(type)) _PyObject_GC_TRACK(obj); return obj; } PyObject * PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) { return type->tp_alloc(type, 0); } /* Helpers for subtyping */ static int traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg) { Py_ssize_t i, n; PyMemberDef *mp; n = Py_SIZE(type); mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); for (i = 0; i < n; i++, mp++) { if (mp->type == T_OBJECT_EX) { char *addr = (char *)self + mp->offset; PyObject *obj = *(PyObject **)addr; if (obj != NULL) { int err = visit(obj, arg); if (err) return err; } } } return 0; } static int subtype_traverse(PyObject *self, visitproc visit, void *arg) { PyTypeObject *type, *base; traverseproc basetraverse; /* Find the nearest base with a different tp_traverse, and traverse slots while we're at it */ type = Py_TYPE(self); base = type; while ((basetraverse = base->tp_traverse) == subtype_traverse) { if (Py_SIZE(base)) { int err = traverse_slots(base, self, visit, arg); if (err) return err; } base = base->tp_base; assert(base); } if (type->tp_dictoffset != base->tp_dictoffset) { PyObject **dictptr = _PyObject_GetDictPtr(self); if (dictptr && *dictptr) Py_VISIT(*dictptr); } if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) /* For a heaptype, the instances count as references to the type. Traverse the type so the collector can find cycles involving this link. */ Py_VISIT(type); if (basetraverse) return basetraverse(self, visit, arg); return 0; } static void clear_slots(PyTypeObject *type, PyObject *self) { Py_ssize_t i, n; PyMemberDef *mp; n = Py_SIZE(type); mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type); for (i = 0; i < n; i++, mp++) { if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) { char *addr = (char *)self + mp->offset; PyObject *obj = *(PyObject **)addr; if (obj != NULL) { *(PyObject **)addr = NULL; Py_DECREF(obj); } } } } static int subtype_clear(PyObject *self) { PyTypeObject *type, *base; inquiry baseclear; /* Find the nearest base with a different tp_clear and clear slots while we're at it */ type = Py_TYPE(self); base = type; while ((baseclear = base->tp_clear) == subtype_clear) { if (Py_SIZE(base)) clear_slots(base, self); base = base->tp_base; assert(base); } /* Clear the instance dict (if any), to break cycles involving only __dict__ slots (as in the case 'self.__dict__ is self'). */ if (type->tp_dictoffset != base->tp_dictoffset) { PyObject **dictptr = _PyObject_GetDictPtr(self); if (dictptr && *dictptr) Py_CLEAR(*dictptr); } if (baseclear) return baseclear(self); return 0; } static void subtype_dealloc(PyObject *self) { PyTypeObject *type, *base; destructor basedealloc; PyThreadState *tstate = PyThreadState_GET(); int has_finalizer; /* Extract the type; we expect it to be a heap type */ type = Py_TYPE(self); assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); /* Test whether the type has GC exactly once */ if (!PyType_IS_GC(type)) { /* It's really rare to find a dynamic type that doesn't have GC; it can only happen when deriving from 'object' and not adding any slots or instance variables. This allows certain simplifications: there's no need to call clear_slots(), or DECREF the dict, or clear weakrefs. */ /* Maybe call finalizer; exit early if resurrected */ if (type->tp_finalize) { if (PyObject_CallFinalizerFromDealloc(self) < 0) return; } if (type->tp_del) { type->tp_del(self); if (self->ob_refcnt > 0) return; } /* Find the nearest base with a different tp_dealloc */ base = type; while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { assert(Py_SIZE(base) == 0); base = base->tp_base; assert(base); } /* Extract the type again; tp_del may have changed it */ type = Py_TYPE(self); /* Call the base tp_dealloc() */ assert(basedealloc); basedealloc(self); /* Can't reference self beyond this point */ Py_DECREF(type); /* Done */ return; } /* We get here only if the type has GC */ /* UnTrack and re-Track around the trashcan macro, alas */ /* See explanation at end of function for full disclosure */ PyObject_GC_UnTrack(self); ++_PyTrash_delete_nesting; ++ tstate->trash_delete_nesting; Py_TRASHCAN_SAFE_BEGIN(self); --_PyTrash_delete_nesting; -- tstate->trash_delete_nesting; /* Find the nearest base with a different tp_dealloc */ base = type; while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) { base = base->tp_base; assert(base); } has_finalizer = type->tp_finalize || type->tp_del; if (type->tp_finalize) { _PyObject_GC_TRACK(self); if (PyObject_CallFinalizerFromDealloc(self) < 0) { /* Resurrected */ goto endlabel; } _PyObject_GC_UNTRACK(self); } /* If we added a weaklist, we clear it. Do this *before* calling tp_del, clearing slots, or clearing the instance dict. GC tracking must be off at this point. weakref callbacks (if any, and whether directly here or indirectly in something we call) may trigger GC, and if self is tracked at that point, it will look like trash to GC and GC will try to delete self again. */ if (type->tp_weaklistoffset && !base->tp_weaklistoffset) PyObject_ClearWeakRefs(self); if (type->tp_del) { _PyObject_GC_TRACK(self); type->tp_del(self); if (self->ob_refcnt > 0) { /* Resurrected */ goto endlabel; } _PyObject_GC_UNTRACK(self); } if (has_finalizer) { /* New weakrefs could be created during the finalizer call. If this occurs, clear them out without calling their finalizers since they might rely on part of the object being finalized that has already been destroyed. */ if (type->tp_weaklistoffset && !base->tp_weaklistoffset) { /* Modeled after GET_WEAKREFS_LISTPTR() */ PyWeakReference **list = (PyWeakReference **) \ PyObject_GET_WEAKREFS_LISTPTR(self); while (*list) _PyWeakref_ClearRef(*list); } } /* Clear slots up to the nearest base with a different tp_dealloc */ base = type; while ((basedealloc = base->tp_dealloc) == subtype_dealloc) { if (Py_SIZE(base)) clear_slots(base, self); base = base->tp_base; assert(base); } /* If we added a dict, DECREF it */ if (type->tp_dictoffset && !base->tp_dictoffset) { PyObject **dictptr = _PyObject_GetDictPtr(self); if (dictptr != NULL) { PyObject *dict = *dictptr; if (dict != NULL) { Py_DECREF(dict); *dictptr = NULL; } } } /* Extract the type again; tp_del may have changed it */ type = Py_TYPE(self); /* Call the base tp_dealloc(); first retrack self if * basedealloc knows about gc. */ if (PyType_IS_GC(base)) _PyObject_GC_TRACK(self); assert(basedealloc); basedealloc(self); /* Can't reference self beyond this point. It's possible tp_del switched our type from a HEAPTYPE to a non-HEAPTYPE, so be careful about reference counting. */ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) Py_DECREF(type); endlabel: ++_PyTrash_delete_nesting; ++ tstate->trash_delete_nesting; Py_TRASHCAN_SAFE_END(self); --_PyTrash_delete_nesting; -- tstate->trash_delete_nesting; /* Explanation of the weirdness around the trashcan macros: Q. What do the trashcan macros do? A. Read the comment titled "Trashcan mechanism" in object.h. For one, this explains why there must be a call to GC-untrack before the trashcan begin macro. Without understanding the trashcan code, the answers to the following questions don't make sense. Q. Why do we GC-untrack before the trashcan and then immediately GC-track again afterward? A. In the case that the base class is GC-aware, the base class probably GC-untracks the object. If it does that using the UNTRACK macro, this will crash when the object is already untracked. Because we don't know what the base class does, the only safe thing is to make sure the object is tracked when we call the base class dealloc. But... The trashcan begin macro requires that the object is *untracked* before it is called. So the dance becomes: GC untrack trashcan begin GC track Q. Why did the last question say "immediately GC-track again"? It's nowhere near immediately. A. Because the code *used* to re-track immediately. Bad Idea. self has a refcount of 0, and if gc ever gets its hands on it (which can happen if any weakref callback gets invoked), it looks like trash to gc too, and gc also tries to delete self then. But we're already deleting self. Double deallocation is a subtle disaster. Q. Why the bizarre (net-zero) manipulation of _PyTrash_delete_nesting around the trashcan macros? A. Some base classes (e.g. list) also use the trashcan mechanism. The following scenario used to be possible: - suppose the trashcan level is one below the trashcan limit - subtype_dealloc() is called - the trashcan limit is not yet reached, so the trashcan level is incremented and the code between trashcan begin and end is executed - this destroys much of the object's contents, including its slots and __dict__ - basedealloc() is called; this is really list_dealloc(), or some other type which also uses the trashcan macros - the trashcan limit is now reached, so the object is put on the trashcan's to-be-deleted-later list - basedealloc() returns - subtype_dealloc() decrefs the object's type - subtype_dealloc() returns - later, the trashcan code starts deleting the objects from its to-be-deleted-later list - subtype_dealloc() is called *AGAIN* for the same object - at the very least (if the destroyed slots and __dict__ don't cause problems) the object's type gets decref'ed a second time, which is *BAD*!!! The remedy is to make sure that if the code between trashcan begin and end in subtype_dealloc() is called, the code between trashcan begin and end in basedealloc() will also be called. This is done by decrementing the level after passing into the trashcan block, and incrementing it just before leaving the block. But now it's possible that a chain of objects consisting solely of objects whose deallocator is subtype_dealloc() will defeat the trashcan mechanism completely: the decremented level means that the effective level never reaches the limit. Therefore, we *increment* the level *before* entering the trashcan block, and matchingly decrement it after leaving. This means the trashcan code will trigger a little early, but that's no big deal. Q. Are there any live examples of code in need of all this complexity? A. Yes. See SF bug 668433 for code that crashed (when Python was compiled in debug mode) before the trashcan level manipulations were added. For more discussion, see SF patches 581742, 575073 and bug 574207. */ } static PyTypeObject *solid_base(PyTypeObject *type); /* type test with subclassing support */ static int type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b) { do { if (a == b) return 1; a = a->tp_base; } while (a != NULL); return (b == &PyBaseObject_Type); } int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) { PyObject *mro; mro = a->tp_mro; if (mro != NULL) { /* Deal with multiple inheritance without recursion by walking the MRO tuple */ Py_ssize_t i, n; assert(PyTuple_Check(mro)); n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) return 1; } return 0; } else /* a is not completely initilized yet; follow tp_base */ return type_is_subtype_base_chain(a, b); } /* Internal routines to do a method lookup in the type without looking in the instance dictionary (so we can't use PyObject_GetAttr) but still binding it to the instance. The arguments are the object, the method name as a C string, and the address of a static variable used to cache the interned Python string. Variants: - lookup_maybe() returns NULL without raising an exception when the _PyType_Lookup() call fails; - lookup_maybe_method() and lookup_method() are similar to lookup_maybe(), but can return unbound PyFunction to avoid temporary method object. Pass self as first argument when unbound == 1. - _PyObject_LookupSpecial() expose lookup_maybe for the benefit of other places. */ forceinline PyObject * lookup_maybe(PyObject *self, _Py_Identifier *attrid) { PyObject *res; res = _PyType_LookupId(Py_TYPE(self), attrid); if (res != NULL) { descrgetfunc f; if ((f = Py_TYPE(res)->tp_descr_get) == NULL) Py_INCREF(res); else res = f(res, self, (PyObject *)(Py_TYPE(self))); } return res; } static PyObject * lookup_maybe_method(PyObject *self, _Py_Identifier *attrid, int *unbound) { PyObject *res = _PyType_LookupId(Py_TYPE(self), attrid); if (res == NULL) { return NULL; } if (PyFunction_Check(res)) { /* Avoid temporary PyMethodObject */ *unbound = 1; Py_INCREF(res); } else { *unbound = 0; descrgetfunc f = Py_TYPE(res)->tp_descr_get; if (f == NULL) { Py_INCREF(res); } else { res = f(res, self, (PyObject *)(Py_TYPE(self))); } } return res; } static PyObject * lookup_method(PyObject *self, _Py_Identifier *attrid, int *unbound) { PyObject *res = lookup_maybe_method(self, attrid, unbound); if (res == NULL && !PyErr_Occurred()) { PyErr_SetObject(PyExc_AttributeError, attrid->object); } return res; } PyObject * _PyObject_LookupSpecial(PyObject *self, _Py_Identifier *attrid) { return lookup_maybe(self, attrid); } static PyObject* call_unbound(int unbound, PyObject *func, PyObject *self, PyObject **args, Py_ssize_t nargs) { if (unbound) { return _PyObject_FastCall_Prepend(func, self, args, nargs); } else { return _PyObject_FastCall(func, args, nargs); } } static PyObject* call_unbound_noarg(int unbound, PyObject *func, PyObject *self) { if (unbound) { PyObject *args[1] = {self}; return _PyObject_FastCall(func, args, 1); } else { return _PyObject_CallNoArg(func); } } /* A variation of PyObject_CallMethodObjArgs that uses lookup_maybe_method() instead of PyObject_GetAttrString(). This uses the same convention as lookup_maybe_method to cache the interned name string object. */ static PyObject * call_method(PyObject *obj, _Py_Identifier *name, PyObject **args, Py_ssize_t nargs) { int unbound; PyObject *func, *retval; func = lookup_maybe_method(obj, name, &unbound); if (func == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_AttributeError, name->object); return NULL; } retval = call_unbound(unbound, func, obj, args, nargs); Py_DECREF(func); return retval; } /* Clone of call_method() that returns NotImplemented when the lookup fails. */ static PyObject * call_maybe(PyObject *obj, _Py_Identifier *name, PyObject **args, Py_ssize_t nargs) { int unbound; PyObject *func, *retval; func = lookup_maybe_method(obj, name, &unbound); if (func == NULL) { if (!PyErr_Occurred()) Py_RETURN_NOTIMPLEMENTED; return NULL; } retval = call_unbound(unbound, func, obj, args, nargs); Py_DECREF(func); return retval; } /* Method resolution order algorithm C3 described in "A Monotonic Superclass Linearization for Dylan", by Kim Barrett, Bob Cassel, Paul Haahr, David A. Moon, Keith Playford, and P. Tucker Withington. (OOPSLA 1996) Some notes about the rules implied by C3: No duplicate bases. It isn't legal to repeat a class in a list of base classes. The next three properties are the 3 constraints in "C3". Local precedence order. If A precedes B in C's MRO, then A will precede B in the MRO of all subclasses of C. Monotonicity. The MRO of a class must be an extension without reordering of the MRO of each of its superclasses. Extended Precedence Graph (EPG). Linearization is consistent if there is a path in the EPG from each class to all its successors in the linearization. See the paper for definition of EPG. */ static int tail_contains(PyObject *list, int whence, PyObject *o) { Py_ssize_t j, size; size = PyList_GET_SIZE(list); for (j = whence+1; j < size; j++) { if (PyList_GET_ITEM(list, j) == o) return 1; } return 0; } static PyObject * class_name(PyObject *cls) { PyObject *name = _PyObject_GetAttrId(cls, &PyId___name__); if (name == NULL) { PyErr_Clear(); name = PyObject_Repr(cls); } if (name == NULL) return NULL; if (!PyUnicode_Check(name)) { Py_DECREF(name); return NULL; } return name; } static int check_duplicates(PyObject *list) { Py_ssize_t i, j, n; /* Let's use a quadratic time algorithm, assuming that the bases lists is short. */ n = PyList_GET_SIZE(list); for (i = 0; i < n; i++) { PyObject *o = PyList_GET_ITEM(list, i); for (j = i + 1; j < n; j++) { if (PyList_GET_ITEM(list, j) == o) { o = class_name(o); if (o != NULL) { PyErr_Format(PyExc_TypeError, "duplicate base class %U", o); Py_DECREF(o); } else { PyErr_SetString(PyExc_TypeError, "duplicate base class"); } return -1; } } } return 0; } /* Raise a TypeError for an MRO order disagreement. It's hard to produce a good error message. In the absence of better insight into error reporting, report the classes that were candidates to be put next into the MRO. There is some conflict between the order in which they should be put in the MRO, but it's hard to diagnose what constraint can't be satisfied. */ static void set_mro_error(PyObject *to_merge, int *remain) { Py_ssize_t i, n, off, to_merge_size; char buf[1000]; PyObject *k, *v; PyObject *set = PyDict_New(); if (!set) return; to_merge_size = PyList_GET_SIZE(to_merge); for (i = 0; i < to_merge_size; i++) { PyObject *L = PyList_GET_ITEM(to_merge, i); if (remain[i] < PyList_GET_SIZE(L)) { PyObject *c = PyList_GET_ITEM(L, remain[i]); if (PyDict_SetItem(set, c, Py_None) < 0) { Py_DECREF(set); return; } } } n = PyDict_GET_SIZE(set); off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \ consistent method resolution\norder (MRO) for bases"); i = 0; while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) { PyObject *name = class_name(k); const char *name_str; if (name != NULL) { name_str = PyUnicode_AsUTF8(name); if (name_str == NULL) name_str = "?"; } else name_str = "?"; off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s", name_str); Py_XDECREF(name); if (--n && (size_t)(off+1) < sizeof(buf)) { buf[off++] = ','; buf[off] = '\0'; } } PyErr_SetString(PyExc_TypeError, buf); Py_DECREF(set); } static int pmerge(PyObject *acc, PyObject* to_merge) { int res = 0; Py_ssize_t i, j, to_merge_size, empty_cnt; int *remain; to_merge_size = PyList_GET_SIZE(to_merge); /* remain stores an index into each sublist of to_merge. remain[i] is the index of the next base in to_merge[i] that is not included in acc. */ remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size); if (remain == NULL) { PyErr_NoMemory(); return -1; } for (i = 0; i < to_merge_size; i++) remain[i] = 0; again: empty_cnt = 0; for (i = 0; i < to_merge_size; i++) { PyObject *candidate; PyObject *cur_list = PyList_GET_ITEM(to_merge, i); if (remain[i] >= PyList_GET_SIZE(cur_list)) { empty_cnt++; continue; } /* Choose next candidate for MRO. The input sequences alone can determine the choice. If not, choose the class which appears in the MRO of the earliest direct superclass of the new class. */ candidate = PyList_GET_ITEM(cur_list, remain[i]); for (j = 0; j < to_merge_size; j++) { PyObject *j_lst = PyList_GET_ITEM(to_merge, j); if (tail_contains(j_lst, remain[j], candidate)) goto skip; /* continue outer loop */ } res = PyList_Append(acc, candidate); if (res < 0) goto out; for (j = 0; j < to_merge_size; j++) { PyObject *j_lst = PyList_GET_ITEM(to_merge, j); if (remain[j] < PyList_GET_SIZE(j_lst) && PyList_GET_ITEM(j_lst, remain[j]) == candidate) { remain[j]++; } } goto again; skip: ; } if (empty_cnt != to_merge_size) { set_mro_error(to_merge, remain); res = -1; } out: PyMem_FREE(remain); return res; } static PyObject * mro_implementation(PyTypeObject *type) { PyObject *result = NULL; PyObject *bases; PyObject *to_merge, *bases_aslist; int res; Py_ssize_t i, n; if (type->tp_dict == NULL) { if (PyType_Ready(type) < 0) return NULL; } /* Find a superclass linearization that honors the constraints of the explicit lists of bases and the constraints implied by each base class. to_merge is a list of lists, where each list is a superclass linearization implied by a base class. The last element of to_merge is the declared list of bases. */ bases = type->tp_bases; n = PyTuple_GET_SIZE(bases); to_merge = PyList_New(n+1); if (to_merge == NULL) return NULL; for (i = 0; i < n; i++) { PyTypeObject *base; PyObject *base_mro_aslist; base = (PyTypeObject *)PyTuple_GET_ITEM(bases, i); if (base->tp_mro == NULL) { PyErr_Format(PyExc_TypeError, "Cannot extend an incomplete type '%.100s'", base->tp_name); goto out; } base_mro_aslist = PySequence_List(base->tp_mro); if (base_mro_aslist == NULL) goto out; PyList_SET_ITEM(to_merge, i, base_mro_aslist); } bases_aslist = PySequence_List(bases); if (bases_aslist == NULL) goto out; /* This is just a basic sanity check. */ if (check_duplicates(bases_aslist) < 0) { Py_DECREF(bases_aslist); goto out; } PyList_SET_ITEM(to_merge, n, bases_aslist); result = Py_BuildValue("[O]", (PyObject *)type); if (result == NULL) goto out; res = pmerge(result, to_merge); if (res < 0) Py_CLEAR(result); out: Py_DECREF(to_merge); return result; } static PyObject * mro_external(PyObject *self) { PyTypeObject *type = (PyTypeObject *)self; return mro_implementation(type); } static int mro_check(PyTypeObject *type, PyObject *mro) { PyTypeObject *solid; Py_ssize_t i, n; solid = solid_base(type); n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { PyTypeObject *base; PyObject *tmp; tmp = PyTuple_GET_ITEM(mro, i); if (!PyType_Check(tmp)) { PyErr_Format( PyExc_TypeError, "mro() returned a non-class ('%.500s')", Py_TYPE(tmp)->tp_name); return -1; } base = (PyTypeObject*)tmp; if (!PyType_IsSubtype(solid, solid_base(base))) { PyErr_Format( PyExc_TypeError, "mro() returned base with unsuitable layout ('%.500s')", base->tp_name); return -1; } } return 0; } /* Lookups an mcls.mro method, invokes it and checks the result (if needed, in case of a custom mro() implementation). Keep in mind that during execution of this function type->tp_mro can be replaced due to possible reentrance (for example, through type_set_bases): - when looking up the mcls.mro attribute (it could be a user-provided descriptor); - from inside a custom mro() itself; - through a finalizer of the return value of mro(). */ static PyObject * mro_invoke(PyTypeObject *type) { PyObject *mro_result; PyObject *new_mro; int custom = (Py_TYPE(type) != &PyType_Type); if (custom) { _Py_IDENTIFIER(mro); int unbound; PyObject *mro_meth = lookup_method((PyObject *)type, &PyId_mro, &unbound); if (mro_meth == NULL) return NULL; mro_result = call_unbound_noarg(unbound, mro_meth, (PyObject *)type); Py_DECREF(mro_meth); } else { mro_result = mro_implementation(type); } if (mro_result == NULL) return NULL; new_mro = PySequence_Tuple(mro_result); Py_DECREF(mro_result); if (new_mro == NULL) return NULL; if (custom && mro_check(type, new_mro) < 0) { Py_DECREF(new_mro); return NULL; } return new_mro; } /* Calculates and assigns a new MRO to type->tp_mro. Return values and invariants: - Returns 1 if a new MRO value has been set to type->tp_mro due to this call of mro_internal (no tricky reentrancy and no errors). In case if p_old_mro argument is not NULL, a previous value of type->tp_mro is put there, and the ownership of this reference is transferred to a caller. Otherwise, the previous value (if any) is decref'ed. - Returns 0 in case when type->tp_mro gets changed because of reentering here through a custom mro() (see a comment to mro_invoke). In this case, a refcount of an old type->tp_mro is adjusted somewhere deeper in the call stack (by the innermost mro_internal or its caller) and may become zero upon returning from here. This also implies that the whole hierarchy of subclasses of the type has seen the new value and updated their MRO accordingly. - Returns -1 in case of an error. */ static int mro_internal(PyTypeObject *type, PyObject **p_old_mro) { PyObject *new_mro, *old_mro; int reent; /* Keep a reference to be able to do a reentrancy check below. Don't let old_mro be GC'ed and its address be reused for another object, like (suddenly!) a new tp_mro. */ old_mro = type->tp_mro; Py_XINCREF(old_mro); new_mro = mro_invoke(type); /* might cause reentrance */ reent = (type->tp_mro != old_mro); Py_XDECREF(old_mro); if (new_mro == NULL) return -1; if (reent) { Py_DECREF(new_mro); return 0; } type->tp_mro = new_mro; type_mro_modified(type, type->tp_mro); /* corner case: the super class might have been hidden from the custom MRO */ type_mro_modified(type, type->tp_bases); PyType_Modified(type); if (p_old_mro != NULL) *p_old_mro = old_mro; /* transfer the ownership */ else Py_XDECREF(old_mro); return 1; } /* Calculate the best base amongst multiple base classes. This is the first one that's on the path to the "solid base". */ static PyTypeObject * best_base(PyObject *bases) { Py_ssize_t i, n; PyTypeObject *base, *winner, *candidate, *base_i; PyObject *base_proto; assert(PyTuple_Check(bases)); n = PyTuple_GET_SIZE(bases); assert(n > 0); base = NULL; winner = NULL; for (i = 0; i < n; i++) { base_proto = PyTuple_GET_ITEM(bases, i); if (!PyType_Check(base_proto)) { PyErr_SetString( PyExc_TypeError, "bases must be types"); return NULL; } base_i = (PyTypeObject *)base_proto; if (base_i->tp_dict == NULL) { if (PyType_Ready(base_i) < 0) return NULL; } if (!PyType_HasFeature(base_i, Py_TPFLAGS_BASETYPE)) { PyErr_Format(PyExc_TypeError, "type '%.100s' is not an acceptable base type", base_i->tp_name); return NULL; } candidate = solid_base(base_i); if (winner == NULL) { winner = candidate; base = base_i; } else if (PyType_IsSubtype(winner, candidate)) ; else if (PyType_IsSubtype(candidate, winner)) { winner = candidate; base = base_i; } else { PyErr_SetString( PyExc_TypeError, "multiple bases have " "instance lay-out conflict"); return NULL; } } assert (base != NULL); return base; } static int extra_ivars(PyTypeObject *type, PyTypeObject *base) { size_t t_size = type->tp_basicsize; size_t b_size = base->tp_basicsize; assert(t_size >= b_size); /* Else type smaller than base! */ if (type->tp_itemsize || base->tp_itemsize) { /* If itemsize is involved, stricter rules */ return t_size != b_size || type->tp_itemsize != base->tp_itemsize; } if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 && type->tp_weaklistoffset + sizeof(PyObject *) == t_size && type->tp_flags & Py_TPFLAGS_HEAPTYPE) t_size -= sizeof(PyObject *); if (type->tp_dictoffset && base->tp_dictoffset == 0 && type->tp_dictoffset + sizeof(PyObject *) == t_size && type->tp_flags & Py_TPFLAGS_HEAPTYPE) t_size -= sizeof(PyObject *); return t_size != b_size; } static PyTypeObject * solid_base(PyTypeObject *type) { PyTypeObject *base; if (type->tp_base) base = solid_base(type->tp_base); else base = &PyBaseObject_Type; if (extra_ivars(type, base)) return type; else return base; } static void object_dealloc(PyObject *); static int object_init(PyObject *, PyObject *, PyObject *); static int update_slot(PyTypeObject *, PyObject *); static void fixup_slot_dispatchers(PyTypeObject *); static int set_names(PyTypeObject *); static int init_subclass(PyTypeObject *, PyObject *); /* * Helpers for __dict__ descriptor. We don't want to expose the dicts * inherited from various builtin types. The builtin base usually provides * its own __dict__ descriptor, so we use that when we can. */ static PyTypeObject * get_builtin_base_with_dict(PyTypeObject *type) { while (type->tp_base != NULL) { if (type->tp_dictoffset != 0 && !(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) return type; type = type->tp_base; } return NULL; } static PyObject * get_dict_descriptor(PyTypeObject *type) { PyObject *descr; descr = _PyType_LookupId(type, &PyId___dict__); if (descr == NULL || !PyDescr_IsData(descr)) return NULL; return descr; } static void raise_dict_descr_error(PyObject *obj) { PyErr_Format(PyExc_TypeError, "this __dict__ descriptor does not support " "'%.200s' objects", Py_TYPE(obj)->tp_name); } static PyObject * subtype_dict(PyObject *obj, void *context) { PyTypeObject *base; base = get_builtin_base_with_dict(Py_TYPE(obj)); if (base != NULL) { descrgetfunc func; PyObject *descr = get_dict_descriptor(base); if (descr == NULL) { raise_dict_descr_error(obj); return NULL; } func = Py_TYPE(descr)->tp_descr_get; if (func == NULL) { raise_dict_descr_error(obj); return NULL; } return func(descr, obj, (PyObject *)(Py_TYPE(obj))); } return PyObject_GenericGetDict(obj, context); } static int subtype_setdict(PyObject *obj, PyObject *value, void *context) { PyObject **dictptr; PyTypeObject *base; base = get_builtin_base_with_dict(Py_TYPE(obj)); if (base != NULL) { descrsetfunc func; PyObject *descr = get_dict_descriptor(base); if (descr == NULL) { raise_dict_descr_error(obj); return -1; } func = Py_TYPE(descr)->tp_descr_set; if (func == NULL) { raise_dict_descr_error(obj); return -1; } return func(descr, obj, value); } /* Almost like PyObject_GenericSetDict, but allow __dict__ to be deleted. */ dictptr = _PyObject_GetDictPtr(obj); if (dictptr == NULL) { PyErr_SetString(PyExc_AttributeError, "This object has no __dict__"); return -1; } if (value != NULL && !PyDict_Check(value)) { PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, " "not a '%.200s'", Py_TYPE(value)->tp_name); return -1; } Py_XINCREF(value); Py_XSETREF(*dictptr, value); return 0; } static PyObject * subtype_getweakref(PyObject *obj, void *context) { PyObject **weaklistptr; PyObject *result; if (Py_TYPE(obj)->tp_weaklistoffset == 0) { PyErr_SetString(PyExc_AttributeError, "This object has no __weakref__"); return NULL; } assert(Py_TYPE(obj)->tp_weaklistoffset > 0); assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <= (size_t)(Py_TYPE(obj)->tp_basicsize)); weaklistptr = (PyObject **) ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset); if (*weaklistptr == NULL) result = Py_None; else result = *weaklistptr; Py_INCREF(result); return result; } /* Three variants on the subtype_getsets list. */ static PyGetSetDef subtype_getsets_full[] = { {"__dict__", subtype_dict, subtype_setdict, PyDoc_STR("dictionary for instance variables (if defined)")}, {"__weakref__", subtype_getweakref, NULL, PyDoc_STR("list of weak references to the object (if defined)")}, {0} }; static PyGetSetDef subtype_getsets_dict_only[] = { {"__dict__", subtype_dict, subtype_setdict, PyDoc_STR("dictionary for instance variables (if defined)")}, {0} }; static PyGetSetDef subtype_getsets_weakref_only[] = { {"__weakref__", subtype_getweakref, NULL, PyDoc_STR("list of weak references to the object (if defined)")}, {0} }; static int valid_identifier(PyObject *s) { if (!PyUnicode_Check(s)) { PyErr_Format(PyExc_TypeError, "__slots__ items must be strings, not '%.200s'", Py_TYPE(s)->tp_name); return 0; } if (!PyUnicode_IsIdentifier(s)) { PyErr_SetString(PyExc_TypeError, "__slots__ must be identifiers"); return 0; } return 1; } /* Forward */ static int object_init(PyObject *self, PyObject *args, PyObject *kwds); static int type_init(PyObject *cls, PyObject *args, PyObject *kwds) { int res; assert(args != NULL && PyTuple_Check(args)); assert(kwds == NULL || PyDict_Check(kwds)); if (kwds != NULL && PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 && PyDict_Check(kwds) && PyDict_GET_SIZE(kwds) != 0) { PyErr_SetString(PyExc_TypeError, "type.__init__() takes no keyword arguments"); return -1; } if (args != NULL && PyTuple_Check(args) && (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) { PyErr_SetString(PyExc_TypeError, "type.__init__() takes 1 or 3 arguments"); return -1; } /* Call object.__init__(self) now. */ /* XXX Could call super(type, cls).__init__() but what's the point? */ args = PyTuple_GetSlice(args, 0, 0); res = object_init(cls, args, NULL); Py_DECREF(args); return res; } unsigned long PyType_GetFlags(PyTypeObject *type) { return type->tp_flags; } /* Determine the most derived metatype. */ PyTypeObject * _PyType_CalculateMetaclass(PyTypeObject *metatype, PyObject *bases) { Py_ssize_t i, nbases; PyTypeObject *winner; PyObject *tmp; PyTypeObject *tmptype; /* Determine the proper metatype to deal with this, and check for metatype conflicts while we're at it. Note that if some other metatype wins to contract, it's possible that its instances are not types. */ nbases = PyTuple_GET_SIZE(bases); winner = metatype; for (i = 0; i < nbases; i++) { tmp = PyTuple_GET_ITEM(bases, i); tmptype = Py_TYPE(tmp); if (PyType_IsSubtype(winner, tmptype)) continue; if (PyType_IsSubtype(tmptype, winner)) { winner = tmptype; continue; } /* else: */ PyErr_SetString(PyExc_TypeError, "metaclass conflict: " "the metaclass of a derived class " "must be a (non-strict) subclass " "of the metaclasses of all its bases"); return NULL; } return winner; } static PyObject * type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds) { PyObject *name, *bases = NULL, *orig_dict, *dict = NULL; PyObject *qualname, *slots = NULL, *tmp, *newslots, *cell; PyTypeObject *type = NULL, *base, *tmptype, *winner; PyHeapTypeObject *et; PyMemberDef *mp; Py_ssize_t i, nbases, nslots, slotoffset, name_size; int j, may_add_dict, may_add_weak, add_dict, add_weak; _Py_IDENTIFIER(__qualname__); _Py_IDENTIFIER(__slots__); _Py_IDENTIFIER(__classcell__); assert(args != NULL && PyTuple_Check(args)); assert(kwds == NULL || PyDict_Check(kwds)); /* Special case: type(x) should return x->ob_type */ /* We only want type itself to accept the one-argument form (#27157) Note: We don't call PyType_CheckExact as that also allows subclasses */ if (metatype == &PyType_Type) { const Py_ssize_t nargs = PyTuple_GET_SIZE(args); const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_GET_SIZE(kwds); if (nargs == 1 && nkwds == 0) { PyObject *x = PyTuple_GET_ITEM(args, 0); Py_INCREF(Py_TYPE(x)); return (PyObject *) Py_TYPE(x); } /* SF bug 475327 -- if that didn't trigger, we need 3 arguments. but PyArg_ParseTupleAndKeywords below may give a msg saying type() needs exactly 3. */ if (nargs != 3) { PyErr_SetString(PyExc_TypeError, "type() takes 1 or 3 arguments"); return NULL; } } /* Check arguments: (name, bases, dict) */ if (!PyArg_ParseTuple(args, "UO!O!:type.__new__", &name, &PyTuple_Type, &bases, &PyDict_Type, &orig_dict)) return NULL; /* Determine the proper metatype to deal with this: */ winner = _PyType_CalculateMetaclass(metatype, bases); if (winner == NULL) { return NULL; } if (winner != metatype) { if (winner->tp_new != type_new) /* Pass it to the winner */ return winner->tp_new(winner, args, kwds); metatype = winner; } /* Adjust for empty tuple bases */ nbases = PyTuple_GET_SIZE(bases); if (nbases == 0) { bases = PyTuple_Pack(1, &PyBaseObject_Type); if (bases == NULL) goto error; nbases = 1; } else Py_INCREF(bases); /* Calculate best base, and check that all bases are type objects */ base = best_base(bases); if (base == NULL) { goto error; } dict = PyDict_Copy(orig_dict); if (dict == NULL) goto error; /* Check for a __slots__ sequence variable in dict, and count it */ slots = _PyDict_GetItemId(dict, &PyId___slots__); nslots = 0; add_dict = 0; add_weak = 0; may_add_dict = base->tp_dictoffset == 0; may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0; if (slots == NULL) { if (may_add_dict) { add_dict++; } if (may_add_weak) { add_weak++; } } else { /* Have slots */ /* Make it into a tuple */ if (PyUnicode_Check(slots)) slots = PyTuple_Pack(1, slots); else slots = PySequence_Tuple(slots); if (slots == NULL) goto error; assert(PyTuple_Check(slots)); /* Are slots allowed? */ nslots = PyTuple_GET_SIZE(slots); if (nslots > 0 && base->tp_itemsize != 0) { PyErr_Format(PyExc_TypeError, "nonempty __slots__ " "not supported for subtype of '%s'", base->tp_name); goto error; } /* Check for valid slot names and two special cases */ for (i = 0; i < nslots; i++) { PyObject *tmp = PyTuple_GET_ITEM(slots, i); if (!valid_identifier(tmp)) goto error; assert(PyUnicode_Check(tmp)); if (_PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) { if (!may_add_dict || add_dict) { PyErr_SetString(PyExc_TypeError, "__dict__ slot disallowed: " "we already got one"); goto error; } add_dict++; } if (_PyUnicode_EqualToASCIIString(tmp, "__weakref__")) { if (!may_add_weak || add_weak) { PyErr_SetString(PyExc_TypeError, "__weakref__ slot disallowed: " "either we already got one, " "or __itemsize__ != 0"); goto error; } add_weak++; } } /* Copy slots into a list, mangle names and sort them. Sorted names are needed for __class__ assignment. Convert them back to tuple at the end. */ newslots = PyList_New(nslots - add_dict - add_weak); if (newslots == NULL) goto error; for (i = j = 0; i < nslots; i++) { tmp = PyTuple_GET_ITEM(slots, i); if ((add_dict && _PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) || (add_weak && _PyUnicode_EqualToASCIIString(tmp, "__weakref__"))) continue; tmp =_Py_Mangle(name, tmp); if (!tmp) { Py_DECREF(newslots); goto error; } PyList_SET_ITEM(newslots, j, tmp); if (PyDict_GetItem(dict, tmp)) { PyErr_Format(PyExc_ValueError, "%R in __slots__ conflicts with class variable", tmp); Py_DECREF(newslots); goto error; } j++; } assert(j == nslots - add_dict - add_weak); nslots = j; Py_CLEAR(slots); if (PyList_Sort(newslots) == -1) { Py_DECREF(newslots); goto error; } slots = PyList_AsTuple(newslots); Py_DECREF(newslots); if (slots == NULL) goto error; /* Secondary bases may provide weakrefs or dict */ if (nbases > 1 && ((may_add_dict && !add_dict) || (may_add_weak && !add_weak))) { for (i = 0; i < nbases; i++) { tmp = PyTuple_GET_ITEM(bases, i); if (tmp == (PyObject *)base) continue; /* Skip primary base */ assert(PyType_Check(tmp)); tmptype = (PyTypeObject *)tmp; if (may_add_dict && !add_dict && tmptype->tp_dictoffset != 0) add_dict++; if (may_add_weak && !add_weak && tmptype->tp_weaklistoffset != 0) add_weak++; if (may_add_dict && !add_dict) continue; if (may_add_weak && !add_weak) continue; /* Nothing more to check */ break; } } } /* Allocate the type object */ type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots); if (type == NULL) goto error; /* Keep name and slots alive in the extended type object */ et = (PyHeapTypeObject *)type; Py_INCREF(name); et->ht_name = name; et->ht_slots = slots; slots = NULL; /* Initialize tp_flags */ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE; if (base->tp_flags & Py_TPFLAGS_HAVE_GC) type->tp_flags |= Py_TPFLAGS_HAVE_GC; /* Initialize essential fields */ type->tp_as_async = &et->as_async; type->tp_as_number = &et->as_number; type->tp_as_sequence = &et->as_sequence; type->tp_as_mapping = &et->as_mapping; type->tp_as_buffer = &et->as_buffer; type->tp_name = PyUnicode_AsUTF8AndSize(name, &name_size); if (!type->tp_name) goto error; if (strlen(type->tp_name) != (size_t)name_size) { PyErr_SetString(PyExc_ValueError, "type name must not contain null characters"); goto error; } /* Set tp_base and tp_bases */ type->tp_bases = bases; bases = NULL; Py_INCREF(base); type->tp_base = base; /* Initialize tp_dict from passed-in dict */ Py_INCREF(dict); type->tp_dict = dict; /* Set __module__ in the dict */ if (_PyDict_GetItemId(dict, &PyId___module__) == NULL) { tmp = PyEval_GetGlobals(); if (tmp != NULL) { tmp = _PyDict_GetItemId(tmp, &PyId___name__); if (tmp != NULL) { if (_PyDict_SetItemId(dict, &PyId___module__, tmp) < 0) goto error; } } } /* Set ht_qualname to dict['__qualname__'] if available, else to __name__. The __qualname__ accessor will look for ht_qualname. */ qualname = _PyDict_GetItemId(dict, &PyId___qualname__); if (qualname != NULL) { if (!PyUnicode_Check(qualname)) { PyErr_Format(PyExc_TypeError, "type __qualname__ must be a str, not %s", Py_TYPE(qualname)->tp_name); goto error; } } et->ht_qualname = qualname ? qualname : et->ht_name; Py_INCREF(et->ht_qualname); if (qualname != NULL && _PyDict_DelItemId(dict, &PyId___qualname__) < 0) goto error; /* Set tp_doc to a copy of dict['__doc__'], if the latter is there and is a string. The __doc__ accessor will first look for tp_doc; if that fails, it will still look into __dict__. */ { PyObject *doc = _PyDict_GetItemId(dict, &PyId___doc__); if (doc != NULL && PyUnicode_Check(doc)) { Py_ssize_t len; const char *doc_str; char *tp_doc; doc_str = PyUnicode_AsUTF8(doc); if (doc_str == NULL) goto error; /* Silently truncate the docstring if it contains null bytes. */ len = strlen(doc_str); tp_doc = (char *)PyObject_MALLOC(len + 1); if (tp_doc == NULL) { PyErr_NoMemory(); goto error; } memcpy(tp_doc, doc_str, len + 1); type->tp_doc = tp_doc; } } /* Special-case __new__: if it's a plain function, make it a static function */ tmp = _PyDict_GetItemId(dict, &PyId___new__); if (tmp != NULL && PyFunction_Check(tmp)) { tmp = PyStaticMethod_New(tmp); if (tmp == NULL) goto error; if (_PyDict_SetItemId(dict, &PyId___new__, tmp) < 0) { Py_DECREF(tmp); goto error; } Py_DECREF(tmp); } /* Special-case __init_subclass__: if it's a plain function, make it a classmethod */ tmp = _PyDict_GetItemId(dict, &PyId___init_subclass__); if (tmp != NULL && PyFunction_Check(tmp)) { tmp = PyClassMethod_New(tmp); if (tmp == NULL) goto error; if (_PyDict_SetItemId(dict, &PyId___init_subclass__, tmp) < 0) { Py_DECREF(tmp); goto error; } Py_DECREF(tmp); } /* Add descriptors for custom slots from __slots__, or for __dict__ */ mp = PyHeapType_GET_MEMBERS(et); slotoffset = base->tp_basicsize; if (et->ht_slots != NULL) { for (i = 0; i < nslots; i++, mp++) { mp->name = PyUnicode_AsUTF8( PyTuple_GET_ITEM(et->ht_slots, i)); if (mp->name == NULL) goto error; mp->type = T_OBJECT_EX; mp->offset = slotoffset; /* __dict__ and __weakref__ are already filtered out */ assert(strcmp(mp->name, "__dict__") != 0); assert(strcmp(mp->name, "__weakref__") != 0); slotoffset += sizeof(PyObject *); } } if (add_dict) { if (base->tp_itemsize) type->tp_dictoffset = -(long)sizeof(PyObject *); else type->tp_dictoffset = slotoffset; slotoffset += sizeof(PyObject *); } if (add_weak) { assert(!base->tp_itemsize); type->tp_weaklistoffset = slotoffset; slotoffset += sizeof(PyObject *); } type->tp_basicsize = slotoffset; type->tp_itemsize = base->tp_itemsize; type->tp_members = PyHeapType_GET_MEMBERS(et); if (type->tp_weaklistoffset && type->tp_dictoffset) type->tp_getset = subtype_getsets_full; else if (type->tp_weaklistoffset && !type->tp_dictoffset) type->tp_getset = subtype_getsets_weakref_only; else if (!type->tp_weaklistoffset && type->tp_dictoffset) type->tp_getset = subtype_getsets_dict_only; else type->tp_getset = NULL; /* Special case some slots */ if (type->tp_dictoffset != 0 || nslots > 0) { if (base->tp_getattr == NULL && base->tp_getattro == NULL) type->tp_getattro = PyObject_GenericGetAttr; if (base->tp_setattr == NULL && base->tp_setattro == NULL) type->tp_setattro = PyObject_GenericSetAttr; } type->tp_dealloc = subtype_dealloc; /* Enable GC unless this class is not adding new instance variables and the base class did not use GC. */ if ((base->tp_flags & Py_TPFLAGS_HAVE_GC) || type->tp_basicsize > base->tp_basicsize) type->tp_flags |= Py_TPFLAGS_HAVE_GC; /* Always override allocation strategy to use regular heap */ type->tp_alloc = PyType_GenericAlloc; if (type->tp_flags & Py_TPFLAGS_HAVE_GC) { type->tp_free = PyObject_GC_Del; type->tp_traverse = subtype_traverse; type->tp_clear = subtype_clear; } else type->tp_free = PyObject_Del; /* store type in class' cell if one is supplied */ cell = _PyDict_GetItemId(dict, &PyId___classcell__); if (cell != NULL) { /* At least one method requires a reference to its defining class */ if (!PyCell_Check(cell)) { PyErr_Format(PyExc_TypeError, "__classcell__ must be a nonlocal cell, not %.200R", Py_TYPE(cell)); goto error; } PyCell_Set(cell, (PyObject *) type); _PyDict_DelItemId(dict, &PyId___classcell__); PyErr_Clear(); } /* Initialize the rest */ if (PyType_Ready(type) < 0) goto error; /* Put the proper slots in place */ fixup_slot_dispatchers(type); if (type->tp_dictoffset) { et->ht_cached_keys = _PyDict_NewKeysForClass(); } if (set_names(type) < 0) goto error; if (init_subclass(type, kwds) < 0) goto error; Py_DECREF(dict); return (PyObject *)type; error: Py_XDECREF(dict); Py_XDECREF(bases); Py_XDECREF(slots); Py_XDECREF(type); return NULL; } PyObject * PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases) { PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0); PyTypeObject *type, *base; PyObject *modname; char *s; char *res_start = (char*)res; PyType_Slot *slot; /* Set the type name and qualname */ s = strrchr(spec->name, '.'); if (s == NULL) s = (char*)spec->name; else s++; if (res == NULL) return NULL; type = &res->ht_type; /* The flags must be initialized early, before the GC traverses us */ type->tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE; res->ht_name = PyUnicode_FromString(s); if (!res->ht_name) goto fail; res->ht_qualname = res->ht_name; Py_INCREF(res->ht_qualname); type->tp_name = spec->name; if (!type->tp_name) goto fail; /* Adjust for empty tuple bases */ if (!bases) { base = &PyBaseObject_Type; /* See whether Py_tp_base(s) was specified */ for (slot = spec->slots; slot->slot; slot++) { if (slot->slot == Py_tp_base) base = slot->pfunc; else if (slot->slot == Py_tp_bases) { bases = slot->pfunc; Py_INCREF(bases); } } if (!bases) bases = PyTuple_Pack(1, base); if (!bases) goto fail; } else Py_INCREF(bases); /* Calculate best base, and check that all bases are type objects */ base = best_base(bases); if (base == NULL) { goto fail; } if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) { PyErr_Format(PyExc_TypeError, "type '%.100s' is not an acceptable base type", base->tp_name); goto fail; } /* Initialize essential fields */ type->tp_as_async = &res->as_async; type->tp_as_number = &res->as_number; type->tp_as_sequence = &res->as_sequence; type->tp_as_mapping = &res->as_mapping; type->tp_as_buffer = &res->as_buffer; /* Set tp_base and tp_bases */ type->tp_bases = bases; bases = NULL; Py_INCREF(base); type->tp_base = base; type->tp_basicsize = spec->basicsize; type->tp_itemsize = spec->itemsize; for (slot = spec->slots; slot->slot; slot++) { if (slot->slot < 0 || (size_t)slot->slot >= Py_ARRAY_LENGTH(slotoffsets)) { PyErr_SetString(PyExc_RuntimeError, "invalid slot offset"); goto fail; } if (slot->slot == Py_tp_base || slot->slot == Py_tp_bases) /* Processed above */ continue; *(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc; /* need to make a copy of the docstring slot, which usually points to a static string literal */ if (slot->slot == Py_tp_doc) { const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, slot->pfunc); size_t len = strlen(old_doc)+1; char *tp_doc = PyObject_MALLOC(len); if (tp_doc == NULL) { PyErr_NoMemory(); goto fail; } memcpy(tp_doc, old_doc, len); type->tp_doc = tp_doc; } } if (type->tp_dealloc == NULL) { /* It's a heap type, so needs the heap types' dealloc. subtype_dealloc will call the base type's tp_dealloc, if necessary. */ type->tp_dealloc = subtype_dealloc; } if (PyType_Ready(type) < 0) goto fail; if (type->tp_dictoffset) { res->ht_cached_keys = _PyDict_NewKeysForClass(); } /* Set type.__module__ */ s = strrchr(spec->name, '.'); if (s != NULL) { int err; modname = PyUnicode_FromStringAndSize( spec->name, (Py_ssize_t)(s - spec->name)); if (modname == NULL) { goto fail; } err = _PyDict_SetItemId(type->tp_dict, &PyId___module__, modname); Py_DECREF(modname); if (err != 0) goto fail; } else { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "builtin type %.200s has no __module__ attribute", spec->name)) goto fail; } return (PyObject*)res; fail: Py_DECREF(res); return NULL; } PyObject * PyType_FromSpec(PyType_Spec *spec) { return PyType_FromSpecWithBases(spec, NULL); } void * PyType_GetSlot(PyTypeObject *type, int slot) { if (!PyType_HasFeature(type, Py_TPFLAGS_HEAPTYPE) || slot < 0) { PyErr_BadInternalCall(); return NULL; } if ((size_t)slot >= Py_ARRAY_LENGTH(slotoffsets)) { /* Extension module requesting slot from a future version */ return NULL; } return *(void**)(((char*)type) + slotoffsets[slot]); } /* Internal API to look for a name through the MRO. This returns a borrowed reference, and doesn't set an exception! */ PyObject * _PyType_Lookup(PyTypeObject *type, PyObject *name) { Py_ssize_t i, n; PyObject *mro, *res, *base, *dict; unsigned int h; if (LIKELY(MCACHE_CACHEABLE_NAME(name)) && LIKELY(PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))) { /* fast path */ h = MCACHE_HASH_METHOD(type, name); if (LIKELY(method_cache[h].version == type->tp_version_tag) && LIKELY(method_cache[h].name == name)) { #if MCACHE_STATS method_cache_hits++; #endif return method_cache[h].value; } } /* Look in tp_dict of types in MRO */ mro = type->tp_mro; if (UNLIKELY(mro == NULL)) { if (UNLIKELY((type->tp_flags & Py_TPFLAGS_READYING) == 0 && PyType_Ready(type) < 0)) { /* It's not ideal to clear the error condition, but this function is documented as not setting an exception, and I don't want to change that. When PyType_Ready() can't proceed, it won't set the "ready" flag, so future attempts to ready the same type will call it again -- hopefully in a context that propagates the exception out. */ PyErr_Clear(); return NULL; } mro = type->tp_mro; if (mro == NULL) { return NULL; } } res = NULL; /* keep a strong reference to mro because type->tp_mro can be replaced during PyDict_GetItem(dict, name) */ Py_INCREF(mro); assert(PyTuple_Check(mro)); n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { base = PyTuple_GET_ITEM(mro, i); assert(PyType_Check(base)); dict = ((PyTypeObject *)base)->tp_dict; assert(dict && PyDict_Check(dict)); res = PyDict_GetItem(dict, name); if (res != NULL) break; } Py_DECREF(mro); if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) { h = MCACHE_HASH_METHOD(type, name); method_cache[h].version = type->tp_version_tag; method_cache[h].value = res; /* borrowed */ Py_INCREF(name); assert(((PyASCIIObject *)(name))->hash != -1); #if MCACHE_STATS if (method_cache[h].name != Py_None && method_cache[h].name != name) method_cache_collisions++; else method_cache_misses++; #endif Py_SETREF(method_cache[h].name, name); } return res; } PyObject * _PyType_LookupId(PyTypeObject *type, struct _Py_Identifier *name) { PyObject *oname; oname = _PyUnicode_FromId(name); /* borrowed */ if (oname == NULL) return NULL; return _PyType_Lookup(type, oname); } /* This is similar to PyObject_GenericGetAttr(), but uses _PyType_Lookup() instead of just looking in type->tp_dict. */ static PyObject * type_getattro(PyTypeObject *type, PyObject *name) { PyTypeObject *metatype = Py_TYPE(type); PyObject *meta_attribute, *attribute; descrgetfunc meta_get; if (!PyUnicode_Check(name)) { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return NULL; } /* Initialize this type (we'll assume the metatype is initialized) */ if (type->tp_dict == NULL) { if (PyType_Ready(type) < 0) return NULL; } /* No readable descriptor found yet */ meta_get = NULL; /* Look for the attribute in the metatype */ meta_attribute = _PyType_Lookup(metatype, name); if (meta_attribute != NULL) { meta_get = Py_TYPE(meta_attribute)->tp_descr_get; if (meta_get != NULL && PyDescr_IsData(meta_attribute)) { /* Data descriptors implement tp_descr_set to intercept * writes. Assume the attribute is not overridden in * type's tp_dict (and bases): call the descriptor now. */ return meta_get(meta_attribute, (PyObject *)type, (PyObject *)metatype); } Py_INCREF(meta_attribute); } /* No data descriptor found on metatype. Look in tp_dict of this * type and its bases */ attribute = _PyType_Lookup(type, name); if (attribute != NULL) { /* Implement descriptor functionality, if any */ descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get; Py_XDECREF(meta_attribute); if (local_get != NULL) { /* NULL 2nd argument indicates the descriptor was * found on the target object itself (or a base) */ return local_get(attribute, (PyObject *)NULL, (PyObject *)type); } Py_INCREF(attribute); return attribute; } /* No attribute found in local __dict__ (or bases): use the * descriptor from the metatype, if any */ if (meta_get != NULL) { PyObject *res; res = meta_get(meta_attribute, (PyObject *)type, (PyObject *)metatype); Py_DECREF(meta_attribute); return res; } /* If an ordinary attribute was found on the metatype, return it now */ if (meta_attribute != NULL) { return meta_attribute; } /* Give up */ PyErr_Format(PyExc_AttributeError, "type object '%.50s' has no attribute '%U'", type->tp_name, name); return NULL; } static int type_setattro(PyTypeObject *type, PyObject *name, PyObject *value) { int res; if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { PyErr_Format( PyExc_TypeError, "can't set attributes of built-in/extension type '%s'", type->tp_name); return -1; } if (PyUnicode_Check(name)) { if (PyUnicode_CheckExact(name)) { if (PyUnicode_READY(name) == -1) return -1; Py_INCREF(name); } else { name = _PyUnicode_Copy(name); if (name == NULL) return -1; } PyUnicode_InternInPlace(&name); if (!PyUnicode_CHECK_INTERNED(name)) { PyErr_SetString(PyExc_MemoryError, "Out of memory interning an attribute name"); Py_DECREF(name); return -1; } } else { /* Will fail in _PyObject_GenericSetAttrWithDict. */ Py_INCREF(name); } res = _PyObject_GenericSetAttrWithDict((PyObject *)type, name, value, NULL); if (res == 0) { res = update_slot(type, name); assert(_PyType_CheckConsistency(type)); } Py_DECREF(name); return res; } extern void _PyDictKeys_DecRef(PyDictKeysObject *keys); static void type_dealloc(PyTypeObject *type) { PyHeapTypeObject *et; PyObject *tp, *val, *tb; /* Assert this is a heap-allocated type object */ assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); _PyObject_GC_UNTRACK(type); PyErr_Fetch(&tp, &val, &tb); remove_all_subclasses(type, type->tp_bases); PyErr_Restore(tp, val, tb); PyObject_ClearWeakRefs((PyObject *)type); et = (PyHeapTypeObject *)type; Py_XDECREF(type->tp_base); Py_XDECREF(type->tp_dict); Py_XDECREF(type->tp_bases); Py_XDECREF(type->tp_mro); Py_XDECREF(type->tp_cache); Py_XDECREF(type->tp_subclasses); /* A type's tp_doc is heap allocated, unlike the tp_doc slots * of most other objects. It's okay to cast it to char *. */ PyObject_Free((char *)type->tp_doc); Py_XDECREF(et->ht_name); Py_XDECREF(et->ht_qualname); Py_XDECREF(et->ht_slots); if (et->ht_cached_keys) _PyDictKeys_DecRef(et->ht_cached_keys); Py_TYPE(type)->tp_free((PyObject *)type); } static PyObject * type_subclasses(PyTypeObject *type, PyObject *args_ignored) { PyObject *list, *raw, *ref; Py_ssize_t i; list = PyList_New(0); if (list == NULL) return NULL; raw = type->tp_subclasses; if (raw == NULL) return list; assert(PyDict_CheckExact(raw)); i = 0; while (PyDict_Next(raw, &i, NULL, &ref)) { assert(PyWeakref_CheckRef(ref)); ref = PyWeakref_GET_OBJECT(ref); if (ref != Py_None) { if (PyList_Append(list, ref) < 0) { Py_DECREF(list); return NULL; } } } return list; } static PyObject * type_prepare(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { return PyDict_New(); } /* Merge the __dict__ of aclass into dict, and recursively also all the __dict__s of aclass's base classes. The order of merging isn't defined, as it's expected that only the final set of dict keys is interesting. Return 0 on success, -1 on error. */ static int merge_class_dict(PyObject *dict, PyObject *aclass) { PyObject *classdict; PyObject *bases; _Py_IDENTIFIER(__bases__); assert(PyDict_Check(dict)); assert(aclass); /* Merge in the type's dict (if any). */ classdict = _PyObject_GetAttrId(aclass, &PyId___dict__); if (classdict == NULL) PyErr_Clear(); else { int status = PyDict_Update(dict, classdict); Py_DECREF(classdict); if (status < 0) return -1; } /* Recursively merge in the base types' (if any) dicts. */ bases = _PyObject_GetAttrId(aclass, &PyId___bases__); if (bases == NULL) PyErr_Clear(); else { /* We have no guarantee that bases is a real tuple */ Py_ssize_t i, n; n = PySequence_Size(bases); /* This better be right */ if (n < 0) PyErr_Clear(); else { for (i = 0; i < n; i++) { int status; PyObject *base = PySequence_GetItem(bases, i); if (base == NULL) { Py_DECREF(bases); return -1; } status = merge_class_dict(dict, base); Py_DECREF(base); if (status < 0) { Py_DECREF(bases); return -1; } } } Py_DECREF(bases); } return 0; } /* __dir__ for type objects: returns __dict__ and __bases__. We deliberately don't suck up its __class__, as methods belonging to the metaclass would probably be more confusing than helpful. */ static PyObject * type_dir(PyObject *self, PyObject *args) { PyObject *result = NULL; PyObject *dict = PyDict_New(); if (dict != NULL && merge_class_dict(dict, self) == 0) result = PyDict_Keys(dict); Py_XDECREF(dict); return result; } static PyObject* type_sizeof(PyObject *self, PyObject *args_unused) { Py_ssize_t size; PyTypeObject *type = (PyTypeObject*)self; if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { PyHeapTypeObject* et = (PyHeapTypeObject*)type; size = sizeof(PyHeapTypeObject); if (et->ht_cached_keys) size += _PyDict_KeysSize(et->ht_cached_keys); } else size = sizeof(PyTypeObject); return PyLong_FromSsize_t(size); } static PyMethodDef type_methods[] = { {"mro", (PyCFunction)mro_external, METH_NOARGS, PyDoc_STR("mro() -> list\nreturn a type's method resolution order")}, {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS, PyDoc_STR("__subclasses__() -> list of immediate subclasses")}, {"__prepare__", (PyCFunction)type_prepare, METH_FASTCALL | METH_KEYWORDS | METH_CLASS, PyDoc_STR("__prepare__() -> dict\n" "used to create the namespace for the class statement")}, {"__instancecheck__", type___instancecheck__, METH_O, PyDoc_STR("__instancecheck__() -> bool\ncheck if an object is an instance")}, {"__subclasscheck__", type___subclasscheck__, METH_O, PyDoc_STR("__subclasscheck__() -> bool\ncheck if a class is a subclass")}, {"__dir__", type_dir, METH_NOARGS, PyDoc_STR("__dir__() -> list\nspecialized __dir__ implementation for types")}, {"__sizeof__", type_sizeof, METH_NOARGS, "__sizeof__() -> int\nreturn memory consumption of the type object"}, {0} }; PyDoc_STRVAR(type_doc, /* this text signature cannot be accurate yet. will fix. --larry */ "type(object_or_name, bases, dict)\n" "type(object) -> the object's type\n" "type(name, bases, dict) -> a new type"); static int type_traverse(PyTypeObject *type, visitproc visit, void *arg) { /* Because of type_is_gc(), the collector only calls this for heaptypes. */ if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { char msg[200]; sprintf(msg, "type_traverse() called for non-heap type '%.100s'", type->tp_name); Py_FatalError(msg); } Py_VISIT(type->tp_dict); Py_VISIT(type->tp_cache); Py_VISIT(type->tp_mro); Py_VISIT(type->tp_bases); Py_VISIT(type->tp_base); /* There's no need to visit type->tp_subclasses or ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved in cycles; tp_subclasses is a list of weak references, and slots is a tuple of strings. */ return 0; } static int type_clear(PyTypeObject *type) { PyDictKeysObject *cached_keys; /* Because of type_is_gc(), the collector only calls this for heaptypes. */ assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE); /* We need to invalidate the method cache carefully before clearing the dict, so that other objects caught in a reference cycle don't start calling destroyed methods. Otherwise, the only field we need to clear is tp_mro, which is part of a hard cycle (its first element is the class itself) that won't be broken otherwise (it's a tuple and tuples don't have a tp_clear handler). None of the other fields need to be cleared, and here's why: tp_cache: Not used; if it were, it would be a dict. tp_bases, tp_base: If these are involved in a cycle, there must be at least one other, mutable object in the cycle, e.g. a base class's dict; the cycle will be broken that way. tp_subclasses: A dict of weak references can't be part of a cycle; and dicts have their own tp_clear. slots (in PyHeapTypeObject): A tuple of strings can't be part of a cycle. */ PyType_Modified(type); cached_keys = ((PyHeapTypeObject *)type)->ht_cached_keys; if (cached_keys != NULL) { ((PyHeapTypeObject *)type)->ht_cached_keys = NULL; _PyDictKeys_DecRef(cached_keys); } if (type->tp_dict) PyDict_Clear(type->tp_dict); Py_CLEAR(type->tp_mro); return 0; } static int type_is_gc(PyTypeObject *type) { return type->tp_flags & Py_TPFLAGS_HEAPTYPE; } PyTypeObject PyType_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "type", /* tp_name */ sizeof(PyHeapTypeObject), /* tp_basicsize */ sizeof(PyMemberDef), /* tp_itemsize */ (destructor)type_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)type_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)type_call, /* tp_call */ 0, /* tp_str */ (getattrofunc)type_getattro, /* tp_getattro */ (setattrofunc)type_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */ type_doc, /* tp_doc */ (traverseproc)type_traverse, /* tp_traverse */ (inquiry)type_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ type_methods, /* tp_methods */ type_members, /* tp_members */ type_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */ type_init, /* tp_init */ 0, /* tp_alloc */ type_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ (inquiry)type_is_gc, /* tp_is_gc */ }; /* The base type of all types (eventually)... except itself. */ /* You may wonder why object.__new__() only complains about arguments when object.__init__() is not overridden, and vice versa. Consider the use cases: 1. When neither is overridden, we want to hear complaints about excess (i.e., any) arguments, since their presence could indicate there's a bug. 2. When defining an Immutable type, we are likely to override only __new__(), since __init__() is called too late to initialize an Immutable object. Since __new__() defines the signature for the type, it would be a pain to have to override __init__() just to stop it from complaining about excess arguments. 3. When defining a Mutable type, we are likely to override only __init__(). So here the converse reasoning applies: we don't want to have to override __new__() just to stop it from complaining. 4. When __init__() is overridden, and the subclass __init__() calls object.__init__(), the latter should complain about excess arguments; ditto for __new__(). Use cases 2 and 3 make it unattractive to unconditionally check for excess arguments. The best solution that addresses all four use cases is as follows: __init__() complains about excess arguments unless __new__() is overridden and __init__() is not overridden (IOW, if __init__() is overridden or __new__() is not overridden); symmetrically, __new__() complains about excess arguments unless __init__() is overridden and __new__() is not overridden (IOW, if __new__() is overridden or __init__() is not overridden). However, for backwards compatibility, this breaks too much code. Therefore, in 2.6, we'll *warn* about excess arguments when both methods are overridden; for all other cases we'll use the above rules. */ /* Forward */ static PyObject * object_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static int excess_args(PyObject *args, PyObject *kwds) { return PyTuple_GET_SIZE(args) || (kwds && PyDict_Check(kwds) && PyDict_GET_SIZE(kwds)); } static int object_init(PyObject *self, PyObject *args, PyObject *kwds) { int err = 0; PyTypeObject *type = Py_TYPE(self); if (excess_args(args, kwds) && (type->tp_new == object_new || type->tp_init != object_init)) { PyErr_SetString(PyExc_TypeError, "object.__init__() takes no parameters"); err = -1; } return err; } static PyObject * object_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { if (excess_args(args, kwds) && (type->tp_init == object_init || type->tp_new != object_new)) { PyErr_SetString(PyExc_TypeError, "object() takes no parameters"); return NULL; } if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) { PyObject *abstract_methods = NULL; PyObject *builtins; PyObject *sorted; PyObject *sorted_methods = NULL; PyObject *joined = NULL; PyObject *comma; _Py_static_string(comma_id, ", "); _Py_IDENTIFIER(sorted); /* Compute ", ".join(sorted(type.__abstractmethods__)) into joined. */ abstract_methods = type_abstractmethods(type, NULL); if (abstract_methods == NULL) goto error; builtins = PyEval_GetBuiltins(); if (builtins == NULL) goto error; sorted = _PyDict_GetItemId(builtins, &PyId_sorted); if (sorted == NULL) goto error; sorted_methods = PyObject_CallFunctionObjArgs(sorted, abstract_methods, NULL); if (sorted_methods == NULL) goto error; comma = _PyUnicode_FromId(&comma_id); if (comma == NULL) goto error; joined = PyUnicode_Join(comma, sorted_methods); if (joined == NULL) goto error; PyErr_Format(PyExc_TypeError, "Can't instantiate abstract class %s " "with abstract methods %U", type->tp_name, joined); error: Py_XDECREF(joined); Py_XDECREF(sorted_methods); Py_XDECREF(abstract_methods); return NULL; } return type->tp_alloc(type, 0); } static void object_dealloc(PyObject *self) { Py_TYPE(self)->tp_free(self); } static PyObject * object_repr(PyObject *self) { PyTypeObject *type; PyObject *mod, *name, *rtn; type = Py_TYPE(self); mod = type_module(type, NULL); if (mod == NULL) PyErr_Clear(); else if (!PyUnicode_Check(mod)) { Py_DECREF(mod); mod = NULL; } name = type_qualname(type, NULL); if (name == NULL) { Py_XDECREF(mod); return NULL; } if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins)) rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self); else rtn = PyUnicode_FromFormat("<%s object at %p>", type->tp_name, self); Py_XDECREF(mod); Py_DECREF(name); return rtn; } static PyObject * object_str(PyObject *self) { unaryfunc f; f = Py_TYPE(self)->tp_repr; if (f == NULL) f = object_repr; return f(self); } static PyObject * object_richcompare(PyObject *self, PyObject *other, int op) { PyObject *res; switch (op) { case Py_EQ: /* Return NotImplemented instead of False, so if two objects are compared, both get a chance at the comparison. See issue #1393. */ res = (self == other) ? Py_True : Py_NotImplemented; Py_INCREF(res); break; case Py_NE: /* By default, __ne__() delegates to __eq__() and inverts the result, unless the latter returns NotImplemented. */ if (self->ob_type->tp_richcompare == NULL) { res = Py_NotImplemented; Py_INCREF(res); break; } res = (*self->ob_type->tp_richcompare)(self, other, Py_EQ); if (res != NULL && res != Py_NotImplemented) { int ok = PyObject_IsTrue(res); Py_DECREF(res); if (ok < 0) res = NULL; else { if (ok) res = Py_False; else res = Py_True; Py_INCREF(res); } } break; default: res = Py_NotImplemented; Py_INCREF(res); break; } return res; } static PyObject * object_get_class(PyObject *self, void *closure) { Py_INCREF(Py_TYPE(self)); return (PyObject *)(Py_TYPE(self)); } static int compatible_with_tp_base(PyTypeObject *child) { PyTypeObject *parent = child->tp_base; return (parent != NULL && child->tp_basicsize == parent->tp_basicsize && child->tp_itemsize == parent->tp_itemsize && child->tp_dictoffset == parent->tp_dictoffset && child->tp_weaklistoffset == parent->tp_weaklistoffset && ((child->tp_flags & Py_TPFLAGS_HAVE_GC) == (parent->tp_flags & Py_TPFLAGS_HAVE_GC)) && (child->tp_dealloc == subtype_dealloc || child->tp_dealloc == parent->tp_dealloc)); } static int same_slots_added(PyTypeObject *a, PyTypeObject *b) { PyTypeObject *base = a->tp_base; Py_ssize_t size; PyObject *slots_a, *slots_b; assert(base == b->tp_base); size = base->tp_basicsize; if (a->tp_dictoffset == size && b->tp_dictoffset == size) size += sizeof(PyObject *); if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size) size += sizeof(PyObject *); /* Check slots compliance */ if (!(a->tp_flags & Py_TPFLAGS_HEAPTYPE) || !(b->tp_flags & Py_TPFLAGS_HEAPTYPE)) { return 0; } slots_a = ((PyHeapTypeObject *)a)->ht_slots; slots_b = ((PyHeapTypeObject *)b)->ht_slots; if (slots_a && slots_b) { if (PyObject_RichCompareBool(slots_a, slots_b, Py_EQ) != 1) return 0; size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a); } return size == a->tp_basicsize && size == b->tp_basicsize; } static int compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, const char* attr) { PyTypeObject *newbase, *oldbase; if (newto->tp_free != oldto->tp_free) { PyErr_Format(PyExc_TypeError, "%s assignment: " "'%s' deallocator differs from '%s'", attr, newto->tp_name, oldto->tp_name); return 0; } /* It's tricky to tell if two arbitrary types are sufficiently compatible as to be interchangeable; e.g., even if they have the same tp_basicsize, they might have totally different struct fields. It's much easier to tell if a type and its supertype are compatible; e.g., if they have the same tp_basicsize, then that means they have identical fields. So to check whether two arbitrary types are compatible, we first find the highest supertype that each is compatible with, and then if those supertypes are compatible then the original types must also be compatible. */ newbase = newto; oldbase = oldto; while (compatible_with_tp_base(newbase)) newbase = newbase->tp_base; while (compatible_with_tp_base(oldbase)) oldbase = oldbase->tp_base; if (newbase != oldbase && (newbase->tp_base != oldbase->tp_base || !same_slots_added(newbase, oldbase))) { PyErr_Format(PyExc_TypeError, "%s assignment: " "'%s' object layout differs from '%s'", attr, newto->tp_name, oldto->tp_name); return 0; } return 1; } static int object_set_class(PyObject *self, PyObject *value, void *closure) { PyTypeObject *oldto = Py_TYPE(self); PyTypeObject *newto; if (value == NULL) { PyErr_SetString(PyExc_TypeError, "can't delete __class__ attribute"); return -1; } if (!PyType_Check(value)) { PyErr_Format(PyExc_TypeError, "__class__ must be set to a class, not '%s' object", Py_TYPE(value)->tp_name); return -1; } newto = (PyTypeObject *)value; /* In versions of CPython prior to 3.5, the code in compatible_for_assignment was not set up to correctly check for memory layout / slot / etc. compatibility for non-HEAPTYPE classes, so we just disallowed __class__ assignment in any case that wasn't HEAPTYPE -> HEAPTYPE. During the 3.5 development cycle, we fixed the code in compatible_for_assignment to correctly check compatibility between arbitrary types, and started allowing __class__ assignment in all cases where the old and new types did in fact have compatible slots and memory layout (regardless of whether they were implemented as HEAPTYPEs or not). Just before 3.5 was released, though, we discovered that this led to problems with immutable types like int, where the interpreter assumes they are immutable and interns some values. Formerly this wasn't a problem, because they really were immutable -- in particular, all the types where the interpreter applied this interning trick happened to also be statically allocated, so the old HEAPTYPE rules were "accidentally" stopping them from allowing __class__ assignment. But with the changes to __class__ assignment, we started allowing code like class MyInt(int): ... # Modifies the type of *all* instances of 1 in the whole program, # including future instances (!), because the 1 object is interned. (1).__class__ = MyInt (see https://bugs.python.org/issue24912). In theory the proper fix would be to identify which classes rely on this invariant and somehow disallow __class__ assignment only for them, perhaps via some mechanism like a new Py_TPFLAGS_IMMUTABLE flag (a "blacklisting" approach). But in practice, since this problem wasn't noticed late in the 3.5 RC cycle, we're taking the conservative approach and reinstating the same HEAPTYPE->HEAPTYPE check that we used to have, plus a "whitelist". For now, the whitelist consists only of ModuleType subtypes, since those are the cases that motivated the patch in the first place -- see https://bugs.python.org/issue22986 -- and since module objects are mutable we can be sure that they are definitely not being interned. So now we allow HEAPTYPE->HEAPTYPE *or* ModuleType subtype -> ModuleType subtype. So far as we know, all the code beyond the following 'if' statement will correctly handle non-HEAPTYPE classes, and the HEAPTYPE check is needed only to protect that subset of non-HEAPTYPE classes for which the interpreter has baked in the assumption that all instances are truly immutable. */ if (!(PyType_IsSubtype(newto, &PyModule_Type) && PyType_IsSubtype(oldto, &PyModule_Type)) && (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) || !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))) { PyErr_Format(PyExc_TypeError, "__class__ assignment only supported for heap types " "or ModuleType subclasses"); return -1; } if (compatible_for_assignment(oldto, newto, "__class__")) { if (newto->tp_flags & Py_TPFLAGS_HEAPTYPE) Py_INCREF(newto); Py_TYPE(self) = newto; if (oldto->tp_flags & Py_TPFLAGS_HEAPTYPE) Py_DECREF(oldto); return 0; } else { return -1; } } static PyGetSetDef object_getsets[] = { {"__class__", object_get_class, object_set_class, PyDoc_STR("the object's class")}, {0} }; /* Stuff to implement __reduce_ex__ for pickle protocols >= 2. We fall back to helpers in copyreg for: - pickle protocols < 2 - calculating the list of slot names (done only once per class) - the __newobj__ function (which is used as a token but never called) */ static PyObject * import_copyreg(void) { PyObject *copyreg_str; PyObject *copyreg_module; PyInterpreterState *interp = PyThreadState_GET()->interp; _Py_IDENTIFIER(copyreg); copyreg_str = _PyUnicode_FromId(&PyId_copyreg); if (copyreg_str == NULL) { return NULL; } /* Try to fetch cached copy of copyreg from sys.modules first in an attempt to avoid the import overhead. Previously this was implemented by storing a reference to the cached module in a static variable, but this broke when multiple embedded interpreters were in use (see issue #17408 and #19088). */ copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str); if (copyreg_module != NULL) { Py_INCREF(copyreg_module); return copyreg_module; } if (PyErr_Occurred()) { return NULL; } return PyImport_Import(copyreg_str); } static PyObject * _PyType_GetSlotNames(PyTypeObject *cls) { PyObject *copyreg; PyObject *slotnames; _Py_IDENTIFIER(__slotnames__); _Py_IDENTIFIER(_slotnames); assert(PyType_Check(cls)); /* Get the slot names from the cache in the class if possible. */ slotnames = _PyDict_GetItemIdWithError(cls->tp_dict, &PyId___slotnames__); if (slotnames != NULL) { if (slotnames != Py_None && !PyList_Check(slotnames)) { PyErr_Format(PyExc_TypeError, "%.200s.__slotnames__ should be a list or None, " "not %.200s", cls->tp_name, Py_TYPE(slotnames)->tp_name); return NULL; } Py_INCREF(slotnames); return slotnames; } else { if (PyErr_Occurred()) { return NULL; } /* The class does not have the slot names cached yet. */ } copyreg = import_copyreg(); if (copyreg == NULL) return NULL; /* Use _slotnames function from the copyreg module to find the slots by this class and its bases. This function will cache the result in __slotnames__. */ slotnames = _PyObject_CallMethodIdObjArgs(copyreg, &PyId__slotnames, cls, NULL); Py_DECREF(copyreg); if (slotnames == NULL) return NULL; if (slotnames != Py_None && !PyList_Check(slotnames)) { PyErr_SetString(PyExc_TypeError, "copyreg._slotnames didn't return a list or None"); Py_DECREF(slotnames); return NULL; } return slotnames; } static PyObject * _PyObject_GetState(PyObject *obj, int required) { PyObject *state; PyObject *getstate; _Py_IDENTIFIER(__getstate__); getstate = _PyObject_GetAttrId(obj, &PyId___getstate__); if (getstate == NULL) { PyObject *slotnames; if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { return NULL; } PyErr_Clear(); if (required && obj->ob_type->tp_itemsize) { PyErr_Format(PyExc_TypeError, "can't pickle %.200s objects", Py_TYPE(obj)->tp_name); return NULL; } { PyObject **dict; dict = _PyObject_GetDictPtr(obj); /* It is possible that the object's dict is not initialized yet. In this case, we will return None for the state. We also return None if the dict is empty to make the behavior consistent regardless whether the dict was initialized or not. This make unit testing easier. */ if (dict != NULL && *dict != NULL && PyDict_GET_SIZE(*dict)) { state = *dict; } else { state = Py_None; } Py_INCREF(state); } slotnames = _PyType_GetSlotNames(Py_TYPE(obj)); if (slotnames == NULL) { Py_DECREF(state); return NULL; } assert(slotnames == Py_None || PyList_Check(slotnames)); if (required) { Py_ssize_t basicsize = PyBaseObject_Type.tp_basicsize; if (obj->ob_type->tp_dictoffset) basicsize += sizeof(PyObject *); if (obj->ob_type->tp_weaklistoffset) basicsize += sizeof(PyObject *); if (slotnames != Py_None) basicsize += sizeof(PyObject *) * Py_SIZE(slotnames); if (obj->ob_type->tp_basicsize > basicsize) { Py_DECREF(slotnames); Py_DECREF(state); PyErr_Format(PyExc_TypeError, "can't pickle %.200s objects", Py_TYPE(obj)->tp_name); return NULL; } } if (slotnames != Py_None && Py_SIZE(slotnames) > 0) { PyObject *slots; Py_ssize_t slotnames_size, i; slots = PyDict_New(); if (slots == NULL) { Py_DECREF(slotnames); Py_DECREF(state); return NULL; } slotnames_size = Py_SIZE(slotnames); for (i = 0; i < slotnames_size; i++) { PyObject *name, *value; name = PyList_GET_ITEM(slotnames, i); Py_INCREF(name); value = PyObject_GetAttr(obj, name); if (value == NULL) { Py_DECREF(name); if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { goto error; } /* It is not an error if the attribute is not present. */ PyErr_Clear(); } else { int err = PyDict_SetItem(slots, name, value); Py_DECREF(name); Py_DECREF(value); if (err) { goto error; } } /* The list is stored on the class so it may mutate while we iterate over it */ if (slotnames_size != Py_SIZE(slotnames)) { PyErr_Format(PyExc_RuntimeError, "__slotsname__ changed size during iteration"); goto error; } /* We handle errors within the loop here. */ if (0) { error: Py_DECREF(slotnames); Py_DECREF(slots); Py_DECREF(state); return NULL; } } /* If we found some slot attributes, pack them in a tuple along the original attribute dictionary. */ if (PyDict_GET_SIZE(slots) > 0) { PyObject *state2; state2 = PyTuple_Pack(2, state, slots); Py_DECREF(state); if (state2 == NULL) { Py_DECREF(slotnames); Py_DECREF(slots); return NULL; } state = state2; } Py_DECREF(slots); } Py_DECREF(slotnames); } else { /* getstate != NULL */ state = _PyObject_CallNoArg(getstate); Py_DECREF(getstate); if (state == NULL) return NULL; } return state; } static int _PyObject_GetNewArguments(PyObject *obj, PyObject **args, PyObject **kwargs) { PyObject *getnewargs, *getnewargs_ex; _Py_IDENTIFIER(__getnewargs_ex__); _Py_IDENTIFIER(__getnewargs__); if (args == NULL || kwargs == NULL) { PyErr_BadInternalCall(); return -1; } /* We first attempt to fetch the arguments for __new__ by calling __getnewargs_ex__ on the object. */ getnewargs_ex = _PyObject_LookupSpecial(obj, &PyId___getnewargs_ex__); if (getnewargs_ex != NULL) { PyObject *newargs = _PyObject_CallNoArg(getnewargs_ex); Py_DECREF(getnewargs_ex); if (newargs == NULL) { return -1; } if (!PyTuple_Check(newargs)) { PyErr_Format(PyExc_TypeError, "__getnewargs_ex__ should return a tuple, " "not '%.200s'", Py_TYPE(newargs)->tp_name); Py_DECREF(newargs); return -1; } if (Py_SIZE(newargs) != 2) { PyErr_Format(PyExc_ValueError, "__getnewargs_ex__ should return a tuple of " "length 2, not %zd", Py_SIZE(newargs)); Py_DECREF(newargs); return -1; } *args = PyTuple_GET_ITEM(newargs, 0); Py_INCREF(*args); *kwargs = PyTuple_GET_ITEM(newargs, 1); Py_INCREF(*kwargs); Py_DECREF(newargs); /* XXX We should perhaps allow None to be passed here. */ if (!PyTuple_Check(*args)) { PyErr_Format(PyExc_TypeError, "first item of the tuple returned by " "__getnewargs_ex__ must be a tuple, not '%.200s'", Py_TYPE(*args)->tp_name); Py_CLEAR(*args); Py_CLEAR(*kwargs); return -1; } if (!PyDict_Check(*kwargs)) { PyErr_Format(PyExc_TypeError, "second item of the tuple returned by " "__getnewargs_ex__ must be a dict, not '%.200s'", Py_TYPE(*kwargs)->tp_name); Py_CLEAR(*args); Py_CLEAR(*kwargs); return -1; } return 0; } else if (PyErr_Occurred()) { return -1; } /* The object does not have __getnewargs_ex__ so we fallback on using __getnewargs__ instead. */ getnewargs = _PyObject_LookupSpecial(obj, &PyId___getnewargs__); if (getnewargs != NULL) { *args = _PyObject_CallNoArg(getnewargs); Py_DECREF(getnewargs); if (*args == NULL) { return -1; } if (!PyTuple_Check(*args)) { PyErr_Format(PyExc_TypeError, "__getnewargs__ should return a tuple, " "not '%.200s'", Py_TYPE(*args)->tp_name); Py_CLEAR(*args); return -1; } *kwargs = NULL; return 0; } else if (PyErr_Occurred()) { return -1; } /* The object does not have __getnewargs_ex__ and __getnewargs__. This may mean __new__ does not takes any arguments on this object, or that the object does not implement the reduce protocol for pickling or copying. */ *args = NULL; *kwargs = NULL; return 0; } static int _PyObject_GetItemsIter(PyObject *obj, PyObject **listitems, PyObject **dictitems) { if (listitems == NULL || dictitems == NULL) { PyErr_BadInternalCall(); return -1; } if (!PyList_Check(obj)) { *listitems = Py_None; Py_INCREF(*listitems); } else { *listitems = PyObject_GetIter(obj); if (*listitems == NULL) return -1; } if (!PyDict_Check(obj)) { *dictitems = Py_None; Py_INCREF(*dictitems); } else { PyObject *items; _Py_IDENTIFIER(items); items = _PyObject_CallMethodIdObjArgs(obj, &PyId_items, NULL); if (items == NULL) { Py_CLEAR(*listitems); return -1; } *dictitems = PyObject_GetIter(items); Py_DECREF(items); if (*dictitems == NULL) { Py_CLEAR(*listitems); return -1; } } assert(*listitems != NULL && *dictitems != NULL); return 0; } static PyObject * reduce_newobj(PyObject *obj) { PyObject *args = NULL, *kwargs = NULL; PyObject *copyreg; PyObject *newobj, *newargs, *state, *listitems, *dictitems; PyObject *result; int hasargs; if (Py_TYPE(obj)->tp_new == NULL) { PyErr_Format(PyExc_TypeError, "can't pickle %.200s objects", Py_TYPE(obj)->tp_name); return NULL; } if (_PyObject_GetNewArguments(obj, &args, &kwargs) < 0) return NULL; copyreg = import_copyreg(); if (copyreg == NULL) { Py_XDECREF(args); Py_XDECREF(kwargs); return NULL; } hasargs = (args != NULL); if (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) { _Py_IDENTIFIER(__newobj__); PyObject *cls; Py_ssize_t i, n; Py_XDECREF(kwargs); newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj__); Py_DECREF(copyreg); if (newobj == NULL) { Py_XDECREF(args); return NULL; } n = args ? PyTuple_GET_SIZE(args) : 0; newargs = PyTuple_New(n+1); if (newargs == NULL) { Py_XDECREF(args); Py_DECREF(newobj); return NULL; } cls = (PyObject *) Py_TYPE(obj); Py_INCREF(cls); PyTuple_SET_ITEM(newargs, 0, cls); for (i = 0; i < n; i++) { PyObject *v = PyTuple_GET_ITEM(args, i); Py_INCREF(v); PyTuple_SET_ITEM(newargs, i+1, v); } Py_XDECREF(args); } else if (args != NULL) { _Py_IDENTIFIER(__newobj_ex__); newobj = _PyObject_GetAttrId(copyreg, &PyId___newobj_ex__); Py_DECREF(copyreg); if (newobj == NULL) { Py_DECREF(args); Py_DECREF(kwargs); return NULL; } newargs = PyTuple_Pack(3, Py_TYPE(obj), args, kwargs); Py_DECREF(args); Py_DECREF(kwargs); if (newargs == NULL) { Py_DECREF(newobj); return NULL; } } else { /* args == NULL */ Py_DECREF(kwargs); PyErr_BadInternalCall(); return NULL; } state = _PyObject_GetState(obj, !hasargs && !PyList_Check(obj) && !PyDict_Check(obj)); if (state == NULL) { Py_DECREF(newobj); Py_DECREF(newargs); return NULL; } if (_PyObject_GetItemsIter(obj, &listitems, &dictitems) < 0) { Py_DECREF(newobj); Py_DECREF(newargs); Py_DECREF(state); return NULL; } result = PyTuple_Pack(5, newobj, newargs, state, listitems, dictitems); Py_DECREF(newobj); Py_DECREF(newargs); Py_DECREF(state); Py_DECREF(listitems); Py_DECREF(dictitems); return result; } /* * There were two problems when object.__reduce__ and object.__reduce_ex__ * were implemented in the same function: * - trying to pickle an object with a custom __reduce__ method that * fell back to object.__reduce__ in certain circumstances led to * infinite recursion at Python level and eventual RecursionError. * - Pickling objects that lied about their type by overwriting the * __class__ descriptor could lead to infinite recursion at C level * and eventual segfault. * * Because of backwards compatibility, the two methods still have to * behave in the same way, even if this is not required by the pickle * protocol. This common functionality was moved to the _common_reduce * function. */ static PyObject * _common_reduce(PyObject *self, int proto) { PyObject *copyreg, *res; if (proto >= 2) return reduce_newobj(self); copyreg = import_copyreg(); if (!copyreg) return NULL; res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto); Py_DECREF(copyreg); return res; } static PyObject * object_reduce(PyObject *self, PyObject *args) { int proto = 0; if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto)) return NULL; return _common_reduce(self, proto); } static PyObject * object_reduce_ex(PyObject *self, PyObject *args) { static PyObject *objreduce; PyObject *reduce, *res; int proto = 0; _Py_IDENTIFIER(__reduce__); if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto)) return NULL; if (objreduce == NULL) { objreduce = _PyDict_GetItemId(PyBaseObject_Type.tp_dict, &PyId___reduce__); if (objreduce == NULL) return NULL; } reduce = _PyObject_GetAttrId(self, &PyId___reduce__); if (reduce == NULL) PyErr_Clear(); else { PyObject *cls, *clsreduce; int override; cls = (PyObject *) Py_TYPE(self); clsreduce = _PyObject_GetAttrId(cls, &PyId___reduce__); if (clsreduce == NULL) { Py_DECREF(reduce); return NULL; } override = (clsreduce != objreduce); Py_DECREF(clsreduce); if (override) { res = _PyObject_CallNoArg(reduce); Py_DECREF(reduce); return res; } else Py_DECREF(reduce); } return _common_reduce(self, proto); } static PyObject * object_subclasshook(PyObject *cls, PyObject *args) { Py_RETURN_NOTIMPLEMENTED; } PyDoc_STRVAR(object_subclasshook_doc, "Abstract classes can override this to customize issubclass().\n" "\n" "This is invoked early on by abc.ABCMeta.__subclasscheck__().\n" "It should return True, False or NotImplemented. If it returns\n" "NotImplemented, the normal algorithm is used. Otherwise, it\n" "overrides the normal algorithm (and the outcome is cached).\n"); static PyObject * object_init_subclass(PyObject *cls, PyObject *arg) { Py_RETURN_NONE; } PyDoc_STRVAR(object_init_subclass_doc, "This method is called when a class is subclassed.\n" "\n" "The default implementation does nothing. It may be\n" "overridden to extend subclasses.\n"); static PyObject * object_format(PyObject *self, PyObject *args) { PyObject *format_spec; PyObject *self_as_str = NULL; PyObject *result = NULL; if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) return NULL; /* Issue 7994: If we're converting to a string, we should reject format specifications */ if (PyUnicode_GET_LENGTH(format_spec) > 0) { PyErr_Format(PyExc_TypeError, "unsupported format string passed to %.200s.__format__", self->ob_type->tp_name); return NULL; } self_as_str = PyObject_Str(self); if (self_as_str != NULL) { result = PyObject_Format(self_as_str, format_spec); Py_DECREF(self_as_str); } return result; } static PyObject * object_sizeof(PyObject *self, PyObject *args) { Py_ssize_t res, isize; res = 0; isize = self->ob_type->tp_itemsize; if (isize > 0) res = Py_SIZE(self) * isize; res += self->ob_type->tp_basicsize; return PyLong_FromSsize_t(res); } /* __dir__ for generic objects: returns __dict__, __class__, and recursively up the __class__.__bases__ chain. */ static PyObject * object_dir(PyObject *self, PyObject *args) { PyObject *result = NULL; PyObject *dict = NULL; PyObject *itsclass = NULL; /* Get __dict__ (which may or may not be a real dict...) */ dict = _PyObject_GetAttrId(self, &PyId___dict__); if (dict == NULL) { PyErr_Clear(); dict = PyDict_New(); } else if (!PyDict_Check(dict)) { Py_DECREF(dict); dict = PyDict_New(); } else { /* Copy __dict__ to avoid mutating it. */ PyObject *temp = PyDict_Copy(dict); Py_DECREF(dict); dict = temp; } if (dict == NULL) goto error; /* Merge in attrs reachable from its class. */ itsclass = _PyObject_GetAttrId(self, &PyId___class__); if (itsclass == NULL) /* XXX(tomer): Perhaps fall back to obj->ob_type if no __class__ exists? */ PyErr_Clear(); else if (merge_class_dict(dict, itsclass) != 0) goto error; result = PyDict_Keys(dict); /* fall through */ error: Py_XDECREF(itsclass); Py_XDECREF(dict); return result; } static PyMethodDef object_methods[] = { {"__reduce_ex__", object_reduce_ex, METH_VARARGS, PyDoc_STR("helper for pickle")}, {"__reduce__", object_reduce, METH_VARARGS, PyDoc_STR("helper for pickle")}, {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS, object_subclasshook_doc}, {"__init_subclass__", object_init_subclass, METH_CLASS | METH_NOARGS, object_init_subclass_doc}, {"__format__", object_format, METH_VARARGS, PyDoc_STR("default object formatter")}, {"__sizeof__", object_sizeof, METH_NOARGS, PyDoc_STR("__sizeof__() -> int\nsize of object in memory, in bytes")}, {"__dir__", object_dir, METH_NOARGS, PyDoc_STR("__dir__() -> list\ndefault dir() implementation")}, {0} }; PyTypeObject PyBaseObject_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "object", /* tp_name */ sizeof(PyObject), /* tp_basicsize */ 0, /* tp_itemsize */ object_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ object_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)_Py_HashPointer, /* tp_hash */ 0, /* tp_call */ object_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ PyDoc_STR("object()\n--\n\nThe most base type"), /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ object_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ object_methods, /* tp_methods */ 0, /* tp_members */ object_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ object_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ object_new, /* tp_new */ PyObject_Del, /* tp_free */ }; /* Add the methods from tp_methods to the __dict__ in a type object */ static int add_methods(PyTypeObject *type, PyMethodDef *meth) { PyObject *dict = type->tp_dict; for (; meth->ml_name != NULL; meth++) { PyObject *descr; int err; int isdescr = 1; if (PyDict_GetItemString(dict, meth->ml_name) && !(meth->ml_flags & METH_COEXIST)) continue; if (meth->ml_flags & METH_CLASS) { if (meth->ml_flags & METH_STATIC) { PyErr_SetString(PyExc_ValueError, "method cannot be both class and static"); return -1; } descr = PyDescr_NewClassMethod(type, meth); } else if (meth->ml_flags & METH_STATIC) { PyObject *cfunc = PyCFunction_NewEx(meth, (PyObject*)type, NULL); if (cfunc == NULL) return -1; descr = PyStaticMethod_New(cfunc); isdescr = 0; // PyStaticMethod is not PyDescrObject Py_DECREF(cfunc); } else { descr = PyDescr_NewMethod(type, meth); } if (descr == NULL) return -1; if (isdescr) { err = PyDict_SetItem(dict, PyDescr_NAME(descr), descr); } else { err = PyDict_SetItemString(dict, meth->ml_name, descr); } Py_DECREF(descr); if (err < 0) return -1; } return 0; } static int add_members(PyTypeObject *type, PyMemberDef *memb) { PyObject *dict = type->tp_dict; for (; memb->name != NULL; memb++) { PyObject *descr; if (PyDict_GetItemString(dict, memb->name)) continue; descr = PyDescr_NewMember(type, memb); if (descr == NULL) return -1; if (PyDict_SetItem(dict, PyDescr_NAME(descr), descr) < 0) { Py_DECREF(descr); return -1; } Py_DECREF(descr); } return 0; } static int add_getset(PyTypeObject *type, PyGetSetDef *gsp) { PyObject *dict = type->tp_dict; for (; gsp->name != NULL; gsp++) { PyObject *descr; if (PyDict_GetItemString(dict, gsp->name)) continue; descr = PyDescr_NewGetSet(type, gsp); if (descr == NULL) return -1; if (PyDict_SetItem(dict, PyDescr_NAME(descr), descr) < 0) { Py_DECREF(descr); return -1; } Py_DECREF(descr); } return 0; } static void inherit_special(PyTypeObject *type, PyTypeObject *base) { /* Copying basicsize is connected to the GC flags */ if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) && (base->tp_flags & Py_TPFLAGS_HAVE_GC) && (!type->tp_traverse && !type->tp_clear)) { type->tp_flags |= Py_TPFLAGS_HAVE_GC; if (type->tp_traverse == NULL) type->tp_traverse = base->tp_traverse; if (type->tp_clear == NULL) type->tp_clear = base->tp_clear; } { /* The condition below could use some explanation. It appears that tp_new is not inherited for static types whose base class is 'object'; this seems to be a precaution so that old extension types don't suddenly become callable (object.__new__ wouldn't insure the invariants that the extension type's own factory function ensures). Heap types, of course, are under our control, so they do inherit tp_new; static extension types that specify some other built-in type as the default also inherit object.__new__. */ if (base != &PyBaseObject_Type || (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) { if (type->tp_new == NULL) type->tp_new = base->tp_new; } } if (type->tp_basicsize == 0) type->tp_basicsize = base->tp_basicsize; /* Copy other non-function slots */ #undef COPYVAL #define COPYVAL(SLOT) \ if (type->SLOT == 0) type->SLOT = base->SLOT COPYVAL(tp_itemsize); COPYVAL(tp_weaklistoffset); COPYVAL(tp_dictoffset); /* Setup fast subclass flags */ if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException)) type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS; else if (PyType_IsSubtype(base, &PyType_Type)) type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS; else if (PyType_IsSubtype(base, &PyLong_Type)) type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS; else if (PyType_IsSubtype(base, &PyBytes_Type)) type->tp_flags |= Py_TPFLAGS_BYTES_SUBCLASS; else if (PyType_IsSubtype(base, &PyUnicode_Type)) type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS; else if (PyType_IsSubtype(base, &PyTuple_Type)) type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS; else if (PyType_IsSubtype(base, &PyList_Type)) type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS; else if (PyType_IsSubtype(base, &PyDict_Type)) type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS; } static int overrides_hash(PyTypeObject *type) { PyObject *dict = type->tp_dict; _Py_IDENTIFIER(__eq__); assert(dict != NULL); if (_PyDict_GetItemId(dict, &PyId___eq__) != NULL) return 1; if (_PyDict_GetItemId(dict, &PyId___hash__) != NULL) return 1; return 0; } static void inherit_slots(PyTypeObject *type, PyTypeObject *base) { PyTypeObject *basebase; #undef SLOTDEFINED #undef COPYSLOT #undef COPYNUM #undef COPYSEQ #undef COPYMAP #undef COPYBUF #define SLOTDEFINED(SLOT) \ (base->SLOT != 0 && \ (basebase == NULL || base->SLOT != basebase->SLOT)) #define COPYSLOT(SLOT) \ if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT #define COPYASYNC(SLOT) COPYSLOT(tp_as_async->SLOT) #define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT) #define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT) #define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT) #define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT) /* This won't inherit indirect slots (from tp_as_number etc.) if type doesn't provide the space. */ if (type->tp_as_number != NULL && base->tp_as_number != NULL) { basebase = base->tp_base; if (basebase->tp_as_number == NULL) basebase = NULL; COPYNUM(nb_add); COPYNUM(nb_subtract); COPYNUM(nb_multiply); COPYNUM(nb_remainder); COPYNUM(nb_divmod); COPYNUM(nb_power); COPYNUM(nb_negative); COPYNUM(nb_positive); COPYNUM(nb_absolute); COPYNUM(nb_bool); COPYNUM(nb_invert); COPYNUM(nb_lshift); COPYNUM(nb_rshift); COPYNUM(nb_and); COPYNUM(nb_xor); COPYNUM(nb_or); COPYNUM(nb_int); COPYNUM(nb_float); COPYNUM(nb_inplace_add); COPYNUM(nb_inplace_subtract); COPYNUM(nb_inplace_multiply); COPYNUM(nb_inplace_remainder); COPYNUM(nb_inplace_power); COPYNUM(nb_inplace_lshift); COPYNUM(nb_inplace_rshift); COPYNUM(nb_inplace_and); COPYNUM(nb_inplace_xor); COPYNUM(nb_inplace_or); COPYNUM(nb_true_divide); COPYNUM(nb_floor_divide); COPYNUM(nb_inplace_true_divide); COPYNUM(nb_inplace_floor_divide); COPYNUM(nb_index); COPYNUM(nb_matrix_multiply); COPYNUM(nb_inplace_matrix_multiply); } if (type->tp_as_async != NULL && base->tp_as_async != NULL) { basebase = base->tp_base; if (basebase->tp_as_async == NULL) basebase = NULL; COPYASYNC(am_await); COPYASYNC(am_aiter); COPYASYNC(am_anext); } if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) { basebase = base->tp_base; if (basebase->tp_as_sequence == NULL) basebase = NULL; COPYSEQ(sq_length); COPYSEQ(sq_concat); COPYSEQ(sq_repeat); COPYSEQ(sq_item); COPYSEQ(sq_ass_item); COPYSEQ(sq_contains); COPYSEQ(sq_inplace_concat); COPYSEQ(sq_inplace_repeat); } if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) { basebase = base->tp_base; if (basebase->tp_as_mapping == NULL) basebase = NULL; COPYMAP(mp_length); COPYMAP(mp_subscript); COPYMAP(mp_ass_subscript); } if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) { basebase = base->tp_base; if (basebase->tp_as_buffer == NULL) basebase = NULL; COPYBUF(bf_getbuffer); COPYBUF(bf_releasebuffer); } basebase = base->tp_base; COPYSLOT(tp_dealloc); if (type->tp_getattr == NULL && type->tp_getattro == NULL) { type->tp_getattr = base->tp_getattr; type->tp_getattro = base->tp_getattro; } if (type->tp_setattr == NULL && type->tp_setattro == NULL) { type->tp_setattr = base->tp_setattr; type->tp_setattro = base->tp_setattro; } /* tp_reserved is ignored */ COPYSLOT(tp_repr); /* tp_hash see tp_richcompare */ COPYSLOT(tp_call); COPYSLOT(tp_str); { /* Copy comparison-related slots only when not overriding them anywhere */ if (type->tp_richcompare == NULL && type->tp_hash == NULL && !overrides_hash(type)) { type->tp_richcompare = base->tp_richcompare; type->tp_hash = base->tp_hash; } } { COPYSLOT(tp_iter); COPYSLOT(tp_iternext); } { COPYSLOT(tp_descr_get); COPYSLOT(tp_descr_set); COPYSLOT(tp_dictoffset); COPYSLOT(tp_init); COPYSLOT(tp_alloc); COPYSLOT(tp_is_gc); if ((type->tp_flags & Py_TPFLAGS_HAVE_FINALIZE) && (base->tp_flags & Py_TPFLAGS_HAVE_FINALIZE)) { COPYSLOT(tp_finalize); } if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) == (base->tp_flags & Py_TPFLAGS_HAVE_GC)) { /* They agree about gc. */ COPYSLOT(tp_free); } else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) && type->tp_free == NULL && base->tp_free == PyObject_Free) { /* A bit of magic to plug in the correct default * tp_free function when a derived class adds gc, * didn't define tp_free, and the base uses the * default non-gc tp_free. */ type->tp_free = PyObject_GC_Del; } /* else they didn't agree about gc, and there isn't something * obvious to be done -- the type is on its own. */ } } static int add_operators(PyTypeObject *); int PyType_Ready(PyTypeObject *type) { PyObject *dict, *bases; PyTypeObject *base; Py_ssize_t i, n; if (type->tp_flags & Py_TPFLAGS_READY) { assert(_PyType_CheckConsistency(type)); return 0; } assert((type->tp_flags & Py_TPFLAGS_READYING) == 0); type->tp_flags |= Py_TPFLAGS_READYING; #ifdef Py_TRACE_REFS /* PyType_Ready is the closest thing we have to a choke point * for type objects, so is the best place I can think of to try * to get type objects into the doubly-linked list of all objects. * Still, not all type objects go thru PyType_Ready. */ _Py_AddToAllObjects((PyObject *)type, 0); #endif if (type->tp_name == NULL) { PyErr_Format(PyExc_SystemError, "Type does not define the tp_name field."); goto error; } /* Initialize tp_base (defaults to BaseObject unless that's us) */ base = type->tp_base; if (base == NULL && type != &PyBaseObject_Type) { base = type->tp_base = &PyBaseObject_Type; Py_INCREF(base); } /* Now the only way base can still be NULL is if type is * &PyBaseObject_Type. */ /* Initialize the base class */ if (base != NULL && base->tp_dict == NULL) { if (PyType_Ready(base) < 0) goto error; } /* Initialize ob_type if NULL. This means extensions that want to be compilable separately on Windows can call PyType_Ready() instead of initializing the ob_type field of their type objects. */ /* The test for base != NULL is really unnecessary, since base is only NULL when type is &PyBaseObject_Type, and we know its ob_type is not NULL (it's initialized to &PyType_Type). But coverity doesn't know that. */ if (Py_TYPE(type) == NULL && base != NULL) Py_TYPE(type) = Py_TYPE(base); /* Initialize tp_bases */ bases = type->tp_bases; if (bases == NULL) { if (base == NULL) bases = PyTuple_New(0); else bases = PyTuple_Pack(1, base); if (bases == NULL) goto error; type->tp_bases = bases; } /* Initialize tp_dict */ dict = type->tp_dict; if (dict == NULL) { dict = PyDict_New(); if (dict == NULL) goto error; type->tp_dict = dict; } /* Add type-specific descriptors to tp_dict */ if (add_operators(type) < 0) goto error; if (type->tp_methods != NULL) { if (add_methods(type, type->tp_methods) < 0) goto error; } if (type->tp_members != NULL) { if (add_members(type, type->tp_members) < 0) goto error; } if (type->tp_getset != NULL) { if (add_getset(type, type->tp_getset) < 0) goto error; } /* Calculate method resolution order */ if (mro_internal(type, NULL) < 0) goto error; /* Inherit special flags from dominant base */ if (type->tp_base != NULL) inherit_special(type, type->tp_base); /* Initialize tp_dict properly */ bases = type->tp_mro; assert(bases != NULL); assert(PyTuple_Check(bases)); n = PyTuple_GET_SIZE(bases); for (i = 1; i < n; i++) { PyObject *b = PyTuple_GET_ITEM(bases, i); if (PyType_Check(b)) inherit_slots(type, (PyTypeObject *)b); } /* All bases of statically allocated type should be statically allocated */ if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) for (i = 0; i < n; i++) { PyObject *b = PyTuple_GET_ITEM(bases, i); if (PyType_Check(b) && (((PyTypeObject *)b)->tp_flags & Py_TPFLAGS_HEAPTYPE)) { PyErr_Format(PyExc_TypeError, "type '%.100s' is not dynamically allocated but " "its base type '%.100s' is dynamically allocated", type->tp_name, ((PyTypeObject *)b)->tp_name); goto error; } } /* Sanity check for tp_free. */ if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) && (type->tp_free == NULL || type->tp_free == PyObject_Del)) { /* This base class needs to call tp_free, but doesn't have * one, or its tp_free is for non-gc'ed objects. */ PyErr_Format(PyExc_TypeError, "type '%.100s' participates in " "gc and is a base type but has inappropriate " "tp_free slot", type->tp_name); goto error; } /* if the type dictionary doesn't contain a __doc__, set it from the tp_doc slot. */ if (_PyDict_GetItemId(type->tp_dict, &PyId___doc__) == NULL) { if (type->tp_doc != NULL) { const char *old_doc = _PyType_DocWithoutSignature(type->tp_name, type->tp_doc); PyObject *doc = PyUnicode_FromString(old_doc); if (doc == NULL) goto error; if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, doc) < 0) { Py_DECREF(doc); goto error; } Py_DECREF(doc); } else { if (_PyDict_SetItemId(type->tp_dict, &PyId___doc__, Py_None) < 0) goto error; } } /* Hack for tp_hash and __hash__. If after all that, tp_hash is still NULL, and __hash__ is not in tp_dict, set tp_hash to PyObject_HashNotImplemented and tp_dict['__hash__'] equal to None. This signals that __hash__ is not inherited. */ if (type->tp_hash == NULL) { if (_PyDict_GetItemId(type->tp_dict, &PyId___hash__) == NULL) { if (_PyDict_SetItemId(type->tp_dict, &PyId___hash__, Py_None) < 0) goto error; type->tp_hash = PyObject_HashNotImplemented; } } /* Some more special stuff */ base = type->tp_base; if (base != NULL) { if (type->tp_as_async == NULL) type->tp_as_async = base->tp_as_async; if (type->tp_as_number == NULL) type->tp_as_number = base->tp_as_number; if (type->tp_as_sequence == NULL) type->tp_as_sequence = base->tp_as_sequence; if (type->tp_as_mapping == NULL) type->tp_as_mapping = base->tp_as_mapping; if (type->tp_as_buffer == NULL) type->tp_as_buffer = base->tp_as_buffer; } /* Link into each base class's list of subclasses */ bases = type->tp_bases; n = PyTuple_GET_SIZE(bases); for (i = 0; i < n; i++) { PyObject *b = PyTuple_GET_ITEM(bases, i); if (PyType_Check(b) && add_subclass((PyTypeObject *)b, type) < 0) goto error; } /* All done -- set the ready flag */ type->tp_flags = (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY; assert(_PyType_CheckConsistency(type)); return 0; error: type->tp_flags &= ~Py_TPFLAGS_READYING; return -1; } static int add_subclass(PyTypeObject *base, PyTypeObject *type) { int result = -1; PyObject *dict, *key, *newobj; dict = base->tp_subclasses; if (dict == NULL) { base->tp_subclasses = dict = PyDict_New(); if (dict == NULL) return -1; } assert(PyDict_CheckExact(dict)); key = PyLong_FromVoidPtr((void *) type); if (key == NULL) return -1; newobj = PyWeakref_NewRef((PyObject *)type, NULL); if (newobj != NULL) { result = PyDict_SetItem(dict, key, newobj); Py_DECREF(newobj); } Py_DECREF(key); return result; } static int add_all_subclasses(PyTypeObject *type, PyObject *bases) { int res = 0; if (bases) { Py_ssize_t i; for (i = 0; i < PyTuple_GET_SIZE(bases); i++) { PyObject *base = PyTuple_GET_ITEM(bases, i); if (PyType_Check(base) && add_subclass((PyTypeObject*)base, type) < 0) res = -1; } } return res; } static void remove_subclass(PyTypeObject *base, PyTypeObject *type) { PyObject *dict, *key; dict = base->tp_subclasses; if (dict == NULL) { return; } assert(PyDict_CheckExact(dict)); key = PyLong_FromVoidPtr((void *) type); if (key == NULL || PyDict_DelItem(dict, key)) { /* This can happen if the type initialization errored out before the base subclasses were updated (e.g. a non-str __qualname__ was passed in the type dict). */ PyErr_Clear(); } Py_XDECREF(key); } static void remove_all_subclasses(PyTypeObject *type, PyObject *bases) { if (bases) { Py_ssize_t i; for (i = 0; i < PyTuple_GET_SIZE(bases); i++) { PyObject *base = PyTuple_GET_ITEM(bases, i); if (PyType_Check(base)) remove_subclass((PyTypeObject*) base, type); } } } static int check_num_args(PyObject *ob, int n) { if (!PyTuple_CheckExact(ob)) { PyErr_SetString(PyExc_SystemError, "PyArg_UnpackTuple() argument list is not a tuple"); return 0; } if (n == PyTuple_GET_SIZE(ob)) return 1; PyErr_Format( PyExc_TypeError, "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob)); return 0; } /* Generic wrappers for overloadable 'operators' such as __getitem__ */ /* There's a wrapper *function* for each distinct function typedef used for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a wrapper *table* for each distinct operation (e.g. __len__, __add__). Most tables have only one entry; the tables for binary operators have two entries, one regular and one with reversed arguments. */ static PyObject * wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped) { lenfunc func = (lenfunc)wrapped; Py_ssize_t res; if (!check_num_args(args, 0)) return NULL; res = (*func)(self); if (res == -1 && PyErr_Occurred()) return NULL; return PyLong_FromLong((long)res); } static PyObject * wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped) { inquiry func = (inquiry)wrapped; int res; if (!check_num_args(args, 0)) return NULL; res = (*func)(self); if (res == -1 && PyErr_Occurred()) return NULL; return PyBool_FromLong((long)res); } static PyObject * wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped) { binaryfunc func = (binaryfunc)wrapped; PyObject *other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); return (*func)(self, other); } static PyObject * wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped) { binaryfunc func = (binaryfunc)wrapped; PyObject *other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); return (*func)(self, other); } static PyObject * wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped) { binaryfunc func = (binaryfunc)wrapped; PyObject *other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); return (*func)(other, self); } static PyObject * wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped) { ternaryfunc func = (ternaryfunc)wrapped; PyObject *other; PyObject *third = Py_None; /* Note: This wrapper only works for __pow__() */ if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) return NULL; return (*func)(self, other, third); } static PyObject * wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped) { ternaryfunc func = (ternaryfunc)wrapped; PyObject *other; PyObject *third = Py_None; /* Note: This wrapper only works for __pow__() */ if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third)) return NULL; return (*func)(other, self, third); } static PyObject * wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped) { unaryfunc func = (unaryfunc)wrapped; if (!check_num_args(args, 0)) return NULL; return (*func)(self); } static PyObject * wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped) { ssizeargfunc func = (ssizeargfunc)wrapped; PyObject* o; Py_ssize_t i; if (!PyArg_UnpackTuple(args, "", 1, 1, &o)) return NULL; i = PyNumber_AsSsize_t(o, PyExc_OverflowError); if (i == -1 && PyErr_Occurred()) return NULL; return (*func)(self, i); } static Py_ssize_t getindex(PyObject *self, PyObject *arg) { Py_ssize_t i; i = PyNumber_AsSsize_t(arg, PyExc_OverflowError); if (i == -1 && PyErr_Occurred()) return -1; if (i < 0) { PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence; if (sq && sq->sq_length) { Py_ssize_t n = (*sq->sq_length)(self); if (n < 0) return -1; i += n; } } return i; } static PyObject * wrap_sq_item(PyObject *self, PyObject *args, void *wrapped) { ssizeargfunc func = (ssizeargfunc)wrapped; PyObject *arg; Py_ssize_t i; if (PyTuple_GET_SIZE(args) == 1) { arg = PyTuple_GET_ITEM(args, 0); i = getindex(self, arg); if (i == -1 && PyErr_Occurred()) return NULL; return (*func)(self, i); } check_num_args(args, 1); assert(PyErr_Occurred()); return NULL; } static PyObject * wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped) { ssizeobjargproc func = (ssizeobjargproc)wrapped; Py_ssize_t i; int res; PyObject *arg, *value; if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value)) return NULL; i = getindex(self, arg); if (i == -1 && PyErr_Occurred()) return NULL; res = (*func)(self, i, value); if (res == -1 && PyErr_Occurred()) return NULL; Py_RETURN_NONE; } static PyObject * wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped) { ssizeobjargproc func = (ssizeobjargproc)wrapped; Py_ssize_t i; int res; PyObject *arg; if (!check_num_args(args, 1)) return NULL; arg = PyTuple_GET_ITEM(args, 0); i = getindex(self, arg); if (i == -1 && PyErr_Occurred()) return NULL; res = (*func)(self, i, NULL); if (res == -1 && PyErr_Occurred()) return NULL; Py_RETURN_NONE; } /* XXX objobjproc is a misnomer; should be objargpred */ static PyObject * wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped) { objobjproc func = (objobjproc)wrapped; int res; PyObject *value; if (!check_num_args(args, 1)) return NULL; value = PyTuple_GET_ITEM(args, 0); res = (*func)(self, value); if (res == -1 && PyErr_Occurred()) return NULL; else return PyBool_FromLong(res); } static PyObject * wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped) { objobjargproc func = (objobjargproc)wrapped; int res; PyObject *key, *value; if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value)) return NULL; res = (*func)(self, key, value); if (res == -1 && PyErr_Occurred()) return NULL; Py_RETURN_NONE; } static PyObject * wrap_delitem(PyObject *self, PyObject *args, void *wrapped) { objobjargproc func = (objobjargproc)wrapped; int res; PyObject *key; if (!check_num_args(args, 1)) return NULL; key = PyTuple_GET_ITEM(args, 0); res = (*func)(self, key, NULL); if (res == -1 && PyErr_Occurred()) return NULL; Py_RETURN_NONE; } /* Helper to check for object.__setattr__ or __delattr__ applied to a type. This is called the Carlo Verre hack after its discoverer. */ static int hackcheck(PyObject *self, setattrofunc func, const char *what) { PyTypeObject *type = Py_TYPE(self); while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE) type = type->tp_base; /* If type is NULL now, this is a really weird type. In the spirit of backwards compatibility (?), just shut up. */ if (type && type->tp_setattro != func) { PyErr_Format(PyExc_TypeError, "can't apply this %s to %s object", what, type->tp_name); return 0; } return 1; } static PyObject * wrap_setattr(PyObject *self, PyObject *args, void *wrapped) { setattrofunc func = (setattrofunc)wrapped; int res; PyObject *name, *value; if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value)) return NULL; if (!hackcheck(self, func, "__setattr__")) return NULL; res = (*func)(self, name, value); if (res < 0) return NULL; Py_RETURN_NONE; } static PyObject * wrap_delattr(PyObject *self, PyObject *args, void *wrapped) { setattrofunc func = (setattrofunc)wrapped; int res; PyObject *name; if (!check_num_args(args, 1)) return NULL; name = PyTuple_GET_ITEM(args, 0); if (!hackcheck(self, func, "__delattr__")) return NULL; res = (*func)(self, name, NULL); if (res < 0) return NULL; Py_RETURN_NONE; } static PyObject * wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped) { hashfunc func = (hashfunc)wrapped; Py_hash_t res; if (!check_num_args(args, 0)) return NULL; res = (*func)(self); if (res == -1 && PyErr_Occurred()) return NULL; return PyLong_FromSsize_t(res); } static PyObject * wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) { ternaryfunc func = (ternaryfunc)wrapped; return (*func)(self, args, kwds); } static PyObject * wrap_del(PyObject *self, PyObject *args, void *wrapped) { destructor func = (destructor)wrapped; if (!check_num_args(args, 0)) return NULL; (*func)(self); Py_RETURN_NONE; } static PyObject * wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op) { richcmpfunc func = (richcmpfunc)wrapped; PyObject *other; if (!check_num_args(args, 1)) return NULL; other = PyTuple_GET_ITEM(args, 0); return (*func)(self, other, op); } #undef RICHCMP_WRAPPER #define RICHCMP_WRAPPER(NAME, OP) \ static PyObject * \ richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \ { \ return wrap_richcmpfunc(self, args, wrapped, OP); \ } RICHCMP_WRAPPER(lt, Py_LT) RICHCMP_WRAPPER(le, Py_LE) RICHCMP_WRAPPER(eq, Py_EQ) RICHCMP_WRAPPER(ne, Py_NE) RICHCMP_WRAPPER(gt, Py_GT) RICHCMP_WRAPPER(ge, Py_GE) static PyObject * wrap_next(PyObject *self, PyObject *args, void *wrapped) { unaryfunc func = (unaryfunc)wrapped; PyObject *res; if (!check_num_args(args, 0)) return NULL; res = (*func)(self); if (res == NULL && !PyErr_Occurred()) PyErr_SetNone(PyExc_StopIteration); return res; } static PyObject * wrap_descr_get(PyObject *self, PyObject *args, void *wrapped) { descrgetfunc func = (descrgetfunc)wrapped; PyObject *obj; PyObject *type = NULL; if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type)) return NULL; if (obj == Py_None) obj = NULL; if (type == Py_None) type = NULL; if (type == NULL &&obj == NULL) { PyErr_SetString(PyExc_TypeError, "__get__(None, None) is invalid"); return NULL; } return (*func)(self, obj, type); } static PyObject * wrap_descr_set(PyObject *self, PyObject *args, void *wrapped) { descrsetfunc func = (descrsetfunc)wrapped; PyObject *obj, *value; int ret; if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value)) return NULL; ret = (*func)(self, obj, value); if (ret < 0) return NULL; Py_RETURN_NONE; } static PyObject * wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped) { descrsetfunc func = (descrsetfunc)wrapped; PyObject *obj; int ret; if (!check_num_args(args, 1)) return NULL; obj = PyTuple_GET_ITEM(args, 0); ret = (*func)(self, obj, NULL); if (ret < 0) return NULL; Py_RETURN_NONE; } static PyObject * wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds) { initproc func = (initproc)wrapped; if (func(self, args, kwds) < 0) return NULL; Py_RETURN_NONE; } static PyObject * tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds) { PyTypeObject *type, *subtype, *staticbase; PyObject *arg0, *res; if (self == NULL || !PyType_Check(self)) Py_FatalError("__new__() called with non-type 'self'"); type = (PyTypeObject *)self; if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) { PyErr_Format(PyExc_TypeError, "%s.__new__(): not enough arguments", type->tp_name); return NULL; } arg0 = PyTuple_GET_ITEM(args, 0); if (!PyType_Check(arg0)) { PyErr_Format(PyExc_TypeError, "%s.__new__(X): X is not a type object (%s)", type->tp_name, Py_TYPE(arg0)->tp_name); return NULL; } subtype = (PyTypeObject *)arg0; if (!PyType_IsSubtype(subtype, type)) { PyErr_Format(PyExc_TypeError, "%s.__new__(%s): %s is not a subtype of %s", type->tp_name, subtype->tp_name, subtype->tp_name, type->tp_name); return NULL; } /* Check that the use doesn't do something silly and unsafe like object.__new__(dict). To do this, we check that the most derived base that's not a heap type is this type. */ staticbase = subtype; while (staticbase && (staticbase->tp_new == slot_tp_new)) staticbase = staticbase->tp_base; /* If staticbase is NULL now, it is a really weird type. In the spirit of backwards compatibility (?), just shut up. */ if (staticbase && staticbase->tp_new != type->tp_new) { PyErr_Format(PyExc_TypeError, "%s.__new__(%s) is not safe, use %s.__new__()", type->tp_name, subtype->tp_name, staticbase->tp_name); return NULL; } args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args)); if (args == NULL) return NULL; res = type->tp_new(subtype, args, kwds); Py_DECREF(args); return res; } static struct PyMethodDef tp_new_methoddef[] = { {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS, PyDoc_STR("__new__($type, *args, **kwargs)\n--\n\n" "Create and return a new object. " "See help(type) for accurate signature.")}, {0} }; static int add_tp_new_wrapper(PyTypeObject *type) { PyObject *func; if (_PyDict_GetItemId(type->tp_dict, &PyId___new__) != NULL) return 0; func = PyCFunction_NewEx(tp_new_methoddef, (PyObject *)type, NULL); if (func == NULL) return -1; if (_PyDict_SetItemId(type->tp_dict, &PyId___new__, func)) { Py_DECREF(func); return -1; } Py_DECREF(func); return 0; } /* Slot wrappers that call the corresponding __foo__ slot. See comments below at override_slots() for more explanation. */ #define SLOT0(FUNCNAME, OPSTR) \ static PyObject * \ FUNCNAME(PyObject *self) \ { \ _Py_static_string(id, OPSTR); \ return call_method(self, &id, NULL, 0); \ } #define SLOT1(FUNCNAME, OPSTR, ARG1TYPE) \ static PyObject * \ FUNCNAME(PyObject *self, ARG1TYPE arg1) \ { \ PyObject* stack[1] = {arg1}; \ _Py_static_string(id, OPSTR); \ return call_method(self, &id, stack, 1); \ } /* Boolean helper for SLOT1BINFULL(). right.__class__ is a nontrivial subclass of left.__class__. */ static int method_is_overloaded(PyObject *left, PyObject *right, struct _Py_Identifier *name) { PyObject *a, *b; int ok; b = _PyObject_GetAttrId((PyObject *)(Py_TYPE(right)), name); if (b == NULL) { PyErr_Clear(); /* If right doesn't have it, it's not overloaded */ return 0; } a = _PyObject_GetAttrId((PyObject *)(Py_TYPE(left)), name); if (a == NULL) { PyErr_Clear(); Py_DECREF(b); /* If right has it but left doesn't, it's overloaded */ return 1; } ok = PyObject_RichCompareBool(a, b, Py_NE); Py_DECREF(a); Py_DECREF(b); if (ok < 0) { PyErr_Clear(); return 0; } return ok; } #define SLOT1BINFULL(FUNCNAME, TESTFUNC, SLOTNAME, OPSTR, ROPSTR) \ static PyObject * \ FUNCNAME(PyObject *self, PyObject *other) \ { \ PyObject* stack[1]; \ _Py_static_string(op_id, OPSTR); \ _Py_static_string(rop_id, ROPSTR); \ int do_other = Py_TYPE(self) != Py_TYPE(other) && \ Py_TYPE(other)->tp_as_number != NULL && \ Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \ if (Py_TYPE(self)->tp_as_number != NULL && \ Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \ PyObject *r; \ if (do_other && \ PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \ method_is_overloaded(self, other, &rop_id)) { \ stack[0] = self; \ r = call_maybe(other, &rop_id, stack, 1); \ if (r != Py_NotImplemented) \ return r; \ Py_DECREF(r); \ do_other = 0; \ } \ stack[0] = other; \ r = call_maybe(self, &op_id, stack, 1); \ if (r != Py_NotImplemented || \ Py_TYPE(other) == Py_TYPE(self)) \ return r; \ Py_DECREF(r); \ } \ if (do_other) { \ stack[0] = self; \ return call_maybe(other, &rop_id, stack, 1); \ } \ Py_RETURN_NOTIMPLEMENTED; \ } #define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \ SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR) static Py_ssize_t slot_sq_length(PyObject *self) { PyObject *res = call_method(self, &PyId___len__, NULL, 0); Py_ssize_t len; if (res == NULL) return -1; len = PyNumber_AsSsize_t(res, PyExc_OverflowError); Py_DECREF(res); if (len < 0) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "__len__() should return >= 0"); return -1; } return len; } /* Super-optimized version of slot_sq_item. Other slots could do the same... */ static PyObject * slot_sq_item(PyObject *self, Py_ssize_t i) { PyObject *func, *ival = NULL, *retval = NULL; descrgetfunc f; func = _PyType_LookupId(Py_TYPE(self), &PyId___getitem__); if (func == NULL) { PyObject *getitem_str = _PyUnicode_FromId(&PyId___getitem__); PyErr_SetObject(PyExc_AttributeError, getitem_str); return NULL; } f = Py_TYPE(func)->tp_descr_get; if (f == NULL) { Py_INCREF(func); } else { func = f(func, self, (PyObject *)(Py_TYPE(self))); if (func == NULL) { return NULL; } } ival = PyLong_FromSsize_t(i); if (ival == NULL) { goto error; } retval = PyObject_CallFunctionObjArgs(func, ival, NULL); Py_DECREF(func); Py_DECREF(ival); return retval; error: Py_DECREF(func); return NULL; } static int slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value) { PyObject *stack[2]; PyObject *res; PyObject *index_obj; index_obj = PyLong_FromSsize_t(index); if (index_obj == NULL) { return -1; } stack[0] = index_obj; if (value == NULL) { res = call_method(self, &PyId___delitem__, stack, 1); } else { stack[1] = value; res = call_method(self, &PyId___setitem__, stack, 2); } Py_DECREF(index_obj); if (res == NULL) { return -1; } Py_DECREF(res); return 0; } static int slot_sq_contains(PyObject *self, PyObject *value) { PyObject *func, *res; int result = -1, unbound; _Py_IDENTIFIER(__contains__); func = lookup_maybe_method(self, &PyId___contains__, &unbound); if (func == Py_None) { Py_DECREF(func); PyErr_Format(PyExc_TypeError, "'%.200s' object is not a container", Py_TYPE(self)->tp_name); return -1; } if (func != NULL) { PyObject *args[1] = {value}; res = call_unbound(unbound, func, self, args, 1); Py_DECREF(func); if (res != NULL) { result = PyObject_IsTrue(res); Py_DECREF(res); } } else if (! PyErr_Occurred()) { /* Possible results: -1 and 1 */ result = (int)_PySequence_IterSearch(self, value, PY_ITERSEARCH_CONTAINS); } return result; } #define slot_mp_length slot_sq_length SLOT1(slot_mp_subscript, "__getitem__", PyObject *) static int slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value) { PyObject *stack[2]; PyObject *res; stack[0] = key; if (value == NULL) { res = call_method(self, &PyId___delitem__, stack, 1); } else { stack[1] = value; res = call_method(self, &PyId___setitem__, stack, 2); } if (res == NULL) return -1; Py_DECREF(res); return 0; } SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__") SLOT1BIN(slot_nb_subtract, nb_subtract, "__sub__", "__rsub__") SLOT1BIN(slot_nb_multiply, nb_multiply, "__mul__", "__rmul__") SLOT1BIN(slot_nb_matrix_multiply, nb_matrix_multiply, "__matmul__", "__rmatmul__") SLOT1BIN(slot_nb_remainder, nb_remainder, "__mod__", "__rmod__") SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__") static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *); SLOT1BINFULL(slot_nb_power_binary, slot_nb_power, nb_power, "__pow__", "__rpow__") static PyObject * slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus) { _Py_IDENTIFIER(__pow__); if (modulus == Py_None) return slot_nb_power_binary(self, other); /* Three-arg power doesn't use __rpow__. But ternary_op can call this when the second argument's type uses slot_nb_power, so check before calling self.__pow__. */ if (Py_TYPE(self)->tp_as_number != NULL && Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) { PyObject* stack[2] = {other, modulus}; return call_method(self, &PyId___pow__, stack, 2); } Py_RETURN_NOTIMPLEMENTED; } SLOT0(slot_nb_negative, "__neg__") SLOT0(slot_nb_positive, "__pos__") SLOT0(slot_nb_absolute, "__abs__") static int slot_nb_bool(PyObject *self) { PyObject *func, *value; int result, unbound; int using_len = 0; _Py_IDENTIFIER(__bool__); func = lookup_maybe_method(self, &PyId___bool__, &unbound); if (func == NULL) { if (PyErr_Occurred()) { return -1; } func = lookup_maybe_method(self, &PyId___len__, &unbound); if (func == NULL) { if (PyErr_Occurred()) { return -1; } return 1; } using_len = 1; } value = call_unbound_noarg(unbound, func, self); if (value == NULL) { goto error; } if (using_len) { /* bool type enforced by slot_nb_len */ result = PyObject_IsTrue(value); } else if (PyBool_Check(value)) { result = PyObject_IsTrue(value); } else { PyErr_Format(PyExc_TypeError, "__bool__ should return " "bool, returned %s", Py_TYPE(value)->tp_name); result = -1; } Py_DECREF(value); Py_DECREF(func); return result; error: Py_DECREF(func); return -1; } static PyObject * slot_nb_index(PyObject *self) { _Py_IDENTIFIER(__index__); return call_method(self, &PyId___index__, NULL, 0); } SLOT0(slot_nb_invert, "__invert__") SLOT1BIN(slot_nb_lshift, nb_lshift, "__lshift__", "__rlshift__") SLOT1BIN(slot_nb_rshift, nb_rshift, "__rshift__", "__rrshift__") SLOT1BIN(slot_nb_and, nb_and, "__and__", "__rand__") SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__") SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__") SLOT0(slot_nb_int, "__int__") SLOT0(slot_nb_float, "__float__") SLOT1(slot_nb_inplace_add, "__iadd__", PyObject *) SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *) SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *) SLOT1(slot_nb_inplace_matrix_multiply, "__imatmul__", PyObject *) SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *) /* Can't use SLOT1 here, because nb_inplace_power is ternary */ static PyObject * slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2) { PyObject *stack[1] = {arg1}; _Py_IDENTIFIER(__ipow__); return call_method(self, &PyId___ipow__, stack, 1); } SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *) SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *) SLOT1(slot_nb_inplace_and, "__iand__", PyObject *) SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *) SLOT1(slot_nb_inplace_or, "__ior__", PyObject *) SLOT1BIN(slot_nb_floor_divide, nb_floor_divide, "__floordiv__", "__rfloordiv__") SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__") SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *) SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *) static PyObject * slot_tp_repr(PyObject *self) { PyObject *func, *res; _Py_IDENTIFIER(__repr__); int unbound; func = lookup_method(self, &PyId___repr__, &unbound); if (func != NULL) { res = call_unbound_noarg(unbound, func, self); Py_DECREF(func); return res; } PyErr_Clear(); return PyUnicode_FromFormat("<%s object at %p>", Py_TYPE(self)->tp_name, self); } SLOT0(slot_tp_str, "__str__") static Py_hash_t slot_tp_hash(PyObject *self) { PyObject *func, *res; Py_ssize_t h; int unbound; func = lookup_method(self, &PyId___hash__, &unbound); if (func == Py_None) { Py_DECREF(func); func = NULL; } if (func == NULL) { return PyObject_HashNotImplemented(self); } res = call_unbound_noarg(unbound, func, self); Py_DECREF(func); if (res == NULL) return -1; if (!PyLong_Check(res)) { PyErr_SetString(PyExc_TypeError, "__hash__ method should return an integer"); return -1; } /* Transform the PyLong `res` to a Py_hash_t `h`. For an existing hashable Python object x, hash(x) will always lie within the range of Py_hash_t. Therefore our transformation must preserve values that already lie within this range, to ensure that if x.__hash__() returns hash(y) then hash(x) == hash(y). */ h = PyLong_AsSsize_t(res); if (h == -1 && PyErr_Occurred()) { /* res was not within the range of a Py_hash_t, so we're free to use any sufficiently bit-mixing transformation; long.__hash__ will do nicely. */ PyErr_Clear(); h = PyLong_Type.tp_hash(res); } /* -1 is reserved for errors. */ if (h == -1) h = -2; Py_DECREF(res); return h; } static PyObject * slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds) { _Py_IDENTIFIER(__call__); int unbound; PyObject *meth = lookup_method(self, &PyId___call__, &unbound); PyObject *res; if (meth == NULL) return NULL; if (unbound) { res = _PyObject_Call_Prepend(meth, self, args, kwds); } else { res = PyObject_Call(meth, args, kwds); } Py_DECREF(meth); return res; } /* There are two slot dispatch functions for tp_getattro. - slot_tp_getattro() is used when __getattribute__ is overridden but no __getattr__ hook is present; - slot_tp_getattr_hook() is used when a __getattr__ hook is present. The code in update_one_slot() always installs slot_tp_getattr_hook(); this detects the absence of __getattr__ and then installs the simpler slot if necessary. */ static PyObject * slot_tp_getattro(PyObject *self, PyObject *name) { PyObject *stack[1] = {name}; return call_method(self, &PyId___getattribute__, stack, 1); } static PyObject * call_attribute(PyObject *self, PyObject *attr, PyObject *name) { PyObject *res, *descr = NULL; descrgetfunc f = Py_TYPE(attr)->tp_descr_get; if (f != NULL) { descr = f(attr, self, (PyObject *)(Py_TYPE(self))); if (descr == NULL) return NULL; else attr = descr; } res = PyObject_CallFunctionObjArgs(attr, name, NULL); Py_XDECREF(descr); return res; } static PyObject * slot_tp_getattr_hook(PyObject *self, PyObject *name) { PyTypeObject *tp = Py_TYPE(self); PyObject *getattr, *getattribute, *res; _Py_IDENTIFIER(__getattr__); /* speed hack: we could use lookup_maybe, but that would resolve the method fully for each attribute lookup for classes with __getattr__, even when the attribute is present. So we use _PyType_Lookup and create the method only when needed, with call_attribute. */ getattr = _PyType_LookupId(tp, &PyId___getattr__); if (getattr == NULL) { /* No __getattr__ hook: use a simpler dispatcher */ tp->tp_getattro = slot_tp_getattro; return slot_tp_getattro(self, name); } Py_INCREF(getattr); /* speed hack: we could use lookup_maybe, but that would resolve the method fully for each attribute lookup for classes with __getattr__, even when self has the default __getattribute__ method. So we use _PyType_Lookup and create the method only when needed, with call_attribute. */ getattribute = _PyType_LookupId(tp, &PyId___getattribute__); if (getattribute == NULL || (Py_TYPE(getattribute) == &PyWrapperDescr_Type && ((PyWrapperDescrObject *)getattribute)->d_wrapped == (void *)PyObject_GenericGetAttr)) res = PyObject_GenericGetAttr(self, name); else { Py_INCREF(getattribute); res = call_attribute(self, getattribute, name); Py_DECREF(getattribute); } if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); res = call_attribute(self, getattr, name); } Py_DECREF(getattr); return res; } static int slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value) { PyObject *stack[2]; PyObject *res; _Py_IDENTIFIER(__delattr__); _Py_IDENTIFIER(__setattr__); stack[0] = name; if (value == NULL) { res = call_method(self, &PyId___delattr__, stack, 1); } else { stack[1] = value; res = call_method(self, &PyId___setattr__, stack, 2); } if (res == NULL) return -1; Py_DECREF(res); return 0; } static _Py_Identifier name_op[] = { {0, "__lt__", 0}, {0, "__le__", 0}, {0, "__eq__", 0}, {0, "__ne__", 0}, {0, "__gt__", 0}, {0, "__ge__", 0} }; static PyObject * slot_tp_richcompare(PyObject *self, PyObject *other, int op) { int unbound; PyObject *func, *res; func = lookup_method(self, &name_op[op], &unbound); if (func == NULL) { PyErr_Clear(); Py_RETURN_NOTIMPLEMENTED; } PyObject *args[1] = {other}; res = call_unbound(unbound, func, self, args, 1); Py_DECREF(func); return res; } static PyObject * slot_tp_iter(PyObject *self) { int unbound; PyObject *func, *res; _Py_IDENTIFIER(__iter__); func = lookup_method(self, &PyId___iter__, &unbound); if (func == Py_None) { Py_DECREF(func); PyErr_Format(PyExc_TypeError, "'%.200s' object is not iterable", Py_TYPE(self)->tp_name); return NULL; } if (func != NULL) { res = call_unbound_noarg(unbound, func, self); Py_DECREF(func); return res; } PyErr_Clear(); func = lookup_method(self, &PyId___getitem__, &unbound); if (func == NULL) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not iterable", Py_TYPE(self)->tp_name); return NULL; } Py_DECREF(func); return PySeqIter_New(self); } static PyObject * slot_tp_iternext(PyObject *self) { _Py_IDENTIFIER(__next__); return call_method(self, &PyId___next__, NULL, 0); } static PyObject * slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type) { PyTypeObject *tp = Py_TYPE(self); PyObject *get; _Py_IDENTIFIER(__get__); get = _PyType_LookupId(tp, &PyId___get__); if (get == NULL) { /* Avoid further slowdowns */ if (tp->tp_descr_get == slot_tp_descr_get) tp->tp_descr_get = NULL; Py_INCREF(self); return self; } if (obj == NULL) obj = Py_None; if (type == NULL) type = Py_None; return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL); } static int slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value) { PyObject* stack[2]; PyObject *res; _Py_IDENTIFIER(__delete__); _Py_IDENTIFIER(__set__); stack[0] = target; if (value == NULL) { res = call_method(self, &PyId___delete__, stack, 1); } else { stack[1] = value; res = call_method(self, &PyId___set__, stack, 2); } if (res == NULL) return -1; Py_DECREF(res); return 0; } static int slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds) { _Py_IDENTIFIER(__init__); int unbound; PyObject *meth = lookup_method(self, &PyId___init__, &unbound); PyObject *res; if (meth == NULL) return -1; if (unbound) { res = _PyObject_Call_Prepend(meth, self, args, kwds); } else { res = PyObject_Call(meth, args, kwds); } Py_DECREF(meth); if (res == NULL) return -1; if (res != Py_None) { PyErr_Format(PyExc_TypeError, "__init__() should return None, not '%.200s'", Py_TYPE(res)->tp_name); Py_DECREF(res); return -1; } Py_DECREF(res); return 0; } static PyObject * slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *func, *result; func = _PyObject_GetAttrId((PyObject *)type, &PyId___new__); if (func == NULL) { return NULL; } result = _PyObject_Call_Prepend(func, (PyObject *)type, args, kwds); Py_DECREF(func); return result; } static void slot_tp_finalize(PyObject *self) { _Py_IDENTIFIER(__del__); int unbound; PyObject *del, *res; PyObject *error_type, *error_value, *error_traceback; /* Save the current exception, if any. */ PyErr_Fetch(&error_type, &error_value, &error_traceback); /* Execute __del__ method, if any. */ del = lookup_maybe_method(self, &PyId___del__, &unbound); if (del != NULL) { res = call_unbound_noarg(unbound, del, self); if (res == NULL) PyErr_WriteUnraisable(del); else Py_DECREF(res); Py_DECREF(del); } /* Restore the saved exception. */ PyErr_Restore(error_type, error_value, error_traceback); } static PyObject * slot_am_await(PyObject *self) { int unbound; PyObject *func, *res; _Py_IDENTIFIER(__await__); func = lookup_method(self, &PyId___await__, &unbound); if (func != NULL) { res = call_unbound_noarg(unbound, func, self); Py_DECREF(func); return res; } PyErr_Format(PyExc_AttributeError, "object %.50s does not have __await__ method", Py_TYPE(self)->tp_name); return NULL; } static PyObject * slot_am_aiter(PyObject *self) { int unbound; PyObject *func, *res; _Py_IDENTIFIER(__aiter__); func = lookup_method(self, &PyId___aiter__, &unbound); if (func != NULL) { res = call_unbound_noarg(unbound, func, self); Py_DECREF(func); return res; } PyErr_Format(PyExc_AttributeError, "object %.50s does not have __aiter__ method", Py_TYPE(self)->tp_name); return NULL; } static PyObject * slot_am_anext(PyObject *self) { int unbound; PyObject *func, *res; _Py_IDENTIFIER(__anext__); func = lookup_method(self, &PyId___anext__, &unbound); if (func != NULL) { res = call_unbound_noarg(unbound, func, self); Py_DECREF(func); return res; } PyErr_Format(PyExc_AttributeError, "object %.50s does not have __anext__ method", Py_TYPE(self)->tp_name); return NULL; } /* Table mapping __foo__ names to tp_foo offsets and slot_tp_foo wrapper functions. The table is ordered by offsets relative to the 'PyHeapTypeObject' structure, which incorporates the additional structures used for numbers, sequences and mappings. Note that multiple names may map to the same slot (e.g. __eq__, __ne__ etc. all map to tp_richcompare) and one name may map to multiple slots (e.g. __str__ affects tp_str as well as tp_repr). The table is terminated with an all-zero entry. (This table is further initialized in init_slotdefs().) */ typedef struct wrapperbase slotdef; #undef TPSLOT #undef FLSLOT #undef AMSLOT #undef ETSLOT #undef SQSLOT #undef MPSLOT #undef NBSLOT #undef UNSLOT #undef IBSLOT #undef BINSLOT #undef RBINSLOT #define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ PyDoc_STR(DOC)} #define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \ {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ PyDoc_STR(DOC), FLAGS} #define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \ PyDoc_STR(DOC)} #define AMSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ ETSLOT(NAME, as_async.SLOT, FUNCTION, WRAPPER, DOC) #define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC) #define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC) #define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC) #define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ NAME "($self, /)\n--\n\n" DOC) #define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \ NAME "($self, value, /)\n--\n\nReturn self" DOC "value.") #define BINSLOT(NAME, SLOT, FUNCTION, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ NAME "($self, value, /)\n--\n\nReturn self" DOC "value.") #define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ NAME "($self, value, /)\n--\n\nReturn value" DOC "self.") #define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \ NAME "($self, value, /)\n--\n\n" DOC) #define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \ NAME "($self, value, /)\n--\n\n" DOC) static slotdef slotdefs[] = { TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""), TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""), TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""), TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""), TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc, "__repr__($self, /)\n--\n\nReturn repr(self)."), TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc, "__hash__($self, /)\n--\n\nReturn hash(self)."), FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call, "__call__($self, /, *args, **kwargs)\n--\n\nCall self as a function.", PyWrapperFlag_KEYWORDS), TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc, "__str__($self, /)\n--\n\nReturn str(self)."), TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook, wrap_binaryfunc, "__getattribute__($self, name, /)\n--\n\nReturn getattr(self, name)."), TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""), TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr, "__setattr__($self, name, value, /)\n--\n\nImplement setattr(self, name, value)."), TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr, "__delattr__($self, name, /)\n--\n\nImplement delattr(self, name)."), TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt, "__lt__($self, value, /)\n--\n\nReturn self<value."), TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le, "__le__($self, value, /)\n--\n\nReturn self<=value."), TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq, "__eq__($self, value, /)\n--\n\nReturn self==value."), TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne, "__ne__($self, value, /)\n--\n\nReturn self!=value."), TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt, "__gt__($self, value, /)\n--\n\nReturn self>value."), TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge, "__ge__($self, value, /)\n--\n\nReturn self>=value."), TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc, "__iter__($self, /)\n--\n\nImplement iter(self)."), TPSLOT("__next__", tp_iternext, slot_tp_iternext, wrap_next, "__next__($self, /)\n--\n\nImplement next(self)."), TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get, "__get__($self, instance, owner, /)\n--\n\nReturn an attribute of instance, which is of type owner."), TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set, "__set__($self, instance, value, /)\n--\n\nSet an attribute of instance to value."), TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set, wrap_descr_delete, "__delete__($self, instance, /)\n--\n\nDelete an attribute of instance."), FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init, "__init__($self, /, *args, **kwargs)\n--\n\n" "Initialize self. See help(type(self)) for accurate signature.", PyWrapperFlag_KEYWORDS), TPSLOT("__new__", tp_new, slot_tp_new, NULL, "__new__(type, /, *args, **kwargs)\n--\n\n" "Create and return new object. See help(type) for accurate signature."), TPSLOT("__del__", tp_finalize, slot_tp_finalize, (wrapperfunc)wrap_del, ""), AMSLOT("__await__", am_await, slot_am_await, wrap_unaryfunc, "__await__($self, /)\n--\n\nReturn an iterator to be used in await expression."), AMSLOT("__aiter__", am_aiter, slot_am_aiter, wrap_unaryfunc, "__aiter__($self, /)\n--\n\nReturn an awaitable, that resolves in asynchronous iterator."), AMSLOT("__anext__", am_anext, slot_am_anext, wrap_unaryfunc, "__anext__($self, /)\n--\n\nReturn a value or raise StopAsyncIteration."), BINSLOT("__add__", nb_add, slot_nb_add, "+"), RBINSLOT("__radd__", nb_add, slot_nb_add, "+"), BINSLOT("__sub__", nb_subtract, slot_nb_subtract, "-"), RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract, "-"), BINSLOT("__mul__", nb_multiply, slot_nb_multiply, "*"), RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply, "*"), BINSLOT("__mod__", nb_remainder, slot_nb_remainder, "%"), RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder, "%"), BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod, "Return divmod(self, value)."), RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod, "Return divmod(value, self)."), NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc, "__pow__($self, value, mod=None, /)\n--\n\nReturn pow(self, value, mod)."), NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r, "__rpow__($self, value, mod=None, /)\n--\n\nReturn pow(value, self, mod)."), UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-self"), UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+self"), UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc, "abs(self)"), UNSLOT("__bool__", nb_bool, slot_nb_bool, wrap_inquirypred, "self != 0"), UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~self"), BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"), RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"), BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"), RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"), BINSLOT("__and__", nb_and, slot_nb_and, "&"), RBINSLOT("__rand__", nb_and, slot_nb_and, "&"), BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"), RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), BINSLOT("__or__", nb_or, slot_nb_or, "|"), RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, "int(self)"), UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc, "float(self)"), IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add, wrap_binaryfunc, "+="), IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract, wrap_binaryfunc, "-="), IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply, wrap_binaryfunc, "*="), IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder, wrap_binaryfunc, "%="), IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power, wrap_binaryfunc, "**="), IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift, wrap_binaryfunc, "<<="), IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift, wrap_binaryfunc, ">>="), IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and, wrap_binaryfunc, "&="), IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor, wrap_binaryfunc, "^="), IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or, wrap_binaryfunc, "|="), BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"), BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"), RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"), IBSLOT("__ifloordiv__", nb_inplace_floor_divide, slot_nb_inplace_floor_divide, wrap_binaryfunc, "//="), IBSLOT("__itruediv__", nb_inplace_true_divide, slot_nb_inplace_true_divide, wrap_binaryfunc, "/="), NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, "__index__($self, /)\n--\n\n" "Return self converted to an integer, if self is suitable " "for use as an index into a list."), BINSLOT("__matmul__", nb_matrix_multiply, slot_nb_matrix_multiply, "@"), RBINSLOT("__rmatmul__", nb_matrix_multiply, slot_nb_matrix_multiply, "@"), IBSLOT("__imatmul__", nb_inplace_matrix_multiply, slot_nb_inplace_matrix_multiply, wrap_binaryfunc, "@="), MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc, "__len__($self, /)\n--\n\nReturn len(self)."), MPSLOT("__getitem__", mp_subscript, slot_mp_subscript, wrap_binaryfunc, "__getitem__($self, key, /)\n--\n\nReturn self[key]."), MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript, wrap_objobjargproc, "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."), MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript, wrap_delitem, "__delitem__($self, key, /)\n--\n\nDelete self[key]."), SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc, "__len__($self, /)\n--\n\nReturn len(self)."), /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL. The logic in abstract.c always falls back to nb_add/nb_multiply in this case. Defining both the nb_* and the sq_* slots to call the user-defined methods has unexpected side-effects, as shown by test_descr.notimplemented() */ SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc, "__add__($self, value, /)\n--\n\nReturn self+value."), SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc, "__mul__($self, value, /)\n--\n\nReturn self*value.n"), SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc, "__rmul__($self, value, /)\n--\n\nReturn self*value."), SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item, "__getitem__($self, key, /)\n--\n\nReturn self[key]."), SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem, "__setitem__($self, key, value, /)\n--\n\nSet self[key] to value."), SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem, "__delitem__($self, key, /)\n--\n\nDelete self[key]."), SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc, "__contains__($self, key, /)\n--\n\nReturn key in self."), SQSLOT("__iadd__", sq_inplace_concat, NULL, wrap_binaryfunc, "__iadd__($self, value, /)\n--\n\nImplement self+=value."), SQSLOT("__imul__", sq_inplace_repeat, NULL, wrap_indexargfunc, "__imul__($self, value, /)\n--\n\nImplement self*=value."), {NULL} }; /* Given a type pointer and an offset gotten from a slotdef entry, return a pointer to the actual slot. This is not quite the same as simply adding the offset to the type pointer, since it takes care to indirect through the proper indirection pointer (as_buffer, etc.); it returns NULL if the indirection pointer is NULL. */ static void ** slotptr(PyTypeObject *type, int ioffset) { char *ptr; long offset = ioffset; /* Note: this depends on the order of the members of PyHeapTypeObject! */ assert(offset >= 0); assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer)); if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) { ptr = (char *)type->tp_as_sequence; offset -= offsetof(PyHeapTypeObject, as_sequence); } else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) { ptr = (char *)type->tp_as_mapping; offset -= offsetof(PyHeapTypeObject, as_mapping); } else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) { ptr = (char *)type->tp_as_number; offset -= offsetof(PyHeapTypeObject, as_number); } else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_async)) { ptr = (char *)type->tp_as_async; offset -= offsetof(PyHeapTypeObject, as_async); } else { ptr = (char *)type; } if (ptr != NULL) ptr += offset; return (void **)ptr; } /* Length of array of slotdef pointers used to store slots with the same __name__. There should be at most MAX_EQUIV-1 slotdef entries with the same __name__, for any __name__. Since that's a static property, it is appropriate to declare fixed-size arrays for this. */ #define MAX_EQUIV 10 /* Return a slot pointer for a given name, but ONLY if the attribute has exactly one slot function. The name must be an interned string. */ static void ** resolve_slotdups(PyTypeObject *type, PyObject *name) { /* XXX Maybe this could be optimized more -- but is it worth it? */ /* pname and ptrs act as a little cache */ static PyObject *pname; static slotdef *ptrs[MAX_EQUIV]; slotdef *p, **pp; void **res, **ptr; if (pname != name) { /* Collect all slotdefs that match name into ptrs. */ pname = name; pp = ptrs; for (p = slotdefs; p->name_strobj; p++) { if (p->name_strobj == name) *pp++ = p; } *pp = NULL; } /* Look in all matching slots of the type; if exactly one of these has a filled-in slot, return its value. Otherwise return NULL. */ res = NULL; for (pp = ptrs; *pp; pp++) { ptr = slotptr(type, (*pp)->offset); if (ptr == NULL || *ptr == NULL) continue; if (res != NULL) return NULL; res = ptr; } return res; } /* Common code for update_slots_callback() and fixup_slot_dispatchers(). This does some incredibly complex thinking and then sticks something into the slot. (It sees if the adjacent slotdefs for the same slot have conflicting interests, and then stores a generic wrapper or a specific function into the slot.) Return a pointer to the next slotdef with a different offset, because that's convenient for fixup_slot_dispatchers(). */ static slotdef * update_one_slot(PyTypeObject *type, slotdef *p) { PyObject *descr; PyWrapperDescrObject *d; void *generic = NULL, *specific = NULL; int use_generic = 0; int offset = p->offset; void **ptr = slotptr(type, offset); if (ptr == NULL) { do { ++p; } while (p->offset == offset); return p; } do { descr = _PyType_Lookup(type, p->name_strobj); if (descr == NULL) { if (ptr == (void**)&type->tp_iternext) { specific = (void *)_PyObject_NextNotImplemented; } continue; } if (Py_TYPE(descr) == &PyWrapperDescr_Type && ((PyWrapperDescrObject *)descr)->d_base->name_strobj == p->name_strobj) { void **tptr = resolve_slotdups(type, p->name_strobj); if (tptr == NULL || tptr == ptr) generic = p->function; d = (PyWrapperDescrObject *)descr; if (d->d_base->wrapper == p->wrapper && PyType_IsSubtype(type, PyDescr_TYPE(d))) { if (specific == NULL || specific == d->d_wrapped) specific = d->d_wrapped; else use_generic = 1; } } else if (Py_TYPE(descr) == &PyCFunction_Type && PyCFunction_GET_FUNCTION(descr) == (PyCFunction)tp_new_wrapper && ptr == (void**)&type->tp_new) { /* The __new__ wrapper is not a wrapper descriptor, so must be special-cased differently. If we don't do this, creating an instance will always use slot_tp_new which will look up __new__ in the MRO which will call tp_new_wrapper which will look through the base classes looking for a static base and call its tp_new (usually PyType_GenericNew), after performing various sanity checks and constructing a new argument list. Cut all that nonsense short -- this speeds up instance creation tremendously. */ specific = (void *)type->tp_new; /* XXX I'm not 100% sure that there isn't a hole in this reasoning that requires additional sanity checks. I'll buy the first person to point out a bug in this reasoning a beer. */ } else if (descr == Py_None && ptr == (void**)&type->tp_hash) { /* We specifically allow __hash__ to be set to None to prevent inheritance of the default implementation from object.__hash__ */ specific = (void *)PyObject_HashNotImplemented; } else { use_generic = 1; generic = p->function; } } while ((++p)->offset == offset); if (specific && !use_generic) *ptr = specific; else *ptr = generic; return p; } /* In the type, update the slots whose slotdefs are gathered in the pp array. This is a callback for update_subclasses(). */ static int update_slots_callback(PyTypeObject *type, void *data) { slotdef **pp = (slotdef **)data; for (; *pp; pp++) update_one_slot(type, *pp); return 0; } static int slotdefs_initialized = 0; /* Initialize the slotdefs table by adding interned string objects for the names. */ static void init_slotdefs(void) { slotdef *p; if (slotdefs_initialized) return; for (p = slotdefs; p->name; p++) { /* Slots must be ordered by their offset in the PyHeapTypeObject. */ assert(!p[1].name || p->offset <= p[1].offset); p->name_strobj = PyUnicode_InternFromString(p->name); if (!p->name_strobj) Py_FatalError("Out of memory interning slotdef names"); } slotdefs_initialized = 1; } /* Undo init_slotdefs, releasing the interned strings. */ static void clear_slotdefs(void) { slotdef *p; for (p = slotdefs; p->name; p++) { Py_CLEAR(p->name_strobj); } slotdefs_initialized = 0; } /* Update the slots after assignment to a class (type) attribute. */ static int update_slot(PyTypeObject *type, PyObject *name) { slotdef *ptrs[MAX_EQUIV]; slotdef *p; slotdef **pp; int offset; /* Clear the VALID_VERSION flag of 'type' and all its subclasses. This could possibly be unified with the update_subclasses() recursion below, but carefully: they each have their own conditions on which to stop recursing into subclasses. */ PyType_Modified(type); init_slotdefs(); pp = ptrs; for (p = slotdefs; p->name; p++) { /* XXX assume name is interned! */ if (p->name_strobj == name) *pp++ = p; } *pp = NULL; for (pp = ptrs; *pp; pp++) { p = *pp; offset = p->offset; while (p > slotdefs && (p-1)->offset == offset) --p; *pp = p; } if (ptrs[0] == NULL) return 0; /* Not an attribute that affects any slots */ return update_subclasses(type, name, update_slots_callback, (void *)ptrs); } /* Store the proper functions in the slot dispatches at class (type) definition time, based upon which operations the class overrides in its dict. */ static void fixup_slot_dispatchers(PyTypeObject *type) { slotdef *p; init_slotdefs(); for (p = slotdefs; p->name; ) p = update_one_slot(type, p); } static void update_all_slots(PyTypeObject* type) { slotdef *p; init_slotdefs(); for (p = slotdefs; p->name; p++) { /* update_slot returns int but can't actually fail */ update_slot(type, p->name_strobj); } } /* Call __set_name__ on all descriptors in a newly generated type */ static int set_names(PyTypeObject *type) { PyObject *names_to_set, *key, *value, *set_name, *tmp; Py_ssize_t i = 0; names_to_set = PyDict_Copy(type->tp_dict); if (names_to_set == NULL) return -1; while (PyDict_Next(names_to_set, &i, &key, &value)) { set_name = lookup_maybe(value, &PyId___set_name__); if (set_name != NULL) { tmp = PyObject_CallFunctionObjArgs(set_name, type, key, NULL); Py_DECREF(set_name); if (tmp == NULL) { _PyErr_FormatFromCause(PyExc_RuntimeError, "Error calling __set_name__ on '%.100s' instance %R " "in '%.100s'", value->ob_type->tp_name, key, type->tp_name); Py_DECREF(names_to_set); return -1; } else Py_DECREF(tmp); } else if (PyErr_Occurred()) { Py_DECREF(names_to_set); return -1; } } Py_DECREF(names_to_set); return 0; } /* Call __init_subclass__ on the parent of a newly generated type */ static int init_subclass(PyTypeObject *type, PyObject *kwds) { PyObject *super, *func, *result; PyObject *args[2] = {(PyObject *)type, (PyObject *)type}; super = _PyObject_FastCall((PyObject *)&PySuper_Type, args, 2); if (super == NULL) { return -1; } func = _PyObject_GetAttrId(super, &PyId___init_subclass__); Py_DECREF(super); if (func == NULL) { return -1; } result = _PyObject_FastCallDict(func, NULL, 0, kwds); Py_DECREF(func); if (result == NULL) { return -1; } Py_DECREF(result); return 0; } /* recurse_down_subclasses() and update_subclasses() are mutually recursive functions to call a callback for all subclasses, but refraining from recursing into subclasses that define 'name'. */ static int update_subclasses(PyTypeObject *type, PyObject *name, update_callback callback, void *data) { if (callback(type, data) < 0) return -1; return recurse_down_subclasses(type, name, callback, data); } static int recurse_down_subclasses(PyTypeObject *type, PyObject *name, update_callback callback, void *data) { PyTypeObject *subclass; PyObject *ref, *subclasses, *dict; Py_ssize_t i; subclasses = type->tp_subclasses; if (subclasses == NULL) return 0; assert(PyDict_CheckExact(subclasses)); i = 0; while (PyDict_Next(subclasses, &i, NULL, &ref)) { assert(PyWeakref_CheckRef(ref)); subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref); assert(subclass != NULL); if ((PyObject *)subclass == Py_None) continue; assert(PyType_Check(subclass)); /* Avoid recursing down into unaffected classes */ dict = subclass->tp_dict; if (dict != NULL && PyDict_Check(dict) && PyDict_GetItem(dict, name) != NULL) continue; if (update_subclasses(subclass, name, callback, data) < 0) return -1; } return 0; } /* This function is called by PyType_Ready() to populate the type's dictionary with method descriptors for function slots. For each function slot (like tp_repr) that's defined in the type, one or more corresponding descriptors are added in the type's tp_dict dictionary under the appropriate name (like __repr__). Some function slots cause more than one descriptor to be added (for example, the nb_add slot adds both __add__ and __radd__ descriptors) and some function slots compete for the same descriptor (for example both sq_item and mp_subscript generate a __getitem__ descriptor). In the latter case, the first slotdef entry encountered wins. Since slotdef entries are sorted by the offset of the slot in the PyHeapTypeObject, this gives us some control over disambiguating between competing slots: the members of PyHeapTypeObject are listed from most general to least general, so the most general slot is preferred. In particular, because as_mapping comes before as_sequence, for a type that defines both mp_subscript and sq_item, mp_subscript wins. This only adds new descriptors and doesn't overwrite entries in tp_dict that were previously defined. The descriptors contain a reference to the C function they must call, so that it's safe if they are copied into a subtype's __dict__ and the subtype has a different C function in its slot -- calling the method defined by the descriptor will call the C function that was used to create it, rather than the C function present in the slot when it is called. (This is important because a subtype may have a C function in the slot that calls the method from the dictionary, and we want to avoid infinite recursion here.) */ static int add_operators(PyTypeObject *type) { PyObject *dict = type->tp_dict; slotdef *p; PyObject *descr; void **ptr; init_slotdefs(); for (p = slotdefs; p->name; p++) { if (p->wrapper == NULL) continue; ptr = slotptr(type, p->offset); if (!ptr || !*ptr) continue; if (PyDict_GetItem(dict, p->name_strobj)) continue; if (*ptr == (void *)PyObject_HashNotImplemented) { /* Classes may prevent the inheritance of the tp_hash slot by storing PyObject_HashNotImplemented in it. Make it visible as a None value for the __hash__ attribute. */ if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0) return -1; } else { descr = PyDescr_NewWrapper(type, p, *ptr); if (descr == NULL) return -1; if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) { Py_DECREF(descr); return -1; } Py_DECREF(descr); } } if (type->tp_new != NULL) { if (add_tp_new_wrapper(type) < 0) return -1; } return 0; } /* Cooperative 'super' */ typedef struct { PyObject_HEAD PyTypeObject *type; PyObject *obj; PyTypeObject *obj_type; } superobject; static PyMemberDef super_members[] = { {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY, "the class invoking super()"}, {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY, "the instance invoking super(); may be None"}, {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY, "the type of the instance invoking super(); may be None"}, {0} }; static void super_dealloc(PyObject *self) { superobject *su = (superobject *)self; _PyObject_GC_UNTRACK(self); Py_XDECREF(su->obj); Py_XDECREF(su->type); Py_XDECREF(su->obj_type); Py_TYPE(self)->tp_free(self); } static PyObject * super_repr(PyObject *self) { superobject *su = (superobject *)self; if (su->obj_type) return PyUnicode_FromFormat( "<super: <class '%s'>, <%s object>>", su->type ? su->type->tp_name : "NULL", su->obj_type->tp_name); else return PyUnicode_FromFormat( "<super: <class '%s'>, NULL>", su->type ? su->type->tp_name : "NULL"); } static PyObject * super_getattro(PyObject *self, PyObject *name) { superobject *su = (superobject *)self; PyTypeObject *starttype; PyObject *mro; Py_ssize_t i, n; starttype = su->obj_type; if (starttype == NULL) goto skip; /* We want __class__ to return the class of the super object (i.e. super, or a subclass), not the class of su->obj. */ if (PyUnicode_Check(name) && PyUnicode_GET_LENGTH(name) == 9 && _PyUnicode_EqualToASCIIId(name, &PyId___class__)) goto skip; mro = starttype->tp_mro; if (mro == NULL) goto skip; assert(PyTuple_Check(mro)); n = PyTuple_GET_SIZE(mro); /* No need to check the last one: it's gonna be skipped anyway. */ for (i = 0; i+1 < n; i++) { if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i)) break; } i++; /* skip su->type (if any) */ if (i >= n) goto skip; /* keep a strong reference to mro because starttype->tp_mro can be replaced during PyDict_GetItem(dict, name) */ Py_INCREF(mro); do { PyObject *res, *tmp, *dict; descrgetfunc f; tmp = PyTuple_GET_ITEM(mro, i); assert(PyType_Check(tmp)); dict = ((PyTypeObject *)tmp)->tp_dict; assert(dict != NULL && PyDict_Check(dict)); res = PyDict_GetItem(dict, name); if (res != NULL) { Py_INCREF(res); f = Py_TYPE(res)->tp_descr_get; if (f != NULL) { tmp = f(res, /* Only pass 'obj' param if this is instance-mode super (See SF ID #743627) */ (su->obj == (PyObject *)starttype) ? NULL : su->obj, (PyObject *)starttype); Py_DECREF(res); res = tmp; } Py_DECREF(mro); return res; } i++; } while (i < n); Py_DECREF(mro); skip: return PyObject_GenericGetAttr(self, name); } static PyTypeObject * supercheck(PyTypeObject *type, PyObject *obj) { /* Check that a super() call makes sense. Return a type object. obj can be a class, or an instance of one: - If it is a class, it must be a subclass of 'type'. This case is used for class methods; the return value is obj. - If it is an instance, it must be an instance of 'type'. This is the normal case; the return value is obj.__class__. But... when obj is an instance, we want to allow for the case where Py_TYPE(obj) is not a subclass of type, but obj.__class__ is! This will allow using super() with a proxy for obj. */ /* Check for first bullet above (special case) */ if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) { Py_INCREF(obj); return (PyTypeObject *)obj; } /* Normal case */ if (PyType_IsSubtype(Py_TYPE(obj), type)) { Py_INCREF(Py_TYPE(obj)); return Py_TYPE(obj); } else { /* Try the slow way */ PyObject *class_attr; class_attr = _PyObject_GetAttrId(obj, &PyId___class__); if (class_attr != NULL && PyType_Check(class_attr) && (PyTypeObject *)class_attr != Py_TYPE(obj)) { int ok = PyType_IsSubtype( (PyTypeObject *)class_attr, type); if (ok) return (PyTypeObject *)class_attr; } if (class_attr == NULL) PyErr_Clear(); else Py_DECREF(class_attr); } PyErr_SetString(PyExc_TypeError, "super(type, obj): " "obj must be an instance or subtype of type"); return NULL; } static PyObject * super_descr_get(PyObject *self, PyObject *obj, PyObject *type) { superobject *su = (superobject *)self; superobject *newobj; if (obj == NULL || obj == Py_None || su->obj != NULL) { /* Not binding to an object, or already bound */ Py_INCREF(self); return self; } if (Py_TYPE(su) != &PySuper_Type) /* If su is an instance of a (strict) subclass of super, call its type */ return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su), su->type, obj, NULL); else { /* Inline the common case */ PyTypeObject *obj_type = supercheck(su->type, obj); if (obj_type == NULL) return NULL; newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type, NULL, NULL); if (newobj == NULL) return NULL; Py_INCREF(su->type); Py_INCREF(obj); newobj->type = su->type; newobj->obj = obj; newobj->obj_type = obj_type; return (PyObject *)newobj; } } static int super_init(PyObject *self, PyObject *args, PyObject *kwds) { superobject *su = (superobject *)self; PyTypeObject *type = NULL; PyObject *obj = NULL; PyTypeObject *obj_type = NULL; if (!_PyArg_NoKeywords("super", kwds)) return -1; if (!PyArg_ParseTuple(args, "|O!O:super", &PyType_Type, &type, &obj)) return -1; if (type == NULL) { /* Call super(), without args -- fill in from __class__ and first local variable on the stack. */ PyFrameObject *f; PyCodeObject *co; Py_ssize_t i, n; f = PyThreadState_GET()->frame; if (f == NULL) { PyErr_SetString(PyExc_RuntimeError, "super(): no current frame"); return -1; } co = f->f_code; if (co == NULL) { PyErr_SetString(PyExc_RuntimeError, "super(): no code object"); return -1; } if (co->co_argcount == 0) { PyErr_SetString(PyExc_RuntimeError, "super(): no arguments"); return -1; } obj = f->f_localsplus[0]; if (obj == NULL && co->co_cell2arg) { /* The first argument might be a cell. */ n = PyTuple_GET_SIZE(co->co_cellvars); for (i = 0; i < n; i++) { if (co->co_cell2arg[i] == 0) { PyObject *cell = f->f_localsplus[co->co_nlocals + i]; assert(PyCell_Check(cell)); obj = PyCell_GET(cell); break; } } } if (obj == NULL) { PyErr_SetString(PyExc_RuntimeError, "super(): arg[0] deleted"); return -1; } if (co->co_freevars == NULL) n = 0; else { assert(PyTuple_Check(co->co_freevars)); n = PyTuple_GET_SIZE(co->co_freevars); } for (i = 0; i < n; i++) { PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); assert(PyUnicode_Check(name)); if (_PyUnicode_EqualToASCIIId(name, &PyId___class__)) { Py_ssize_t index = co->co_nlocals + PyTuple_GET_SIZE(co->co_cellvars) + i; PyObject *cell = f->f_localsplus[index]; if (cell == NULL || !PyCell_Check(cell)) { PyErr_SetString(PyExc_RuntimeError, "super(): bad __class__ cell"); return -1; } type = (PyTypeObject *) PyCell_GET(cell); if (type == NULL) { PyErr_SetString(PyExc_RuntimeError, "super(): empty __class__ cell"); return -1; } if (!PyType_Check(type)) { PyErr_Format(PyExc_RuntimeError, "super(): __class__ is not a type (%s)", Py_TYPE(type)->tp_name); return -1; } break; } } if (type == NULL) { PyErr_SetString(PyExc_RuntimeError, "super(): __class__ cell not found"); return -1; } } if (obj == Py_None) obj = NULL; if (obj != NULL) { obj_type = supercheck(type, obj); if (obj_type == NULL) return -1; Py_INCREF(obj); } Py_INCREF(type); Py_XSETREF(su->type, type); Py_XSETREF(su->obj, obj); Py_XSETREF(su->obj_type, obj_type); return 0; } PyDoc_STRVAR(super_doc, "super() -> same as super(__class__, <first argument>)\n" "super(type) -> unbound super object\n" "super(type, obj) -> bound super object; requires isinstance(obj, type)\n" "super(type, type2) -> bound super object; requires issubclass(type2, type)\n" "Typical use to call a cooperative superclass method:\n" "class C(B):\n" " def meth(self, arg):\n" " super().meth(arg)\n" "This works for class methods too:\n" "class C(B):\n" " @classmethod\n" " def cmeth(cls, arg):\n" " super().cmeth(arg)\n"); static int super_traverse(PyObject *self, visitproc visit, void *arg) { superobject *su = (superobject *)self; Py_VISIT(su->obj); Py_VISIT(su->type); Py_VISIT(su->obj_type); return 0; } PyTypeObject PySuper_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "super", /* tp_name */ sizeof(superobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ super_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ super_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ super_getattro, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ super_doc, /* tp_doc */ super_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ super_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ super_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ super_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ };
242,312
7,714
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/typeslots.inc
/* clang-format off */ /* Generated by typeslots.py */ 0, 0, offsetof(PyHeapTypeObject, as_mapping.mp_ass_subscript), offsetof(PyHeapTypeObject, as_mapping.mp_length), offsetof(PyHeapTypeObject, as_mapping.mp_subscript), offsetof(PyHeapTypeObject, as_number.nb_absolute), offsetof(PyHeapTypeObject, as_number.nb_add), offsetof(PyHeapTypeObject, as_number.nb_and), offsetof(PyHeapTypeObject, as_number.nb_bool), offsetof(PyHeapTypeObject, as_number.nb_divmod), offsetof(PyHeapTypeObject, as_number.nb_float), offsetof(PyHeapTypeObject, as_number.nb_floor_divide), offsetof(PyHeapTypeObject, as_number.nb_index), offsetof(PyHeapTypeObject, as_number.nb_inplace_add), offsetof(PyHeapTypeObject, as_number.nb_inplace_and), offsetof(PyHeapTypeObject, as_number.nb_inplace_floor_divide), offsetof(PyHeapTypeObject, as_number.nb_inplace_lshift), offsetof(PyHeapTypeObject, as_number.nb_inplace_multiply), offsetof(PyHeapTypeObject, as_number.nb_inplace_or), offsetof(PyHeapTypeObject, as_number.nb_inplace_power), offsetof(PyHeapTypeObject, as_number.nb_inplace_remainder), offsetof(PyHeapTypeObject, as_number.nb_inplace_rshift), offsetof(PyHeapTypeObject, as_number.nb_inplace_subtract), offsetof(PyHeapTypeObject, as_number.nb_inplace_true_divide), offsetof(PyHeapTypeObject, as_number.nb_inplace_xor), offsetof(PyHeapTypeObject, as_number.nb_int), offsetof(PyHeapTypeObject, as_number.nb_invert), offsetof(PyHeapTypeObject, as_number.nb_lshift), offsetof(PyHeapTypeObject, as_number.nb_multiply), offsetof(PyHeapTypeObject, as_number.nb_negative), offsetof(PyHeapTypeObject, as_number.nb_or), offsetof(PyHeapTypeObject, as_number.nb_positive), offsetof(PyHeapTypeObject, as_number.nb_power), offsetof(PyHeapTypeObject, as_number.nb_remainder), offsetof(PyHeapTypeObject, as_number.nb_rshift), offsetof(PyHeapTypeObject, as_number.nb_subtract), offsetof(PyHeapTypeObject, as_number.nb_true_divide), offsetof(PyHeapTypeObject, as_number.nb_xor), offsetof(PyHeapTypeObject, as_sequence.sq_ass_item), offsetof(PyHeapTypeObject, as_sequence.sq_concat), offsetof(PyHeapTypeObject, as_sequence.sq_contains), offsetof(PyHeapTypeObject, as_sequence.sq_inplace_concat), offsetof(PyHeapTypeObject, as_sequence.sq_inplace_repeat), offsetof(PyHeapTypeObject, as_sequence.sq_item), offsetof(PyHeapTypeObject, as_sequence.sq_length), offsetof(PyHeapTypeObject, as_sequence.sq_repeat), offsetof(PyHeapTypeObject, ht_type.tp_alloc), offsetof(PyHeapTypeObject, ht_type.tp_base), offsetof(PyHeapTypeObject, ht_type.tp_bases), offsetof(PyHeapTypeObject, ht_type.tp_call), offsetof(PyHeapTypeObject, ht_type.tp_clear), offsetof(PyHeapTypeObject, ht_type.tp_dealloc), offsetof(PyHeapTypeObject, ht_type.tp_del), offsetof(PyHeapTypeObject, ht_type.tp_descr_get), offsetof(PyHeapTypeObject, ht_type.tp_descr_set), offsetof(PyHeapTypeObject, ht_type.tp_doc), offsetof(PyHeapTypeObject, ht_type.tp_getattr), offsetof(PyHeapTypeObject, ht_type.tp_getattro), offsetof(PyHeapTypeObject, ht_type.tp_hash), offsetof(PyHeapTypeObject, ht_type.tp_init), offsetof(PyHeapTypeObject, ht_type.tp_is_gc), offsetof(PyHeapTypeObject, ht_type.tp_iter), offsetof(PyHeapTypeObject, ht_type.tp_iternext), offsetof(PyHeapTypeObject, ht_type.tp_methods), offsetof(PyHeapTypeObject, ht_type.tp_new), offsetof(PyHeapTypeObject, ht_type.tp_repr), offsetof(PyHeapTypeObject, ht_type.tp_richcompare), offsetof(PyHeapTypeObject, ht_type.tp_setattr), offsetof(PyHeapTypeObject, ht_type.tp_setattro), offsetof(PyHeapTypeObject, ht_type.tp_str), offsetof(PyHeapTypeObject, ht_type.tp_traverse), offsetof(PyHeapTypeObject, ht_type.tp_members), offsetof(PyHeapTypeObject, ht_type.tp_getset), offsetof(PyHeapTypeObject, ht_type.tp_free), offsetof(PyHeapTypeObject, as_number.nb_matrix_multiply), offsetof(PyHeapTypeObject, as_number.nb_inplace_matrix_multiply), offsetof(PyHeapTypeObject, as_async.am_await), offsetof(PyHeapTypeObject, as_async.am_aiter), offsetof(PyHeapTypeObject, as_async.am_anext), offsetof(PyHeapTypeObject, ht_type.tp_finalize),
3,991
83
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/unicodeobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "libc/assert.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/intrin/likely.h" #include "libc/intrin/weaken.h" #include "libc/log/countbranch.h" #include "libc/str/str.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytes_methods.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/memoryobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/osmodule.h" #include "third_party/python/Include/pycapsule.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pystrtod.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/ucnhash.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Include/yoink.h" #include "third_party/python/Modules/unicodedata.h" /* clang-format off */ PYTHON_PROVIDE("_string"); PYTHON_PROVIDE("_string.__doc__"); PYTHON_PROVIDE("_string.__loader__"); PYTHON_PROVIDE("_string.__name__"); PYTHON_PROVIDE("_string.__package__"); PYTHON_PROVIDE("_string.__spec__"); PYTHON_PROVIDE("_string.formatter_field_name_split"); PYTHON_PROVIDE("_string.formatter_parser"); #include "third_party/python/Objects/stringlib/eq.inc" /** * @fileoverview Unicode Objects * * Since the implementation of PEP 393 in Python 3.3, Unicode objects * internally use a variety of representations, in order to allow * handling the complete range of Unicode characters while staying * memory efficient. There are special cases for strings where all code * points are below 128, 256, or 65536; otherwise, code points must be * below 1114112 (which is the full Unicode range). * * Py_UNICODE* and UTF-8 representations are created on demand and * cached in the Unicode object. The Py_UNICODE* representation is * deprecated and inefficient. * * Due to the transition between the old APIs and the new APIs, Unicode * objects can internally be in two states depending on how they were * created: * * * “canonical” Unicode objects are all objects created by a * non-deprecated Unicode API. They use the most efficient * representation allowed by the implementation. * * * “legacy” Unicode objects have been created through one of the * deprecated APIs (typically PyUnicode_FromUnicode()) and only bear * the Py_UNICODE* representation; you will have to call * PyUnicode_READY() on them before calling any other API. * * The “legacy” Unicode object will be removed in Python 3.12 with * deprecated APIs. All Unicode objects will be “canonical” since then. * See PEP 623 for more information. */ /* Unicode implementation based on original code by Fredrik Lundh, modified by Marc-Andre Lemburg <[email protected]>. Major speed upgrades to the method implementations at the Reykjavik NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke. Copyright (c) Corporation for National Research Initiatives. -------------------------------------------------------------------- The original string type implementation is: Copyright (c) 1999 by Secret Labs AB Copyright (c) 1999 by Fredrik Lundh By obtaining, using, and/or copying this software and/or its associated documentation, you agree that you have read, understood, and will comply with the following terms and conditions: Permission to use, copy, modify, and distribute this software and its associated documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies, and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Secret Labs AB or the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -------------------------------------------------------------------- */ /*[clinic input] class str "PyUnicodeObject *" "&PyUnicode_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=604e916854800fa8]*/ /* --- Globals ------------------------------------------------------------ NOTE: In the interpreter's initialization phase, some globals are currently initialized dynamically as needed. In the process Unicode objects may be created before the Unicode type is ready. */ /* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */ #define MAX_UNICODE 0x10ffff #ifdef Py_DEBUG # define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0) #else # define _PyUnicode_CHECK(op) PyUnicode_Check(op) #endif #define _PyUnicode_UTF8(op) \ (((PyCompactUnicodeObject*)(op))->utf8) #define PyUnicode_UTF8(op) \ (assert(_PyUnicode_CHECK(op)), \ assert(PyUnicode_IS_READY(op)), \ PyUnicode_IS_COMPACT_ASCII(op) ? \ ((char*)((PyASCIIObject*)(op) + 1)) : \ _PyUnicode_UTF8(op)) #define _PyUnicode_UTF8_LENGTH(op) \ (((PyCompactUnicodeObject*)(op))->utf8_length) #define PyUnicode_UTF8_LENGTH(op) \ (assert(_PyUnicode_CHECK(op)), \ assert(PyUnicode_IS_READY(op)), \ PyUnicode_IS_COMPACT_ASCII(op) ? \ ((PyASCIIObject*)(op))->length : \ _PyUnicode_UTF8_LENGTH(op)) #define _PyUnicode_WSTR(op) \ (((PyASCIIObject*)(op))->wstr) #define _PyUnicode_WSTR_LENGTH(op) \ (((PyCompactUnicodeObject*)(op))->wstr_length) #define _PyUnicode_LENGTH(op) \ (((PyASCIIObject *)(op))->length) #define _PyUnicode_STATE(op) \ (((PyASCIIObject *)(op))->state) #define _PyUnicode_HASH(op) \ (((PyASCIIObject *)(op))->hash) #define _PyUnicode_KIND(op) \ (assert(_PyUnicode_CHECK(op)), \ ((PyASCIIObject *)(op))->state.kind) #define _PyUnicode_GET_LENGTH(op) \ (assert(_PyUnicode_CHECK(op)), \ ((PyASCIIObject *)(op))->length) #define _PyUnicode_DATA_ANY(op) \ (((PyUnicodeObject*)(op))->data.any) #undef PyUnicode_READY #define PyUnicode_READY(op) \ (assert(_PyUnicode_CHECK(op)), \ (PyUnicode_IS_READY(op) ? \ 0 : \ _PyUnicode_Ready(op))) #define _PyUnicode_SHARE_UTF8(op) \ (assert(_PyUnicode_CHECK(op)), \ assert(!PyUnicode_IS_COMPACT_ASCII(op)), \ (_PyUnicode_UTF8(op) == PyUnicode_DATA(op))) #define _PyUnicode_SHARE_WSTR(op) \ (assert(_PyUnicode_CHECK(op)), \ (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op))) /* true if the Unicode object has an allocated UTF-8 memory block (not shared with other data) */ #define _PyUnicode_HAS_UTF8_MEMORY(op) \ ((!PyUnicode_IS_COMPACT_ASCII(op) \ && _PyUnicode_UTF8(op) \ && _PyUnicode_UTF8(op) != PyUnicode_DATA(op))) /* true if the Unicode object has an allocated wstr memory block (not shared with other data) */ #define _PyUnicode_HAS_WSTR_MEMORY(op) \ ((_PyUnicode_WSTR(op) && \ (!PyUnicode_IS_READY(op) || \ _PyUnicode_WSTR(op) != PyUnicode_DATA(op)))) /* Generic helper macro to convert characters of different types. from_type and to_type have to be valid type names, begin and end are pointers to the source characters which should be of type "from_type *". to is a pointer of type "to_type *" and points to the buffer where the result characters are written to. */ #define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \ do { \ to_type *_to = (to_type *)(to); \ const from_type *_iter = (from_type *)(begin); \ const from_type *_end = (from_type *)(end); \ Py_ssize_t n = (_end) - (_iter); \ const from_type *_unrolled_end = \ _iter + _Py_SIZE_ROUND_DOWN(n, 4); \ while (_iter < (_unrolled_end)) { \ _to[0] = (to_type) _iter[0]; \ _to[1] = (to_type) _iter[1]; \ _to[2] = (to_type) _iter[2]; \ _to[3] = (to_type) _iter[3]; \ _iter += 4; _to += 4; \ } \ while (_iter < (_end)) \ *_to++ = (to_type) *_iter++; \ } while (0) #ifdef MS_WINDOWS /* On Windows, overallocate by 50% is the best factor */ # define OVERALLOCATE_FACTOR 2 #else /* On Linux, overallocate by 25% is the best factor */ # define OVERALLOCATE_FACTOR 4 #endif /* This dictionary holds all interned unicode strings. Note that references to strings in this dictionary are *not* counted in the string's ob_refcnt. When the interned string reaches a refcnt of 0 the string deallocation function will delete the reference from this dictionary. Another way to look at this is that to say that the actual reference count of a string is: s->ob_refcnt + (s->state ? 2 : 0) */ static PyObject *interned = NULL; /* The empty Unicode object is shared to improve performance. */ static PyObject *unicode_empty = NULL; #define _Py_INCREF_UNICODE_EMPTY() \ do { \ if (unicode_empty != NULL) \ Py_INCREF(unicode_empty); \ else { \ unicode_empty = PyUnicode_New(0, 0); \ if (unicode_empty != NULL) { \ Py_INCREF(unicode_empty); \ assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \ } \ } \ } while (0) #define _Py_RETURN_UNICODE_EMPTY() \ do { \ _Py_INCREF_UNICODE_EMPTY(); \ return unicode_empty; \ } while (0) #define FILL(kind, data, value, start, length) \ do { \ assert(0 <= start); \ assert(kind != PyUnicode_WCHAR_KIND); \ switch (kind) { \ case PyUnicode_1BYTE_KIND: { \ assert(value <= 0xff); \ Py_UCS1 ch = (unsigned char)value; \ Py_UCS1 *to = (Py_UCS1 *)data + start; \ memset(to, ch, length); \ break; \ } \ case PyUnicode_2BYTE_KIND: { \ assert(value <= 0xffff); \ Py_UCS2 ch = (Py_UCS2)value; \ Py_UCS2 *to = (Py_UCS2 *)data + start; \ const Py_UCS2 *end = to + length; \ for (; to < end; ++to) *to = ch; \ break; \ } \ case PyUnicode_4BYTE_KIND: { \ assert(value <= MAX_UNICODE); \ Py_UCS4 ch = value; \ Py_UCS4 * to = (Py_UCS4 *)data + start; \ const Py_UCS4 *end = to + length; \ for (; to < end; ++to) *to = ch; \ break; \ } \ default: assert(0); \ } \ } while (0) /* Forward declaration */ static inline int _PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch); /* List of static strings. */ static _Py_Identifier *static_strings = NULL; /* Single character Unicode strings in the Latin-1 range are being shared as well. */ static PyObject *unicode_latin1[256] = {NULL}; /* Fast detection of the most frequent whitespace characters */ const unsigned char _Py_ascii_whitespace[] = { 0, 0, 0, 0, 0, 0, 0, 0, /* case 0x0009: * CHARACTER TABULATION */ /* case 0x000A: * LINE FEED */ /* case 0x000B: * LINE TABULATION */ /* case 0x000C: * FORM FEED */ /* case 0x000D: * CARRIAGE RETURN */ 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* case 0x001C: * FILE SEPARATOR */ /* case 0x001D: * GROUP SEPARATOR */ /* case 0x001E: * RECORD SEPARATOR */ /* case 0x001F: * UNIT SEPARATOR */ 0, 0, 0, 0, 1, 1, 1, 1, /* case 0x0020: * SPACE */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* forward */ static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length); static PyObject* get_latin1_char(unsigned char ch); static int unicode_modifiable(PyObject *unicode); static PyObject * _PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size); static PyObject * _PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size); static PyObject * _PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size); static PyObject * unicode_encode_call_errorhandler(const char *errors, PyObject **errorHandler,const char *encoding, const char *reason, PyObject *unicode, PyObject **exceptionObject, Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos); static void raise_encode_exception(PyObject **exceptionObject, const char *encoding, PyObject *unicode, Py_ssize_t startpos, Py_ssize_t endpos, const char *reason); /* Same for linebreaks */ static const unsigned char ascii_linebreak[] = { 0, 0, 0, 0, 0, 0, 0, 0, /* 0x000A, * LINE FEED */ /* 0x000B, * LINE TABULATION */ /* 0x000C, * FORM FEED */ /* 0x000D, * CARRIAGE RETURN */ 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x001C, * FILE SEPARATOR */ /* 0x001D, * GROUP SEPARATOR */ /* 0x001E, * RECORD SEPARATOR */ 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; #include "third_party/python/Objects/clinic/unicodeobject.inc" typedef enum { _Py_ERROR_UNKNOWN=0, _Py_ERROR_STRICT, _Py_ERROR_SURROGATEESCAPE, _Py_ERROR_REPLACE, _Py_ERROR_IGNORE, _Py_ERROR_BACKSLASHREPLACE, _Py_ERROR_SURROGATEPASS, _Py_ERROR_XMLCHARREFREPLACE, _Py_ERROR_OTHER } _Py_error_handler; static _Py_error_handler get_error_handler(const char *errors) { if (errors == NULL || strcmp(errors, "strict") == 0) { return _Py_ERROR_STRICT; } if (strcmp(errors, "surrogateescape") == 0) { return _Py_ERROR_SURROGATEESCAPE; } if (strcmp(errors, "replace") == 0) { return _Py_ERROR_REPLACE; } if (strcmp(errors, "ignore") == 0) { return _Py_ERROR_IGNORE; } if (strcmp(errors, "backslashreplace") == 0) { return _Py_ERROR_BACKSLASHREPLACE; } if (strcmp(errors, "surrogatepass") == 0) { return _Py_ERROR_SURROGATEPASS; } if (strcmp(errors, "xmlcharrefreplace") == 0) { return _Py_ERROR_XMLCHARREFREPLACE; } return _Py_ERROR_OTHER; } #ifdef Py_DEBUG int _PyUnicode_CheckConsistency(PyObject *op, int check_content) { PyASCIIObject *ascii; unsigned int kind; assert(PyUnicode_Check(op)); ascii = (PyASCIIObject *)op; kind = ascii->state.kind; if (ascii->state.ascii == 1 && ascii->state.compact == 1) { assert(kind == PyUnicode_1BYTE_KIND); assert(ascii->state.ready == 1); } else { PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op; void *data; if (ascii->state.compact == 1) { data = compact + 1; assert(kind == PyUnicode_1BYTE_KIND || kind == PyUnicode_2BYTE_KIND || kind == PyUnicode_4BYTE_KIND); assert(ascii->state.ascii == 0); assert(ascii->state.ready == 1); assert (compact->utf8 != data); } else { PyUnicodeObject *unicode = (PyUnicodeObject *)op; data = unicode->data.any; if (kind == PyUnicode_WCHAR_KIND) { assert(ascii->length == 0); assert(ascii->hash == -1); assert(ascii->state.compact == 0); assert(ascii->state.ascii == 0); assert(ascii->state.ready == 0); assert(ascii->state.interned == SSTATE_NOT_INTERNED); assert(ascii->wstr != NULL); assert(data == NULL); assert(compact->utf8 == NULL); } else { assert(kind == PyUnicode_1BYTE_KIND || kind == PyUnicode_2BYTE_KIND || kind == PyUnicode_4BYTE_KIND); assert(ascii->state.compact == 0); assert(ascii->state.ready == 1); assert(data != NULL); if (ascii->state.ascii) { assert (compact->utf8 == data); assert (compact->utf8_length == ascii->length); } else assert (compact->utf8 != data); } } if (kind != PyUnicode_WCHAR_KIND) { if ( #if SIZEOF_WCHAR_T == 2 kind == PyUnicode_2BYTE_KIND #else kind == PyUnicode_4BYTE_KIND #endif ) { assert(ascii->wstr == data); assert(compact->wstr_length == ascii->length); } else assert(ascii->wstr != data); } if (compact->utf8 == NULL) assert(compact->utf8_length == 0); if (ascii->wstr == NULL) assert(compact->wstr_length == 0); } /* check that the best kind is used */ if (check_content && kind != PyUnicode_WCHAR_KIND) { Py_ssize_t i; Py_UCS4 maxchar = 0; void *data; Py_UCS4 ch; data = PyUnicode_DATA(ascii); for (i=0; i < ascii->length; i++) { ch = PyUnicode_READ(kind, data, i); if (ch > maxchar) maxchar = ch; } if (kind == PyUnicode_1BYTE_KIND) { if (ascii->state.ascii == 0) { assert(maxchar >= 128); assert(maxchar <= 255); } else assert(maxchar < 128); } else if (kind == PyUnicode_2BYTE_KIND) { assert(maxchar >= 0x100); assert(maxchar <= 0xFFFF); } else { assert(maxchar >= 0x10000); assert(maxchar <= MAX_UNICODE); } assert(PyUnicode_READ(kind, data, ascii->length) == 0); } return 1; } #endif static PyObject* unicode_result_wchar(PyObject *unicode) { #ifndef Py_DEBUG Py_ssize_t len; len = _PyUnicode_WSTR_LENGTH(unicode); if (len == 0) { Py_DECREF(unicode); _Py_RETURN_UNICODE_EMPTY(); } if (len == 1) { wchar_t ch = _PyUnicode_WSTR(unicode)[0]; if ((Py_UCS4)ch < 256) { PyObject *latin1_char = get_latin1_char((unsigned char)ch); Py_DECREF(unicode); return latin1_char; } } if (_PyUnicode_Ready(unicode) < 0) { Py_DECREF(unicode); return NULL; } #else assert(Py_REFCNT(unicode) == 1); /* don't make the result ready in debug mode to ensure that the caller makes the string ready before using it */ assert(_PyUnicode_CheckConsistency(unicode, 1)); #endif return unicode; } static PyObject* unicode_result_ready(PyObject *unicode) { Py_ssize_t length; length = PyUnicode_GET_LENGTH(unicode); if (length == 0) { if (unicode != unicode_empty) { Py_DECREF(unicode); _Py_RETURN_UNICODE_EMPTY(); } return unicode_empty; } if (length == 1) { void *data = PyUnicode_DATA(unicode); int kind = PyUnicode_KIND(unicode); Py_UCS4 ch = PyUnicode_READ(kind, data, 0); if (ch < 256) { PyObject *latin1_char = unicode_latin1[ch]; if (latin1_char != NULL) { if (unicode != latin1_char) { Py_INCREF(latin1_char); Py_DECREF(unicode); } return latin1_char; } else { assert(_PyUnicode_CheckConsistency(unicode, 1)); Py_INCREF(unicode); unicode_latin1[ch] = unicode; return unicode; } } } assert(_PyUnicode_CheckConsistency(unicode, 1)); return unicode; } PyObject* unicode_result(PyObject *unicode) { assert(_PyUnicode_CHECK(unicode)); if (PyUnicode_IS_READY(unicode)) return unicode_result_ready(unicode); else return unicode_result_wchar(unicode); } static PyObject* unicode_result_unchanged(PyObject *unicode) { if (PyUnicode_CheckExact(unicode)) { if (PyUnicode_READY(unicode) == -1) return NULL; Py_INCREF(unicode); return unicode; } else /* Subtype -- return genuine unicode string with the same value. */ return _PyUnicode_Copy(unicode); } /* Implementation of the "backslashreplace" error handler for 8-bit encodings: ASCII, Latin1, UTF-8, etc. */ static char* backslashreplace(_PyBytesWriter *writer, char *str, PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend) { Py_ssize_t size, i; Py_UCS4 ch; enum PyUnicode_Kind kind; void *data; assert(PyUnicode_IS_READY(unicode)); kind = PyUnicode_KIND(unicode); data = PyUnicode_DATA(unicode); size = 0; /* determine replacement size */ for (i = collstart; i < collend; ++i) { Py_ssize_t incr; ch = PyUnicode_READ(kind, data, i); if (ch < 0x100) incr = 2+2; else if (ch < 0x10000) incr = 2+4; else { assert(ch <= MAX_UNICODE); incr = 2+8; } if (size > PY_SSIZE_T_MAX - incr) { PyErr_SetString(PyExc_OverflowError, "encoded result is too long for a Python string"); return NULL; } size += incr; } str = _PyBytesWriter_Prepare(writer, str, size); if (str == NULL) return NULL; /* generate replacement */ for (i = collstart; i < collend; ++i) { ch = PyUnicode_READ(kind, data, i); *str++ = '\\'; if (ch >= 0x00010000) { *str++ = 'U'; *str++ = Py_hexdigits[(ch>>28)&0xf]; *str++ = Py_hexdigits[(ch>>24)&0xf]; *str++ = Py_hexdigits[(ch>>20)&0xf]; *str++ = Py_hexdigits[(ch>>16)&0xf]; *str++ = Py_hexdigits[(ch>>12)&0xf]; *str++ = Py_hexdigits[(ch>>8)&0xf]; } else if (ch >= 0x100) { *str++ = 'u'; *str++ = Py_hexdigits[(ch>>12)&0xf]; *str++ = Py_hexdigits[(ch>>8)&0xf]; } else *str++ = 'x'; *str++ = Py_hexdigits[(ch>>4)&0xf]; *str++ = Py_hexdigits[ch&0xf]; } return str; } /* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings: ASCII, Latin1, UTF-8, etc. */ static char* xmlcharrefreplace(_PyBytesWriter *writer, char *str, PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend) { Py_ssize_t size, i; Py_UCS4 ch; enum PyUnicode_Kind kind; void *data; assert(PyUnicode_IS_READY(unicode)); kind = PyUnicode_KIND(unicode); data = PyUnicode_DATA(unicode); size = 0; /* determine replacement size */ for (i = collstart; i < collend; ++i) { Py_ssize_t incr; ch = PyUnicode_READ(kind, data, i); if (ch < 10) incr = 2+1+1; else if (ch < 100) incr = 2+2+1; else if (ch < 1000) incr = 2+3+1; else if (ch < 10000) incr = 2+4+1; else if (ch < 100000) incr = 2+5+1; else if (ch < 1000000) incr = 2+6+1; else { assert(ch <= MAX_UNICODE); incr = 2+7+1; } if (size > PY_SSIZE_T_MAX - incr) { PyErr_SetString(PyExc_OverflowError, "encoded result is too long for a Python string"); return NULL; } size += incr; } str = _PyBytesWriter_Prepare(writer, str, size); if (str == NULL) return NULL; /* generate replacement */ for (i = collstart; i < collend; ++i) { str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i)); } return str; } /* --- Bloom Filters ----------------------------------------------------- */ /* stuff to implement simple "bloom filters" for Unicode characters. to keep things simple, we use a single bitmask, using the least 5 bits from each unicode characters as the bit index. */ /* the linebreak mask is set up by Unicode_Init below */ #if LONG_BIT >= 128 #define BLOOM_WIDTH 128 #elif LONG_BIT >= 64 #define BLOOM_WIDTH 64 #elif LONG_BIT >= 32 #define BLOOM_WIDTH 32 #else #error "LONG_BIT is smaller than 32" #endif #define BLOOM_MASK unsigned long static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0; #define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1))))) #define BLOOM_LINEBREAK(ch) \ ((ch) < 128U ? ascii_linebreak[(ch)] : \ (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch))) static inline BLOOM_MASK make_bloom_mask(int kind, void* ptr, Py_ssize_t len) { #define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \ do { \ TYPE *data = (TYPE *)PTR; \ TYPE *end = data + LEN; \ Py_UCS4 ch; \ for (; data != end; data++) { \ ch = *data; \ MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \ } \ break; \ } while (0) /* calculate simple bloom-style bitmask for a given unicode string */ BLOOM_MASK mask; mask = 0; switch (kind) { case PyUnicode_1BYTE_KIND: BLOOM_UPDATE(Py_UCS1, mask, ptr, len); break; case PyUnicode_2BYTE_KIND: BLOOM_UPDATE(Py_UCS2, mask, ptr, len); break; case PyUnicode_4BYTE_KIND: BLOOM_UPDATE(Py_UCS4, mask, ptr, len); break; default: assert(0); } return mask; #undef BLOOM_UPDATE } static int ensure_unicode(PyObject *obj) { if (!PyUnicode_Check(obj)) { PyErr_Format(PyExc_TypeError, "must be str, not %.100s", Py_TYPE(obj)->tp_name); return -1; } return PyUnicode_READY(obj); } /* Compilation of templated routines */ #include "third_party/python/Objects/stringlib/asciilib.inc" #include "third_party/python/Objects/stringlib/fastsearch.inc" #include "third_party/python/Objects/stringlib/partition.inc" #include "third_party/python/Objects/stringlib/split.inc" #include "third_party/python/Objects/stringlib/count.inc" #include "third_party/python/Objects/stringlib/find.inc" #include "third_party/python/Objects/stringlib/find_max_char.inc" #include "third_party/python/Objects/stringlib/undef.inc" #include "third_party/python/Objects/stringlib/ucs1lib.inc" #include "third_party/python/Objects/stringlib/fastsearch.inc" #include "third_party/python/Objects/stringlib/partition.inc" #include "third_party/python/Objects/stringlib/split.inc" #include "third_party/python/Objects/stringlib/count.inc" #include "third_party/python/Objects/stringlib/find.inc" #include "third_party/python/Objects/stringlib/replace.inc" #include "third_party/python/Objects/stringlib/find_max_char.inc" #include "third_party/python/Objects/stringlib/undef.inc" #include "third_party/python/Objects/stringlib/ucs2lib.inc" #include "third_party/python/Objects/stringlib/fastsearch.inc" #include "third_party/python/Objects/stringlib/partition.inc" #include "third_party/python/Objects/stringlib/split.inc" #include "third_party/python/Objects/stringlib/count.inc" #include "third_party/python/Objects/stringlib/find.inc" #include "third_party/python/Objects/stringlib/replace.inc" #include "third_party/python/Objects/stringlib/find_max_char.inc" #include "third_party/python/Objects/stringlib/undef.inc" #include "third_party/python/Objects/stringlib/ucs4lib.inc" #include "third_party/python/Objects/stringlib/fastsearch.inc" #include "third_party/python/Objects/stringlib/partition.inc" #include "third_party/python/Objects/stringlib/split.inc" #include "third_party/python/Objects/stringlib/count.inc" #include "third_party/python/Objects/stringlib/find.inc" #include "third_party/python/Objects/stringlib/replace.inc" #include "third_party/python/Objects/stringlib/find_max_char.inc" #include "third_party/python/Objects/stringlib/undef.inc" #include "third_party/python/Objects/stringlib/unicodedefs.inc" #include "third_party/python/Objects/stringlib/fastsearch.inc" #include "third_party/python/Objects/stringlib/count.inc" #include "third_party/python/Objects/stringlib/find.inc" #include "third_party/python/Objects/stringlib/undef.inc" /* --- Unicode Object ----------------------------------------------------- */ static PyObject * fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s)); static inline Py_ssize_t findchar(const void *s, int kind, Py_ssize_t size, Py_UCS4 ch, int direction) { switch (kind) { case PyUnicode_1BYTE_KIND: if ((Py_UCS1) ch != ch) return -1; if (direction > 0) return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch); else return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch); case PyUnicode_2BYTE_KIND: if ((Py_UCS2) ch != ch) return -1; if (direction > 0) return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch); else return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch); case PyUnicode_4BYTE_KIND: if (direction > 0) return ucs4lib_find_char((Py_UCS4 *) s, size, ch); else return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch); default: assert(0); return -1; } } #ifdef Py_DEBUG /* Fill the data of a Unicode string with invalid characters to detect bugs earlier. _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an invalid character in Unicode 6.0. */ static void unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length) { int kind = PyUnicode_KIND(unicode); Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode); Py_ssize_t length = _PyUnicode_LENGTH(unicode); if (length <= old_length) return; memset(data + old_length * kind, 0xff, (length - old_length) * kind); } #endif static PyObject* resize_compact(PyObject *unicode, Py_ssize_t length) { Py_ssize_t char_size; Py_ssize_t struct_size; Py_ssize_t new_size; int share_wstr; PyObject *new_unicode; #ifdef Py_DEBUG Py_ssize_t old_length = _PyUnicode_LENGTH(unicode); #endif assert(unicode_modifiable(unicode)); assert(PyUnicode_IS_READY(unicode)); assert(PyUnicode_IS_COMPACT(unicode)); char_size = PyUnicode_KIND(unicode); if (PyUnicode_IS_ASCII(unicode)) struct_size = sizeof(PyASCIIObject); else struct_size = sizeof(PyCompactUnicodeObject); share_wstr = _PyUnicode_SHARE_WSTR(unicode); if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) { PyErr_NoMemory(); return NULL; } new_size = (struct_size + (length + 1) * char_size); if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) { PyObject_DEL(_PyUnicode_UTF8(unicode)); _PyUnicode_UTF8(unicode) = NULL; _PyUnicode_UTF8_LENGTH(unicode) = 0; } _Py_DEC_REFTOTAL; _Py_ForgetReference(unicode); new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size); if (new_unicode == NULL) { _Py_NewReference(unicode); PyErr_NoMemory(); return NULL; } unicode = new_unicode; _Py_NewReference(unicode); _PyUnicode_LENGTH(unicode) = length; if (share_wstr) { _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode); if (!PyUnicode_IS_ASCII(unicode)) _PyUnicode_WSTR_LENGTH(unicode) = length; } else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) { PyObject_DEL(_PyUnicode_WSTR(unicode)); _PyUnicode_WSTR(unicode) = NULL; if (!PyUnicode_IS_ASCII(unicode)) _PyUnicode_WSTR_LENGTH(unicode) = 0; } #ifdef Py_DEBUG unicode_fill_invalid(unicode, old_length); #endif PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode), length, 0); assert(_PyUnicode_CheckConsistency(unicode, 0)); return unicode; } static int resize_inplace(PyObject *unicode, Py_ssize_t length) { wchar_t *wstr; Py_ssize_t new_size; assert(!PyUnicode_IS_COMPACT(unicode)); assert(Py_REFCNT(unicode) == 1); if (PyUnicode_IS_READY(unicode)) { Py_ssize_t char_size; int share_wstr, share_utf8; void *data; #ifdef Py_DEBUG Py_ssize_t old_length = _PyUnicode_LENGTH(unicode); #endif data = _PyUnicode_DATA_ANY(unicode); char_size = PyUnicode_KIND(unicode); share_wstr = _PyUnicode_SHARE_WSTR(unicode); share_utf8 = _PyUnicode_SHARE_UTF8(unicode); if (length > (PY_SSIZE_T_MAX / char_size - 1)) { PyErr_NoMemory(); return -1; } new_size = (length + 1) * char_size; if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode)) { PyObject_DEL(_PyUnicode_UTF8(unicode)); _PyUnicode_UTF8(unicode) = NULL; _PyUnicode_UTF8_LENGTH(unicode) = 0; } data = (PyObject *)PyObject_REALLOC(data, new_size); if (data == NULL) { PyErr_NoMemory(); return -1; } _PyUnicode_DATA_ANY(unicode) = data; if (share_wstr) { _PyUnicode_WSTR(unicode) = data; _PyUnicode_WSTR_LENGTH(unicode) = length; } if (share_utf8) { _PyUnicode_UTF8(unicode) = data; _PyUnicode_UTF8_LENGTH(unicode) = length; } _PyUnicode_LENGTH(unicode) = length; PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0); #ifdef Py_DEBUG unicode_fill_invalid(unicode, old_length); #endif if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) { assert(_PyUnicode_CheckConsistency(unicode, 0)); return 0; } } assert(_PyUnicode_WSTR(unicode) != NULL); /* check for integer overflow */ if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) { PyErr_NoMemory(); return -1; } new_size = sizeof(wchar_t) * (length + 1); wstr = _PyUnicode_WSTR(unicode); wstr = PyObject_REALLOC(wstr, new_size); if (!wstr) { PyErr_NoMemory(); return -1; } _PyUnicode_WSTR(unicode) = wstr; _PyUnicode_WSTR(unicode)[length] = 0; _PyUnicode_WSTR_LENGTH(unicode) = length; assert(_PyUnicode_CheckConsistency(unicode, 0)); return 0; } static PyObject* resize_copy(PyObject *unicode, Py_ssize_t length) { Py_ssize_t copy_length; if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) { PyObject *copy; if (PyUnicode_READY(unicode) == -1) return NULL; copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode)); if (copy == NULL) return NULL; copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode)); _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length); return copy; } else { PyObject *w; w = (PyObject*)_PyUnicode_New(length); if (w == NULL) return NULL; copy_length = _PyUnicode_WSTR_LENGTH(unicode); copy_length = Py_MIN(copy_length, length); memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode), copy_length * sizeof(wchar_t)); return w; } } /* We allocate one more byte to make sure the string is Ux0000 terminated; some code (e.g. new_identifier) relies on that. XXX This allocator could further be enhanced by assuring that the free list never reduces its size below 1. */ static PyUnicodeObject * _PyUnicode_New(Py_ssize_t length) { PyUnicodeObject *unicode; size_t new_size; /* Optimization for empty strings */ if (length == 0 && unicode_empty != NULL) { Py_INCREF(unicode_empty); return (PyUnicodeObject*)unicode_empty; } /* Ensure we won't overflow the size. */ if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) { return (PyUnicodeObject *)PyErr_NoMemory(); } if (length < 0) { PyErr_SetString(PyExc_SystemError, "Negative size passed to _PyUnicode_New"); return NULL; } unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type); if (unicode == NULL) return NULL; new_size = sizeof(Py_UNICODE) * ((size_t)length + 1); _PyUnicode_WSTR_LENGTH(unicode) = length; _PyUnicode_HASH(unicode) = -1; _PyUnicode_STATE(unicode).interned = 0; _PyUnicode_STATE(unicode).kind = 0; _PyUnicode_STATE(unicode).compact = 0; _PyUnicode_STATE(unicode).ready = 0; _PyUnicode_STATE(unicode).ascii = 0; _PyUnicode_DATA_ANY(unicode) = NULL; _PyUnicode_LENGTH(unicode) = 0; _PyUnicode_UTF8(unicode) = NULL; _PyUnicode_UTF8_LENGTH(unicode) = 0; _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size); if (!_PyUnicode_WSTR(unicode)) { Py_DECREF(unicode); PyErr_NoMemory(); return NULL; } /* Initialize the first element to guard against cases where * the caller fails before initializing str -- unicode_resize() * reads str[0], and the Keep-Alive optimization can keep memory * allocated for str alive across a call to unicode_dealloc(unicode). * We don't want unicode_resize to read uninitialized memory in * that case. */ _PyUnicode_WSTR(unicode)[0] = 0; _PyUnicode_WSTR(unicode)[length] = 0; assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0)); return unicode; } static const char* unicode_kind_name(PyObject *unicode) { /* don't check consistency: unicode_kind_name() is called from _PyUnicode_Dump() */ if (!PyUnicode_IS_COMPACT(unicode)) { if (!PyUnicode_IS_READY(unicode)) return "wstr"; switch (PyUnicode_KIND(unicode)) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(unicode)) return "legacy ascii"; else return "legacy latin1"; case PyUnicode_2BYTE_KIND: return "legacy UCS2"; case PyUnicode_4BYTE_KIND: return "legacy UCS4"; default: return "<legacy invalid kind>"; } } assert(PyUnicode_IS_READY(unicode)); switch (PyUnicode_KIND(unicode)) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(unicode)) return "ascii"; else return "latin1"; case PyUnicode_2BYTE_KIND: return "UCS2"; case PyUnicode_4BYTE_KIND: return "UCS4"; default: return "<invalid compact kind>"; } } #ifdef Py_DEBUG /* Functions wrapping macros for use in debugger */ char *_PyUnicode_utf8(void *unicode){ return PyUnicode_UTF8(unicode); } void *_PyUnicode_compact_data(void *unicode) { return _PyUnicode_COMPACT_DATA(unicode); } void *_PyUnicode_data(void *unicode){ printf("obj %p\n", unicode); printf("compact %d\n", PyUnicode_IS_COMPACT(unicode)); printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode)); printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1))); printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1))); printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode)); return PyUnicode_DATA(unicode); } void _PyUnicode_Dump(PyObject *op) { PyASCIIObject *ascii = (PyASCIIObject *)op; PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op; PyUnicodeObject *unicode = (PyUnicodeObject *)op; void *data; if (ascii->state.compact) { if (ascii->state.ascii) data = (ascii + 1); else data = (compact + 1); } else data = unicode->data.any; printf("%s: len=%" PY_FORMAT_SIZE_T "u, ", unicode_kind_name(op), ascii->length); if (ascii->wstr == data) printf("shared "); printf("wstr=%p", ascii->wstr); if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) { printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length); if (!ascii->state.compact && compact->utf8 == unicode->data.any) printf("shared "); printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)", compact->utf8, compact->utf8_length); } printf(", data=%p\n", data); } #endif PyObject * PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar) { PyObject *obj; PyCompactUnicodeObject *unicode; void *data; enum PyUnicode_Kind kind; int is_sharing, is_ascii; Py_ssize_t char_size; Py_ssize_t struct_size; /* Optimization for empty strings */ if (size == 0 && unicode_empty != NULL) { Py_INCREF(unicode_empty); return unicode_empty; } is_ascii = 0; is_sharing = 0; struct_size = sizeof(PyCompactUnicodeObject); if (maxchar < 128) { kind = PyUnicode_1BYTE_KIND; char_size = 1; is_ascii = 1; struct_size = sizeof(PyASCIIObject); } else if (maxchar < 256) { kind = PyUnicode_1BYTE_KIND; char_size = 1; } else if (maxchar < 65536) { kind = PyUnicode_2BYTE_KIND; char_size = 2; if (sizeof(wchar_t) == 2) is_sharing = 1; } else { if (maxchar > MAX_UNICODE) { PyErr_SetString(PyExc_SystemError, "invalid maximum character passed to PyUnicode_New"); return NULL; } kind = PyUnicode_4BYTE_KIND; char_size = 4; if (sizeof(wchar_t) == 4) is_sharing = 1; } /* Ensure we won't overflow the size. */ if (size < 0) { PyErr_SetString(PyExc_SystemError, "Negative size passed to PyUnicode_New"); return NULL; } if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) return PyErr_NoMemory(); /* Duplicated allocation code from _PyObject_New() instead of a call to * PyObject_New() so we are able to allocate space for the object and * it's data buffer. */ obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size); if (obj == NULL) return PyErr_NoMemory(); obj = PyObject_INIT(obj, &PyUnicode_Type); if (obj == NULL) return NULL; unicode = (PyCompactUnicodeObject *)obj; if (is_ascii) data = ((PyASCIIObject*)obj) + 1; else data = unicode + 1; _PyUnicode_LENGTH(unicode) = size; _PyUnicode_HASH(unicode) = -1; _PyUnicode_STATE(unicode).interned = 0; _PyUnicode_STATE(unicode).kind = kind; _PyUnicode_STATE(unicode).compact = 1; _PyUnicode_STATE(unicode).ready = 1; _PyUnicode_STATE(unicode).ascii = is_ascii; if (is_ascii) { ((char*)data)[size] = 0; _PyUnicode_WSTR(unicode) = NULL; } else if (kind == PyUnicode_1BYTE_KIND) { ((char*)data)[size] = 0; _PyUnicode_WSTR(unicode) = NULL; _PyUnicode_WSTR_LENGTH(unicode) = 0; unicode->utf8 = NULL; unicode->utf8_length = 0; } else { unicode->utf8 = NULL; unicode->utf8_length = 0; if (kind == PyUnicode_2BYTE_KIND) ((Py_UCS2*)data)[size] = 0; else /* kind == PyUnicode_4BYTE_KIND */ ((Py_UCS4*)data)[size] = 0; if (is_sharing) { _PyUnicode_WSTR_LENGTH(unicode) = size; _PyUnicode_WSTR(unicode) = (wchar_t *)data; } else { _PyUnicode_WSTR_LENGTH(unicode) = 0; _PyUnicode_WSTR(unicode) = NULL; } } #ifdef Py_DEBUG unicode_fill_invalid((PyObject*)unicode, 0); #endif assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0)); return obj; } #if SIZEOF_WCHAR_T == 2 /* Helper function to convert a 16-bits wchar_t representation to UCS4, this will decode surrogate pairs, the other conversions are implemented as macros for efficiency. This function assumes that unicode can hold one more code point than wstr characters for a terminating null character. */ static void unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end, PyObject *unicode) { const wchar_t *iter; Py_UCS4 *ucs4_out; assert(unicode != NULL); assert(_PyUnicode_CHECK(unicode)); assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND); ucs4_out = PyUnicode_4BYTE_DATA(unicode); for (iter = begin; iter < end; ) { assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) + _PyUnicode_GET_LENGTH(unicode))); if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0]) && (iter+1) < end && Py_UNICODE_IS_LOW_SURROGATE(iter[1])) { *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]); iter += 2; } else { *ucs4_out++ = *iter; iter++; } } assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) + _PyUnicode_GET_LENGTH(unicode))); } #endif int unicode_check_modifiable(PyObject *unicode) { if (!unicode_modifiable(unicode)) { PyErr_SetString(PyExc_SystemError, "Cannot modify a string currently used"); return -1; } return 0; } static int _copy_characters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many, int check_maxchar) { unsigned int from_kind, to_kind; void *from_data, *to_data; assert(0 <= how_many); assert(0 <= from_start); assert(0 <= to_start); assert(PyUnicode_Check(from)); assert(PyUnicode_IS_READY(from)); assert(from_start + how_many <= PyUnicode_GET_LENGTH(from)); assert(PyUnicode_Check(to)); assert(PyUnicode_IS_READY(to)); assert(to_start + how_many <= PyUnicode_GET_LENGTH(to)); if (how_many == 0) return 0; from_kind = PyUnicode_KIND(from); from_data = PyUnicode_DATA(from); to_kind = PyUnicode_KIND(to); to_data = PyUnicode_DATA(to); #ifdef Py_DEBUG if (!check_maxchar && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to)) { const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to); Py_UCS4 ch; Py_ssize_t i; for (i=0; i < how_many; i++) { ch = PyUnicode_READ(from_kind, from_data, from_start + i); assert(ch <= to_maxchar); } } #endif if (from_kind == to_kind) { if (check_maxchar && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)) { /* Writing Latin-1 characters into an ASCII string requires to check that all written characters are pure ASCII */ Py_UCS4 max_char; max_char = ucs1lib_find_max_char(from_data, (Py_UCS1*)from_data + how_many); if (max_char >= 128) return -1; } memcpy((char*)to_data + to_kind * to_start, (char*)from_data + from_kind * from_start, to_kind * how_many); } else if (from_kind == PyUnicode_1BYTE_KIND && to_kind == PyUnicode_2BYTE_KIND) { _PyUnicode_CONVERT_BYTES( Py_UCS1, Py_UCS2, PyUnicode_1BYTE_DATA(from) + from_start, PyUnicode_1BYTE_DATA(from) + from_start + how_many, PyUnicode_2BYTE_DATA(to) + to_start ); } else if (from_kind == PyUnicode_1BYTE_KIND && to_kind == PyUnicode_4BYTE_KIND) { _PyUnicode_CONVERT_BYTES( Py_UCS1, Py_UCS4, PyUnicode_1BYTE_DATA(from) + from_start, PyUnicode_1BYTE_DATA(from) + from_start + how_many, PyUnicode_4BYTE_DATA(to) + to_start ); } else if (from_kind == PyUnicode_2BYTE_KIND && to_kind == PyUnicode_4BYTE_KIND) { _PyUnicode_CONVERT_BYTES( Py_UCS2, Py_UCS4, PyUnicode_2BYTE_DATA(from) + from_start, PyUnicode_2BYTE_DATA(from) + from_start + how_many, PyUnicode_4BYTE_DATA(to) + to_start ); } else { assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to)); if (!check_maxchar) { if (from_kind == PyUnicode_2BYTE_KIND && to_kind == PyUnicode_1BYTE_KIND) { _PyUnicode_CONVERT_BYTES( Py_UCS2, Py_UCS1, PyUnicode_2BYTE_DATA(from) + from_start, PyUnicode_2BYTE_DATA(from) + from_start + how_many, PyUnicode_1BYTE_DATA(to) + to_start ); } else if (from_kind == PyUnicode_4BYTE_KIND && to_kind == PyUnicode_1BYTE_KIND) { _PyUnicode_CONVERT_BYTES( Py_UCS4, Py_UCS1, PyUnicode_4BYTE_DATA(from) + from_start, PyUnicode_4BYTE_DATA(from) + from_start + how_many, PyUnicode_1BYTE_DATA(to) + to_start ); } else if (from_kind == PyUnicode_4BYTE_KIND && to_kind == PyUnicode_2BYTE_KIND) { _PyUnicode_CONVERT_BYTES( Py_UCS4, Py_UCS2, PyUnicode_4BYTE_DATA(from) + from_start, PyUnicode_4BYTE_DATA(from) + from_start + how_many, PyUnicode_2BYTE_DATA(to) + to_start ); } else { assert(0); return -1; } } else { const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to); Py_UCS4 ch; Py_ssize_t i; for (i=0; i < how_many; i++) { ch = PyUnicode_READ(from_kind, from_data, from_start + i); if (ch > to_maxchar) return -1; PyUnicode_WRITE(to_kind, to_data, to_start + i, ch); } } } return 0; } void _PyUnicode_FastCopyCharacters( PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many) { (void)_copy_characters(to, to_start, from, from_start, how_many, 0); } Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many) { int err; if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) { PyErr_BadInternalCall(); return -1; } if (PyUnicode_READY(from) == -1) return -1; if (PyUnicode_READY(to) == -1) return -1; if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return -1; } if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return -1; } if (how_many < 0) { PyErr_SetString(PyExc_SystemError, "how_many cannot be negative"); return -1; } how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many); if (to_start + how_many > PyUnicode_GET_LENGTH(to)) { PyErr_Format(PyExc_SystemError, "Cannot write %zi characters at %zi " "in a string of %zi characters", how_many, to_start, PyUnicode_GET_LENGTH(to)); return -1; } if (how_many == 0) return 0; if (unicode_check_modifiable(to)) return -1; err = _copy_characters(to, to_start, from, from_start, how_many, 1); if (err) { PyErr_Format(PyExc_SystemError, "Cannot copy %s characters " "into a string of %s characters", unicode_kind_name(from), unicode_kind_name(to)); return -1; } return how_many; } /* Find the maximum code point and count the number of surrogate pairs so a correct string length can be computed before converting a string to UCS4. This function counts single surrogates as a character and not as a pair. Return 0 on success, or -1 on error. */ static int find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end, Py_UCS4 *maxchar, Py_ssize_t *num_surrogates) { const wchar_t *iter; Py_UCS4 ch; assert(num_surrogates != NULL && maxchar != NULL); *num_surrogates = 0; *maxchar = 0; for (iter = begin; iter < end; ) { #if SIZEOF_WCHAR_T == 2 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0]) && (iter+1) < end && Py_UNICODE_IS_LOW_SURROGATE(iter[1])) { ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]); ++(*num_surrogates); iter += 2; } else #endif { ch = *iter; iter++; } if (ch > *maxchar) { *maxchar = ch; if (*maxchar > MAX_UNICODE) { PyErr_Format(PyExc_ValueError, "character U+%x is not in range [U+0000; U+10ffff]", ch); return -1; } } } return 0; } int _PyUnicode_Ready(PyObject *unicode) { wchar_t *end; Py_UCS4 maxchar = 0; Py_ssize_t num_surrogates; #if SIZEOF_WCHAR_T == 2 Py_ssize_t length_wo_surrogates; #endif /* _PyUnicode_Ready() is only intended for old-style API usage where strings were created using _PyObject_New() and where no canonical representation (the str field) has been set yet aka strings which are not yet ready. */ assert(_PyUnicode_CHECK(unicode)); assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND); assert(_PyUnicode_WSTR(unicode) != NULL); assert(_PyUnicode_DATA_ANY(unicode) == NULL); assert(_PyUnicode_UTF8(unicode) == NULL); /* Actually, it should neither be interned nor be anything else: */ assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED); end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode); if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end, &maxchar, &num_surrogates) == -1) return -1; if (maxchar < 256) { _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1); if (!_PyUnicode_DATA_ANY(unicode)) { PyErr_NoMemory(); return -1; } _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char, _PyUnicode_WSTR(unicode), end, PyUnicode_1BYTE_DATA(unicode)); PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0'; _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode); _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND; if (maxchar < 128) { _PyUnicode_STATE(unicode).ascii = 1; _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode); _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode); } else { _PyUnicode_STATE(unicode).ascii = 0; _PyUnicode_UTF8(unicode) = NULL; _PyUnicode_UTF8_LENGTH(unicode) = 0; } PyObject_FREE(_PyUnicode_WSTR(unicode)); _PyUnicode_WSTR(unicode) = NULL; _PyUnicode_WSTR_LENGTH(unicode) = 0; } /* In this case we might have to convert down from 4-byte native wchar_t to 2-byte unicode. */ else if (maxchar < 65536) { assert(num_surrogates == 0 && "FindMaxCharAndNumSurrogatePairs() messed up"); #if SIZEOF_WCHAR_T == 2 /* We can share representations and are done. */ _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode); PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0'; _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode); _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND; _PyUnicode_UTF8(unicode) = NULL; _PyUnicode_UTF8_LENGTH(unicode) = 0; #else /* sizeof(wchar_t) == 4 */ _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC( 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1)); if (!_PyUnicode_DATA_ANY(unicode)) { PyErr_NoMemory(); return -1; } _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2, _PyUnicode_WSTR(unicode), end, PyUnicode_2BYTE_DATA(unicode)); PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0'; _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode); _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND; _PyUnicode_UTF8(unicode) = NULL; _PyUnicode_UTF8_LENGTH(unicode) = 0; PyObject_FREE(_PyUnicode_WSTR(unicode)); _PyUnicode_WSTR(unicode) = NULL; _PyUnicode_WSTR_LENGTH(unicode) = 0; #endif } /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */ else { #if SIZEOF_WCHAR_T == 2 /* in case the native representation is 2-bytes, we need to allocate a new normalized 4-byte version. */ length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates; if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) { PyErr_NoMemory(); return -1; } _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1)); if (!_PyUnicode_DATA_ANY(unicode)) { PyErr_NoMemory(); return -1; } _PyUnicode_LENGTH(unicode) = length_wo_surrogates; _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND; _PyUnicode_UTF8(unicode) = NULL; _PyUnicode_UTF8_LENGTH(unicode) = 0; /* unicode_convert_wchar_to_ucs4() requires a ready string */ _PyUnicode_STATE(unicode).ready = 1; unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode); PyObject_FREE(_PyUnicode_WSTR(unicode)); _PyUnicode_WSTR(unicode) = NULL; _PyUnicode_WSTR_LENGTH(unicode) = 0; #else assert(num_surrogates == 0); _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode); _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode); _PyUnicode_UTF8(unicode) = NULL; _PyUnicode_UTF8_LENGTH(unicode) = 0; _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND; #endif PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0'; } _PyUnicode_STATE(unicode).ready = 1; assert(_PyUnicode_CheckConsistency(unicode, 1)); return 0; } static void unicode_dealloc(PyObject *unicode) { switch (PyUnicode_CHECK_INTERNED(unicode)) { case SSTATE_NOT_INTERNED: break; case SSTATE_INTERNED_MORTAL: /* revive dead object temporarily for DelItem */ Py_REFCNT(unicode) = 3; if (PyDict_DelItem(interned, unicode) != 0) Py_FatalError( "deletion of interned string failed"); break; case SSTATE_INTERNED_IMMORTAL: Py_FatalError("Immortal interned string died."); /* fall through */ default: Py_FatalError("Inconsistent interned string state."); } if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) PyObject_DEL(_PyUnicode_WSTR(unicode)); if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) PyObject_DEL(_PyUnicode_UTF8(unicode)); if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) PyObject_DEL(_PyUnicode_DATA_ANY(unicode)); Py_TYPE(unicode)->tp_free(unicode); } #ifdef Py_DEBUG static int unicode_is_singleton(PyObject *unicode) { PyASCIIObject *ascii = (PyASCIIObject *)unicode; if (unicode == unicode_empty) return 1; if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1) { Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0); if (ch < 256 && unicode_latin1[ch] == unicode) return 1; } return 0; } #endif static int unicode_modifiable(PyObject *unicode) { assert(_PyUnicode_CHECK(unicode)); if (Py_REFCNT(unicode) != 1) return 0; if (_PyUnicode_HASH(unicode) != -1) return 0; if (PyUnicode_CHECK_INTERNED(unicode)) return 0; if (!PyUnicode_CheckExact(unicode)) return 0; #ifdef Py_DEBUG /* singleton refcount is greater than 1 */ assert(!unicode_is_singleton(unicode)); #endif return 1; } static int unicode_resize(PyObject **p_unicode, Py_ssize_t length) { PyObject *unicode; Py_ssize_t old_length; assert(p_unicode != NULL); unicode = *p_unicode; assert(unicode != NULL); assert(PyUnicode_Check(unicode)); assert(0 <= length); if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND) old_length = PyUnicode_WSTR_LENGTH(unicode); else old_length = PyUnicode_GET_LENGTH(unicode); if (old_length == length) return 0; if (length == 0) { _Py_INCREF_UNICODE_EMPTY(); if (!unicode_empty) return -1; Py_SETREF(*p_unicode, unicode_empty); return 0; } if (!unicode_modifiable(unicode)) { PyObject *copy = resize_copy(unicode, length); if (copy == NULL) return -1; Py_SETREF(*p_unicode, copy); return 0; } if (PyUnicode_IS_COMPACT(unicode)) { PyObject *new_unicode = resize_compact(unicode, length); if (new_unicode == NULL) return -1; *p_unicode = new_unicode; return 0; } return resize_inplace(unicode, length); } int PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length) { PyObject *unicode; if (p_unicode == NULL) { PyErr_BadInternalCall(); return -1; } unicode = *p_unicode; if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0) { PyErr_BadInternalCall(); return -1; } return unicode_resize(p_unicode, length); } /* Copy an ASCII or latin1 char* string into a Python Unicode string. WARNING: The function doesn't copy the terminating null character and doesn't check the maximum character (may write a latin1 character in an ASCII string). */ static void unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str, Py_ssize_t len) { enum PyUnicode_Kind kind = PyUnicode_KIND(unicode); void *data = PyUnicode_DATA(unicode); const char *end = str + len; switch (kind) { case PyUnicode_1BYTE_KIND: { assert(index + len <= PyUnicode_GET_LENGTH(unicode)); #ifdef Py_DEBUG if (PyUnicode_IS_ASCII(unicode)) { Py_UCS4 maxchar = ucs1lib_find_max_char( (const Py_UCS1*)str, (const Py_UCS1*)str + len); assert(maxchar < 128); } #endif memcpy((char *) data + index, str, len); break; } case PyUnicode_2BYTE_KIND: { Py_UCS2 *start = (Py_UCS2 *)data + index; Py_UCS2 *ucs2 = start; assert(index <= PyUnicode_GET_LENGTH(unicode)); for (; str < end; ++ucs2, ++str) *ucs2 = (Py_UCS2)*str; assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode)); break; } default: { Py_UCS4 *start = (Py_UCS4 *)data + index; Py_UCS4 *ucs4 = start; assert(kind == PyUnicode_4BYTE_KIND); assert(index <= PyUnicode_GET_LENGTH(unicode)); for (; str < end; ++ucs4, ++str) *ucs4 = (Py_UCS4)*str; assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode)); } } } static PyObject* get_latin1_char(unsigned char ch) { PyObject *unicode = unicode_latin1[ch]; if (!unicode) { unicode = PyUnicode_New(1, ch); if (!unicode) return NULL; PyUnicode_1BYTE_DATA(unicode)[0] = ch; assert(_PyUnicode_CheckConsistency(unicode, 1)); unicode_latin1[ch] = unicode; } Py_INCREF(unicode); return unicode; } static PyObject* unicode_char(Py_UCS4 ch) { PyObject *unicode; assert(ch <= MAX_UNICODE); if (ch < 256) return get_latin1_char(ch); unicode = PyUnicode_New(1, ch); if (unicode == NULL) return NULL; switch (PyUnicode_KIND(unicode)) { case PyUnicode_1BYTE_KIND: PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch; break; case PyUnicode_2BYTE_KIND: PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch; break; default: assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND); PyUnicode_4BYTE_DATA(unicode)[0] = ch; } assert(_PyUnicode_CheckConsistency(unicode, 1)); return unicode; } PyObject * PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size) { PyObject *unicode; Py_UCS4 maxchar = 0; Py_ssize_t num_surrogates; if (u == NULL) return (PyObject*)_PyUnicode_New(size); /* If the Unicode data is known at construction time, we can apply some optimizations which share commonly used objects. */ /* Optimization for empty strings */ if (size == 0) _Py_RETURN_UNICODE_EMPTY(); /* Single character Unicode objects in the Latin-1 range are shared when using this constructor */ if (size == 1 && (Py_UCS4)*u < 256) return get_latin1_char((unsigned char)*u); /* If not empty and not single character, copy the Unicode data into the new object */ if (find_maxchar_surrogates(u, u + size, &maxchar, &num_surrogates) == -1) return NULL; unicode = PyUnicode_New(size - num_surrogates, maxchar); if (!unicode) return NULL; switch (PyUnicode_KIND(unicode)) { case PyUnicode_1BYTE_KIND: _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char, u, u + size, PyUnicode_1BYTE_DATA(unicode)); break; case PyUnicode_2BYTE_KIND: #if Py_UNICODE_SIZE == 2 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2); #else _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2, u, u + size, PyUnicode_2BYTE_DATA(unicode)); #endif break; case PyUnicode_4BYTE_KIND: #if SIZEOF_WCHAR_T == 2 /* This is the only case which has to process surrogates, thus a simple copy loop is not enough and we need a function. */ unicode_convert_wchar_to_ucs4(u, u + size, unicode); #else assert(num_surrogates == 0); memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4); #endif break; default: assert(0 && "Impossible state"); } return unicode_result(unicode); } PyObject * PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) { if (size < 0) { PyErr_SetString(PyExc_SystemError, "Negative size passed to PyUnicode_FromStringAndSize"); return NULL; } if (u != NULL) return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL); else return (PyObject *)_PyUnicode_New(size); } PyObject * PyUnicode_FromString(const char *u) { size_t size = strlen(u); if (size > PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "input too long"); return NULL; } return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL); } PyObject * _PyUnicode_FromId(_Py_Identifier *id) { if (!id->object) { id->object = PyUnicode_DecodeUTF8Stateful(id->string, strlen(id->string), NULL, NULL); if (!id->object) return NULL; PyUnicode_InternInPlace(&id->object); assert(!id->next); id->next = static_strings; static_strings = id; } return id->object; } void _PyUnicode_ClearStaticStrings() { _Py_Identifier *tmp, *s = static_strings; while (s) { Py_CLEAR(s->object); tmp = s->next; s->next = NULL; s = tmp; } static_strings = NULL; } /* Internal function, doesn't check maximum character */ PyObject* _PyUnicode_FromASCII(const char *buffer, Py_ssize_t size) { const unsigned char *s = (const unsigned char *)buffer; PyObject *unicode; if (size == 1) { #ifdef Py_DEBUG assert((unsigned char)s[0] < 128); #endif return get_latin1_char(s[0]); } unicode = PyUnicode_New(size, 127); if (!unicode) return NULL; memcpy(PyUnicode_1BYTE_DATA(unicode), s, size); assert(_PyUnicode_CheckConsistency(unicode, 1)); return unicode; } static Py_UCS4 kind_maxchar_limit(unsigned int kind) { switch (kind) { case PyUnicode_1BYTE_KIND: return 0x80; case PyUnicode_2BYTE_KIND: return 0x100; case PyUnicode_4BYTE_KIND: return 0x10000; default: assert(0 && "invalid kind"); return MAX_UNICODE; } } static inline Py_UCS4 align_maxchar(Py_UCS4 maxchar) { if (maxchar <= 127) return 127; else if (maxchar <= 255) return 255; else if (maxchar <= 65535) return 65535; else return MAX_UNICODE; } static PyObject* _PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size) { PyObject *res; unsigned char max_char; if (size == 0) _Py_RETURN_UNICODE_EMPTY(); assert(size > 0); if (size == 1) return get_latin1_char(u[0]); max_char = ucs1lib_find_max_char(u, u + size); res = PyUnicode_New(size, max_char); if (!res) return NULL; memcpy(PyUnicode_1BYTE_DATA(res), u, size); assert(_PyUnicode_CheckConsistency(res, 1)); return res; } static PyObject* _PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size) { PyObject *res; Py_UCS2 max_char; if (size == 0) _Py_RETURN_UNICODE_EMPTY(); assert(size > 0); if (size == 1) return unicode_char(u[0]); max_char = ucs2lib_find_max_char(u, u + size); res = PyUnicode_New(size, max_char); if (!res) return NULL; if (max_char >= 256) memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size); else { _PyUnicode_CONVERT_BYTES( Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res)); } assert(_PyUnicode_CheckConsistency(res, 1)); return res; } static PyObject* _PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size) { PyObject *res; Py_UCS4 max_char; if (size == 0) _Py_RETURN_UNICODE_EMPTY(); assert(size > 0); if (size == 1) return unicode_char(u[0]); max_char = ucs4lib_find_max_char(u, u + size); res = PyUnicode_New(size, max_char); if (!res) return NULL; if (max_char < 256) _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res)); else if (max_char < 0x10000) _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size, PyUnicode_2BYTE_DATA(res)); else memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size); assert(_PyUnicode_CheckConsistency(res, 1)); return res; } PyObject* PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size) { if (size < 0) { PyErr_SetString(PyExc_ValueError, "size must be positive"); return NULL; } switch (kind) { case PyUnicode_1BYTE_KIND: return _PyUnicode_FromUCS1(buffer, size); case PyUnicode_2BYTE_KIND: return _PyUnicode_FromUCS2(buffer, size); case PyUnicode_4BYTE_KIND: return _PyUnicode_FromUCS4(buffer, size); default: PyErr_SetString(PyExc_SystemError, "invalid kind"); return NULL; } } Py_UCS4 _PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end) { enum PyUnicode_Kind kind; void *startptr, *endptr; assert(PyUnicode_IS_READY(unicode)); assert(0 <= start); assert(end <= PyUnicode_GET_LENGTH(unicode)); assert(start <= end); if (start == 0 && end == PyUnicode_GET_LENGTH(unicode)) return PyUnicode_MAX_CHAR_VALUE(unicode); if (start == end) return 127; if (PyUnicode_IS_ASCII(unicode)) return 127; kind = PyUnicode_KIND(unicode); startptr = PyUnicode_DATA(unicode); endptr = (char *)startptr + end * kind; startptr = (char *)startptr + start * kind; switch(kind) { case PyUnicode_1BYTE_KIND: return ucs1lib_find_max_char(startptr, endptr); case PyUnicode_2BYTE_KIND: return ucs2lib_find_max_char(startptr, endptr); case PyUnicode_4BYTE_KIND: return ucs4lib_find_max_char(startptr, endptr); default: assert(0); return 0; } } /* Ensure that a string uses the most efficient storage, if it is not the case: create a new string with of the right kind. Write NULL into *p_unicode on error. */ static void unicode_adjust_maxchar(PyObject **p_unicode) { PyObject *unicode, *copy; Py_UCS4 max_char; Py_ssize_t len; unsigned int kind; assert(p_unicode != NULL); unicode = *p_unicode; assert(PyUnicode_IS_READY(unicode)); if (PyUnicode_IS_ASCII(unicode)) return; len = PyUnicode_GET_LENGTH(unicode); kind = PyUnicode_KIND(unicode); if (kind == PyUnicode_1BYTE_KIND) { const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode); max_char = ucs1lib_find_max_char(u, u + len); if (max_char >= 128) return; } else if (kind == PyUnicode_2BYTE_KIND) { const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode); max_char = ucs2lib_find_max_char(u, u + len); if (max_char >= 256) return; } else { const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode); assert(kind == PyUnicode_4BYTE_KIND); max_char = ucs4lib_find_max_char(u, u + len); if (max_char >= 0x10000) return; } copy = PyUnicode_New(len, max_char); if (copy != NULL) _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len); Py_DECREF(unicode); *p_unicode = copy; } PyObject* _PyUnicode_Copy(PyObject *unicode) { Py_ssize_t length; PyObject *copy; if (!PyUnicode_Check(unicode)) { PyErr_BadInternalCall(); return NULL; } if (PyUnicode_READY(unicode) == -1) return NULL; length = PyUnicode_GET_LENGTH(unicode); copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode)); if (!copy) return NULL; assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode)); memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode), length * PyUnicode_KIND(unicode)); assert(_PyUnicode_CheckConsistency(copy, 1)); return copy; } /* Widen Unicode objects to larger buffers. Don't write terminating null character. Return NULL on error. */ void* _PyUnicode_AsKind(PyObject *s, unsigned int kind) { Py_ssize_t len; void *result; unsigned int skind; if (PyUnicode_READY(s) == -1) return NULL; len = PyUnicode_GET_LENGTH(s); skind = PyUnicode_KIND(s); if (skind >= kind) { PyErr_SetString(PyExc_SystemError, "invalid widening attempt"); return NULL; } switch (kind) { case PyUnicode_2BYTE_KIND: result = PyMem_New(Py_UCS2, len); if (!result) return PyErr_NoMemory(); assert(skind == PyUnicode_1BYTE_KIND); _PyUnicode_CONVERT_BYTES( Py_UCS1, Py_UCS2, PyUnicode_1BYTE_DATA(s), PyUnicode_1BYTE_DATA(s) + len, result); return result; case PyUnicode_4BYTE_KIND: result = PyMem_New(Py_UCS4, len); if (!result) return PyErr_NoMemory(); if (skind == PyUnicode_2BYTE_KIND) { _PyUnicode_CONVERT_BYTES( Py_UCS2, Py_UCS4, PyUnicode_2BYTE_DATA(s), PyUnicode_2BYTE_DATA(s) + len, result); } else { assert(skind == PyUnicode_1BYTE_KIND); _PyUnicode_CONVERT_BYTES( Py_UCS1, Py_UCS4, PyUnicode_1BYTE_DATA(s), PyUnicode_1BYTE_DATA(s) + len, result); } return result; default: break; } PyErr_SetString(PyExc_SystemError, "invalid kind"); return NULL; } static Py_UCS4* as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize, int copy_null) { int kind; void *data; Py_ssize_t len, targetlen; if (PyUnicode_READY(string) == -1) return NULL; kind = PyUnicode_KIND(string); data = PyUnicode_DATA(string); len = PyUnicode_GET_LENGTH(string); targetlen = len; if (copy_null) targetlen++; if (!target) { target = PyMem_New(Py_UCS4, targetlen); if (!target) { PyErr_NoMemory(); return NULL; } } else { if (targetsize < targetlen) { PyErr_Format(PyExc_SystemError, "string is longer than the buffer"); if (copy_null && 0 < targetsize) target[0] = 0; return NULL; } } if (kind == PyUnicode_1BYTE_KIND) { Py_UCS1 *start = (Py_UCS1 *) data; _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target); } else if (kind == PyUnicode_2BYTE_KIND) { Py_UCS2 *start = (Py_UCS2 *) data; _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target); } else { assert(kind == PyUnicode_4BYTE_KIND); memcpy(target, data, len * sizeof(Py_UCS4)); } if (copy_null) target[len] = 0; return target; } Py_UCS4* PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize, int copy_null) { if (target == NULL || targetsize < 0) { PyErr_BadInternalCall(); return NULL; } return as_ucs4(string, target, targetsize, copy_null); } Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *string) { return as_ucs4(string, NULL, 0, 1); } PyObject * PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size) { if (w == NULL) { if (size == 0) _Py_RETURN_UNICODE_EMPTY(); PyErr_BadInternalCall(); return NULL; } if (size == -1) { size = wcslen(w); } return PyUnicode_FromUnicode(w, size); } /* maximum number of characters required for output of %lld or %p. We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits, plus 1 for the sign. 53/22 is an upper bound for log10(256). */ #define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22) static int unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str, Py_ssize_t width, Py_ssize_t precision) { Py_ssize_t length, fill, arglen; Py_UCS4 maxchar; if (PyUnicode_READY(str) == -1) return -1; length = PyUnicode_GET_LENGTH(str); if ((precision == -1 || precision >= length) && width <= length) return _PyUnicodeWriter_WriteStr(writer, str); if (precision != -1) length = Py_MIN(precision, length); arglen = Py_MAX(length, width); if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar) maxchar = _PyUnicode_FindMaxChar(str, 0, length); else maxchar = writer->maxchar; if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1) return -1; if (width > length) { fill = width - length; if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1) return -1; writer->pos += fill; } _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos, str, 0, length); writer->pos += length; return 0; } static int unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str, Py_ssize_t width, Py_ssize_t precision) { /* UTF-8 */ Py_ssize_t length; PyObject *unicode; int res; length = strlen(str); if (precision != -1) length = Py_MIN(length, precision); unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL); if (unicode == NULL) return -1; res = unicode_fromformat_write_str(writer, unicode, width, -1); Py_DECREF(unicode); return res; } static const char* unicode_fromformat_arg(_PyUnicodeWriter *writer, const char *f, va_list *vargs) { const char *p; Py_ssize_t len; int zeropad; Py_ssize_t width; Py_ssize_t precision; int longflag; int longlongflag; int size_tflag; Py_ssize_t fill; p = f; f++; zeropad = 0; if (*f == '0') { zeropad = 1; f++; } /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */ width = -1; if (Py_ISDIGIT(*f)) { width = *f - '0'; f++; while (Py_ISDIGIT(*f)) { if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) { PyErr_SetString(PyExc_ValueError, "width too big"); return NULL; } width = (width * 10) + (*f - '0'); f++; } } precision = -1; if (*f == '.') { f++; if (Py_ISDIGIT(*f)) { precision = (*f - '0'); f++; while (Py_ISDIGIT(*f)) { if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) { PyErr_SetString(PyExc_ValueError, "precision too big"); return NULL; } precision = (precision * 10) + (*f - '0'); f++; } } if (*f == '%') { /* "%.3%s" => f points to "3" */ f--; } } if (*f == '\0') { /* bogus format "%.123" => go backward, f points to "3" */ f--; } /* Handle %ld, %lu, %lld and %llu. */ longflag = 0; longlongflag = 0; size_tflag = 0; if (*f == 'l') { if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') { longflag = 1; ++f; } else if (f[1] == 'l' && (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) { longlongflag = 1; f += 2; } } /* handle the size_t flag. */ else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) { size_tflag = 1; ++f; } if (f[1] == '\0') writer->overallocate = 0; switch (*f) { case 'c': { int ordinal = va_arg(*vargs, int); if (ordinal < 0 || ordinal > MAX_UNICODE) { PyErr_SetString(PyExc_OverflowError, "character argument not in range(0x110000)"); return NULL; } if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0) return NULL; break; } case 'i': case 'd': case 'u': case 'x': { /* used by sprintf */ char buffer[MAX_LONG_LONG_CHARS]; Py_ssize_t arglen; if (*f == 'u') { if (longflag) len = sprintf(buffer, "%lu", va_arg(*vargs, unsigned long)); else if (longlongflag) len = sprintf(buffer, "%llu", va_arg(*vargs, unsigned long long)); else if (size_tflag) len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u", va_arg(*vargs, size_t)); else len = sprintf(buffer, "%u", va_arg(*vargs, unsigned int)); } else if (*f == 'x') { len = sprintf(buffer, "%x", va_arg(*vargs, int)); } else { if (longflag) len = sprintf(buffer, "%li", va_arg(*vargs, long)); else if (longlongflag) len = sprintf(buffer, "%lli", va_arg(*vargs, long long)); else if (size_tflag) len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i", va_arg(*vargs, Py_ssize_t)); else len = sprintf(buffer, "%i", va_arg(*vargs, int)); } assert(len >= 0); if (precision < len) precision = len; arglen = Py_MAX(precision, width); if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1) return NULL; if (width > precision) { Py_UCS4 fillchar; fill = width - precision; fillchar = zeropad?'0':' '; if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1) return NULL; writer->pos += fill; } if (precision > len) { fill = precision - len; if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1) return NULL; writer->pos += fill; } if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0) return NULL; break; } case 'p': { char number[MAX_LONG_LONG_CHARS]; len = sprintf(number, "%p", va_arg(*vargs, void*)); assert(len >= 0); /* %p is ill-defined: ensure leading 0x. */ if (number[1] == 'X') number[1] = 'x'; else if (number[1] != 'x') { memmove(number + 2, number, strlen(number) + 1); number[0] = '0'; number[1] = 'x'; len += 2; } if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0) return NULL; break; } case 's': { /* UTF-8 */ const char *s = va_arg(*vargs, const char*); if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0) return NULL; break; } case 'U': { PyObject *obj = va_arg(*vargs, PyObject *); assert(obj && _PyUnicode_CHECK(obj)); if (unicode_fromformat_write_str(writer, obj, width, precision) == -1) return NULL; break; } case 'V': { PyObject *obj = va_arg(*vargs, PyObject *); const char *str = va_arg(*vargs, const char *); if (obj) { assert(_PyUnicode_CHECK(obj)); if (unicode_fromformat_write_str(writer, obj, width, precision) == -1) return NULL; } else { assert(str != NULL); if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0) return NULL; } break; } case 'S': { PyObject *obj = va_arg(*vargs, PyObject *); PyObject *str; assert(obj); str = PyObject_Str(obj); if (!str) return NULL; if (unicode_fromformat_write_str(writer, str, width, precision) == -1) { Py_DECREF(str); return NULL; } Py_DECREF(str); break; } case 'R': { PyObject *obj = va_arg(*vargs, PyObject *); PyObject *repr; assert(obj); repr = PyObject_Repr(obj); if (!repr) return NULL; if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) { Py_DECREF(repr); return NULL; } Py_DECREF(repr); break; } case 'A': { PyObject *obj = va_arg(*vargs, PyObject *); PyObject *ascii; assert(obj); ascii = PyObject_ASCII(obj); if (!ascii) return NULL; if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) { Py_DECREF(ascii); return NULL; } Py_DECREF(ascii); break; } case '%': if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0) return NULL; break; default: /* if we stumble upon an unknown formatting code, copy the rest of the format string to the output string. (we cannot just skip the code, since there's no way to know what's in the argument list) */ len = strlen(p); if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1) return NULL; f = p+len; return f; } f++; return f; } PyObject * PyUnicode_FromFormatV(const char *format, va_list vargs) { va_list vargs2; const char *f; _PyUnicodeWriter writer; _PyUnicodeWriter_Init(&writer); writer.min_length = strlen(format) + 100; writer.overallocate = 1; // Copy varags to be able to pass a reference to a subfunction. va_copy(vargs2, vargs); for (f = format; *f; ) { if (*f == '%') { f = unicode_fromformat_arg(&writer, f, &vargs2); if (f == NULL) goto fail; } else { const char *p; Py_ssize_t len; p = f; do { if ((unsigned char)*p > 127) { PyErr_Format(PyExc_ValueError, "PyUnicode_FromFormatV() expects an ASCII-encoded format " "string, got a non-ASCII byte: 0x%02x", (unsigned char)*p); goto fail; } p++; } while (*p != '\0' && *p != '%'); len = p - f; if (*p == '\0') writer.overallocate = 0; if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0) goto fail; f = p; } } va_end(vargs2); return _PyUnicodeWriter_Finish(&writer); fail: va_end(vargs2); _PyUnicodeWriter_Dealloc(&writer); return NULL; } /** * Return value: New reference. * * Take a C printf()-style format string and a variable number of * arguments, calculate the size of the resulting Python Unicode string * and return a string with the values formatted into it. The variable * arguments must be C types and must correspond exactly to the format * characters in the format ASCII-encoded string. The following format * characters are allowed: * * Format Type Comment * %% n/a The literal % character. * %c int A single character, represented as a C int. * %d int Equivalent to printf("%d") * %u unsigned int Equivalent to printf("%u") * %ld long Equivalent to printf("%ld") * %li long Equivalent to printf("%li") * %lu unsigned long Equivalent to printf("%lu") * %lld long long Equivalent to printf("%lld") * %lli long long Equivalent to printf("%lli") * %llu unsigned long long Equivalent to printf("%llu") * %zd Py_ssize_t Equivalent to printf("%zd") * %zi Py_ssize_t Equivalent to printf("%zi") * %zu size_t Equivalent to printf("%zu") * %i int Equivalent to printf("%i") * %x int Equivalent to printf("%x") * %s const char* A null-terminated C character array. * The hex representation of a C pointer. * Mostly equivalent to printf("%p") * %p const void* except that it is guaranteed to start * with the literal 0x regardless of what * the platform’s printf yields. * %A PyObject* The result of calling ascii(). * %U PyObject* A Unicode object. * A Unicode object (which may be NULL) * %V PyObject*, const and a null-terminated C character array * char* as a second parameter (which will be * used, if the first parameter is NULL). * %S PyObject* The result of calling PyObject_Str(). * %R PyObject* The result of calling PyObject_Repr(). * * An unrecognized format character causes all the rest of the format * string to be copied as-is to the result string, and any extra * arguments discarded. * * Note * * The width formatter unit is number of characters rather than bytes. * The precision formatter unit is number of bytes for "%s" and "%V" (if * the PyObject* argument is NULL), and a number of characters for "%A", * "%U", "%S", "%R" and "%V" (if the PyObject* argument is not NULL). * * 1(1,2,3,4,5,6,7,8,9,10,11,12,13) * * For integer specifiers (d, u, ld, li, lu, lld, lli, llu, * zd, zi, zu, i, x): the 0-conversion flag has effect even * when a precision is given. * * Changed in version 3.2: Support for "%lld" and "%llu" added. * * Changed in version 3.3: Support for "%li", "%lli" and "%zi" added. * * Changed in version 3.4: Support width and precision formatter for * "%s", "%A", "%U", "%V", "%S", "%R" added. */ PyObject * PyUnicode_FromFormat(const char *format, ...) { PyObject* ret; va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, format); #else va_start(vargs); #endif ret = PyUnicode_FromFormatV(format, vargs); va_end(vargs); return ret; } /* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString(): convert a Unicode object to a wide character string. - If w is NULL: return the number of wide characters (including the null character) required to convert the unicode object. Ignore size argument. - Otherwise: return the number of wide characters (excluding the null character) written into w. Write at most size wide characters (including the null character). */ static Py_ssize_t unicode_aswidechar(PyObject *unicode, wchar_t *w, Py_ssize_t size) { Py_ssize_t res; const wchar_t *wstr; wstr = PyUnicode_AsUnicodeAndSize(unicode, &res); if (wstr == NULL) return -1; if (w != NULL) { if (size > res) size = res + 1; else res = size; memcpy(w, wstr, size * sizeof(wchar_t)); return res; } else return res + 1; } Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *w, Py_ssize_t size) { if (unicode == NULL) { PyErr_BadInternalCall(); return -1; } return unicode_aswidechar(unicode, w, size); } wchar_t* PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size) { wchar_t* buffer; Py_ssize_t buflen; if (unicode == NULL) { PyErr_BadInternalCall(); return NULL; } buflen = unicode_aswidechar(unicode, NULL, 0); if (buflen == -1) return NULL; buffer = PyMem_NEW(wchar_t, buflen); if (buffer == NULL) { PyErr_NoMemory(); return NULL; } buflen = unicode_aswidechar(unicode, buffer, buflen); if (buflen == -1) { PyMem_FREE(buffer); return NULL; } if (size != NULL) *size = buflen; return buffer; } PyObject * PyUnicode_FromOrdinal(int ordinal) { if (ordinal < 0 || ordinal > MAX_UNICODE) { PyErr_SetString(PyExc_ValueError, "chr() arg not in range(0x110000)"); return NULL; } return unicode_char((Py_UCS4)ordinal); } PyObject * PyUnicode_FromObject(PyObject *obj) { /* XXX Perhaps we should make this API an alias of PyObject_Str() instead ?! */ if (PyUnicode_CheckExact(obj)) { if (PyUnicode_READY(obj) == -1) return NULL; Py_INCREF(obj); return obj; } if (PyUnicode_Check(obj)) { /* For a Unicode subtype that's not a Unicode object, return a true Unicode object with the same data. */ return _PyUnicode_Copy(obj); } PyErr_Format(PyExc_TypeError, "Can't convert '%.100s' object to str implicitly", Py_TYPE(obj)->tp_name); return NULL; } PyObject * PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors) { Py_buffer buffer; PyObject *v; if (obj == NULL) { PyErr_BadInternalCall(); return NULL; } /* Decoding bytes objects is the most common case and should be fast */ if (PyBytes_Check(obj)) { if (PyBytes_GET_SIZE(obj) == 0) _Py_RETURN_UNICODE_EMPTY(); v = PyUnicode_Decode( PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj), encoding, errors); return v; } if (PyUnicode_Check(obj)) { PyErr_SetString(PyExc_TypeError, "decoding str is not supported"); return NULL; } /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */ if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) { PyErr_Format(PyExc_TypeError, "decoding to str: need a bytes-like object, %.80s found", Py_TYPE(obj)->tp_name); return NULL; } if (buffer.len == 0) { PyBuffer_Release(&buffer); _Py_RETURN_UNICODE_EMPTY(); } v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors); PyBuffer_Release(&buffer); return v; } /* Normalize an encoding name: similar to encodings.normalize_encoding(), but also convert to lowercase. Return 1 on success, or 0 on error (encoding is longer than lower_len-1). */ int _Py_normalize_encoding(const char *encoding, char *lower, size_t lower_len) { const char *e; char *l; char *l_end; int punct; assert(encoding != NULL); e = encoding; l = lower; l_end = &lower[lower_len - 1]; punct = 0; while (1) { char c = *e; if (c == 0) { break; } if (Py_ISALNUM(c) || c == '.') { if (punct && l != lower) { if (l == l_end) { return 0; } *l++ = '_'; } punct = 0; if (l == l_end) { return 0; } *l++ = Py_TOLOWER(c); } else { punct = 1; } e++; } *l = '\0'; return 1; } PyObject * PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) { PyObject *buffer = NULL, *unicode; Py_buffer info; char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */ if (UNLIKELY(encoding == NULL)) { return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL); } /* [jart] faster path based on profiling */ if (encoding[0] == 'l' && encoding[1] == 'a' && encoding[2] == 't' && encoding[3] == 'i' && encoding[4] == 'n' && (encoding[5] == '1' || ((encoding[5] == '-' || encoding[5] == '_') && encoding[6] == '1'))) { return PyUnicode_DecodeLatin1(s, size, errors); } /* Shortcuts for common default encodings */ if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) { char *lower = buflower; /* Fast paths */ if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') { lower += 3; if (*lower == '_') { /* Match "utf8" and "utf_8" */ lower++; } if (lower[0] == '8' && lower[1] == 0) { return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL); } else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) { return PyUnicode_DecodeUTF16(s, size, errors, 0); } else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) { return PyUnicode_DecodeUTF32(s, size, errors, 0); } } else { if (strcmp(lower, "ascii") == 0 || strcmp(lower, "us_ascii") == 0) { return PyUnicode_DecodeASCII(s, size, errors); } else if (strcmp(lower, "latin1") == 0 || strcmp(lower, "latin_1") == 0 || strcmp(lower, "iso_8859_1") == 0 || strcmp(lower, "iso8859_1") == 0) { return PyUnicode_DecodeLatin1(s, size, errors); } } } /* Decode via the codec registry */ buffer = NULL; if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0) goto onError; buffer = PyMemoryView_FromBuffer(&info); if (buffer == NULL) goto onError; unicode = _PyCodec_DecodeText(buffer, encoding, errors); if (unicode == NULL) goto onError; if (!PyUnicode_Check(unicode)) { PyErr_Format(PyExc_TypeError, "'%.400s' decoder returned '%.400s' instead of 'str'; " "use codecs.decode() to decode to arbitrary types", encoding, Py_TYPE(unicode)->tp_name); Py_DECREF(unicode); goto onError; } Py_DECREF(buffer); return unicode_result(unicode); onError: Py_XDECREF(buffer); return NULL; } static size_t wcstombs_errorpos(const wchar_t *wstr) { size_t len; #if SIZEOF_WCHAR_T == 2 wchar_t buf[3]; #else wchar_t buf[2]; #endif char outbuf[MB_LEN_MAX]; const wchar_t *start, *previous; #if SIZEOF_WCHAR_T == 2 buf[2] = 0; #else buf[1] = 0; #endif start = wstr; while (*wstr != L'\0') { previous = wstr; #if SIZEOF_WCHAR_T == 2 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0]) && Py_UNICODE_IS_LOW_SURROGATE(wstr[1])) { buf[0] = wstr[0]; buf[1] = wstr[1]; wstr += 2; } else { buf[0] = *wstr; buf[1] = 0; wstr++; } #else buf[0] = *wstr; wstr++; #endif len = wcstombs(outbuf, buf, sizeof(outbuf)); if (len == (size_t)-1) return previous - start; } /* failed to find the unencodable character */ return 0; } static int locale_error_handler(const char *errors, int *surrogateescape) { _Py_error_handler error_handler = get_error_handler(errors); switch (error_handler) { case _Py_ERROR_STRICT: *surrogateescape = 0; return 0; case _Py_ERROR_SURROGATEESCAPE: *surrogateescape = 1; return 0; default: PyErr_Format(PyExc_ValueError, "only 'strict' and 'surrogateescape' error handlers " "are supported, not '%s'", errors); return -1; } } static PyObject * unicode_encode_locale(PyObject *unicode, const char *errors, int current_locale) { Py_ssize_t wlen, wlen2; wchar_t *wstr; PyObject *bytes = NULL; char *errmsg; PyObject *reason = NULL; PyObject *exc; size_t error_pos; int surrogateescape; if (locale_error_handler(errors, &surrogateescape) < 0) return NULL; wstr = PyUnicode_AsWideCharString(unicode, &wlen); if (wstr == NULL) return NULL; wlen2 = wcslen(wstr); if (wlen2 != wlen) { PyMem_Free(wstr); PyErr_SetString(PyExc_ValueError, "embedded null character"); return NULL; } if (surrogateescape) { /* "surrogateescape" error handler */ char *str; str = _Py_EncodeLocaleEx(wstr, &error_pos, current_locale); if (str == NULL) { if (error_pos == (size_t)-1) { PyErr_NoMemory(); PyMem_Free(wstr); return NULL; } else { goto encode_error; } } PyMem_Free(wstr); bytes = PyBytes_FromString(str); PyMem_Free(str); } else { /* strict mode */ size_t len, len2; len = wcstombs(NULL, wstr, 0); if (len == (size_t)-1) { error_pos = (size_t)-1; goto encode_error; } bytes = PyBytes_FromStringAndSize(NULL, len); if (bytes == NULL) { PyMem_Free(wstr); return NULL; } len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1); if (len2 == (size_t)-1 || len2 > len) { error_pos = (size_t)-1; goto encode_error; } PyMem_Free(wstr); } return bytes; encode_error: errmsg = strerror(errno); assert(errmsg != NULL); if (error_pos == (size_t)-1) error_pos = wcstombs_errorpos(wstr); PyMem_Free(wstr); Py_XDECREF(bytes); if (errmsg != NULL) { size_t errlen; wstr = Py_DecodeLocale(errmsg, &errlen); if (wstr != NULL) { reason = PyUnicode_FromWideChar(wstr, errlen); PyMem_RawFree(wstr); } else errmsg = NULL; } if (errmsg == NULL) reason = PyUnicode_FromString( "wcstombs() encountered an unencodable " "wide character"); if (reason == NULL) return NULL; exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO", "locale", unicode, (Py_ssize_t)error_pos, (Py_ssize_t)(error_pos+1), reason); Py_DECREF(reason); if (exc != NULL) { PyCodec_StrictErrors(exc); Py_XDECREF(exc); } return NULL; } PyObject * PyUnicode_EncodeLocale(PyObject *unicode, const char *errors) { return unicode_encode_locale(unicode, errors, 1); } PyObject * PyUnicode_EncodeFSDefault(PyObject *unicode) { #if defined(__APPLE__) || defined(__COSMOPOLITAN__) return _PyUnicode_AsUTF8String(unicode, Py_FileSystemDefaultEncodeErrors); #else PyInterpreterState *interp = PyThreadState_GET()->interp; /* Bootstrap check: if the filesystem codec is implemented in Python, we cannot use it to encode and decode filenames before it is loaded. Load the Python codec requires to encode at least its own filename. Use the C version of the locale codec until the codec registry is initialized and the Python codec is loaded. Py_FileSystemDefaultEncoding is shared between all interpreters, we cannot only rely on it: check also interp->fscodec_initialized for subinterpreters. */ if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) { return PyUnicode_AsEncodedString(unicode, Py_FileSystemDefaultEncoding, Py_FileSystemDefaultEncodeErrors); } else { return unicode_encode_locale(unicode, Py_FileSystemDefaultEncodeErrors, 0); } #endif } PyObject * PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors) { PyObject *v; char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */ if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (encoding == NULL) { return _PyUnicode_AsUTF8String(unicode, errors); } /* Shortcuts for common default encodings */ if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) { char *lower = buflower; /* Fast paths */ if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') { lower += 3; if (*lower == '_') { /* Match "utf8" and "utf_8" */ lower++; } if (lower[0] == '8' && lower[1] == 0) { return _PyUnicode_AsUTF8String(unicode, errors); } else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) { return _PyUnicode_EncodeUTF16(unicode, errors, 0); } else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) { return _PyUnicode_EncodeUTF32(unicode, errors, 0); } } else { if (strcmp(lower, "ascii") == 0 || strcmp(lower, "us_ascii") == 0) { return _PyUnicode_AsASCIIString(unicode, errors); } #ifdef MS_WINDOWS else if (strcmp(lower, "mbcs") == 0) { return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors); } #endif else if (strcmp(lower, "latin1") == 0 || strcmp(lower, "latin_1") == 0 || strcmp(lower, "iso_8859_1") == 0 || strcmp(lower, "iso8859_1") == 0) { return _PyUnicode_AsLatin1String(unicode, errors); } } } /* Encode via the codec registry */ v = _PyCodec_EncodeText(unicode, encoding, errors); if (v == NULL) return NULL; /* The normal path */ if (PyBytes_Check(v)) return v; /* If the codec returns a buffer, raise a warning and convert to bytes */ if (PyByteArray_Check(v)) { int error; PyObject *b; error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "encoder %s returned bytearray instead of bytes; " "use codecs.encode() to encode to arbitrary types", encoding); if (error) { Py_DECREF(v); return NULL; } b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v)); Py_DECREF(v); return b; } PyErr_Format(PyExc_TypeError, "'%.400s' encoder returned '%.400s' instead of 'bytes'; " "use codecs.encode() to encode to arbitrary types", encoding, Py_TYPE(v)->tp_name); Py_DECREF(v); return NULL; } static size_t mbstowcs_errorpos(const char *str, size_t len) { #ifdef HAVE_MBRTOWC const char *start = str; mbstate_t mbs; size_t converted; wchar_t ch; bzero(&mbs, sizeof mbs); while (len) { converted = mbrtowc(&ch, str, len, &mbs); if (converted == 0) /* Reached end of string */ break; if (converted == (size_t)-1 || converted == (size_t)-2) { /* Conversion error or incomplete character */ return str - start; } else { str += converted; len -= converted; } } /* failed to find the undecodable byte sequence */ return 0; #endif return 0; } static PyObject* unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors, int current_locale) { wchar_t smallbuf[256]; size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf); wchar_t *wstr; size_t wlen, wlen2; PyObject *unicode; int surrogateescape; size_t error_pos; char *errmsg; PyObject *reason = NULL; /* initialize to prevent gcc warning */ PyObject *exc; if (locale_error_handler(errors, &surrogateescape) < 0) return NULL; if (str[len] != '\0' || (size_t)len != strlen(str)) { PyErr_SetString(PyExc_ValueError, "embedded null byte"); return NULL; } if (surrogateescape) { /* "surrogateescape" error handler */ wstr = _Py_DecodeLocaleEx(str, &wlen, current_locale); if (wstr == NULL) { if (wlen == (size_t)-1) PyErr_NoMemory(); else PyErr_SetFromErrno(PyExc_OSError); return NULL; } unicode = PyUnicode_FromWideChar(wstr, wlen); PyMem_RawFree(wstr); } else { /* strict mode */ #ifndef HAVE_BROKEN_MBSTOWCS wlen = mbstowcs(NULL, str, 0); #else wlen = len; #endif if (wlen == (size_t)-1) goto decode_error; if (wlen+1 <= smallbuf_len) { wstr = smallbuf; } else { wstr = PyMem_New(wchar_t, wlen+1); if (!wstr) return PyErr_NoMemory(); } wlen2 = mbstowcs(wstr, str, wlen+1); if (wlen2 == (size_t)-1) { if (wstr != smallbuf) PyMem_Free(wstr); goto decode_error; } #ifdef HAVE_BROKEN_MBSTOWCS assert(wlen2 == wlen); #endif unicode = PyUnicode_FromWideChar(wstr, wlen2); if (wstr != smallbuf) PyMem_Free(wstr); } return unicode; decode_error: reason = NULL; errmsg = strerror(errno); assert(errmsg != NULL); error_pos = mbstowcs_errorpos(str, len); if (errmsg != NULL) { size_t errlen; wstr = Py_DecodeLocale(errmsg, &errlen); if (wstr != NULL) { reason = PyUnicode_FromWideChar(wstr, errlen); PyMem_RawFree(wstr); } } if (reason == NULL) reason = PyUnicode_FromString( "mbstowcs() encountered an invalid multibyte sequence"); if (reason == NULL) return NULL; exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO", "locale", str, len, (Py_ssize_t)error_pos, (Py_ssize_t)(error_pos+1), reason); Py_DECREF(reason); if (exc != NULL) { PyCodec_StrictErrors(exc); Py_XDECREF(exc); } return NULL; } PyObject* PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t size, const char *errors) { return unicode_decode_locale(str, size, errors, 1); } PyObject* PyUnicode_DecodeLocale(const char *str, const char *errors) { Py_ssize_t size = (Py_ssize_t)strlen(str); return unicode_decode_locale(str, size, errors, 1); } PyObject* PyUnicode_DecodeFSDefault(const char *s) { Py_ssize_t size = (Py_ssize_t)strlen(s); return PyUnicode_DecodeFSDefaultAndSize(s, size); } PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size) { #if defined(__APPLE__) || defined(__COSMOPOLITAN__) return PyUnicode_DecodeUTF8Stateful(s, size, Py_FileSystemDefaultEncodeErrors, NULL); #else PyInterpreterState *interp = PyThreadState_GET()->interp; /* Bootstrap check: if the filesystem codec is implemented in Python, we cannot use it to encode and decode filenames before it is loaded. Load the Python codec requires to encode at least its own filename. Use the C version of the locale codec until the codec registry is initialized and the Python codec is loaded. Py_FileSystemDefaultEncoding is shared between all interpreters, we cannot only rely on it: check also interp->fscodec_initialized for subinterpreters. */ if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) { return PyUnicode_Decode(s, size, Py_FileSystemDefaultEncoding, Py_FileSystemDefaultEncodeErrors); } else { return unicode_decode_locale(s, size, Py_FileSystemDefaultEncodeErrors, 0); } #endif } int PyUnicode_FSConverter(PyObject* arg, void* addr) { PyObject *path = NULL; PyObject *output = NULL; Py_ssize_t size; void *data; if (arg == NULL) { Py_DECREF(*(PyObject**)addr); *(PyObject**)addr = NULL; return 1; } path = PyOS_FSPath(arg); if (path == NULL) { return 0; } if (PyBytes_Check(path)) { output = path; } else { // PyOS_FSPath() guarantees its returned value is bytes or str. output = PyUnicode_EncodeFSDefault(path); Py_DECREF(path); if (!output) { return 0; } assert(PyBytes_Check(output)); } size = PyBytes_GET_SIZE(output); data = PyBytes_AS_STRING(output); if ((size_t)size != strlen(data)) { PyErr_SetString(PyExc_ValueError, "embedded null byte"); Py_DECREF(output); return 0; } *(PyObject**)addr = output; return Py_CLEANUP_SUPPORTED; } int PyUnicode_FSDecoder(PyObject* arg, void* addr) { int is_buffer = 0; PyObject *path = NULL; PyObject *output = NULL; if (arg == NULL) { Py_DECREF(*(PyObject**)addr); *(PyObject**)addr = NULL; return 1; } is_buffer = PyObject_CheckBuffer(arg); if (!is_buffer) { path = PyOS_FSPath(arg); if (path == NULL) { return 0; } } else { path = arg; Py_INCREF(arg); } if (PyUnicode_Check(path)) { if (PyUnicode_READY(path) == -1) { Py_DECREF(path); return 0; } output = path; } else if (PyBytes_Check(path) || is_buffer) { PyObject *path_bytes = NULL; if (!PyBytes_Check(path) && PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "path should be string, bytes, or os.PathLike, not %.200s", Py_TYPE(arg)->tp_name)) { Py_DECREF(path); return 0; } path_bytes = PyBytes_FromObject(path); Py_DECREF(path); if (!path_bytes) { return 0; } output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes), PyBytes_GET_SIZE(path_bytes)); Py_DECREF(path_bytes); if (!output) { return 0; } } else { PyErr_Format(PyExc_TypeError, "path should be string, bytes, or os.PathLike, not %.200s", Py_TYPE(arg)->tp_name); Py_DECREF(path); return 0; } if (PyUnicode_READY(output) == -1) { Py_DECREF(output); return 0; } if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output), PyUnicode_GET_LENGTH(output), 0, 1) >= 0) { PyErr_SetString(PyExc_ValueError, "embedded null character"); Py_DECREF(output); return 0; } *(PyObject**)addr = output; return Py_CLEANUP_SUPPORTED; } /** * Returns pointer to the UTF-8 encoding of the Unicode object, and * store the size of the encoded representation (in bytes) in size. The * size argument can be NULL; in this case no size will be stored. The * returned buffer always has an extra null byte appended (not included * in size), regardless of whether there are any other null code points. * * In the case of an error, NULL is returned with an exception set and * no size is stored. * * This caches the UTF-8 representation of the string in the Unicode * object, and subsequent calls will return a pointer to the same * buffer. The caller is not responsible for deallocating the buffer. */ char * PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize) { PyObject *bytes; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(unicode) == -1) return NULL; if (PyUnicode_UTF8(unicode) == NULL) { assert(!PyUnicode_IS_COMPACT_ASCII(unicode)); bytes = _PyUnicode_AsUTF8String(unicode, NULL); if (bytes == NULL) return NULL; _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1); if (_PyUnicode_UTF8(unicode) == NULL) { PyErr_NoMemory(); Py_DECREF(bytes); return NULL; } _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes); memcpy(_PyUnicode_UTF8(unicode), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(unicode) + 1); Py_DECREF(bytes); } if (psize) *psize = PyUnicode_UTF8_LENGTH(unicode); return PyUnicode_UTF8(unicode); } char * PyUnicode_AsUTF8(PyObject *unicode) { return PyUnicode_AsUTF8AndSize(unicode, NULL); } Py_UNICODE * PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size) { const unsigned char *one_byte; #if SIZEOF_WCHAR_T == 4 const Py_UCS2 *two_bytes; #else const Py_UCS4 *four_bytes; const Py_UCS4 *ucs4_end; Py_ssize_t num_surrogates; #endif wchar_t *w; wchar_t *wchar_end; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (_PyUnicode_WSTR(unicode) == NULL) { /* Non-ASCII compact unicode object */ assert(_PyUnicode_KIND(unicode) != 0); assert(PyUnicode_IS_READY(unicode)); if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) { #if SIZEOF_WCHAR_T == 2 four_bytes = PyUnicode_4BYTE_DATA(unicode); ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode); num_surrogates = 0; for (; four_bytes < ucs4_end; ++four_bytes) { if (*four_bytes > 0xFFFF) ++num_surrogates; } _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC( sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates)); if (!_PyUnicode_WSTR(unicode)) { PyErr_NoMemory(); return NULL; } _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates; w = _PyUnicode_WSTR(unicode); wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode); four_bytes = PyUnicode_4BYTE_DATA(unicode); for (; four_bytes < ucs4_end; ++four_bytes, ++w) { if (*four_bytes > 0xFFFF) { assert(*four_bytes <= MAX_UNICODE); /* encode surrogate pair in this case */ *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes); *w = Py_UNICODE_LOW_SURROGATE(*four_bytes); } else *w = *four_bytes; if (w > wchar_end) { assert(0 && "Miscalculated string end"); } } *w = 0; #else /* sizeof(wchar_t) == 4 */ Py_FatalError("Impossible unicode object state, wstr and str " "should share memory already."); return NULL; #endif } else { if ((size_t)_PyUnicode_LENGTH(unicode) > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) { PyErr_NoMemory(); return NULL; } _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1)); if (!_PyUnicode_WSTR(unicode)) { PyErr_NoMemory(); return NULL; } if (!PyUnicode_IS_COMPACT_ASCII(unicode)) _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode); w = _PyUnicode_WSTR(unicode); wchar_end = w + _PyUnicode_LENGTH(unicode); if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) { one_byte = PyUnicode_1BYTE_DATA(unicode); for (; w < wchar_end; ++one_byte, ++w) *w = *one_byte; /* null-terminate the wstr */ *w = 0; } else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) { #if SIZEOF_WCHAR_T == 4 two_bytes = PyUnicode_2BYTE_DATA(unicode); for (; w < wchar_end; ++two_bytes, ++w) *w = *two_bytes; /* null-terminate the wstr */ *w = 0; #else /* sizeof(wchar_t) == 2 */ PyObject_FREE(_PyUnicode_WSTR(unicode)); _PyUnicode_WSTR(unicode) = NULL; Py_FatalError("Impossible unicode object state, wstr " "and str should share memory already."); return NULL; #endif } else { assert(0 && "This should never happen."); } } } if (size != NULL) *size = PyUnicode_WSTR_LENGTH(unicode); return _PyUnicode_WSTR(unicode); } Py_UNICODE * PyUnicode_AsUnicode(PyObject *unicode) { return PyUnicode_AsUnicodeAndSize(unicode, NULL); } Py_ssize_t PyUnicode_GetSize(PyObject *unicode) { if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); goto onError; } return PyUnicode_GET_SIZE(unicode); onError: return -1; } Py_ssize_t PyUnicode_GetLength(PyObject *unicode) { if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return -1; } if (PyUnicode_READY(unicode) == -1) return -1; return PyUnicode_GET_LENGTH(unicode); } Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index) { void *data; int kind; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return (Py_UCS4)-1; } if (PyUnicode_READY(unicode) == -1) { return (Py_UCS4)-1; } if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return (Py_UCS4)-1; } data = PyUnicode_DATA(unicode); kind = PyUnicode_KIND(unicode); return PyUnicode_READ(kind, data, index); } const char * PyUnicode_GetDefaultEncoding(void) { return "utf-8"; } /* create or adjust a UnicodeDecodeError */ static void make_decode_exception(PyObject **exceptionObject, const char *encoding, const char *input, Py_ssize_t length, Py_ssize_t startpos, Py_ssize_t endpos, const char *reason) { if (*exceptionObject == NULL) { *exceptionObject = PyUnicodeDecodeError_Create( encoding, input, length, startpos, endpos, reason); } else { if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos)) goto onError; if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos)) goto onError; if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason)) goto onError; } return; onError: Py_CLEAR(*exceptionObject); } #ifdef MS_WINDOWS /* error handling callback helper: build arguments, call the callback and check the arguments, if no exception occurred, copy the replacement to the output and adjust various state variables. return 0 on success, -1 on error */ static int unicode_decode_call_errorhandler_wchar( const char *errors, PyObject **errorHandler, const char *encoding, const char *reason, const char **input, const char **inend, Py_ssize_t *startinpos, Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr, PyObject **output, Py_ssize_t *outpos) { static const char *argparse = "O!n;decoding error handler must return (str, int) tuple"; PyObject *restuple = NULL; PyObject *repunicode = NULL; Py_ssize_t outsize; Py_ssize_t insize; Py_ssize_t requiredsize; Py_ssize_t newpos; PyObject *inputobj = NULL; wchar_t *repwstr; Py_ssize_t repwlen; assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND); outsize = _PyUnicode_WSTR_LENGTH(*output); if (*errorHandler == NULL) { *errorHandler = PyCodec_LookupError(errors); if (*errorHandler == NULL) goto onError; } make_decode_exception(exceptionObject, encoding, *input, *inend - *input, *startinpos, *endinpos, reason); if (*exceptionObject == NULL) goto onError; restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL); if (restuple == NULL) goto onError; if (!PyTuple_Check(restuple)) { PyErr_SetString(PyExc_TypeError, &argparse[4]); goto onError; } if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos)) goto onError; /* Copy back the bytes variables, which might have been modified by the callback */ inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject); if (!inputobj) goto onError; if (!PyBytes_Check(inputobj)) { PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes"); } *input = PyBytes_AS_STRING(inputobj); insize = PyBytes_GET_SIZE(inputobj); *inend = *input + insize; /* we can DECREF safely, as the exception has another reference, so the object won't go away. */ Py_DECREF(inputobj); if (newpos<0) newpos = insize+newpos; if (newpos<0 || newpos>insize) { PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos); goto onError; } repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen); if (repwstr == NULL) goto onError; /* need more space? (at least enough for what we have+the replacement+the rest of the string (starting at the new input position), so we won't have to check space when there are no errors in the rest of the string) */ requiredsize = *outpos; if (requiredsize > PY_SSIZE_T_MAX - repwlen) goto overflow; requiredsize += repwlen; if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos)) goto overflow; requiredsize += insize - newpos; if (requiredsize > outsize) { if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize) requiredsize = 2*outsize; if (unicode_resize(output, requiredsize) < 0) goto onError; } wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen); *outpos += repwlen; *endinpos = newpos; *inptr = *input + newpos; /* we made it! */ Py_XDECREF(restuple); return 0; overflow: PyErr_SetString(PyExc_OverflowError, "decoded result is too long for a Python string"); onError: Py_XDECREF(restuple); return -1; } #endif /* MS_WINDOWS */ static int unicode_decode_call_errorhandler_writer( const char *errors, PyObject **errorHandler, const char *encoding, const char *reason, const char **input, const char **inend, Py_ssize_t *startinpos, Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr, _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */) { static const char *argparse = "O!n;decoding error handler must return (str, int) tuple"; PyObject *restuple = NULL; PyObject *repunicode = NULL; Py_ssize_t insize; Py_ssize_t newpos; Py_ssize_t replen; Py_ssize_t remain; PyObject *inputobj = NULL; int need_to_grow = 0; const char *new_inptr; if (*errorHandler == NULL) { *errorHandler = PyCodec_LookupError(errors); if (*errorHandler == NULL) goto onError; } make_decode_exception(exceptionObject, encoding, *input, *inend - *input, *startinpos, *endinpos, reason); if (*exceptionObject == NULL) goto onError; restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL); if (restuple == NULL) goto onError; if (!PyTuple_Check(restuple)) { PyErr_SetString(PyExc_TypeError, &argparse[4]); goto onError; } if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos)) goto onError; /* Copy back the bytes variables, which might have been modified by the callback */ inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject); if (!inputobj) goto onError; if (!PyBytes_Check(inputobj)) { PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes"); } remain = *inend - *input - *endinpos; *input = PyBytes_AS_STRING(inputobj); insize = PyBytes_GET_SIZE(inputobj); *inend = *input + insize; /* we can DECREF safely, as the exception has another reference, so the object won't go away. */ Py_DECREF(inputobj); if (newpos<0) newpos = insize+newpos; if (newpos<0 || newpos>insize) { PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos); goto onError; } if (PyUnicode_READY(repunicode) < 0) goto onError; replen = PyUnicode_GET_LENGTH(repunicode); if (replen > 1) { writer->min_length += replen - 1; need_to_grow = 1; } new_inptr = *input + newpos; if (*inend - new_inptr > remain) { /* We don't know the decoding algorithm here so we make the worst assumption that one byte decodes to one unicode character. If unfortunately one byte could decode to more unicode characters, the decoder may write out-of-bound then. Is it possible for the algorithms using this function? */ writer->min_length += *inend - new_inptr - remain; need_to_grow = 1; } if (need_to_grow) { writer->overallocate = 1; if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos, PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1) goto onError; } if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1) goto onError; *endinpos = newpos; *inptr = new_inptr; /* we made it! */ Py_XDECREF(restuple); return 0; onError: Py_XDECREF(restuple); return -1; } /* --- UTF-7 Codec -------------------------------------------------------- */ /* See RFC2152 for details. We encode conservatively and decode liberally. */ /* Three simple macros defining base-64. */ /* Is c a base-64 character? */ #define IS_BASE64(c) \ (((c) >= 'A' && (c) <= 'Z') || \ ((c) >= 'a' && (c) <= 'z') || \ ((c) >= '0' && (c) <= '9') || \ (c) == '+' || (c) == '/') /* given that c is a base-64 character, what is its base-64 value? */ #define FROM_BASE64(c) \ (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \ ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \ ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \ (c) == '+' ? 62 : 63) /* What is the base-64 character of the bottom 6 bits of n? */ #define TO_BASE64(n) \ ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f]) /* DECODE_DIRECT: this byte encountered in a UTF-7 string should be * decoded as itself. We are permissive on decoding; the only ASCII * byte not decoding to itself is the + which begins a base64 * string. */ #define DECODE_DIRECT(c) \ ((c) <= 127 && (c) != '+') /* The UTF-7 encoder treats ASCII characters differently according to * whether they are Set D, Set O, Whitespace, or special (i.e. none of * the above). See RFC2152. This array identifies these different * sets: * 0 : "Set D" * alphanumeric and '(),-./:? * 1 : "Set O" * !"#$%&*;<=>@[]^_`{|} * 2 : "whitespace" * ht nl cr sp * 3 : special (must be base64 encoded) * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127) */ static char utf7_category[128] = { /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3, /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* sp ! " # $ % & ' ( ) * + , - . / */ 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0, /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, /* @ A B C D E F G H I J K L M N O */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* P Q R S T U V W X Y Z [ \ ] ^ _ */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1, /* ` a b c d e f g h i j k l m n o */ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* p q r s t u v w x y z { | } ~ del */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3, }; /* ENCODE_DIRECT: this character should be encoded as itself. The * answer depends on whether we are encoding set O as itself, and also * on whether we are encoding whitespace as itself. RFC2152 makes it * clear that the answers to these questions vary between * applications, so this code needs to be flexible. */ #define ENCODE_DIRECT(c, directO, directWS) \ ((c) < 128 && (c) > 0 && \ ((utf7_category[(c)] == 0) || \ (directWS && (utf7_category[(c)] == 2)) || \ (directO && (utf7_category[(c)] == 1)))) PyObject * PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors) { return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL); } /* The decoder. The only state we preserve is our read position, * i.e. how many characters we have consumed. So if we end in the * middle of a shift sequence we have to back off the read position * and the output to the beginning of the sequence, otherwise we lose * all the shift state (seen bits, number of bits seen, high * surrogate). */ PyObject * PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) { const char *starts = s; Py_ssize_t startinpos; Py_ssize_t endinpos; const char *e; _PyUnicodeWriter writer; const char *errmsg = ""; int inShift = 0; Py_ssize_t shiftOutStart; unsigned int base64bits = 0; unsigned long base64buffer = 0; Py_UCS4 surrogate = 0; PyObject *errorHandler = NULL; PyObject *exc = NULL; if (size == 0) { if (consumed) *consumed = 0; _Py_RETURN_UNICODE_EMPTY(); } /* Start off assuming it's all ASCII. Widen later as necessary. */ _PyUnicodeWriter_Init(&writer); writer.min_length = size; shiftOutStart = 0; e = s + size; while (s < e) { Py_UCS4 ch; restart: ch = (unsigned char) *s; if (inShift) { /* in a base-64 section */ if (IS_BASE64(ch)) { /* consume a base-64 character */ base64buffer = (base64buffer << 6) | FROM_BASE64(ch); base64bits += 6; s++; if (base64bits >= 16) { /* we have enough bits for a UTF-16 value */ Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16)); base64bits -= 16; base64buffer &= (1 << base64bits) - 1; /* clear high bits */ assert(outCh <= 0xffff); if (surrogate) { /* expecting a second surrogate */ if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) { Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh); if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0) goto onError; surrogate = 0; continue; } else { if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0) goto onError; surrogate = 0; } } if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) { /* first surrogate */ surrogate = outCh; } else { if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0) goto onError; } } } else { /* now leaving a base-64 section */ inShift = 0; if (base64bits > 0) { /* left-over bits */ if (base64bits >= 6) { /* We've seen at least one base-64 character */ s++; errmsg = "partial character in shift sequence"; goto utf7Error; } else { /* Some bits remain; they should be zero */ if (base64buffer != 0) { s++; errmsg = "non-zero padding bits in shift sequence"; goto utf7Error; } } } if (surrogate && DECODE_DIRECT(ch)) { if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0) goto onError; } surrogate = 0; if (ch == '-') { /* '-' is absorbed; other terminating characters are preserved */ s++; } } } else if ( ch == '+' ) { startinpos = s-starts; s++; /* consume '+' */ if (s < e && *s == '-') { /* '+-' encodes '+' */ s++; if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0) goto onError; } else { /* begin base64-encoded section */ inShift = 1; surrogate = 0; shiftOutStart = writer.pos; base64bits = 0; base64buffer = 0; } } else if (DECODE_DIRECT(ch)) { /* character decodes as itself */ s++; if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) goto onError; } else { startinpos = s-starts; s++; errmsg = "unexpected special character"; goto utf7Error; } continue; utf7Error: endinpos = s-starts; if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, "utf7", errmsg, &starts, &e, &startinpos, &endinpos, &exc, &s, &writer)) goto onError; } /* end of string */ if (inShift && !consumed) { /* in shift sequence, no more to follow */ /* if we're in an inconsistent state, that's an error */ inShift = 0; if (surrogate || (base64bits >= 6) || (base64bits > 0 && base64buffer != 0)) { endinpos = size; if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, "utf7", "unterminated shift sequence", &starts, &e, &startinpos, &endinpos, &exc, &s, &writer)) goto onError; if (s < e) goto restart; } } /* return state */ if (consumed) { if (inShift) { *consumed = startinpos; if (writer.pos != shiftOutStart && writer.maxchar > 127) { PyObject *result = PyUnicode_FromKindAndData( writer.kind, writer.data, shiftOutStart); Py_XDECREF(errorHandler); Py_XDECREF(exc); _PyUnicodeWriter_Dealloc(&writer); return result; } writer.pos = shiftOutStart; /* back off output */ } else { *consumed = s-starts; } } Py_XDECREF(errorHandler); Py_XDECREF(exc); return _PyUnicodeWriter_Finish(&writer); onError: Py_XDECREF(errorHandler); Py_XDECREF(exc); _PyUnicodeWriter_Dealloc(&writer); return NULL; } PyObject * _PyUnicode_EncodeUTF7(PyObject *str, int base64SetO, int base64WhiteSpace, const char *errors) { int kind; void *data; Py_ssize_t len; PyObject *v; int inShift = 0; Py_ssize_t i; unsigned int base64bits = 0; unsigned long base64buffer = 0; char * out; char * start; if (PyUnicode_READY(str) == -1) return NULL; kind = PyUnicode_KIND(str); data = PyUnicode_DATA(str); len = PyUnicode_GET_LENGTH(str); if (len == 0) return PyBytes_FromStringAndSize(NULL, 0); /* It might be possible to tighten this worst case */ if (len > PY_SSIZE_T_MAX / 8) return PyErr_NoMemory(); v = PyBytes_FromStringAndSize(NULL, len * 8); if (v == NULL) return NULL; start = out = PyBytes_AS_STRING(v); for (i = 0; i < len; ++i) { Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (inShift) { if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) { /* shifting out */ if (base64bits) { /* output remaining bits */ *out++ = TO_BASE64(base64buffer << (6-base64bits)); base64buffer = 0; base64bits = 0; } inShift = 0; /* Characters not in the BASE64 set implicitly unshift the sequence so no '-' is required, except if the character is itself a '-' */ if (IS_BASE64(ch) || ch == '-') { *out++ = '-'; } *out++ = (char) ch; } else { goto encode_char; } } else { /* not in a shift sequence */ if (ch == '+') { *out++ = '+'; *out++ = '-'; } else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) { *out++ = (char) ch; } else { *out++ = '+'; inShift = 1; goto encode_char; } } continue; encode_char: if (ch >= 0x10000) { assert(ch <= MAX_UNICODE); /* code first surrogate */ base64bits += 16; base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch); while (base64bits >= 6) { *out++ = TO_BASE64(base64buffer >> (base64bits-6)); base64bits -= 6; } /* prepare second surrogate */ ch = Py_UNICODE_LOW_SURROGATE(ch); } base64bits += 16; base64buffer = (base64buffer << 16) | ch; while (base64bits >= 6) { *out++ = TO_BASE64(base64buffer >> (base64bits-6)); base64bits -= 6; } } if (base64bits) *out++= TO_BASE64(base64buffer << (6-base64bits) ); if (inShift) *out++ = '-'; if (_PyBytes_Resize(&v, out - start) < 0) return NULL; return v; } PyObject * PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors) { PyObject *result; PyObject *tmp = PyUnicode_FromUnicode(s, size); if (tmp == NULL) return NULL; result = _PyUnicode_EncodeUTF7(tmp, base64SetO, base64WhiteSpace, errors); Py_DECREF(tmp); return result; } #undef IS_BASE64 #undef FROM_BASE64 #undef TO_BASE64 #undef DECODE_DIRECT #undef ENCODE_DIRECT /* --- UTF-8 Codec -------------------------------------------------------- */ PyObject * PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors) { return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL); } #include "third_party/python/Objects/stringlib/asciilib.inc" #include "third_party/python/Objects/stringlib/codecs.inc" #include "third_party/python/Objects/stringlib/undef.inc" #include "third_party/python/Objects/stringlib/ucs1lib.inc" #include "third_party/python/Objects/stringlib/codecs.inc" #include "third_party/python/Objects/stringlib/undef.inc" #include "third_party/python/Objects/stringlib/ucs2lib.inc" #include "third_party/python/Objects/stringlib/codecs.inc" #include "third_party/python/Objects/stringlib/undef.inc" #include "third_party/python/Objects/stringlib/ucs4lib.inc" #include "third_party/python/Objects/stringlib/codecs.inc" #include "third_party/python/Objects/stringlib/undef.inc" /* Mask to quickly check whether a C 'long' contains a non-ASCII, UTF8-encoded char. */ #if (SIZEOF_LONG == 8) # define ASCII_CHAR_MASK 0x8080808080808080UL #elif (SIZEOF_LONG == 4) # define ASCII_CHAR_MASK 0x80808080UL #else # error C 'long' size should be either 4 or 8! #endif static optimizespeed Py_ssize_t ascii_decode(const char *start, const char *end, Py_UCS1 *dest) { const char *p = start; const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG); /* * Issue #17237: m68k is a bit different from most architectures in * that objects do not use "natural alignment" - for example, int and * long are only aligned at 2-byte boundaries. Therefore the assert() * won't work; also, tests have shown that skipping the "optimised * version" will even speed up m68k. */ while (p < end) { /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h for an explanation. */ if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) { /* Help allocation */ const char *_p = p; while (_p < aligned_end) { unsigned long value = *(unsigned long *) _p; if (value & ASCII_CHAR_MASK) break; _p += SIZEOF_LONG; } p = _p; if (_p == end) break; } if ((unsigned char)*p & 0x80) break; ++p; } memcpy(dest, start, p - start); return p - start; } PyObject * PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed) { _PyUnicodeWriter writer; const char *starts = s; const char *end = s + size; Py_ssize_t startinpos; Py_ssize_t endinpos; const char *errmsg = ""; PyObject *error_handler_obj = NULL; PyObject *exc = NULL; _Py_error_handler error_handler = _Py_ERROR_UNKNOWN; if (size == 0) { if (consumed) *consumed = 0; _Py_RETURN_UNICODE_EMPTY(); } /* ASCII is equivalent to the first 128 ordinals in Unicode. */ if (size == 1 && (unsigned char)s[0] < 128) { if (consumed) *consumed = 1; return get_latin1_char((unsigned char)s[0]); } _PyUnicodeWriter_Init(&writer); writer.min_length = size; if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1) goto onError; writer.pos = ascii_decode(s, end, writer.data); s += writer.pos; while (s < end) { Py_UCS4 ch; int kind = writer.kind; if (kind == PyUnicode_1BYTE_KIND) { if (PyUnicode_IS_ASCII(writer.buffer)) ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos); else ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos); } else if (kind == PyUnicode_2BYTE_KIND) { ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos); } else { assert(kind == PyUnicode_4BYTE_KIND); ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos); } switch (ch) { case 0: if (s == end || consumed) goto End; errmsg = "unexpected end of data"; startinpos = s - starts; endinpos = end - starts; break; case 1: errmsg = "invalid start byte"; startinpos = s - starts; endinpos = startinpos + 1; break; case 2: case 3: case 4: errmsg = "invalid continuation byte"; startinpos = s - starts; endinpos = startinpos + ch - 1; break; default: if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) goto onError; continue; } if (error_handler == _Py_ERROR_UNKNOWN) error_handler = get_error_handler(errors); switch (error_handler) { case _Py_ERROR_IGNORE: s += (endinpos - startinpos); break; case _Py_ERROR_REPLACE: if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0) goto onError; s += (endinpos - startinpos); break; case _Py_ERROR_SURROGATEESCAPE: { Py_ssize_t i; if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0) goto onError; for (i=startinpos; i<endinpos; i++) { ch = (Py_UCS4)(unsigned char)(starts[i]); PyUnicode_WRITE(writer.kind, writer.data, writer.pos, ch + 0xdc00); writer.pos++; } s += (endinpos - startinpos); break; } default: if (unicode_decode_call_errorhandler_writer( errors, &error_handler_obj, "utf-8", errmsg, &starts, &end, &startinpos, &endinpos, &exc, &s, &writer)) goto onError; } } End: if (consumed) *consumed = s - starts; Py_XDECREF(error_handler_obj); Py_XDECREF(exc); return _PyUnicodeWriter_Finish(&writer); onError: Py_XDECREF(error_handler_obj); Py_XDECREF(exc); _PyUnicodeWriter_Dealloc(&writer); return NULL; } /* Simplified UTF-8 decoder using surrogateescape error handler, used to decode the command line arguments on Mac OS X and Android. Return a pointer to a newly allocated wide character string (use PyMem_RawFree() to free the memory), or NULL on memory allocation error. */ wchar_t* _Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size) { const char *e; wchar_t *unicode; Py_ssize_t outpos; /* Note: size will always be longer than the resulting Unicode character count */ if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) return NULL; unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t)); if (!unicode) return NULL; /* Unpack UTF-8 encoded data */ e = s + size; outpos = 0; while (s < e) { Py_UCS4 ch; #if SIZEOF_WCHAR_T == 4 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos); #else ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos); #endif if (ch > 0xFF) { #if SIZEOF_WCHAR_T == 4 assert(0); #else assert(ch > 0xFFFF && ch <= MAX_UNICODE); /* compute and append the two surrogates: */ unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch); unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch); #endif } else { if (!ch && s == e) break; /* surrogateescape */ unicode[outpos++] = 0xDC00 + (unsigned char)*s++; } } unicode[outpos] = L'\0'; return unicode; } /* Primary internal function which creates utf8 encoded bytes objects. Allocation strategy: if the string is short, convert into a stack buffer and allocate exactly as much space needed at the end. Else allocate the maximum possible needed (4 result bytes per Unicode character), and return the excess memory at the end. */ PyObject * _PyUnicode_AsUTF8String(PyObject *unicode, const char *errors) { enum PyUnicode_Kind kind; void *data; Py_ssize_t size; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(unicode) == -1) return NULL; if (PyUnicode_UTF8(unicode)) return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode), PyUnicode_UTF8_LENGTH(unicode)); kind = PyUnicode_KIND(unicode); data = PyUnicode_DATA(unicode); size = PyUnicode_GET_LENGTH(unicode); switch (kind) { default: assert(0); case PyUnicode_1BYTE_KIND: /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */ assert(!PyUnicode_IS_ASCII(unicode)); return ucs1lib_utf8_encoder(unicode, data, size, errors); case PyUnicode_2BYTE_KIND: return ucs2lib_utf8_encoder(unicode, data, size, errors); case PyUnicode_4BYTE_KIND: return ucs4lib_utf8_encoder(unicode, data, size, errors); } } PyObject * PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors) { PyObject *v, *unicode; unicode = PyUnicode_FromUnicode(s, size); if (unicode == NULL) return NULL; v = _PyUnicode_AsUTF8String(unicode, errors); Py_DECREF(unicode); return v; } /** * Encodes Unicode object using UTF-8 and return the result as Python * bytes object. Error handling is “strict”. Return NULL if an exception * was raised by the codec. * * @return new reference */ PyObject * PyUnicode_AsUTF8String(PyObject *unicode) { return _PyUnicode_AsUTF8String(unicode, NULL); } /* --- UTF-32 Codec ------------------------------------------------------- */ PyObject * PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder) { return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL); } PyObject * PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) { const char *starts = s; Py_ssize_t startinpos; Py_ssize_t endinpos; _PyUnicodeWriter writer; const unsigned char *q, *e; int le, bo = 0; /* assume native ordering by default */ const char *encoding; const char *errmsg = ""; PyObject *errorHandler = NULL; PyObject *exc = NULL; q = (unsigned char *)s; e = q + size; if (byteorder) bo = *byteorder; /* Check for BOM marks (U+FEFF) in the input and adjust current byte order setting accordingly. In native mode, the leading BOM mark is skipped, in all other modes, it is copied to the output stream as-is (giving a ZWNBSP character). */ if (bo == 0 && size >= 4) { Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0]; if (bom == 0x0000FEFF) { bo = -1; q += 4; } else if (bom == 0xFFFE0000) { bo = 1; q += 4; } if (byteorder) *byteorder = bo; } if (q == e) { if (consumed) *consumed = size; _Py_RETURN_UNICODE_EMPTY(); } #ifdef WORDS_BIGENDIAN le = bo < 0; #else le = bo <= 0; #endif encoding = le ? "utf-32-le" : "utf-32-be"; _PyUnicodeWriter_Init(&writer); writer.min_length = (e - q + 3) / 4; if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1) goto onError; while (1) { Py_UCS4 ch = 0; Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer); if (e - q >= 4) { enum PyUnicode_Kind kind = writer.kind; void *data = writer.data; const unsigned char *last = e - 4; Py_ssize_t pos = writer.pos; if (le) { do { ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0]; if (ch > maxch) break; if (kind != PyUnicode_1BYTE_KIND && Py_UNICODE_IS_SURROGATE(ch)) break; PyUnicode_WRITE(kind, data, pos++, ch); q += 4; } while (q <= last); } else { do { ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3]; if (ch > maxch) break; if (kind != PyUnicode_1BYTE_KIND && Py_UNICODE_IS_SURROGATE(ch)) break; PyUnicode_WRITE(kind, data, pos++, ch); q += 4; } while (q <= last); } writer.pos = pos; } if (Py_UNICODE_IS_SURROGATE(ch)) { errmsg = "code point in surrogate code point range(0xd800, 0xe000)"; startinpos = ((const char *)q) - starts; endinpos = startinpos + 4; } else if (ch <= maxch) { if (q == e || consumed) break; /* remaining bytes at the end? (size should be divisible by 4) */ errmsg = "truncated data"; startinpos = ((const char *)q) - starts; endinpos = ((const char *)e) - starts; } else { if (ch < 0x110000) { if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) goto onError; q += 4; continue; } errmsg = "code point not in range(0x110000)"; startinpos = ((const char *)q) - starts; endinpos = startinpos + 4; } /* The remaining input chars are ignored if the callback chooses to skip the input */ if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, encoding, errmsg, &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q, &writer)) goto onError; } if (consumed) *consumed = (const char *)q-starts; Py_XDECREF(errorHandler); Py_XDECREF(exc); return _PyUnicodeWriter_Finish(&writer); onError: _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(errorHandler); Py_XDECREF(exc); return NULL; } PyObject * _PyUnicode_EncodeUTF32(PyObject *str, const char *errors, int byteorder) { enum PyUnicode_Kind kind; const void *data; Py_ssize_t len; PyObject *v; uint32_t *out; #if PY_LITTLE_ENDIAN int native_ordering = byteorder <= 0; #else int native_ordering = byteorder >= 0; #endif const char *encoding; Py_ssize_t nsize, pos; PyObject *errorHandler = NULL; PyObject *exc = NULL; PyObject *rep = NULL; if (!PyUnicode_Check(str)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(str) == -1) return NULL; kind = PyUnicode_KIND(str); data = PyUnicode_DATA(str); len = PyUnicode_GET_LENGTH(str); if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0)) return PyErr_NoMemory(); nsize = len + (byteorder == 0); v = PyBytes_FromStringAndSize(NULL, nsize * 4); if (v == NULL) return NULL; /* output buffer is 4-bytes aligned */ assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4)); out = (uint32_t *)PyBytes_AS_STRING(v); if (byteorder == 0) *out++ = 0xFEFF; if (len == 0) goto done; if (byteorder == -1) encoding = "utf-32-le"; else if (byteorder == 1) encoding = "utf-32-be"; else encoding = "utf-32"; if (kind == PyUnicode_1BYTE_KIND) { ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering); goto done; } pos = 0; while (pos < len) { Py_ssize_t repsize, moreunits; if (kind == PyUnicode_2BYTE_KIND) { pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos, &out, native_ordering); } else { assert(kind == PyUnicode_4BYTE_KIND); pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos, &out, native_ordering); } if (pos == len) break; rep = unicode_encode_call_errorhandler( errors, &errorHandler, encoding, "surrogates not allowed", str, &exc, pos, pos + 1, &pos); if (!rep) goto error; if (PyBytes_Check(rep)) { repsize = PyBytes_GET_SIZE(rep); if (repsize & 3) { raise_encode_exception(&exc, encoding, str, pos - 1, pos, "surrogates not allowed"); goto error; } moreunits = repsize / 4; } else { assert(PyUnicode_Check(rep)); if (PyUnicode_READY(rep) < 0) goto error; moreunits = repsize = PyUnicode_GET_LENGTH(rep); if (!PyUnicode_IS_ASCII(rep)) { raise_encode_exception(&exc, encoding, str, pos - 1, pos, "surrogates not allowed"); goto error; } } /* four bytes are reserved for each surrogate */ if (moreunits > 1) { Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v); if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) { /* integer overflow */ PyErr_NoMemory(); goto error; } if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0) goto error; out = (uint32_t*) PyBytes_AS_STRING(v) + outpos; } if (PyBytes_Check(rep)) { memcpy(out, PyBytes_AS_STRING(rep), repsize); out += moreunits; } else /* rep is unicode */ { assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND); ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize, &out, native_ordering); } Py_CLEAR(rep); } /* Cut back to size actually needed. This is necessary for, for example, encoding of a string containing isolated surrogates and the 'ignore' handler is used. */ nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v); if (nsize != PyBytes_GET_SIZE(v)) _PyBytes_Resize(&v, nsize); Py_XDECREF(errorHandler); Py_XDECREF(exc); done: return v; error: Py_XDECREF(rep); Py_XDECREF(errorHandler); Py_XDECREF(exc); Py_XDECREF(v); return NULL; } PyObject * PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) { PyObject *result; PyObject *tmp = PyUnicode_FromUnicode(s, size); if (tmp == NULL) return NULL; result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder); Py_DECREF(tmp); return result; } PyObject * PyUnicode_AsUTF32String(PyObject *unicode) { return _PyUnicode_EncodeUTF32(unicode, NULL, 0); } /* --- UTF-16 Codec ------------------------------------------------------- */ PyObject * PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder) { return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL); } PyObject * PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) { const char *starts = s; Py_ssize_t startinpos; Py_ssize_t endinpos; _PyUnicodeWriter writer; const unsigned char *q, *e; int bo = 0; /* assume native ordering by default */ int native_ordering; const char *errmsg = ""; PyObject *errorHandler = NULL; PyObject *exc = NULL; const char *encoding; q = (unsigned char *)s; e = q + size; if (byteorder) bo = *byteorder; /* Check for BOM marks (U+FEFF) in the input and adjust current byte order setting accordingly. In native mode, the leading BOM mark is skipped, in all other modes, it is copied to the output stream as-is (giving a ZWNBSP character). */ if (bo == 0 && size >= 2) { const Py_UCS4 bom = (q[1] << 8) | q[0]; if (bom == 0xFEFF) { q += 2; bo = -1; } else if (bom == 0xFFFE) { q += 2; bo = 1; } if (byteorder) *byteorder = bo; } if (q == e) { if (consumed) *consumed = size; _Py_RETURN_UNICODE_EMPTY(); } #if PY_LITTLE_ENDIAN native_ordering = bo <= 0; encoding = bo <= 0 ? "utf-16-le" : "utf-16-be"; #else native_ordering = bo >= 0; encoding = bo >= 0 ? "utf-16-be" : "utf-16-le"; #endif /* Note: size will always be longer than the resulting Unicode character count normally. Error handler will take care of resizing when needed. */ _PyUnicodeWriter_Init(&writer); writer.min_length = (e - q + 1) / 2; if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1) goto onError; while (1) { Py_UCS4 ch = 0; if (e - q >= 2) { int kind = writer.kind; if (kind == PyUnicode_1BYTE_KIND) { if (PyUnicode_IS_ASCII(writer.buffer)) ch = asciilib_utf16_decode(&q, e, (Py_UCS1*)writer.data, &writer.pos, native_ordering); else ch = ucs1lib_utf16_decode(&q, e, (Py_UCS1*)writer.data, &writer.pos, native_ordering); } else if (kind == PyUnicode_2BYTE_KIND) { ch = ucs2lib_utf16_decode(&q, e, (Py_UCS2*)writer.data, &writer.pos, native_ordering); } else { assert(kind == PyUnicode_4BYTE_KIND); ch = ucs4lib_utf16_decode(&q, e, (Py_UCS4*)writer.data, &writer.pos, native_ordering); } } switch (ch) { case 0: /* remaining byte at the end? (size should be even) */ if (q == e || consumed) goto End; errmsg = "truncated data"; startinpos = ((const char *)q) - starts; endinpos = ((const char *)e) - starts; break; /* The remaining input chars are ignored if the callback chooses to skip the input */ case 1: q -= 2; if (consumed) goto End; errmsg = "unexpected end of data"; startinpos = ((const char *)q) - starts; endinpos = ((const char *)e) - starts; break; case 2: errmsg = "illegal encoding"; startinpos = ((const char *)q) - 2 - starts; endinpos = startinpos + 2; break; case 3: errmsg = "illegal UTF-16 surrogate"; startinpos = ((const char *)q) - 4 - starts; endinpos = startinpos + 2; break; default: if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) goto onError; continue; } if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, encoding, errmsg, &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q, &writer)) goto onError; } End: if (consumed) *consumed = (const char *)q-starts; Py_XDECREF(errorHandler); Py_XDECREF(exc); return _PyUnicodeWriter_Finish(&writer); onError: _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(errorHandler); Py_XDECREF(exc); return NULL; } PyObject * _PyUnicode_EncodeUTF16(PyObject *str, const char *errors, int byteorder) { enum PyUnicode_Kind kind; const void *data; Py_ssize_t len; PyObject *v; unsigned short *out; Py_ssize_t pairs; #if PY_BIG_ENDIAN int native_ordering = byteorder >= 0; #else int native_ordering = byteorder <= 0; #endif const char *encoding; Py_ssize_t nsize, pos; PyObject *errorHandler = NULL; PyObject *exc = NULL; PyObject *rep = NULL; if (!PyUnicode_Check(str)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(str) == -1) return NULL; kind = PyUnicode_KIND(str); data = PyUnicode_DATA(str); len = PyUnicode_GET_LENGTH(str); pairs = 0; if (kind == PyUnicode_4BYTE_KIND) { const Py_UCS4 *in = (const Py_UCS4 *)data; const Py_UCS4 *end = in + len; while (in < end) { if (*in++ >= 0x10000) { pairs++; } } } if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) { return PyErr_NoMemory(); } nsize = len + pairs + (byteorder == 0); v = PyBytes_FromStringAndSize(NULL, nsize * 2); if (v == NULL) { return NULL; } /* output buffer is 2-bytes aligned */ assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2)); out = (unsigned short *)PyBytes_AS_STRING(v); if (byteorder == 0) { *out++ = 0xFEFF; } if (len == 0) { goto done; } if (kind == PyUnicode_1BYTE_KIND) { ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering); goto done; } if (byteorder < 0) { encoding = "utf-16-le"; } else if (byteorder > 0) { encoding = "utf-16-be"; } else { encoding = "utf-16"; } pos = 0; while (pos < len) { Py_ssize_t repsize, moreunits; if (kind == PyUnicode_2BYTE_KIND) { pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos, &out, native_ordering); } else { assert(kind == PyUnicode_4BYTE_KIND); pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos, &out, native_ordering); } if (pos == len) break; rep = unicode_encode_call_errorhandler( errors, &errorHandler, encoding, "surrogates not allowed", str, &exc, pos, pos + 1, &pos); if (!rep) goto error; if (PyBytes_Check(rep)) { repsize = PyBytes_GET_SIZE(rep); if (repsize & 1) { raise_encode_exception(&exc, encoding, str, pos - 1, pos, "surrogates not allowed"); goto error; } moreunits = repsize / 2; } else { assert(PyUnicode_Check(rep)); if (PyUnicode_READY(rep) < 0) goto error; moreunits = repsize = PyUnicode_GET_LENGTH(rep); if (!PyUnicode_IS_ASCII(rep)) { raise_encode_exception(&exc, encoding, str, pos - 1, pos, "surrogates not allowed"); goto error; } } /* two bytes are reserved for each surrogate */ if (moreunits > 1) { Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v); if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) { /* integer overflow */ PyErr_NoMemory(); goto error; } if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0) goto error; out = (unsigned short*) PyBytes_AS_STRING(v) + outpos; } if (PyBytes_Check(rep)) { memcpy(out, PyBytes_AS_STRING(rep), repsize); out += moreunits; } else /* rep is unicode */ { assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND); ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize, &out, native_ordering); } Py_CLEAR(rep); } /* Cut back to size actually needed. This is necessary for, for example, encoding of a string containing isolated surrogates and the 'ignore' handler is used. */ nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v); if (nsize != PyBytes_GET_SIZE(v)) _PyBytes_Resize(&v, nsize); Py_XDECREF(errorHandler); Py_XDECREF(exc); done: return v; error: Py_XDECREF(rep); Py_XDECREF(errorHandler); Py_XDECREF(exc); Py_XDECREF(v); return NULL; #undef STORECHAR } PyObject * PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) { PyObject *result; PyObject *tmp = PyUnicode_FromUnicode(s, size); if (tmp == NULL) return NULL; result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder); Py_DECREF(tmp); return result; } PyObject * PyUnicode_AsUTF16String(PyObject *unicode) { return _PyUnicode_EncodeUTF16(unicode, NULL, 0); } /* --- Unicode Escape Codec ----------------------------------------------- */ PyObject * _PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors, const char **first_invalid_escape) { const char *starts = s; _PyUnicodeWriter writer; const char *end; PyObject *errorHandler = NULL; PyObject *exc = NULL; // so we can remember if we've seen an invalid escape char or not *first_invalid_escape = NULL; if (size == 0) { _Py_RETURN_UNICODE_EMPTY(); } /* Escaped strings will always be longer than the resulting Unicode string, so we start with size here and then reduce the length after conversion to the true value. (but if the error callback returns a long replacement string we'll have to allocate more space) */ _PyUnicodeWriter_Init(&writer); writer.min_length = size; if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) { goto onError; } end = s + size; while (s < end) { unsigned char c = (unsigned char) *s++; Py_UCS4 ch; int count; Py_ssize_t startinpos; Py_ssize_t endinpos; const char *message; #define WRITE_ASCII_CHAR(ch) \ do { \ assert(ch <= 127); \ assert(writer.pos < writer.size); \ PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \ } while(0) #define WRITE_CHAR(ch) \ do { \ if (ch <= writer.maxchar) { \ assert(writer.pos < writer.size); \ PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \ } \ else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \ goto onError; \ } \ } while(0) /* Non-escape characters are interpreted as Unicode ordinals */ if (c != '\\') { WRITE_CHAR(c); continue; } startinpos = s - starts - 1; /* \ - Escapes */ if (s >= end) { message = "\\ at end of string"; goto error; } c = (unsigned char) *s++; assert(writer.pos < writer.size); switch (c) { /* \x escapes */ case '\n': continue; case '\\': WRITE_ASCII_CHAR('\\'); continue; case '\'': WRITE_ASCII_CHAR('\''); continue; case '\"': WRITE_ASCII_CHAR('\"'); continue; case 'b': WRITE_ASCII_CHAR('\b'); continue; /* FF */ case 'f': WRITE_ASCII_CHAR('\014'); continue; case 't': WRITE_ASCII_CHAR('\t'); continue; case 'n': WRITE_ASCII_CHAR('\n'); continue; case 'r': WRITE_ASCII_CHAR('\r'); continue; /* VT */ case 'v': WRITE_ASCII_CHAR('\013'); continue; /* BEL, not classic C */ case 'a': WRITE_ASCII_CHAR('\007'); continue; /* [jart] ansi escape */ case 'e': WRITE_ASCII_CHAR('\033'); continue; /* \OOO (octal) escapes */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': ch = c - '0'; if (s < end && '0' <= *s && *s <= '7') { ch = (ch<<3) + *s++ - '0'; if (s < end && '0' <= *s && *s <= '7') { ch = (ch<<3) + *s++ - '0'; } } WRITE_CHAR(ch); continue; /* hex escapes */ /* \xXX */ case 'x': count = 2; message = "truncated \\xXX escape"; goto hexescape; /* \uXXXX */ case 'u': count = 4; message = "truncated \\uXXXX escape"; goto hexescape; /* \UXXXXXXXX */ case 'U': count = 8; message = "truncated \\UXXXXXXXX escape"; hexescape: for (ch = 0; count && s < end; ++s, --count) { c = (unsigned char)*s; ch <<= 4; if (c >= '0' && c <= '9') { ch += c - '0'; } else if (c >= 'a' && c <= 'f') { ch += c - ('a' - 10); } else if (c >= 'A' && c <= 'F') { ch += c - ('A' - 10); } else { break; } } if (count) { goto error; } /* when we get here, ch is a 32-bit unicode character */ if (ch > MAX_UNICODE) { message = "illegal Unicode character"; goto error; } WRITE_CHAR(ch); continue; /* \N{name} */ case 'N': if (!_weaken(_PyUnicode_GetCode)) { PyErr_SetString( PyExc_UnicodeError, "\\N escapes not supported " "(you must yoink pyc:unicodedata or _PyUnicode_GetCode)"); goto onError; } message = "malformed \\N character escape"; if (s < end && *s == '{') { const char *start = ++s; size_t namelen; /* look for the closing brace */ while (s < end && *s != '}') s++; namelen = s - start; if (namelen && s < end) { /* found a name. look it up in the unicode database */ s++; ch = 0xffffffff; /* in case 'getcode' messes up */ if (namelen <= INT_MAX && _weaken(_PyUnicode_GetCode)(NULL, start, (int)namelen, &ch, 0)) { assert(ch <= MAX_UNICODE); WRITE_CHAR(ch); continue; } message = "unknown Unicode character name"; } } goto error; default: if (*first_invalid_escape == NULL) { *first_invalid_escape = s-1; /* Back up one char, since we've already incremented s. */ } WRITE_ASCII_CHAR('\\'); WRITE_CHAR(c); continue; } error: endinpos = s-starts; writer.min_length = end - s + writer.pos; if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, "unicodeescape", message, &starts, &end, &startinpos, &endinpos, &exc, &s, &writer)) { goto onError; } assert(end - s <= writer.size - writer.pos); #undef WRITE_ASCII_CHAR #undef WRITE_CHAR } Py_XDECREF(errorHandler); Py_XDECREF(exc); return _PyUnicodeWriter_Finish(&writer); onError: _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(errorHandler); Py_XDECREF(exc); return NULL; } PyObject * PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) { const char *first_invalid_escape; PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors, &first_invalid_escape); if (result == NULL) return NULL; if (first_invalid_escape != NULL) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "invalid escape sequence '\\%c'", (unsigned char)*first_invalid_escape) < 0) { Py_DECREF(result); return NULL; } } return result; } /* Return a Unicode-Escape string version of the Unicode object. */ PyObject * PyUnicode_AsUnicodeEscapeString(PyObject *unicode) { Py_ssize_t i, len; PyObject *repr; char *p; enum PyUnicode_Kind kind; void *data; Py_ssize_t expandsize; /* Initial allocation is based on the longest-possible character escape. For UCS1 strings it's '\xxx', 4 bytes per source character. For UCS2 strings it's '\uxxxx', 6 bytes per source character. For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character. */ if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(unicode) == -1) { return NULL; } len = PyUnicode_GET_LENGTH(unicode); if (len == 0) { return PyBytes_FromStringAndSize(NULL, 0); } kind = PyUnicode_KIND(unicode); data = PyUnicode_DATA(unicode); /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6 bytes, and 1 byte characters 4. */ expandsize = kind * 2 + 2; if (len > PY_SSIZE_T_MAX / expandsize) { return PyErr_NoMemory(); } repr = PyBytes_FromStringAndSize(NULL, expandsize * len); if (repr == NULL) { return NULL; } p = PyBytes_AS_STRING(repr); for (i = 0; i < len; i++) { Py_UCS4 ch = PyUnicode_READ(kind, data, i); /* U+0000-U+00ff range */ if (ch < 0x100) { if (ch >= ' ' && ch < 127) { if (ch != '\\') { /* Copy printable US ASCII as-is */ *p++ = (char) ch; } /* Escape backslashes */ else { *p++ = '\\'; *p++ = '\\'; } } /* Map special whitespace to '\t', \n', '\r' */ else if (ch == '\t') { *p++ = '\\'; *p++ = 't'; } else if (ch == '\n') { *p++ = '\\'; *p++ = 'n'; } else if (ch == '\r') { *p++ = '\\'; *p++ = 'r'; } /* Map non-printable US ASCII and 8-bit characters to '\xHH' */ else { *p++ = '\\'; *p++ = 'x'; *p++ = Py_hexdigits[(ch >> 4) & 0x000F]; *p++ = Py_hexdigits[ch & 0x000F]; } } /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */ else if (ch < 0x10000) { *p++ = '\\'; *p++ = 'u'; *p++ = Py_hexdigits[(ch >> 12) & 0x000F]; *p++ = Py_hexdigits[(ch >> 8) & 0x000F]; *p++ = Py_hexdigits[(ch >> 4) & 0x000F]; *p++ = Py_hexdigits[ch & 0x000F]; } /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */ else { /* Make sure that the first two digits are zero */ assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff); *p++ = '\\'; *p++ = 'U'; *p++ = '0'; *p++ = '0'; *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F]; *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F]; *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F]; *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F]; *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F]; *p++ = Py_hexdigits[ch & 0x0000000F]; } } assert(p - PyBytes_AS_STRING(repr) > 0); if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) { return NULL; } return repr; } PyObject * PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size) { PyObject *result; PyObject *tmp = PyUnicode_FromUnicode(s, size); if (tmp == NULL) { return NULL; } result = PyUnicode_AsUnicodeEscapeString(tmp); Py_DECREF(tmp); return result; } /* --- Raw Unicode Escape Codec ------------------------------------------- */ PyObject * PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors) { const char *starts = s; _PyUnicodeWriter writer; const char *end; PyObject *errorHandler = NULL; PyObject *exc = NULL; if (size == 0) { _Py_RETURN_UNICODE_EMPTY(); } /* Escaped strings will always be longer than the resulting Unicode string, so we start with size here and then reduce the length after conversion to the true value. (But decoding error handler might have to resize the string) */ _PyUnicodeWriter_Init(&writer); writer.min_length = size; if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) { goto onError; } end = s + size; while (s < end) { unsigned char c = (unsigned char) *s++; Py_UCS4 ch; int count; Py_ssize_t startinpos; Py_ssize_t endinpos; const char *message; #define WRITE_CHAR(ch) \ do { \ if (ch <= writer.maxchar) { \ assert(writer.pos < writer.size); \ PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \ } \ else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \ goto onError; \ } \ } while(0) /* Non-escape characters are interpreted as Unicode ordinals */ if (c != '\\' || s >= end) { WRITE_CHAR(c); continue; } c = (unsigned char) *s++; if (c == 'u') { count = 4; message = "truncated \\uXXXX escape"; } else if (c == 'U') { count = 8; message = "truncated \\UXXXXXXXX escape"; } else { assert(writer.pos < writer.size); PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\'); WRITE_CHAR(c); continue; } startinpos = s - starts - 2; /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */ for (ch = 0; count && s < end; ++s, --count) { c = (unsigned char)*s; ch <<= 4; if (c >= '0' && c <= '9') { ch += c - '0'; } else if (c >= 'a' && c <= 'f') { ch += c - ('a' - 10); } else if (c >= 'A' && c <= 'F') { ch += c - ('A' - 10); } else { break; } } if (!count) { if (ch <= MAX_UNICODE) { WRITE_CHAR(ch); continue; } message = "\\Uxxxxxxxx out of range"; } endinpos = s-starts; writer.min_length = end - s + writer.pos; if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, "rawunicodeescape", message, &starts, &end, &startinpos, &endinpos, &exc, &s, &writer)) { goto onError; } assert(end - s <= writer.size - writer.pos); #undef WRITE_CHAR } Py_XDECREF(errorHandler); Py_XDECREF(exc); return _PyUnicodeWriter_Finish(&writer); onError: _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(errorHandler); Py_XDECREF(exc); return NULL; } PyObject * PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode) { PyObject *repr; char *p; Py_ssize_t expandsize, pos; int kind; void *data; Py_ssize_t len; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(unicode) == -1) { return NULL; } kind = PyUnicode_KIND(unicode); data = PyUnicode_DATA(unicode); len = PyUnicode_GET_LENGTH(unicode); if (kind == PyUnicode_1BYTE_KIND) { return PyBytes_FromStringAndSize(data, len); } /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6 bytes, and 1 byte characters 4. */ expandsize = kind * 2 + 2; if (len > PY_SSIZE_T_MAX / expandsize) { return PyErr_NoMemory(); } repr = PyBytes_FromStringAndSize(NULL, expandsize * len); if (repr == NULL) { return NULL; } if (len == 0) { return repr; } p = PyBytes_AS_STRING(repr); for (pos = 0; pos < len; pos++) { Py_UCS4 ch = PyUnicode_READ(kind, data, pos); /* U+0000-U+00ff range: Copy 8-bit characters as-is */ if (ch < 0x100) { *p++ = (char) ch; } /* U+0000-U+00ff range: Map 16-bit characters to '\uHHHH' */ else if (ch < 0x10000) { *p++ = '\\'; *p++ = 'u'; *p++ = Py_hexdigits[(ch >> 12) & 0xf]; *p++ = Py_hexdigits[(ch >> 8) & 0xf]; *p++ = Py_hexdigits[(ch >> 4) & 0xf]; *p++ = Py_hexdigits[ch & 15]; } /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */ else { assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff); *p++ = '\\'; *p++ = 'U'; *p++ = '0'; *p++ = '0'; *p++ = Py_hexdigits[(ch >> 20) & 0xf]; *p++ = Py_hexdigits[(ch >> 16) & 0xf]; *p++ = Py_hexdigits[(ch >> 12) & 0xf]; *p++ = Py_hexdigits[(ch >> 8) & 0xf]; *p++ = Py_hexdigits[(ch >> 4) & 0xf]; *p++ = Py_hexdigits[ch & 15]; } } assert(p > PyBytes_AS_STRING(repr)); if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) { return NULL; } return repr; } PyObject * PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size) { PyObject *result; PyObject *tmp = PyUnicode_FromUnicode(s, size); if (tmp == NULL) return NULL; result = PyUnicode_AsRawUnicodeEscapeString(tmp); Py_DECREF(tmp); return result; } /* --- Unicode Internal Codec ------------------------------------------- */ PyObject * _PyUnicode_DecodeUnicodeInternal(const char *s, Py_ssize_t size, const char *errors) { const char *starts = s; Py_ssize_t startinpos; Py_ssize_t endinpos; _PyUnicodeWriter writer; const char *end; const char *reason; PyObject *errorHandler = NULL; PyObject *exc = NULL; if (PyErr_WarnEx(PyExc_DeprecationWarning, "unicode_internal codec has been deprecated", 1)) return NULL; if (size < 0) { PyErr_BadInternalCall(); return NULL; } if (size == 0) _Py_RETURN_UNICODE_EMPTY(); _PyUnicodeWriter_Init(&writer); if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) { PyErr_NoMemory(); goto onError; } writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE; end = s + size; while (s < end) { Py_UNICODE uch; Py_UCS4 ch; if (end - s < Py_UNICODE_SIZE) { endinpos = end-starts; reason = "truncated input"; goto error; } /* We copy the raw representation one byte at a time because the pointer may be unaligned (see test_codeccallbacks). */ ((char *) &uch)[0] = s[0]; ((char *) &uch)[1] = s[1]; #ifdef Py_UNICODE_WIDE ((char *) &uch)[2] = s[2]; ((char *) &uch)[3] = s[3]; #endif ch = uch; #ifdef Py_UNICODE_WIDE /* We have to sanity check the raw data, otherwise doom looms for some malformed UCS-4 data. */ if (ch > 0x10ffff) { endinpos = s - starts + Py_UNICODE_SIZE; reason = "illegal code point (> 0x10FFFF)"; goto error; } #endif s += Py_UNICODE_SIZE; #ifndef Py_UNICODE_WIDE if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE) { Py_UNICODE uch2; ((char *) &uch2)[0] = s[0]; ((char *) &uch2)[1] = s[1]; if (Py_UNICODE_IS_LOW_SURROGATE(uch2)) { ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2); s += Py_UNICODE_SIZE; } } #endif if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) goto onError; continue; error: startinpos = s - starts; if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, "unicode_internal", reason, &starts, &end, &startinpos, &endinpos, &exc, &s, &writer)) goto onError; } Py_XDECREF(errorHandler); Py_XDECREF(exc); return _PyUnicodeWriter_Finish(&writer); onError: _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(errorHandler); Py_XDECREF(exc); return NULL; } /* --- Latin-1 Codec ------------------------------------------------------ */ PyObject * PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors) { /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */ return _PyUnicode_FromUCS1((unsigned char*)s, size); } /* create or adjust a UnicodeEncodeError */ static void make_encode_exception(PyObject **exceptionObject, const char *encoding, PyObject *unicode, Py_ssize_t startpos, Py_ssize_t endpos, const char *reason) { if (*exceptionObject == NULL) { *exceptionObject = PyObject_CallFunction( PyExc_UnicodeEncodeError, "sOnns", encoding, unicode, startpos, endpos, reason); } else { if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos)) goto onError; if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos)) goto onError; if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason)) goto onError; return; onError: Py_CLEAR(*exceptionObject); } } /* raises a UnicodeEncodeError */ static void raise_encode_exception(PyObject **exceptionObject, const char *encoding, PyObject *unicode, Py_ssize_t startpos, Py_ssize_t endpos, const char *reason) { make_encode_exception(exceptionObject, encoding, unicode, startpos, endpos, reason); if (*exceptionObject != NULL) PyCodec_StrictErrors(*exceptionObject); } /* error handling callback helper: build arguments, call the callback and check the arguments, put the result into newpos and return the replacement string, which has to be freed by the caller */ static PyObject * unicode_encode_call_errorhandler(const char *errors, PyObject **errorHandler, const char *encoding, const char *reason, PyObject *unicode, PyObject **exceptionObject, Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos) { static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple"; Py_ssize_t len; PyObject *restuple; PyObject *resunicode; if (*errorHandler == NULL) { *errorHandler = PyCodec_LookupError(errors); if (*errorHandler == NULL) return NULL; } if (PyUnicode_READY(unicode) == -1) return NULL; len = PyUnicode_GET_LENGTH(unicode); make_encode_exception(exceptionObject, encoding, unicode, startpos, endpos, reason); if (*exceptionObject == NULL) return NULL; restuple = PyObject_CallFunctionObjArgs( *errorHandler, *exceptionObject, NULL); if (restuple == NULL) return NULL; if (!PyTuple_Check(restuple)) { PyErr_SetString(PyExc_TypeError, &argparse[3]); Py_DECREF(restuple); return NULL; } if (!PyArg_ParseTuple(restuple, argparse, &resunicode, newpos)) { Py_DECREF(restuple); return NULL; } if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) { PyErr_SetString(PyExc_TypeError, &argparse[3]); Py_DECREF(restuple); return NULL; } if (*newpos<0) *newpos = len + *newpos; if (*newpos<0 || *newpos>len) { PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos); Py_DECREF(restuple); return NULL; } Py_INCREF(resunicode); Py_DECREF(restuple); return resunicode; } PyObject * unicode_encode_ucs1(PyObject *unicode, const char *errors, const Py_UCS4 limit) { /* input state */ Py_ssize_t pos=0, size; int kind; void *data; /* pointer into the output */ char *str; const char *encoding = (limit == 256) ? "latin-1" : "ascii"; const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)"; PyObject *error_handler_obj = NULL; PyObject *exc = NULL; _Py_error_handler error_handler = _Py_ERROR_UNKNOWN; PyObject *rep = NULL; /* output object */ _PyBytesWriter writer; if (PyUnicode_READY(unicode) == -1) return NULL; size = PyUnicode_GET_LENGTH(unicode); kind = PyUnicode_KIND(unicode); data = PyUnicode_DATA(unicode); /* allocate enough for a simple encoding without replacements, if we need more, we'll resize */ if (size == 0) return PyBytes_FromStringAndSize(NULL, 0); _PyBytesWriter_Init(&writer); str = _PyBytesWriter_Alloc(&writer, size); if (str == NULL) return NULL; while (pos < size) { Py_UCS4 ch = PyUnicode_READ(kind, data, pos); /* can we encode this? */ if (ch < limit) { /* no overflow check, because we know that the space is enough */ *str++ = (char)ch; ++pos; } else { Py_ssize_t newpos, i; /* startpos for collecting unencodable chars */ Py_ssize_t collstart = pos; Py_ssize_t collend = collstart + 1; /* find all unecodable characters */ while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit)) ++collend; /* Only overallocate the buffer if it's not the last write */ writer.overallocate = (collend < size); /* cache callback name lookup (if not done yet, i.e. it's the first error) */ if (error_handler == _Py_ERROR_UNKNOWN) error_handler = get_error_handler(errors); switch (error_handler) { case _Py_ERROR_STRICT: raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason); goto onError; case _Py_ERROR_REPLACE: memset(str, '?', collend - collstart); str += (collend - collstart); /* fall through */ case _Py_ERROR_IGNORE: pos = collend; break; case _Py_ERROR_BACKSLASHREPLACE: /* subtract preallocated bytes */ writer.min_size -= (collend - collstart); str = backslashreplace(&writer, str, unicode, collstart, collend); if (str == NULL) goto onError; pos = collend; break; case _Py_ERROR_XMLCHARREFREPLACE: /* subtract preallocated bytes */ writer.min_size -= (collend - collstart); str = xmlcharrefreplace(&writer, str, unicode, collstart, collend); if (str == NULL) goto onError; pos = collend; break; case _Py_ERROR_SURROGATEESCAPE: for (i = collstart; i < collend; ++i) { ch = PyUnicode_READ(kind, data, i); if (ch < 0xdc80 || 0xdcff < ch) { /* Not a UTF-8b surrogate */ break; } *str++ = (char)(ch - 0xdc00); ++pos; } if (i >= collend) break; collstart = pos; assert(collstart != collend); /* fall through */ default: rep = unicode_encode_call_errorhandler(errors, &error_handler_obj, encoding, reason, unicode, &exc, collstart, collend, &newpos); if (rep == NULL) goto onError; /* subtract preallocated bytes */ writer.min_size -= 1; if (PyBytes_Check(rep)) { /* Directly copy bytes result to output. */ str = _PyBytesWriter_WriteBytes(&writer, str, PyBytes_AS_STRING(rep), PyBytes_GET_SIZE(rep)); } else { assert(PyUnicode_Check(rep)); if (PyUnicode_READY(rep) < 0) goto onError; if (PyUnicode_IS_ASCII(rep)) { /* Fast path: all characters are smaller than limit */ assert(limit >= 128); assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND); str = _PyBytesWriter_WriteBytes(&writer, str, PyUnicode_DATA(rep), PyUnicode_GET_LENGTH(rep)); } else { Py_ssize_t repsize = PyUnicode_GET_LENGTH(rep); str = _PyBytesWriter_Prepare(&writer, str, repsize); if (str == NULL) goto onError; /* check if there is anything unencodable in the replacement and copy it to the output */ for (i = 0; repsize-->0; ++i, ++str) { ch = PyUnicode_READ_CHAR(rep, i); if (ch >= limit) { raise_encode_exception(&exc, encoding, unicode, pos, pos+1, reason); goto onError; } *str = (char)ch; } } } if (str == NULL) goto onError; pos = newpos; Py_CLEAR(rep); } /* If overallocation was disabled, ensure that it was the last write. Otherwise, we missed an optimization */ assert(writer.overallocate || pos == size); } } Py_XDECREF(error_handler_obj); Py_XDECREF(exc); return _PyBytesWriter_Finish(&writer, str); onError: Py_XDECREF(rep); _PyBytesWriter_Dealloc(&writer); Py_XDECREF(error_handler_obj); Py_XDECREF(exc); return NULL; } PyObject * _PyUnicode_AsLatin1String(PyObject *unicode, const char *errors) { if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(unicode) == -1) return NULL; /* Fast path: if it is a one-byte string, construct bytes object directly. */ if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode), PyUnicode_GET_LENGTH(unicode)); /* Non-Latin-1 characters present. Defer to above function to raise the exception. */ return unicode_encode_ucs1(unicode, errors, 256); } PyObject* PyUnicode_AsLatin1String(PyObject *unicode) { return _PyUnicode_AsLatin1String(unicode, NULL); } /* --- 7-bit ASCII Codec -------------------------------------------------- */ PyObject * PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors) { const char *starts = s; _PyUnicodeWriter writer; int kind; void *data; Py_ssize_t startinpos; Py_ssize_t endinpos; Py_ssize_t outpos; const char *e; PyObject *error_handler_obj = NULL; PyObject *exc = NULL; _Py_error_handler error_handler = _Py_ERROR_UNKNOWN; if (size == 0) _Py_RETURN_UNICODE_EMPTY(); /* ASCII is equivalent to the first 128 ordinals in Unicode. */ if (size == 1 && (unsigned char)s[0] < 128) return get_latin1_char((unsigned char)s[0]); _PyUnicodeWriter_Init(&writer); writer.min_length = size; if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0) return NULL; e = s + size; data = writer.data; outpos = ascii_decode(s, e, (Py_UCS1 *)data); writer.pos = outpos; if (writer.pos == size) return _PyUnicodeWriter_Finish(&writer); s += writer.pos; kind = writer.kind; while (s < e) { unsigned char c = (unsigned char)*s; if (c < 128) { PyUnicode_WRITE(kind, data, writer.pos, c); writer.pos++; ++s; continue; } /* byte outsize range 0x00..0x7f: call the error handler */ if (error_handler == _Py_ERROR_UNKNOWN) error_handler = get_error_handler(errors); switch (error_handler) { case _Py_ERROR_REPLACE: case _Py_ERROR_SURROGATEESCAPE: /* Fast-path: the error handler only writes one character, but we may switch to UCS2 at the first write */ if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0) goto onError; kind = writer.kind; data = writer.data; if (error_handler == _Py_ERROR_REPLACE) PyUnicode_WRITE(kind, data, writer.pos, 0xfffd); else PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00); writer.pos++; ++s; break; case _Py_ERROR_IGNORE: ++s; break; default: startinpos = s-starts; endinpos = startinpos + 1; if (unicode_decode_call_errorhandler_writer( errors, &error_handler_obj, "ascii", "ordinal not in range(128)", &starts, &e, &startinpos, &endinpos, &exc, &s, &writer)) goto onError; kind = writer.kind; data = writer.data; } } Py_XDECREF(error_handler_obj); Py_XDECREF(exc); return _PyUnicodeWriter_Finish(&writer); onError: _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(error_handler_obj); Py_XDECREF(exc); return NULL; } PyObject * _PyUnicode_AsASCIIString(PyObject *unicode, const char *errors) { if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(unicode) == -1) return NULL; /* Fast path: if it is an ASCII-only string, construct bytes object directly. Else defer to above function to raise the exception. */ if (PyUnicode_IS_ASCII(unicode)) return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode), PyUnicode_GET_LENGTH(unicode)); return unicode_encode_ucs1(unicode, errors, 128); } PyObject * PyUnicode_AsASCIIString(PyObject *unicode) { return _PyUnicode_AsASCIIString(unicode, NULL); } /* --- Character Mapping Codec -------------------------------------------- */ static int charmap_decode_string(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors, _PyUnicodeWriter *writer) { const char *starts = s; const char *e; Py_ssize_t startinpos, endinpos; PyObject *errorHandler = NULL, *exc = NULL; Py_ssize_t maplen; enum PyUnicode_Kind mapkind; void *mapdata; Py_UCS4 x; unsigned char ch; if (PyUnicode_READY(mapping) == -1) return -1; maplen = PyUnicode_GET_LENGTH(mapping); mapdata = PyUnicode_DATA(mapping); mapkind = PyUnicode_KIND(mapping); e = s + size; if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) { /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1 * is disabled in encoding aliases, latin1 is preferred because * its implementation is faster. */ Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata; Py_UCS1 *outdata = (Py_UCS1 *)writer->data; Py_UCS4 maxchar = writer->maxchar; assert (writer->kind == PyUnicode_1BYTE_KIND); while (s < e) { ch = *s; x = mapdata_ucs1[ch]; if (x > maxchar) { if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1) goto onError; maxchar = writer->maxchar; outdata = (Py_UCS1 *)writer->data; } outdata[writer->pos] = x; writer->pos++; ++s; } return 0; } while (s < e) { if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) { enum PyUnicode_Kind outkind = writer->kind; Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata; if (outkind == PyUnicode_1BYTE_KIND) { Py_UCS1 *outdata = (Py_UCS1 *)writer->data; Py_UCS4 maxchar = writer->maxchar; while (s < e) { ch = *s; x = mapdata_ucs2[ch]; if (x > maxchar) goto Error; outdata[writer->pos] = x; writer->pos++; ++s; } break; } else if (outkind == PyUnicode_2BYTE_KIND) { Py_UCS2 *outdata = (Py_UCS2 *)writer->data; while (s < e) { ch = *s; x = mapdata_ucs2[ch]; if (x == 0xFFFE) goto Error; outdata[writer->pos] = x; writer->pos++; ++s; } break; } } ch = *s; if (ch < maplen) x = PyUnicode_READ(mapkind, mapdata, ch); else x = 0xfffe; /* invalid value */ Error: if (x == 0xfffe) { /* undefined mapping */ startinpos = s-starts; endinpos = startinpos+1; if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, "charmap", "character maps to <undefined>", &starts, &e, &startinpos, &endinpos, &exc, &s, writer)) { goto onError; } continue; } if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0) goto onError; ++s; } Py_XDECREF(errorHandler); Py_XDECREF(exc); return 0; onError: Py_XDECREF(errorHandler); Py_XDECREF(exc); return -1; } static int charmap_decode_mapping(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors, _PyUnicodeWriter *writer) { const char *starts = s; const char *e; Py_ssize_t startinpos, endinpos; PyObject *errorHandler = NULL, *exc = NULL; unsigned char ch; PyObject *key, *item = NULL; e = s + size; while (s < e) { ch = *s; /* Get mapping (char ordinal -> integer, Unicode char or None) */ key = PyLong_FromLong((long)ch); if (key == NULL) goto onError; item = PyObject_GetItem(mapping, key); Py_DECREF(key); if (item == NULL) { if (PyErr_ExceptionMatches(PyExc_LookupError)) { /* No mapping found means: mapping is undefined. */ PyErr_Clear(); goto Undefined; } else goto onError; } /* Apply mapping */ if (item == Py_None) goto Undefined; if (PyLong_Check(item)) { long value = PyLong_AS_LONG(item); if (value == 0xFFFE) goto Undefined; if (value < 0 || value > MAX_UNICODE) { PyErr_Format(PyExc_TypeError, "character mapping must be in range(0x%lx)", (unsigned long)MAX_UNICODE + 1); goto onError; } if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0) goto onError; } else if (PyUnicode_Check(item)) { if (PyUnicode_READY(item) == -1) goto onError; if (PyUnicode_GET_LENGTH(item) == 1) { Py_UCS4 value = PyUnicode_READ_CHAR(item, 0); if (value == 0xFFFE) goto Undefined; if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0) goto onError; } else { writer->overallocate = 1; if (_PyUnicodeWriter_WriteStr(writer, item) == -1) goto onError; } } else { /* wrong return value */ PyErr_SetString(PyExc_TypeError, "character mapping must return integer, None or str"); goto onError; } Py_CLEAR(item); ++s; continue; Undefined: /* undefined mapping */ Py_CLEAR(item); startinpos = s-starts; endinpos = startinpos+1; if (unicode_decode_call_errorhandler_writer( errors, &errorHandler, "charmap", "character maps to <undefined>", &starts, &e, &startinpos, &endinpos, &exc, &s, writer)) { goto onError; } } Py_XDECREF(errorHandler); Py_XDECREF(exc); return 0; onError: Py_XDECREF(item); Py_XDECREF(errorHandler); Py_XDECREF(exc); return -1; } PyObject * PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors) { _PyUnicodeWriter writer; /* Default to Latin-1 */ if (mapping == NULL) return PyUnicode_DecodeLatin1(s, size, errors); if (size == 0) _Py_RETURN_UNICODE_EMPTY(); _PyUnicodeWriter_Init(&writer); writer.min_length = size; if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1) goto onError; if (PyUnicode_CheckExact(mapping)) { if (charmap_decode_string(s, size, mapping, errors, &writer) < 0) goto onError; } else { if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0) goto onError; } return _PyUnicodeWriter_Finish(&writer); onError: _PyUnicodeWriter_Dealloc(&writer); return NULL; } /* Charmap encoding: the lookup table */ struct encoding_map { PyObject_HEAD unsigned char level1[32]; int count2, count3; unsigned char level23[1]; }; static PyObject* encoding_map_size(PyObject *obj, PyObject* args) { struct encoding_map *map = (struct encoding_map*)obj; return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 + 128*map->count3); } static PyMethodDef encoding_map_methods[] = { {"size", encoding_map_size, METH_NOARGS, PyDoc_STR("Return the size (in bytes) of this object") }, { 0 } }; static void encoding_map_dealloc(PyObject* o) { PyObject_FREE(o); } static PyTypeObject EncodingMapType = { PyVarObject_HEAD_INIT(NULL, 0) "EncodingMap", /*tp_name*/ sizeof(struct encoding_map), /*tp_basicsize*/ 0, /*tp_itemsize*/ /* methods */ encoding_map_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ encoding_map_methods, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ 0, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ }; PyObject* PyUnicode_BuildEncodingMap(PyObject* string) { PyObject *result; struct encoding_map *mresult; int i; int need_dict = 0; unsigned char level1[32]; unsigned char level2[512]; unsigned char *mlevel1, *mlevel2, *mlevel3; int count2 = 0, count3 = 0; int kind; void *data; Py_ssize_t length; Py_UCS4 ch; if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) { PyErr_BadArgument(); return NULL; } kind = PyUnicode_KIND(string); data = PyUnicode_DATA(string); length = PyUnicode_GET_LENGTH(string); length = Py_MIN(length, 256); memset(level1, 0xFF, sizeof level1); memset(level2, 0xFF, sizeof level2); /* If there isn't a one-to-one mapping of NULL to \0, or if there are non-BMP characters, we need to use a mapping dictionary. */ if (PyUnicode_READ(kind, data, 0) != 0) need_dict = 1; for (i = 1; i < length; i++) { int l1, l2; ch = PyUnicode_READ(kind, data, i); if (ch == 0 || ch > 0xFFFF) { need_dict = 1; break; } if (ch == 0xFFFE) /* unmapped character */ continue; l1 = ch >> 11; l2 = ch >> 7; if (level1[l1] == 0xFF) level1[l1] = count2++; if (level2[l2] == 0xFF) level2[l2] = count3++; } if (count2 >= 0xFF || count3 >= 0xFF) need_dict = 1; if (need_dict) { PyObject *result = PyDict_New(); PyObject *key, *value; if (!result) return NULL; for (i = 0; i < length; i++) { key = PyLong_FromLong(PyUnicode_READ(kind, data, i)); value = PyLong_FromLong(i); if (!key || !value) goto failed1; if (PyDict_SetItem(result, key, value) == -1) goto failed1; Py_DECREF(key); Py_DECREF(value); } return result; failed1: Py_XDECREF(key); Py_XDECREF(value); Py_DECREF(result); return NULL; } /* Create a three-level trie */ result = PyObject_MALLOC(sizeof(struct encoding_map) + 16*count2 + 128*count3 - 1); if (!result) return PyErr_NoMemory(); PyObject_Init(result, &EncodingMapType); mresult = (struct encoding_map*)result; mresult->count2 = count2; mresult->count3 = count3; mlevel1 = mresult->level1; mlevel2 = mresult->level23; mlevel3 = mresult->level23 + 16*count2; memcpy(mlevel1, level1, 32); memset(mlevel2, 0xFF, 16*count2); bzero(mlevel3, 128*count3); count3 = 0; for (i = 1; i < length; i++) { int o1, o2, o3, i2, i3; Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (ch == 0xFFFE) /* unmapped character */ continue; o1 = ch>>11; o2 = (ch>>7) & 0xF; i2 = 16*mlevel1[o1] + o2; if (mlevel2[i2] == 0xFF) mlevel2[i2] = count3++; o3 = ch & 0x7F; i3 = 128*mlevel2[i2] + o3; mlevel3[i3] = i; } return result; } static int encoding_map_lookup(Py_UCS4 c, PyObject *mapping) { struct encoding_map *map = (struct encoding_map*)mapping; int l1 = c>>11; int l2 = (c>>7) & 0xF; int l3 = c & 0x7F; int i; if (c > 0xFFFF) return -1; if (c == 0) return 0; /* level 1*/ i = map->level1[l1]; if (i == 0xFF) { return -1; } /* level 2*/ i = map->level23[16*i+l2]; if (i == 0xFF) { return -1; } /* level 3 */ i = map->level23[16*map->count2 + 128*i + l3]; if (i == 0) { return -1; } return i; } /* Lookup the character ch in the mapping. If the character can't be found, Py_None is returned (or NULL, if another error occurred). */ static PyObject * charmapencode_lookup(Py_UCS4 c, PyObject *mapping) { PyObject *w = PyLong_FromLong((long)c); PyObject *x; if (w == NULL) return NULL; x = PyObject_GetItem(mapping, w); Py_DECREF(w); if (x == NULL) { if (PyErr_ExceptionMatches(PyExc_LookupError)) { /* No mapping found means: mapping is undefined. */ PyErr_Clear(); x = Py_None; Py_INCREF(x); return x; } else return NULL; } else if (x == Py_None) return x; else if (PyLong_Check(x)) { long value = PyLong_AS_LONG(x); if (value < 0 || value > 255) { PyErr_SetString(PyExc_TypeError, "character mapping must be in range(256)"); Py_DECREF(x); return NULL; } return x; } else if (PyBytes_Check(x)) return x; else { /* wrong return value */ PyErr_Format(PyExc_TypeError, "character mapping must return integer, bytes or None, not %.400s", x->ob_type->tp_name); Py_DECREF(x); return NULL; } } static int charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize) { Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj); /* exponentially overallocate to minimize reallocations */ if (requiredsize < 2*outsize) requiredsize = 2*outsize; if (_PyBytes_Resize(outobj, requiredsize)) return -1; return 0; } typedef enum charmapencode_result { enc_SUCCESS, enc_FAILED, enc_EXCEPTION } charmapencode_result; /* lookup the character, put the result in the output string and adjust various state variables. Resize the output bytes object if not enough space is available. Return a new reference to the object that was put in the output buffer, or Py_None, if the mapping was undefined (in which case no character was written) or NULL, if a reallocation error occurred. The caller must decref the result */ static charmapencode_result charmapencode_output(Py_UCS4 c, PyObject *mapping, PyObject **outobj, Py_ssize_t *outpos) { PyObject *rep; char *outstart; Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj); if (Py_TYPE(mapping) == &EncodingMapType) { int res = encoding_map_lookup(c, mapping); Py_ssize_t requiredsize = *outpos+1; if (res == -1) return enc_FAILED; if (outsize<requiredsize) if (charmapencode_resize(outobj, outpos, requiredsize)) return enc_EXCEPTION; outstart = PyBytes_AS_STRING(*outobj); outstart[(*outpos)++] = (char)res; return enc_SUCCESS; } rep = charmapencode_lookup(c, mapping); if (rep==NULL) return enc_EXCEPTION; else if (rep==Py_None) { Py_DECREF(rep); return enc_FAILED; } else { if (PyLong_Check(rep)) { Py_ssize_t requiredsize = *outpos+1; if (outsize<requiredsize) if (charmapencode_resize(outobj, outpos, requiredsize)) { Py_DECREF(rep); return enc_EXCEPTION; } outstart = PyBytes_AS_STRING(*outobj); outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep); } else { const char *repchars = PyBytes_AS_STRING(rep); Py_ssize_t repsize = PyBytes_GET_SIZE(rep); Py_ssize_t requiredsize = *outpos+repsize; if (outsize<requiredsize) if (charmapencode_resize(outobj, outpos, requiredsize)) { Py_DECREF(rep); return enc_EXCEPTION; } outstart = PyBytes_AS_STRING(*outobj); memcpy(outstart + *outpos, repchars, repsize); *outpos += repsize; } } Py_DECREF(rep); return enc_SUCCESS; } /* handle an error in PyUnicode_EncodeCharmap Return 0 on success, -1 on error */ static int charmap_encoding_error( PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping, PyObject **exceptionObject, _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors, PyObject **res, Py_ssize_t *respos) { PyObject *repunicode = NULL; /* initialize to prevent gcc warning */ Py_ssize_t size, repsize; Py_ssize_t newpos; enum PyUnicode_Kind kind; void *data; Py_ssize_t index; /* startpos for collecting unencodable chars */ Py_ssize_t collstartpos = *inpos; Py_ssize_t collendpos = *inpos+1; Py_ssize_t collpos; char *encoding = "charmap"; char *reason = "character maps to <undefined>"; charmapencode_result x; Py_UCS4 ch; int val; if (PyUnicode_READY(unicode) == -1) return -1; size = PyUnicode_GET_LENGTH(unicode); /* find all unencodable characters */ while (collendpos < size) { PyObject *rep; if (Py_TYPE(mapping) == &EncodingMapType) { ch = PyUnicode_READ_CHAR(unicode, collendpos); val = encoding_map_lookup(ch, mapping); if (val != -1) break; ++collendpos; continue; } ch = PyUnicode_READ_CHAR(unicode, collendpos); rep = charmapencode_lookup(ch, mapping); if (rep==NULL) return -1; else if (rep!=Py_None) { Py_DECREF(rep); break; } Py_DECREF(rep); ++collendpos; } /* cache callback name lookup * (if not done yet, i.e. it's the first error) */ if (*error_handler == _Py_ERROR_UNKNOWN) *error_handler = get_error_handler(errors); switch (*error_handler) { case _Py_ERROR_STRICT: raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason); return -1; case _Py_ERROR_REPLACE: for (collpos = collstartpos; collpos<collendpos; ++collpos) { x = charmapencode_output('?', mapping, res, respos); if (x==enc_EXCEPTION) { return -1; } else if (x==enc_FAILED) { raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason); return -1; } } /* fall through */ case _Py_ERROR_IGNORE: *inpos = collendpos; break; case _Py_ERROR_XMLCHARREFREPLACE: /* generate replacement (temporarily (mis)uses p) */ for (collpos = collstartpos; collpos < collendpos; ++collpos) { char buffer[2+29+1+1]; char *cp; sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos)); for (cp = buffer; *cp; ++cp) { x = charmapencode_output(*cp, mapping, res, respos); if (x==enc_EXCEPTION) return -1; else if (x==enc_FAILED) { raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason); return -1; } } } *inpos = collendpos; break; default: repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj, encoding, reason, unicode, exceptionObject, collstartpos, collendpos, &newpos); if (repunicode == NULL) return -1; if (PyBytes_Check(repunicode)) { /* Directly copy bytes result to output. */ Py_ssize_t outsize = PyBytes_Size(*res); Py_ssize_t requiredsize; repsize = PyBytes_Size(repunicode); requiredsize = *respos + repsize; if (requiredsize > outsize) /* Make room for all additional bytes. */ if (charmapencode_resize(res, respos, requiredsize)) { Py_DECREF(repunicode); return -1; } memcpy(PyBytes_AsString(*res) + *respos, PyBytes_AsString(repunicode), repsize); *respos += repsize; *inpos = newpos; Py_DECREF(repunicode); break; } /* generate replacement */ if (PyUnicode_READY(repunicode) == -1) { Py_DECREF(repunicode); return -1; } repsize = PyUnicode_GET_LENGTH(repunicode); data = PyUnicode_DATA(repunicode); kind = PyUnicode_KIND(repunicode); for (index = 0; index < repsize; index++) { Py_UCS4 repch = PyUnicode_READ(kind, data, index); x = charmapencode_output(repch, mapping, res, respos); if (x==enc_EXCEPTION) { Py_DECREF(repunicode); return -1; } else if (x==enc_FAILED) { Py_DECREF(repunicode); raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason); return -1; } } *inpos = newpos; Py_DECREF(repunicode); } return 0; } PyObject * _PyUnicode_EncodeCharmap(PyObject *unicode, PyObject *mapping, const char *errors) { /* output object */ PyObject *res = NULL; /* current input position */ Py_ssize_t inpos = 0; Py_ssize_t size; /* current output position */ Py_ssize_t respos = 0; PyObject *error_handler_obj = NULL; PyObject *exc = NULL; _Py_error_handler error_handler = _Py_ERROR_UNKNOWN; void *data; int kind; if (PyUnicode_READY(unicode) == -1) return NULL; size = PyUnicode_GET_LENGTH(unicode); data = PyUnicode_DATA(unicode); kind = PyUnicode_KIND(unicode); /* Default to Latin-1 */ if (mapping == NULL) return unicode_encode_ucs1(unicode, errors, 256); /* allocate enough for a simple encoding without replacements, if we need more, we'll resize */ res = PyBytes_FromStringAndSize(NULL, size); if (res == NULL) goto onError; if (size == 0) return res; while (inpos<size) { Py_UCS4 ch = PyUnicode_READ(kind, data, inpos); /* try to encode it */ charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos); if (x==enc_EXCEPTION) /* error */ goto onError; if (x==enc_FAILED) { /* unencodable character */ if (charmap_encoding_error(unicode, &inpos, mapping, &exc, &error_handler, &error_handler_obj, errors, &res, &respos)) { goto onError; } } else /* done with this character => adjust input position */ ++inpos; } /* Resize if we allocated to much */ if (respos<PyBytes_GET_SIZE(res)) if (_PyBytes_Resize(&res, respos) < 0) goto onError; Py_XDECREF(exc); Py_XDECREF(error_handler_obj); return res; onError: Py_XDECREF(res); Py_XDECREF(exc); Py_XDECREF(error_handler_obj); return NULL; } PyObject * PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping) { if (!PyUnicode_Check(unicode) || mapping == NULL) { PyErr_BadArgument(); return NULL; } return _PyUnicode_EncodeCharmap(unicode, mapping, NULL); } /* create or adjust a UnicodeTranslateError */ static void make_translate_exception(PyObject **exceptionObject, PyObject *unicode, Py_ssize_t startpos, Py_ssize_t endpos, const char *reason) { if (*exceptionObject == NULL) { *exceptionObject = _PyUnicodeTranslateError_Create( unicode, startpos, endpos, reason); } else { if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos)) goto onError; if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos)) goto onError; if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason)) goto onError; return; onError: Py_CLEAR(*exceptionObject); } } /* error handling callback helper: build arguments, call the callback and check the arguments, put the result into newpos and return the replacement string, which has to be freed by the caller */ static PyObject * unicode_translate_call_errorhandler(const char *errors, PyObject **errorHandler, const char *reason, PyObject *unicode, PyObject **exceptionObject, Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos) { static const char *argparse = "O!n;translating error handler must return (str, int) tuple"; Py_ssize_t i_newpos; PyObject *restuple; PyObject *resunicode; if (*errorHandler == NULL) { *errorHandler = PyCodec_LookupError(errors); if (*errorHandler == NULL) return NULL; } make_translate_exception(exceptionObject, unicode, startpos, endpos, reason); if (*exceptionObject == NULL) return NULL; restuple = PyObject_CallFunctionObjArgs( *errorHandler, *exceptionObject, NULL); if (restuple == NULL) return NULL; if (!PyTuple_Check(restuple)) { PyErr_SetString(PyExc_TypeError, &argparse[4]); Py_DECREF(restuple); return NULL; } if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &resunicode, &i_newpos)) { Py_DECREF(restuple); return NULL; } if (i_newpos<0) *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos; else *newpos = i_newpos; if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) { PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos); Py_DECREF(restuple); return NULL; } Py_INCREF(resunicode); Py_DECREF(restuple); return resunicode; } /* Lookup the character ch in the mapping and put the result in result, which must be decrefed by the caller. Return 0 on success, -1 on error */ static int charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result) { PyObject *w = PyLong_FromLong((long)c); PyObject *x; if (w == NULL) return -1; x = PyObject_GetItem(mapping, w); Py_DECREF(w); if (x == NULL) { if (PyErr_ExceptionMatches(PyExc_LookupError)) { /* No mapping found means: use 1:1 mapping. */ PyErr_Clear(); *result = NULL; return 0; } else return -1; } else if (x == Py_None) { *result = x; return 0; } else if (PyLong_Check(x)) { long value = PyLong_AS_LONG(x); if (value < 0 || value > MAX_UNICODE) { PyErr_Format(PyExc_ValueError, "character mapping must be in range(0x%x)", MAX_UNICODE+1); Py_DECREF(x); return -1; } *result = x; return 0; } else if (PyUnicode_Check(x)) { *result = x; return 0; } else { /* wrong return value */ PyErr_SetString(PyExc_TypeError, "character mapping must return integer, None or str"); Py_DECREF(x); return -1; } } /* lookup the character, write the result into the writer. Return 1 if the result was written into the writer, return 0 if the mapping was undefined, raise an exception return -1 on error. */ static int charmaptranslate_output(Py_UCS4 ch, PyObject *mapping, _PyUnicodeWriter *writer) { PyObject *item; if (charmaptranslate_lookup(ch, mapping, &item)) return -1; if (item == NULL) { /* not found => default to 1:1 mapping */ if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) { return -1; } return 1; } if (item == Py_None) { Py_DECREF(item); return 0; } if (PyLong_Check(item)) { long ch = (Py_UCS4)PyLong_AS_LONG(item); /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already used it */ if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) { Py_DECREF(item); return -1; } Py_DECREF(item); return 1; } if (!PyUnicode_Check(item)) { Py_DECREF(item); return -1; } if (_PyUnicodeWriter_WriteStr(writer, item) < 0) { Py_DECREF(item); return -1; } Py_DECREF(item); return 1; } static int unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch, Py_UCS1 *translate) { PyObject *item = NULL; int ret = 0; if (charmaptranslate_lookup(ch, mapping, &item)) { return -1; } if (item == Py_None) { /* deletion */ translate[ch] = 0xfe; } else if (item == NULL) { /* not found => default to 1:1 mapping */ translate[ch] = ch; return 1; } else if (PyLong_Check(item)) { long replace = PyLong_AS_LONG(item); /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already used it */ if (127 < replace) { /* invalid character or character outside ASCII: skip the fast translate */ goto exit; } translate[ch] = (Py_UCS1)replace; } else if (PyUnicode_Check(item)) { Py_UCS4 replace; if (PyUnicode_READY(item) == -1) { Py_DECREF(item); return -1; } if (PyUnicode_GET_LENGTH(item) != 1) goto exit; replace = PyUnicode_READ_CHAR(item, 0); if (replace > 127) goto exit; translate[ch] = (Py_UCS1)replace; } else { /* not None, NULL, long or unicode */ goto exit; } ret = 1; exit: Py_DECREF(item); return ret; } /* Fast path for ascii => ascii translation. Return 1 if the whole string was translated into writer, return 0 if the input string was partially translated into writer, raise an exception and return -1 on error. */ static int unicode_fast_translate(PyObject *input, PyObject *mapping, _PyUnicodeWriter *writer, int ignore, Py_ssize_t *input_pos) { Py_UCS1 ascii_table[128], ch, ch2; Py_ssize_t len; Py_UCS1 *in, *end, *out; int res = 0; len = PyUnicode_GET_LENGTH(input); memset(ascii_table, 0xff, 128); in = PyUnicode_1BYTE_DATA(input); end = in + len; assert(PyUnicode_IS_ASCII(writer->buffer)); assert(PyUnicode_GET_LENGTH(writer->buffer) == len); out = PyUnicode_1BYTE_DATA(writer->buffer); for (; in < end; in++) { ch = *in; ch2 = ascii_table[ch]; if (ch2 == 0xff) { int translate = unicode_fast_translate_lookup(mapping, ch, ascii_table); if (translate < 0) return -1; if (translate == 0) goto exit; ch2 = ascii_table[ch]; } if (ch2 == 0xfe) { if (ignore) continue; goto exit; } assert(ch2 < 128); *out = ch2; out++; } res = 1; exit: writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer); *input_pos = in - PyUnicode_1BYTE_DATA(input); return res; } PyObject * _PyUnicode_TranslateCharmap(PyObject *input, PyObject *mapping, const char *errors) { /* input object */ char *data; Py_ssize_t size, i; int kind; /* output buffer */ _PyUnicodeWriter writer; /* error handler */ char *reason = "character maps to <undefined>"; PyObject *errorHandler = NULL; PyObject *exc = NULL; int ignore; int res; if (mapping == NULL) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(input) == -1) return NULL; data = (char*)PyUnicode_DATA(input); kind = PyUnicode_KIND(input); size = PyUnicode_GET_LENGTH(input); if (size == 0) return PyUnicode_FromObject(input); /* allocate enough for a simple 1:1 translation without replacements, if we need more, we'll resize */ _PyUnicodeWriter_Init(&writer); if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1) goto onError; ignore = (errors != NULL && strcmp(errors, "ignore") == 0); if (PyUnicode_READY(input) == -1) return NULL; if (PyUnicode_IS_ASCII(input)) { res = unicode_fast_translate(input, mapping, &writer, ignore, &i); if (res < 0) { _PyUnicodeWriter_Dealloc(&writer); return NULL; } if (res == 1) return _PyUnicodeWriter_Finish(&writer); } else { i = 0; } while (i<size) { /* try to encode it */ int translate; PyObject *repunicode = NULL; /* initialize to prevent gcc warning */ Py_ssize_t newpos; /* startpos for collecting untranslatable chars */ Py_ssize_t collstart; Py_ssize_t collend; Py_UCS4 ch; ch = PyUnicode_READ(kind, data, i); translate = charmaptranslate_output(ch, mapping, &writer); if (translate < 0) goto onError; if (translate != 0) { /* it worked => adjust input pointer */ ++i; continue; } /* untranslatable character */ collstart = i; collend = i+1; /* find all untranslatable characters */ while (collend < size) { PyObject *x; ch = PyUnicode_READ(kind, data, collend); if (charmaptranslate_lookup(ch, mapping, &x)) goto onError; Py_XDECREF(x); if (x != Py_None) break; ++collend; } if (ignore) { i = collend; } else { repunicode = unicode_translate_call_errorhandler(errors, &errorHandler, reason, input, &exc, collstart, collend, &newpos); if (repunicode == NULL) goto onError; if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) { Py_DECREF(repunicode); goto onError; } Py_DECREF(repunicode); i = newpos; } } Py_XDECREF(exc); Py_XDECREF(errorHandler); return _PyUnicodeWriter_Finish(&writer); onError: _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(exc); Py_XDECREF(errorHandler); return NULL; } PyObject * PyUnicode_Translate(PyObject *str, PyObject *mapping, const char *errors) { if (ensure_unicode(str) < 0) return NULL; return _PyUnicode_TranslateCharmap(str, mapping, errors); } static Py_UCS4 fix_decimal_and_space_to_ascii(PyObject *self) { /* No need to call PyUnicode_READY(self) because this function is only called as a callback from fixup() which does it already. */ const Py_ssize_t len = PyUnicode_GET_LENGTH(self); const int kind = PyUnicode_KIND(self); void *data = PyUnicode_DATA(self); Py_UCS4 maxchar = 127, ch, fixed; int modified = 0; Py_ssize_t i; for (i = 0; i < len; ++i) { ch = PyUnicode_READ(kind, data, i); fixed = 0; if (ch > 127) { if (Py_UNICODE_ISSPACE(ch)) fixed = ' '; else { const int decimal = Py_UNICODE_TODECIMAL(ch); if (decimal >= 0) fixed = '0' + decimal; } if (fixed != 0) { modified = 1; maxchar = Py_MAX(maxchar, fixed); PyUnicode_WRITE(kind, data, i, fixed); } else maxchar = Py_MAX(maxchar, ch); } } return (modified) ? maxchar : 0; } PyObject * _PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode) { if (!PyUnicode_Check(unicode)) { PyErr_BadInternalCall(); return NULL; } if (PyUnicode_READY(unicode) == -1) return NULL; if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) { /* If the string is already ASCII, just return the same string */ Py_INCREF(unicode); return unicode; } return fixup(unicode, fix_decimal_and_space_to_ascii); } PyObject * PyUnicode_TransformDecimalToASCII(Py_UNICODE *s, Py_ssize_t length) { PyObject *decimal; Py_ssize_t i; Py_UCS4 maxchar; enum PyUnicode_Kind kind; void *data; maxchar = 127; for (i = 0; i < length; i++) { Py_UCS4 ch = s[i]; if (ch > 127) { int decimal = Py_UNICODE_TODECIMAL(ch); if (decimal >= 0) ch = '0' + decimal; maxchar = Py_MAX(maxchar, ch); } } /* Copy to a new string */ decimal = PyUnicode_New(length, maxchar); if (decimal == NULL) return decimal; kind = PyUnicode_KIND(decimal); data = PyUnicode_DATA(decimal); /* Iterate over code points */ for (i = 0; i < length; i++) { Py_UCS4 ch = s[i]; if (ch > 127) { int decimal = Py_UNICODE_TODECIMAL(ch); if (decimal >= 0) ch = '0' + decimal; } PyUnicode_WRITE(kind, data, i, ch); } return unicode_result(decimal); } /* --- Decimal Encoder ---------------------------------------------------- */ int PyUnicode_EncodeDecimal(Py_UNICODE *s, Py_ssize_t length, char *output, const char *errors) { PyObject *unicode; Py_ssize_t i; enum PyUnicode_Kind kind; void *data; if (output == NULL) { PyErr_BadArgument(); return -1; } unicode = PyUnicode_FromUnicode(s, length); if (unicode == NULL) return -1; if (PyUnicode_READY(unicode) == -1) { Py_DECREF(unicode); return -1; } kind = PyUnicode_KIND(unicode); data = PyUnicode_DATA(unicode); for (i=0; i < length; ) { PyObject *exc; Py_UCS4 ch; int decimal; Py_ssize_t startpos; ch = PyUnicode_READ(kind, data, i); if (Py_UNICODE_ISSPACE(ch)) { *output++ = ' '; i++; continue; } decimal = Py_UNICODE_TODECIMAL(ch); if (decimal >= 0) { *output++ = '0' + decimal; i++; continue; } if (0 < ch && ch < 256) { *output++ = (char)ch; i++; continue; } startpos = i; exc = NULL; raise_encode_exception(&exc, "decimal", unicode, startpos, startpos+1, "invalid decimal Unicode string"); Py_XDECREF(exc); Py_DECREF(unicode); return -1; } /* 0-terminate the output string */ *output++ = '\0'; Py_DECREF(unicode); return 0; } /* --- Helpers ------------------------------------------------------------ */ /* helper macro to fixup start/end slice values */ #define ADJUST_INDICES(start, end, len) \ if (end > len) \ end = len; \ else if (end < 0) { \ end += len; \ if (end < 0) \ end = 0; \ } \ if (start < 0) { \ start += len; \ if (start < 0) \ start = 0; \ } static Py_ssize_t any_find_slice(PyObject* s1, PyObject* s2, Py_ssize_t start, Py_ssize_t end, int direction) { int kind1, kind2; void *buf1, *buf2; Py_ssize_t len1, len2, result; kind1 = PyUnicode_KIND(s1); kind2 = PyUnicode_KIND(s2); if (kind1 < kind2) return -1; len1 = PyUnicode_GET_LENGTH(s1); len2 = PyUnicode_GET_LENGTH(s2); ADJUST_INDICES(start, end, len1); if (end - start < len2) return -1; buf1 = PyUnicode_DATA(s1); buf2 = PyUnicode_DATA(s2); if (len2 == 1) { Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0); result = findchar((const char *)buf1 + kind1*start, kind1, end - start, ch, direction); if (result == -1) return -1; else return start + result; } if (kind2 != kind1) { buf2 = _PyUnicode_AsKind(s2, kind1); if (!buf2) return -2; } if (direction > 0) { switch (kind1) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2)) result = asciilib_find_slice(buf1, len1, buf2, len2, start, end); else result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end); break; case PyUnicode_2BYTE_KIND: result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end); break; case PyUnicode_4BYTE_KIND: result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end); break; default: assert(0); result = -2; } } else { switch (kind1) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2)) result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end); else result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end); break; case PyUnicode_2BYTE_KIND: result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end); break; case PyUnicode_4BYTE_KIND: result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end); break; default: assert(0); result = -2; } } if (kind2 != kind1) PyMem_Free(buf2); return result; } /* _PyUnicode_InsertThousandsGrouping() helper functions */ #include "third_party/python/Objects/stringlib/localeutil.inc" /** * InsertThousandsGrouping: * @writer: Unicode writer. * @n_buffer: Number of characters in @buffer. * @digits: Digits we're reading from. If count is non-NULL, this is unused. * @d_pos: Start of digits string. * @n_digits: The number of digits in the string, in which we want * to put the grouping chars. * @min_width: The minimum width of the digits in the output string. * Output will be zero-padded on the left to fill. * @grouping: see definition in localeconv(). * @thousands_sep: see definition in localeconv(). * * There are 2 modes: counting and filling. If @writer is NULL, * we are in counting mode, else filling mode. * If counting, the required buffer size is returned. * If filling, we know the buffer will be large enough, so we don't * need to pass in the buffer size. * Inserts thousand grouping characters (as defined by grouping and * thousands_sep) into @writer. * * Return value: -1 on error, number of characters otherwise. **/ Py_ssize_t _PyUnicode_InsertThousandsGrouping( _PyUnicodeWriter *writer, Py_ssize_t n_buffer, PyObject *digits, Py_ssize_t d_pos, Py_ssize_t n_digits, Py_ssize_t min_width, const char *grouping, PyObject *thousands_sep, Py_UCS4 *maxchar) { min_width = Py_MAX(0, min_width); if (writer) { assert(digits != NULL); assert(maxchar == NULL); } else { assert(digits == NULL); assert(maxchar != NULL); } assert(0 <= d_pos); assert(0 <= n_digits); assert(grouping != NULL); if (digits != NULL) { if (PyUnicode_READY(digits) == -1) { return -1; } } if (PyUnicode_READY(thousands_sep) == -1) { return -1; } Py_ssize_t count = 0; Py_ssize_t n_zeros; int loop_broken = 0; int use_separator = 0; /* First time through, don't append the separator. They only go between groups. */ Py_ssize_t buffer_pos; Py_ssize_t digits_pos; Py_ssize_t len; Py_ssize_t n_chars; Py_ssize_t remaining = n_digits; /* Number of chars remaining to be looked at */ /* A generator that returns all of the grouping widths, until it returns 0. */ GroupGenerator groupgen; GroupGenerator_init(&groupgen, grouping); const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep); /* if digits are not grouped, thousands separator should be an empty string */ assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0)); digits_pos = d_pos + n_digits; if (writer) { buffer_pos = writer->pos + n_buffer; assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer)); assert(digits_pos <= PyUnicode_GET_LENGTH(digits)); } else { buffer_pos = n_buffer; } if (!writer) { *maxchar = 127; } while ((len = GroupGenerator_next(&groupgen)) > 0) { len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1)); n_zeros = Py_MAX(0, len - remaining); n_chars = Py_MAX(0, Py_MIN(remaining, len)); /* Use n_zero zero's and n_chars chars */ /* Count only, don't do anything. */ count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars; /* Copy into the writer. */ InsertThousandsGrouping_fill(writer, &buffer_pos, digits, &digits_pos, n_chars, n_zeros, use_separator ? thousands_sep : NULL, thousands_sep_len, maxchar); /* Use a separator next time. */ use_separator = 1; remaining -= n_chars; min_width -= len; if (remaining <= 0 && min_width <= 0) { loop_broken = 1; break; } min_width -= thousands_sep_len; } if (!loop_broken) { /* We left the loop without using a break statement. */ len = Py_MAX(Py_MAX(remaining, min_width), 1); n_zeros = Py_MAX(0, len - remaining); n_chars = Py_MAX(0, Py_MIN(remaining, len)); /* Use n_zero zero's and n_chars chars */ count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars; /* Copy into the writer. */ InsertThousandsGrouping_fill(writer, &buffer_pos, digits, &digits_pos, n_chars, n_zeros, use_separator ? thousands_sep : NULL, thousands_sep_len, maxchar); } return count; } Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end) { Py_ssize_t result; int kind1, kind2; void *buf1 = NULL, *buf2 = NULL; Py_ssize_t len1, len2; if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0) return -1; kind1 = PyUnicode_KIND(str); kind2 = PyUnicode_KIND(substr); if (kind1 < kind2) return 0; len1 = PyUnicode_GET_LENGTH(str); len2 = PyUnicode_GET_LENGTH(substr); ADJUST_INDICES(start, end, len1); if (end - start < len2) return 0; buf1 = PyUnicode_DATA(str); buf2 = PyUnicode_DATA(substr); if (kind2 != kind1) { buf2 = _PyUnicode_AsKind(substr, kind1); if (!buf2) goto onError; } switch (kind1) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr)) result = asciilib_count( ((Py_UCS1*)buf1) + start, end - start, buf2, len2, PY_SSIZE_T_MAX ); else result = ucs1lib_count( ((Py_UCS1*)buf1) + start, end - start, buf2, len2, PY_SSIZE_T_MAX ); break; case PyUnicode_2BYTE_KIND: result = ucs2lib_count( ((Py_UCS2*)buf1) + start, end - start, buf2, len2, PY_SSIZE_T_MAX ); break; case PyUnicode_4BYTE_KIND: result = ucs4lib_count( ((Py_UCS4*)buf1) + start, end - start, buf2, len2, PY_SSIZE_T_MAX ); break; default: assert(0); result = 0; } if (kind2 != kind1) PyMem_Free(buf2); return result; onError: if (kind2 != kind1 && buf2) PyMem_Free(buf2); return -1; } Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) { if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0) return -2; return any_find_slice(str, substr, start, end, direction); } Py_ssize_t PyUnicode_FindChar(PyObject *str, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction) { int kind; Py_ssize_t result; if (PyUnicode_READY(str) == -1) return -2; if (start < 0 || end < 0) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return -2; } if (end > PyUnicode_GET_LENGTH(str)) end = PyUnicode_GET_LENGTH(str); if (start >= end) return -1; kind = PyUnicode_KIND(str); result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start, kind, end-start, ch, direction); if (result == -1) return -1; else return start + result; } static int tailmatch(PyObject *self, PyObject *substring, Py_ssize_t start, Py_ssize_t end, int direction) { int kind_self; int kind_sub; void *data_self; void *data_sub; Py_ssize_t offset; Py_ssize_t i; Py_ssize_t end_sub; if (PyUnicode_READY(self) == -1 || PyUnicode_READY(substring) == -1) return -1; ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self)); end -= PyUnicode_GET_LENGTH(substring); if (end < start) return 0; if (PyUnicode_GET_LENGTH(substring) == 0) return 1; kind_self = PyUnicode_KIND(self); data_self = PyUnicode_DATA(self); kind_sub = PyUnicode_KIND(substring); data_sub = PyUnicode_DATA(substring); end_sub = PyUnicode_GET_LENGTH(substring) - 1; if (direction > 0) offset = end; else offset = start; if (PyUnicode_READ(kind_self, data_self, offset) == PyUnicode_READ(kind_sub, data_sub, 0) && PyUnicode_READ(kind_self, data_self, offset + end_sub) == PyUnicode_READ(kind_sub, data_sub, end_sub)) { /* If both are of the same kind, memcmp is sufficient */ if (kind_self == kind_sub) { return !bcmp((char *)data_self + (offset * PyUnicode_KIND(substring)), data_sub, PyUnicode_GET_LENGTH(substring) * PyUnicode_KIND(substring)); } /* otherwise we have to compare each character by first accessing it */ else { /* We do not need to compare 0 and len(substring)-1 because the if statement above ensured already that they are equal when we end up here. */ for (i = 1; i < end_sub; ++i) { if (PyUnicode_READ(kind_self, data_self, offset + i) != PyUnicode_READ(kind_sub, data_sub, i)) return 0; } return 1; } } return 0; } Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) { if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0) return -1; return tailmatch(str, substr, start, end, direction); } /* Apply fixfct filter to the Unicode object self and return a reference to the modified object */ static PyObject * fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s)) { PyObject *u; Py_UCS4 maxchar_old, maxchar_new = 0; PyObject *v; u = _PyUnicode_Copy(self); if (u == NULL) return NULL; maxchar_old = PyUnicode_MAX_CHAR_VALUE(u); /* fix functions return the new maximum character in a string, if the kind of the resulting unicode object does not change, everything is fine. Otherwise we need to change the string kind and re-run the fix function. */ maxchar_new = fixfct(u); if (maxchar_new == 0) { /* no changes */; if (PyUnicode_CheckExact(self)) { Py_DECREF(u); Py_INCREF(self); return self; } else return u; } maxchar_new = align_maxchar(maxchar_new); if (maxchar_new == maxchar_old) return u; /* In case the maximum character changed, we need to convert the string to the new category. */ v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new); if (v == NULL) { Py_DECREF(u); return NULL; } if (maxchar_new > maxchar_old) { /* If the maxchar increased so that the kind changed, not all characters are representable anymore and we need to fix the string again. This only happens in very few cases. */ _PyUnicode_FastCopyCharacters(v, 0, self, 0, PyUnicode_GET_LENGTH(self)); maxchar_old = fixfct(v); assert(maxchar_old > 0 && maxchar_old <= maxchar_new); } else { _PyUnicode_FastCopyCharacters(v, 0, u, 0, PyUnicode_GET_LENGTH(self)); } Py_DECREF(u); assert(_PyUnicode_CheckConsistency(v, 1)); return v; } static PyObject * ascii_upper_or_lower(PyObject *self, int lower) { Py_ssize_t len = PyUnicode_GET_LENGTH(self); char *resdata, *data = PyUnicode_DATA(self); PyObject *res; res = PyUnicode_New(len, 127); if (res == NULL) return NULL; resdata = PyUnicode_DATA(res); if (lower) _Py_bytes_lower(resdata, data, len); else _Py_bytes_upper(resdata, data, len); return res; } static Py_UCS4 handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i) { Py_ssize_t j; int final_sigma; Py_UCS4 c = 0; /* initialize to prevent gcc warning */ /* U+03A3 is in the Final_Sigma context when, it is found like this: \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased}) where ! is a negation and \p{xxx} is a character with property xxx. */ for (j = i - 1; j >= 0; j--) { c = PyUnicode_READ(kind, data, j); if (!_PyUnicode_IsCaseIgnorable(c)) break; } final_sigma = j >= 0 && _PyUnicode_IsCased(c); if (final_sigma) { for (j = i + 1; j < length; j++) { c = PyUnicode_READ(kind, data, j); if (!_PyUnicode_IsCaseIgnorable(c)) break; } final_sigma = j == length || !_PyUnicode_IsCased(c); } return (final_sigma) ? 0x3C2 : 0x3C3; } static int lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i, Py_UCS4 c, Py_UCS4 *mapped) { /* Obscure special case. */ if (c == 0x3A3) { mapped[0] = handle_capital_sigma(kind, data, length, i); return 1; } return _PyUnicode_ToLowerFull(c, mapped); } static Py_ssize_t do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) { Py_ssize_t i, k = 0; int n_res, j; Py_UCS4 c, mapped[3]; c = PyUnicode_READ(kind, data, 0); n_res = _PyUnicode_ToUpperFull(c, mapped); for (j = 0; j < n_res; j++) { *maxchar = Py_MAX(*maxchar, mapped[j]); res[k++] = mapped[j]; } for (i = 1; i < length; i++) { c = PyUnicode_READ(kind, data, i); n_res = lower_ucs4(kind, data, length, i, c, mapped); for (j = 0; j < n_res; j++) { *maxchar = Py_MAX(*maxchar, mapped[j]); res[k++] = mapped[j]; } } return k; } static Py_ssize_t do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) { Py_ssize_t i, k = 0; for (i = 0; i < length; i++) { Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3]; int n_res, j; if (Py_UNICODE_ISUPPER(c)) { n_res = lower_ucs4(kind, data, length, i, c, mapped); } else if (Py_UNICODE_ISLOWER(c)) { n_res = _PyUnicode_ToUpperFull(c, mapped); } else { n_res = 1; mapped[0] = c; } for (j = 0; j < n_res; j++) { *maxchar = Py_MAX(*maxchar, mapped[j]); res[k++] = mapped[j]; } } return k; } static Py_ssize_t do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar, int lower) { Py_ssize_t i, k = 0; for (i = 0; i < length; i++) { Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3]; int n_res, j; if (lower) n_res = lower_ucs4(kind, data, length, i, c, mapped); else n_res = _PyUnicode_ToUpperFull(c, mapped); for (j = 0; j < n_res; j++) { *maxchar = Py_MAX(*maxchar, mapped[j]); res[k++] = mapped[j]; } } return k; } static Py_ssize_t do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) { return do_upper_or_lower(kind, data, length, res, maxchar, 0); } static Py_ssize_t do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) { return do_upper_or_lower(kind, data, length, res, maxchar, 1); } static Py_ssize_t do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) { Py_ssize_t i, k = 0; for (i = 0; i < length; i++) { Py_UCS4 c = PyUnicode_READ(kind, data, i); Py_UCS4 mapped[3]; int j, n_res = _PyUnicode_ToFoldedFull(c, mapped); for (j = 0; j < n_res; j++) { *maxchar = Py_MAX(*maxchar, mapped[j]); res[k++] = mapped[j]; } } return k; } static Py_ssize_t do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) { Py_ssize_t i, k = 0; int previous_is_cased; previous_is_cased = 0; for (i = 0; i < length; i++) { const Py_UCS4 c = PyUnicode_READ(kind, data, i); Py_UCS4 mapped[3]; int n_res, j; if (previous_is_cased) n_res = lower_ucs4(kind, data, length, i, c, mapped); else n_res = _PyUnicode_ToTitleFull(c, mapped); for (j = 0; j < n_res; j++) { *maxchar = Py_MAX(*maxchar, mapped[j]); res[k++] = mapped[j]; } previous_is_cased = _PyUnicode_IsCased(c); } return k; } static PyObject * case_operation(PyObject *self, Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *)) { PyObject *res = NULL; Py_ssize_t length, newlength = 0; int kind, outkind; void *data, *outdata; Py_UCS4 maxchar = 0, *tmp, *tmpend; assert(PyUnicode_IS_READY(self)); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); length = PyUnicode_GET_LENGTH(self); if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) { PyErr_SetString(PyExc_OverflowError, "string is too long"); return NULL; } tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length); if (tmp == NULL) return PyErr_NoMemory(); newlength = perform(kind, data, length, tmp, &maxchar); res = PyUnicode_New(newlength, maxchar); if (res == NULL) goto leave; tmpend = tmp + newlength; outdata = PyUnicode_DATA(res); outkind = PyUnicode_KIND(res); switch (outkind) { case PyUnicode_1BYTE_KIND: _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata); break; case PyUnicode_2BYTE_KIND: _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata); break; case PyUnicode_4BYTE_KIND: memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength); break; default: assert(0); break; } leave: PyMem_FREE(tmp); return res; } PyObject * PyUnicode_Join(PyObject *separator, PyObject *seq) { PyObject *res; PyObject *fseq; Py_ssize_t seqlen; PyObject **items; fseq = PySequence_Fast(seq, "can only join an iterable"); if (fseq == NULL) { return NULL; } /* NOTE: the following code can't call back into Python code, * so we are sure that fseq won't be mutated. */ items = PySequence_Fast_ITEMS(fseq); seqlen = PySequence_Fast_GET_SIZE(fseq); res = _PyUnicode_JoinArray(separator, items, seqlen); Py_DECREF(fseq); return res; } PyObject * _PyUnicode_JoinArray(PyObject *separator, PyObject **items, Py_ssize_t seqlen) { PyObject *res = NULL; /* the result */ PyObject *sep = NULL; Py_ssize_t seplen; PyObject *item; Py_ssize_t sz, i, res_offset; Py_UCS4 maxchar; Py_UCS4 item_maxchar; int use_memcpy; unsigned char *res_data = NULL, *sep_data = NULL; PyObject *last_obj; unsigned int kind = 0; /* If empty sequence, return u"". */ if (seqlen == 0) { _Py_RETURN_UNICODE_EMPTY(); } /* If singleton sequence with an exact Unicode, return that. */ last_obj = NULL; if (seqlen == 1) { if (PyUnicode_CheckExact(items[0])) { res = items[0]; Py_INCREF(res); return res; } seplen = 0; maxchar = 0; } else { /* Set up sep and seplen */ if (separator == NULL) { /* fall back to a blank space separator */ sep = PyUnicode_FromOrdinal(' '); if (!sep) goto onError; seplen = 1; maxchar = 32; } else { if (!PyUnicode_Check(separator)) { PyErr_Format(PyExc_TypeError, "separator: expected str instance," " %.80s found", Py_TYPE(separator)->tp_name); goto onError; } if (PyUnicode_READY(separator)) goto onError; sep = separator; seplen = PyUnicode_GET_LENGTH(separator); maxchar = PyUnicode_MAX_CHAR_VALUE(separator); /* inc refcount to keep this code path symmetric with the above case of a blank separator */ Py_INCREF(sep); } last_obj = sep; } /* There are at least two things to join, or else we have a subclass * of str in the sequence. * Do a pre-pass to figure out the total amount of space we'll * need (sz), and see whether all argument are strings. */ sz = 0; #ifdef Py_DEBUG use_memcpy = 0; #else use_memcpy = 1; #endif for (i = 0; i < seqlen; i++) { size_t add_sz; item = items[i]; if (!PyUnicode_Check(item)) { PyErr_Format(PyExc_TypeError, "sequence item %zd: expected str instance," " %.80s found", i, Py_TYPE(item)->tp_name); goto onError; } if (PyUnicode_READY(item) == -1) goto onError; add_sz = PyUnicode_GET_LENGTH(item); item_maxchar = PyUnicode_MAX_CHAR_VALUE(item); maxchar = Py_MAX(maxchar, item_maxchar); if (i != 0) { add_sz += seplen; } if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) { PyErr_SetString(PyExc_OverflowError, "join() result is too long for a Python string"); goto onError; } sz += add_sz; if (use_memcpy && last_obj != NULL) { if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item)) use_memcpy = 0; } last_obj = item; } res = PyUnicode_New(sz, maxchar); if (res == NULL) goto onError; /* Catenate everything. */ #ifdef Py_DEBUG use_memcpy = 0; #else if (use_memcpy) { res_data = PyUnicode_1BYTE_DATA(res); kind = PyUnicode_KIND(res); if (seplen != 0) sep_data = PyUnicode_1BYTE_DATA(sep); } #endif if (use_memcpy) { for (i = 0; i < seqlen; ++i) { Py_ssize_t itemlen; item = items[i]; /* Copy item, and maybe the separator. */ if (i && seplen != 0) { memcpy(res_data, sep_data, kind * seplen); res_data += kind * seplen; } itemlen = PyUnicode_GET_LENGTH(item); if (itemlen != 0) { memcpy(res_data, PyUnicode_DATA(item), kind * itemlen); res_data += kind * itemlen; } } assert(res_data == PyUnicode_1BYTE_DATA(res) + kind * PyUnicode_GET_LENGTH(res)); } else { for (i = 0, res_offset = 0; i < seqlen; ++i) { Py_ssize_t itemlen; item = items[i]; /* Copy item, and maybe the separator. */ if (i && seplen != 0) { _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen); res_offset += seplen; } itemlen = PyUnicode_GET_LENGTH(item); if (itemlen != 0) { _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen); res_offset += itemlen; } } assert(res_offset == PyUnicode_GET_LENGTH(res)); } Py_XDECREF(sep); assert(_PyUnicode_CheckConsistency(res, 1)); return res; onError: Py_XDECREF(sep); Py_XDECREF(res); return NULL; } void _PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char) { const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode); void *data = PyUnicode_DATA(unicode); assert(PyUnicode_IS_READY(unicode)); assert(unicode_modifiable(unicode)); assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode)); assert(start >= 0); assert(start + length <= PyUnicode_GET_LENGTH(unicode)); FILL(kind, data, fill_char, start, length); } Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char) { Py_ssize_t maxlen; if (!PyUnicode_Check(unicode)) { PyErr_BadInternalCall(); return -1; } if (PyUnicode_READY(unicode) == -1) return -1; if (unicode_check_modifiable(unicode)) return -1; if (start < 0) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return -1; } if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) { PyErr_SetString(PyExc_ValueError, "fill character is bigger than " "the string maximum character"); return -1; } maxlen = PyUnicode_GET_LENGTH(unicode) - start; length = Py_MIN(maxlen, length); if (length <= 0) return 0; _PyUnicode_FastFill(unicode, start, length, fill_char); return length; } static PyObject * pad(PyObject *self, Py_ssize_t left, Py_ssize_t right, Py_UCS4 fill) { PyObject *u; Py_UCS4 maxchar; int kind; void *data; if (left < 0) left = 0; if (right < 0) right = 0; if (left == 0 && right == 0) return unicode_result_unchanged(self); if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) || right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) { PyErr_SetString(PyExc_OverflowError, "padded string is too long"); return NULL; } maxchar = PyUnicode_MAX_CHAR_VALUE(self); maxchar = Py_MAX(maxchar, fill); u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar); if (!u) return NULL; kind = PyUnicode_KIND(u); data = PyUnicode_DATA(u); if (left) FILL(kind, data, fill, 0, left); if (right) FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right); _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self)); assert(_PyUnicode_CheckConsistency(u, 1)); return u; } PyObject * PyUnicode_Splitlines(PyObject *string, int keepends) { PyObject *list; if (ensure_unicode(string) < 0) return NULL; switch (PyUnicode_KIND(string)) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(string)) list = asciilib_splitlines( string, PyUnicode_1BYTE_DATA(string), PyUnicode_GET_LENGTH(string), keepends); else list = ucs1lib_splitlines( string, PyUnicode_1BYTE_DATA(string), PyUnicode_GET_LENGTH(string), keepends); break; case PyUnicode_2BYTE_KIND: list = ucs2lib_splitlines( string, PyUnicode_2BYTE_DATA(string), PyUnicode_GET_LENGTH(string), keepends); break; case PyUnicode_4BYTE_KIND: list = ucs4lib_splitlines( string, PyUnicode_4BYTE_DATA(string), PyUnicode_GET_LENGTH(string), keepends); break; default: assert(0); list = 0; } return list; } static PyObject * split(PyObject *self, PyObject *substring, Py_ssize_t maxcount) { int kind1, kind2; void *buf1, *buf2; Py_ssize_t len1, len2; PyObject* out; if (maxcount < 0) maxcount = PY_SSIZE_T_MAX; if (PyUnicode_READY(self) == -1) return NULL; if (substring == NULL) switch (PyUnicode_KIND(self)) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(self)) return asciilib_split_whitespace( self, PyUnicode_1BYTE_DATA(self), PyUnicode_GET_LENGTH(self), maxcount ); else return ucs1lib_split_whitespace( self, PyUnicode_1BYTE_DATA(self), PyUnicode_GET_LENGTH(self), maxcount ); case PyUnicode_2BYTE_KIND: return ucs2lib_split_whitespace( self, PyUnicode_2BYTE_DATA(self), PyUnicode_GET_LENGTH(self), maxcount ); case PyUnicode_4BYTE_KIND: return ucs4lib_split_whitespace( self, PyUnicode_4BYTE_DATA(self), PyUnicode_GET_LENGTH(self), maxcount ); default: assert(0); return NULL; } if (PyUnicode_READY(substring) == -1) return NULL; kind1 = PyUnicode_KIND(self); kind2 = PyUnicode_KIND(substring); len1 = PyUnicode_GET_LENGTH(self); len2 = PyUnicode_GET_LENGTH(substring); if (kind1 < kind2 || len1 < len2) { out = PyList_New(1); if (out == NULL) return NULL; Py_INCREF(self); PyList_SET_ITEM(out, 0, self); return out; } buf1 = PyUnicode_DATA(self); buf2 = PyUnicode_DATA(substring); if (kind2 != kind1) { buf2 = _PyUnicode_AsKind(substring, kind1); if (!buf2) return NULL; } switch (kind1) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring)) out = asciilib_split( self, buf1, len1, buf2, len2, maxcount); else out = ucs1lib_split( self, buf1, len1, buf2, len2, maxcount); break; case PyUnicode_2BYTE_KIND: out = ucs2lib_split( self, buf1, len1, buf2, len2, maxcount); break; case PyUnicode_4BYTE_KIND: out = ucs4lib_split( self, buf1, len1, buf2, len2, maxcount); break; default: out = NULL; } if (kind2 != kind1) PyMem_Free(buf2); return out; } static PyObject * rsplit(PyObject *self, PyObject *substring, Py_ssize_t maxcount) { int kind1, kind2; void *buf1, *buf2; Py_ssize_t len1, len2; PyObject* out; if (maxcount < 0) maxcount = PY_SSIZE_T_MAX; if (PyUnicode_READY(self) == -1) return NULL; if (substring == NULL) switch (PyUnicode_KIND(self)) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(self)) return asciilib_rsplit_whitespace( self, PyUnicode_1BYTE_DATA(self), PyUnicode_GET_LENGTH(self), maxcount ); else return ucs1lib_rsplit_whitespace( self, PyUnicode_1BYTE_DATA(self), PyUnicode_GET_LENGTH(self), maxcount ); case PyUnicode_2BYTE_KIND: return ucs2lib_rsplit_whitespace( self, PyUnicode_2BYTE_DATA(self), PyUnicode_GET_LENGTH(self), maxcount ); case PyUnicode_4BYTE_KIND: return ucs4lib_rsplit_whitespace( self, PyUnicode_4BYTE_DATA(self), PyUnicode_GET_LENGTH(self), maxcount ); default: assert(0); return NULL; } if (PyUnicode_READY(substring) == -1) return NULL; kind1 = PyUnicode_KIND(self); kind2 = PyUnicode_KIND(substring); len1 = PyUnicode_GET_LENGTH(self); len2 = PyUnicode_GET_LENGTH(substring); if (kind1 < kind2 || len1 < len2) { out = PyList_New(1); if (out == NULL) return NULL; Py_INCREF(self); PyList_SET_ITEM(out, 0, self); return out; } buf1 = PyUnicode_DATA(self); buf2 = PyUnicode_DATA(substring); if (kind2 != kind1) { buf2 = _PyUnicode_AsKind(substring, kind1); if (!buf2) return NULL; } switch (kind1) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring)) out = asciilib_rsplit( self, buf1, len1, buf2, len2, maxcount); else out = ucs1lib_rsplit( self, buf1, len1, buf2, len2, maxcount); break; case PyUnicode_2BYTE_KIND: out = ucs2lib_rsplit( self, buf1, len1, buf2, len2, maxcount); break; case PyUnicode_4BYTE_KIND: out = ucs4lib_rsplit( self, buf1, len1, buf2, len2, maxcount); break; default: out = NULL; } if (kind2 != kind1) PyMem_Free(buf2); return out; } static Py_ssize_t anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1, PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset) { switch (kind) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2)) return asciilib_find(buf1, len1, buf2, len2, offset); else return ucs1lib_find(buf1, len1, buf2, len2, offset); case PyUnicode_2BYTE_KIND: return ucs2lib_find(buf1, len1, buf2, len2, offset); case PyUnicode_4BYTE_KIND: return ucs4lib_find(buf1, len1, buf2, len2, offset); } assert(0); return -1; } static Py_ssize_t anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen, PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount) { switch (kind) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1)) return asciilib_count(sbuf, slen, buf1, len1, maxcount); else return ucs1lib_count(sbuf, slen, buf1, len1, maxcount); case PyUnicode_2BYTE_KIND: return ucs2lib_count(sbuf, slen, buf1, len1, maxcount); case PyUnicode_4BYTE_KIND: return ucs4lib_count(sbuf, slen, buf1, len1, maxcount); } assert(0); return 0; } static void replace_1char_inplace(PyObject *u, Py_ssize_t pos, Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount) { int kind = PyUnicode_KIND(u); void *data = PyUnicode_DATA(u); Py_ssize_t len = PyUnicode_GET_LENGTH(u); if (kind == PyUnicode_1BYTE_KIND) { ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos, (Py_UCS1 *)data + len, u1, u2, maxcount); } else if (kind == PyUnicode_2BYTE_KIND) { ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos, (Py_UCS2 *)data + len, u1, u2, maxcount); } else { assert(kind == PyUnicode_4BYTE_KIND); ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos, (Py_UCS4 *)data + len, u1, u2, maxcount); } } static PyObject * replace(PyObject *self, PyObject *str1, PyObject *str2, Py_ssize_t maxcount) { PyObject *u; char *sbuf = PyUnicode_DATA(self); char *buf1 = PyUnicode_DATA(str1); char *buf2 = PyUnicode_DATA(str2); int srelease = 0, release1 = 0, release2 = 0; int skind = PyUnicode_KIND(self); int kind1 = PyUnicode_KIND(str1); int kind2 = PyUnicode_KIND(str2); Py_ssize_t slen = PyUnicode_GET_LENGTH(self); Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1); Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2); int mayshrink; Py_UCS4 maxchar, maxchar_str1, maxchar_str2; if (maxcount < 0) maxcount = PY_SSIZE_T_MAX; else if (maxcount == 0 || slen == 0) goto nothing; if (str1 == str2) goto nothing; maxchar = PyUnicode_MAX_CHAR_VALUE(self); maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1); if (maxchar < maxchar_str1) /* substring too wide to be present */ goto nothing; maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2); /* Replacing str1 with str2 may cause a maxchar reduction in the result string. */ mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1); maxchar = Py_MAX(maxchar, maxchar_str2); if (len1 == len2) { /* same length */ if (len1 == 0) goto nothing; if (len1 == 1) { /* replace characters */ Py_UCS4 u1, u2; Py_ssize_t pos; u1 = PyUnicode_READ(kind1, buf1, 0); pos = findchar(sbuf, skind, slen, u1, 1); if (pos < 0) goto nothing; u2 = PyUnicode_READ(kind2, buf2, 0); u = PyUnicode_New(slen, maxchar); if (!u) goto error; _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen); replace_1char_inplace(u, pos, u1, u2, maxcount); } else { int rkind = skind; char *res; Py_ssize_t i; if (kind1 < rkind) { /* widen substring */ buf1 = _PyUnicode_AsKind(str1, rkind); if (!buf1) goto error; release1 = 1; } i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0); if (i < 0) goto nothing; if (rkind > kind2) { /* widen replacement */ buf2 = _PyUnicode_AsKind(str2, rkind); if (!buf2) goto error; release2 = 1; } else if (rkind < kind2) { /* widen self and buf1 */ rkind = kind2; if (release1) PyMem_Free(buf1); release1 = 0; sbuf = _PyUnicode_AsKind(self, rkind); if (!sbuf) goto error; srelease = 1; buf1 = _PyUnicode_AsKind(str1, rkind); if (!buf1) goto error; release1 = 1; } u = PyUnicode_New(slen, maxchar); if (!u) goto error; assert(PyUnicode_KIND(u) == rkind); res = PyUnicode_DATA(u); memcpy(res, sbuf, rkind * slen); /* change everything in-place, starting with this one */ memcpy(res + rkind * i, buf2, rkind * len2); i += len1; while ( --maxcount > 0) { i = anylib_find(rkind, self, sbuf+rkind*i, slen-i, str1, buf1, len1, i); if (i == -1) break; memcpy(res + rkind * i, buf2, rkind * len2); i += len1; } } } else { Py_ssize_t n, i, j, ires; Py_ssize_t new_size; int rkind = skind; char *res; if (kind1 < rkind) { /* widen substring */ buf1 = _PyUnicode_AsKind(str1, rkind); if (!buf1) goto error; release1 = 1; } n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount); if (n == 0) goto nothing; if (kind2 < rkind) { /* widen replacement */ buf2 = _PyUnicode_AsKind(str2, rkind); if (!buf2) goto error; release2 = 1; } else if (kind2 > rkind) { /* widen self and buf1 */ rkind = kind2; sbuf = _PyUnicode_AsKind(self, rkind); if (!sbuf) goto error; srelease = 1; if (release1) PyMem_Free(buf1); release1 = 0; buf1 = _PyUnicode_AsKind(str1, rkind); if (!buf1) goto error; release1 = 1; } /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) - PyUnicode_GET_LENGTH(str1))); */ if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) { PyErr_SetString(PyExc_OverflowError, "replace string is too long"); goto error; } new_size = slen + n * (len2 - len1); if (new_size == 0) { _Py_INCREF_UNICODE_EMPTY(); if (!unicode_empty) goto error; u = unicode_empty; goto done; } if (new_size > (PY_SSIZE_T_MAX / rkind)) { PyErr_SetString(PyExc_OverflowError, "replace string is too long"); goto error; } u = PyUnicode_New(new_size, maxchar); if (!u) goto error; assert(PyUnicode_KIND(u) == rkind); res = PyUnicode_DATA(u); ires = i = 0; if (len1 > 0) { while (n-- > 0) { /* look for next match */ j = anylib_find(rkind, self, sbuf + rkind * i, slen-i, str1, buf1, len1, i); if (j == -1) break; else if (j > i) { /* copy unchanged part [i:j] */ memcpy(res + rkind * ires, sbuf + rkind * i, rkind * (j-i)); ires += j - i; } /* copy substitution string */ if (len2 > 0) { memcpy(res + rkind * ires, buf2, rkind * len2); ires += len2; } i = j + len1; } if (i < slen) /* copy tail [i:] */ memcpy(res + rkind * ires, sbuf + rkind * i, rkind * (slen-i)); } else { /* interleave */ while (n > 0) { memcpy(res + rkind * ires, buf2, rkind * len2); ires += len2; if (--n <= 0) break; memcpy(res + rkind * ires, sbuf + rkind * i, rkind); ires++; i++; } memcpy(res + rkind * ires, sbuf + rkind * i, rkind * (slen-i)); } } if (mayshrink) { unicode_adjust_maxchar(&u); if (u == NULL) goto error; } done: if (srelease) PyMem_FREE(sbuf); if (release1) PyMem_FREE(buf1); if (release2) PyMem_FREE(buf2); assert(_PyUnicode_CheckConsistency(u, 1)); return u; nothing: /* nothing to replace; return original string (when possible) */ if (srelease) PyMem_FREE(sbuf); if (release1) PyMem_FREE(buf1); if (release2) PyMem_FREE(buf2); return unicode_result_unchanged(self); error: if (srelease && sbuf) PyMem_FREE(sbuf); if (release1 && buf1) PyMem_FREE(buf1); if (release2 && buf2) PyMem_FREE(buf2); return NULL; } /* --- Unicode Object Methods --------------------------------------------- */ PyDoc_STRVAR(title__doc__, "S.title() -> str\n\ \n\ Return a titlecased version of S, i.e. words start with title case\n\ characters, all remaining cased characters have lower case."); static PyObject* unicode_title(PyObject *self) { if (PyUnicode_READY(self) == -1) return NULL; return case_operation(self, do_title); } PyDoc_STRVAR(capitalize__doc__, "S.capitalize() -> str\n\ \n\ Return a capitalized version of S, i.e. make the first character\n\ have upper case and the rest lower case."); static PyObject* unicode_capitalize(PyObject *self) { if (PyUnicode_READY(self) == -1) return NULL; if (PyUnicode_GET_LENGTH(self) == 0) return unicode_result_unchanged(self); return case_operation(self, do_capitalize); } PyDoc_STRVAR(casefold__doc__, "S.casefold() -> str\n\ \n\ Return a version of S suitable for caseless comparisons."); static PyObject * unicode_casefold(PyObject *self) { if (PyUnicode_READY(self) == -1) return NULL; if (PyUnicode_IS_ASCII(self)) return ascii_upper_or_lower(self, 1); return case_operation(self, do_casefold); } /* Argument converter. Accepts a single Unicode character. */ static int convert_uc(PyObject *obj, void *addr) { Py_UCS4 *fillcharloc = (Py_UCS4 *)addr; if (!PyUnicode_Check(obj)) { PyErr_Format(PyExc_TypeError, "The fill character must be a unicode character, " "not %.100s", Py_TYPE(obj)->tp_name); return 0; } if (PyUnicode_READY(obj) < 0) return 0; if (PyUnicode_GET_LENGTH(obj) != 1) { PyErr_SetString(PyExc_TypeError, "The fill character must be exactly one character long"); return 0; } *fillcharloc = PyUnicode_READ_CHAR(obj, 0); return 1; } PyDoc_STRVAR(center__doc__, "S.center(width[, fillchar]) -> str\n\ \n\ Return S centered in a string of length width. Padding is\n\ done using the specified fill character (default is a space)"); static PyObject * unicode_center(PyObject *self, PyObject *args) { Py_ssize_t marg, left; Py_ssize_t width; Py_UCS4 fillchar = ' '; if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; if (PyUnicode_GET_LENGTH(self) >= width) return unicode_result_unchanged(self); marg = width - PyUnicode_GET_LENGTH(self); left = marg / 2 + (marg & width & 1); return pad(self, left, marg - left, fillchar); } /* This function assumes that str1 and str2 are readied by the caller. */ static int unicode_compare(PyObject *str1, PyObject *str2) { #define COMPARE(TYPE1, TYPE2) \ do { \ TYPE1* p1 = (TYPE1 *)data1; \ TYPE2* p2 = (TYPE2 *)data2; \ TYPE1* end = p1 + len; \ Py_UCS4 c1, c2; \ for (; p1 != end; p1++, p2++) { \ c1 = *p1; \ c2 = *p2; \ if (c1 != c2) \ return (c1 < c2) ? -1 : 1; \ } \ } \ while (0) int kind1, kind2; void *data1, *data2; Py_ssize_t len1, len2, len; kind1 = PyUnicode_KIND(str1); kind2 = PyUnicode_KIND(str2); data1 = PyUnicode_DATA(str1); data2 = PyUnicode_DATA(str2); len1 = PyUnicode_GET_LENGTH(str1); len2 = PyUnicode_GET_LENGTH(str2); len = Py_MIN(len1, len2); switch(kind1) { case PyUnicode_1BYTE_KIND: { switch(kind2) { case PyUnicode_1BYTE_KIND: { int cmp = memcmp(data1, data2, len); /* normalize result of memcmp() into the range [-1; 1] */ if (cmp < 0) return -1; if (cmp > 0) return 1; break; } case PyUnicode_2BYTE_KIND: COMPARE(Py_UCS1, Py_UCS2); break; case PyUnicode_4BYTE_KIND: COMPARE(Py_UCS1, Py_UCS4); break; default: assert(0); } break; } case PyUnicode_2BYTE_KIND: { switch(kind2) { case PyUnicode_1BYTE_KIND: COMPARE(Py_UCS2, Py_UCS1); break; case PyUnicode_2BYTE_KIND: { COMPARE(Py_UCS2, Py_UCS2); break; } case PyUnicode_4BYTE_KIND: COMPARE(Py_UCS2, Py_UCS4); break; default: assert(0); } break; } case PyUnicode_4BYTE_KIND: { switch(kind2) { case PyUnicode_1BYTE_KIND: COMPARE(Py_UCS4, Py_UCS1); break; case PyUnicode_2BYTE_KIND: COMPARE(Py_UCS4, Py_UCS2); break; case PyUnicode_4BYTE_KIND: { #if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len); /* normalize result of wmemcmp() into the range [-1; 1] */ if (cmp < 0) return -1; if (cmp > 0) return 1; #else COMPARE(Py_UCS4, Py_UCS4); #endif break; } default: assert(0); } break; } default: assert(0); } if (len1 == len2) return 0; if (len1 < len2) return -1; else return 1; #undef COMPARE } static inline int unicode_compare_eq(PyObject *str1, PyObject *str2) { int kind; void *data1, *data2; Py_ssize_t len; len = PyUnicode_GET_LENGTH(str1); if (PyUnicode_GET_LENGTH(str2) != len) return 0; kind = PyUnicode_KIND(str1); if (PyUnicode_KIND(str2) != kind) return 0; data1 = PyUnicode_DATA(str1); data2 = PyUnicode_DATA(str2); return !bcmp(data1, data2, len * kind); } int PyUnicode_Compare(PyObject *left, PyObject *right) { if (PyUnicode_Check(left) && PyUnicode_Check(right)) { if (PyUnicode_READY(left) == -1 || PyUnicode_READY(right) == -1) return -1; /* a string is equal to itself */ if (left == right) return 0; return unicode_compare(left, right); } PyErr_Format(PyExc_TypeError, "Can't compare %.100s and %.100s", left->ob_type->tp_name, right->ob_type->tp_name); return -1; } int PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str) { Py_ssize_t i; int kind; Py_UCS4 chr; const unsigned char *ustr = (const unsigned char *)str; assert(_PyUnicode_CHECK(uni)); if (!PyUnicode_IS_READY(uni)) { const wchar_t *ws = _PyUnicode_WSTR(uni); /* Compare Unicode string and source character set string */ for (i = 0; (chr = ws[i]) && ustr[i]; i++) { if (chr != ustr[i]) return (chr < ustr[i]) ? -1 : 1; } /* This check keeps Python strings that end in '\0' from comparing equal to C strings identical up to that point. */ if (_PyUnicode_WSTR_LENGTH(uni) != i || chr) return 1; /* uni is longer */ if (ustr[i]) return -1; /* str is longer */ return 0; } kind = PyUnicode_KIND(uni); if (kind == PyUnicode_1BYTE_KIND) { const void *data = PyUnicode_1BYTE_DATA(uni); size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni); size_t len, len2 = strlen(str); int cmp; len = Py_MIN(len1, len2); cmp = memcmp(data, str, len); if (cmp != 0) { if (cmp < 0) return -1; else return 1; } if (len1 > len2) return 1; /* uni is longer */ if (len1 < len2) return -1; /* str is longer */ return 0; } else { void *data = PyUnicode_DATA(uni); /* Compare Unicode string and source character set string */ for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++) if (chr != (unsigned char)str[i]) return (chr < (unsigned char)(str[i])) ? -1 : 1; /* This check keeps Python strings that end in '\0' from comparing equal to C strings identical up to that point. */ if (PyUnicode_GET_LENGTH(uni) != i || chr) return 1; /* uni is longer */ if (str[i]) return -1; /* str is longer */ return 0; } } static int non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str) { size_t i, len; const wchar_t *p; len = (size_t)_PyUnicode_WSTR_LENGTH(unicode); if (strlen(str) != len) return 0; p = _PyUnicode_WSTR(unicode); assert(p); for (i = 0; i < len; i++) { unsigned char c = (unsigned char)str[i]; if (c >= 128 || p[i] != (wchar_t)c) return 0; } return 1; } static int IsPureAscii(const char *p) { int c; while ((c = *p++)) { if (c & 128) { return 0; } } return 1; } int _PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str) { size_t len; assert(str); assert(IsPureAscii(str)); assert(_PyUnicode_CHECK(unicode)); if (PyUnicode_READY(unicode) == -1) { /* Memory error or bad data */ PyErr_Clear(); return non_ready_unicode_equal_to_ascii_string(unicode, str); } if (!PyUnicode_IS_ASCII(unicode)) return 0; len = (size_t)PyUnicode_GET_LENGTH(unicode); return strlen(str) == len && !bcmp(PyUnicode_1BYTE_DATA(unicode), str, len); } int _PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right) { PyObject *right_uni; Py_hash_t hash; assert(_PyUnicode_CHECK(left)); assert(right->string); assert(IsPureAscii(right->string)); if (PyUnicode_READY(left) == -1) { /* memory error or bad data */ PyErr_Clear(); return non_ready_unicode_equal_to_ascii_string(left, right->string); } if (!PyUnicode_IS_ASCII(left)) return 0; right_uni = _PyUnicode_FromId(right); /* borrowed */ if (right_uni == NULL) { /* memory error or bad data */ PyErr_Clear(); return _PyUnicode_EqualToASCIIString(left, right->string); } if (left == right_uni) return 1; if (PyUnicode_CHECK_INTERNED(left)) return 0; assert(_PyUnicode_HASH(right_uni) != -1); hash = _PyUnicode_HASH(left); if (hash != -1 && hash != _PyUnicode_HASH(right_uni)) return 0; return unicode_compare_eq(left, right_uni); } #define TEST_COND(cond) \ ((cond) ? Py_True : Py_False) PyObject * PyUnicode_RichCompare(PyObject *left, PyObject *right, int op) { int result; PyObject *v; if (UNLIKELY(!PyUnicode_Check(left) || !PyUnicode_Check(right))) Py_RETURN_NOTIMPLEMENTED; if (UNLIKELY(PyUnicode_READY(left) == -1 || PyUnicode_READY(right) == -1)) return NULL; if (left == right) { switch (op) { case Py_EQ: case Py_LE: case Py_GE: /* a string is equal to itself */ v = Py_True; break; case Py_NE: case Py_LT: case Py_GT: v = Py_False; break; default: PyErr_BadArgument(); return NULL; } } else if (op == Py_EQ || op == Py_NE) { result = unicode_compare_eq(left, right); result ^= (op == Py_NE); v = TEST_COND(result); } else { result = unicode_compare(left, right); /* Convert the return value to a Boolean */ switch (op) { case Py_LE: v = TEST_COND(result <= 0); break; case Py_GE: v = TEST_COND(result >= 0); break; case Py_LT: v = TEST_COND(result == -1); break; case Py_GT: v = TEST_COND(result == 1); break; default: PyErr_BadArgument(); return NULL; } } Py_INCREF(v); return v; } int _PyUnicode_EQ(PyObject *aa, PyObject *bb) { return unicode_eq(aa, bb); } int PyUnicode_Contains(PyObject *str, PyObject *substr) { int kind1, kind2; void *buf1, *buf2; Py_ssize_t len1, len2; int result; if (!PyUnicode_Check(substr)) { PyErr_Format(PyExc_TypeError, "'in <string>' requires string as left operand, not %.100s", Py_TYPE(substr)->tp_name); return -1; } if (PyUnicode_READY(substr) == -1) return -1; if (ensure_unicode(str) < 0) return -1; kind1 = PyUnicode_KIND(str); kind2 = PyUnicode_KIND(substr); if (kind1 < kind2) return 0; len1 = PyUnicode_GET_LENGTH(str); len2 = PyUnicode_GET_LENGTH(substr); if (len1 < len2) return 0; buf1 = PyUnicode_DATA(str); buf2 = PyUnicode_DATA(substr); if (len2 == 1) { Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0); result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1; return result; } if (kind2 != kind1) { buf2 = _PyUnicode_AsKind(substr, kind1); if (!buf2) return -1; } switch (kind1) { case PyUnicode_1BYTE_KIND: result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1; break; case PyUnicode_2BYTE_KIND: result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1; break; case PyUnicode_4BYTE_KIND: result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1; break; default: result = -1; assert(0); } if (kind2 != kind1) PyMem_Free(buf2); return result; } /* Concat to string or Unicode object giving a new Unicode object. */ PyObject * PyUnicode_Concat(PyObject *left, PyObject *right) { PyObject *result; Py_UCS4 maxchar, maxchar2; Py_ssize_t left_len, right_len, new_len; if (ensure_unicode(left) < 0 || ensure_unicode(right) < 0) return NULL; /* Shortcuts */ if (left == unicode_empty) return PyUnicode_FromObject(right); if (right == unicode_empty) return PyUnicode_FromObject(left); left_len = PyUnicode_GET_LENGTH(left); right_len = PyUnicode_GET_LENGTH(right); if (left_len > PY_SSIZE_T_MAX - right_len) { PyErr_SetString(PyExc_OverflowError, "strings are too large to concat"); return NULL; } new_len = left_len + right_len; maxchar = PyUnicode_MAX_CHAR_VALUE(left); maxchar2 = PyUnicode_MAX_CHAR_VALUE(right); maxchar = Py_MAX(maxchar, maxchar2); /* Concat the two Unicode strings */ result = PyUnicode_New(new_len, maxchar); if (result == NULL) return NULL; _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len); _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len); assert(_PyUnicode_CheckConsistency(result, 1)); return result; } void PyUnicode_Append(PyObject **p_left, PyObject *right) { PyObject *left, *res; Py_UCS4 maxchar, maxchar2; Py_ssize_t left_len, right_len, new_len; if (p_left == NULL) { if (!PyErr_Occurred()) PyErr_BadInternalCall(); return; } left = *p_left; if (right == NULL || left == NULL || !PyUnicode_Check(left) || !PyUnicode_Check(right)) { if (!PyErr_Occurred()) PyErr_BadInternalCall(); goto error; } if (PyUnicode_READY(left) == -1) goto error; if (PyUnicode_READY(right) == -1) goto error; /* Shortcuts */ if (left == unicode_empty) { Py_DECREF(left); Py_INCREF(right); *p_left = right; return; } if (right == unicode_empty) return; left_len = PyUnicode_GET_LENGTH(left); right_len = PyUnicode_GET_LENGTH(right); if (left_len > PY_SSIZE_T_MAX - right_len) { PyErr_SetString(PyExc_OverflowError, "strings are too large to concat"); goto error; } new_len = left_len + right_len; if (unicode_modifiable(left) && PyUnicode_CheckExact(right) && PyUnicode_KIND(right) <= PyUnicode_KIND(left) /* Don't resize for ascii += latin1. Convert ascii to latin1 requires to change the structure size, but characters are stored just after the structure, and so it requires to move all characters which is not so different than duplicating the string. */ && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right))) { /* append inplace */ if (unicode_resize(p_left, new_len) != 0) goto error; /* copy 'right' into the newly allocated area of 'left' */ _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len); } else { maxchar = PyUnicode_MAX_CHAR_VALUE(left); maxchar2 = PyUnicode_MAX_CHAR_VALUE(right); maxchar = Py_MAX(maxchar, maxchar2); /* Concat the two Unicode strings */ res = PyUnicode_New(new_len, maxchar); if (res == NULL) goto error; _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len); _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len); Py_DECREF(left); *p_left = res; } assert(_PyUnicode_CheckConsistency(*p_left, 1)); return; error: Py_CLEAR(*p_left); } void PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right) { PyUnicode_Append(pleft, right); Py_XDECREF(right); } /* Wraps stringlib_parse_args_finds() and additionally ensures that the first argument is a unicode object. */ static inline int parse_args_finds_unicode(const char * function_name, PyObject *args, PyObject **substring, Py_ssize_t *start, Py_ssize_t *end) { if(stringlib_parse_args_finds(function_name, args, substring, start, end)) { if (ensure_unicode(*substring) < 0) return 0; return 1; } return 0; } PyDoc_STRVAR(count__doc__, "S.count(sub[, start[, end]]) -> int\n\ \n\ Return the number of non-overlapping occurrences of substring sub in\n\ string S[start:end]. Optional arguments start and end are\n\ interpreted as in slice notation."); static PyObject * unicode_count(PyObject *self, PyObject *args) { PyObject *substring = NULL; /* initialize to fix a compiler warning */ Py_ssize_t start = 0; Py_ssize_t end = PY_SSIZE_T_MAX; PyObject *result; int kind1, kind2; void *buf1, *buf2; Py_ssize_t len1, len2, iresult; if (!parse_args_finds_unicode("count", args, &substring, &start, &end)) return NULL; kind1 = PyUnicode_KIND(self); kind2 = PyUnicode_KIND(substring); if (kind1 < kind2) return PyLong_FromLong(0); len1 = PyUnicode_GET_LENGTH(self); len2 = PyUnicode_GET_LENGTH(substring); ADJUST_INDICES(start, end, len1); if (end - start < len2) return PyLong_FromLong(0); buf1 = PyUnicode_DATA(self); buf2 = PyUnicode_DATA(substring); if (kind2 != kind1) { buf2 = _PyUnicode_AsKind(substring, kind1); if (!buf2) return NULL; } switch (kind1) { case PyUnicode_1BYTE_KIND: iresult = ucs1lib_count( ((Py_UCS1*)buf1) + start, end - start, buf2, len2, PY_SSIZE_T_MAX ); break; case PyUnicode_2BYTE_KIND: iresult = ucs2lib_count( ((Py_UCS2*)buf1) + start, end - start, buf2, len2, PY_SSIZE_T_MAX ); break; case PyUnicode_4BYTE_KIND: iresult = ucs4lib_count( ((Py_UCS4*)buf1) + start, end - start, buf2, len2, PY_SSIZE_T_MAX ); break; default: assert(0); iresult = 0; } result = PyLong_FromSsize_t(iresult); if (kind2 != kind1) PyMem_Free(buf2); return result; } PyDoc_STRVAR(encode__doc__, "S.encode(encoding='utf-8', errors='strict') -> bytes\n\ \n\ Encode S using the codec registered for encoding. Default encoding\n\ is 'utf-8'. errors may be given to set a different error\n\ handling scheme. Default is 'strict' meaning that encoding errors raise\n\ a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\ 'xmlcharrefreplace' as well as any other name registered with\n\ codecs.register_error that can handle UnicodeEncodeErrors."); static PyObject * unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs) { static char *kwlist[] = {"encoding", "errors", 0}; char *encoding = NULL; char *errors = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode", kwlist, &encoding, &errors)) return NULL; return PyUnicode_AsEncodedString(self, encoding, errors); } PyDoc_STRVAR(expandtabs__doc__, "S.expandtabs(tabsize=8) -> str\n\ \n\ Return a copy of S where all tab characters are expanded using spaces.\n\ If tabsize is not given, a tab size of 8 characters is assumed."); static PyObject* unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds) { Py_ssize_t i, j, line_pos, src_len, incr; Py_UCS4 ch; PyObject *u; void *src_data, *dest_data; static char *kwlist[] = {"tabsize", 0}; int tabsize = 8; int kind; int found; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs", kwlist, &tabsize)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; /* First pass: determine size of output string */ src_len = PyUnicode_GET_LENGTH(self); i = j = line_pos = 0; kind = PyUnicode_KIND(self); src_data = PyUnicode_DATA(self); found = 0; for (; i < src_len; i++) { ch = PyUnicode_READ(kind, src_data, i); if (ch == '\t') { found = 1; if (tabsize > 0) { incr = tabsize - (line_pos % tabsize); /* cannot overflow */ if (j > PY_SSIZE_T_MAX - incr) goto overflow; line_pos += incr; j += incr; } } else { if (j > PY_SSIZE_T_MAX - 1) goto overflow; line_pos++; j++; if (ch == '\n' || ch == '\r') line_pos = 0; } } if (!found) return unicode_result_unchanged(self); /* Second pass: create output string and fill it */ u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self)); if (!u) return NULL; dest_data = PyUnicode_DATA(u); i = j = line_pos = 0; for (; i < src_len; i++) { ch = PyUnicode_READ(kind, src_data, i); if (ch == '\t') { if (tabsize > 0) { incr = tabsize - (line_pos % tabsize); line_pos += incr; FILL(kind, dest_data, ' ', j, incr); j += incr; } } else { line_pos++; PyUnicode_WRITE(kind, dest_data, j, ch); j++; if (ch == '\n' || ch == '\r') line_pos = 0; } } assert (j == PyUnicode_GET_LENGTH(u)); return unicode_result(u); overflow: PyErr_SetString(PyExc_OverflowError, "new string is too long"); return NULL; } PyDoc_STRVAR(find__doc__, "S.find(sub[, start[, end]]) -> int\n\ \n\ Return the lowest index in S where substring sub is found,\n\ such that sub is contained within S[start:end]. Optional\n\ arguments start and end are interpreted as in slice notation.\n\ \n\ Return -1 on failure."); static PyObject * unicode_find(PyObject *self, PyObject *args) { /* initialize variables to prevent gcc warning */ PyObject *substring = NULL; Py_ssize_t start = 0; Py_ssize_t end = 0; Py_ssize_t result; if (!parse_args_finds_unicode("find", args, &substring, &start, &end)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; result = any_find_slice(self, substring, start, end, 1); if (result == -2) return NULL; return PyLong_FromSsize_t(result); } static PyObject * unicode_getitem(PyObject *self, Py_ssize_t index) { void *data; enum PyUnicode_Kind kind; Py_UCS4 ch; if (!PyUnicode_Check(self)) { PyErr_BadArgument(); return NULL; } if (PyUnicode_READY(self) == -1) { return NULL; } if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return NULL; } kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); ch = PyUnicode_READ(kind, data, index); return unicode_char(ch); } /* Believe it or not, this produces the same value for ASCII strings as bytes_hash(). */ static Py_hash_t unicode_hash(PyObject *self) { Py_ssize_t len; Py_uhash_t x; /* Unsigned for defined overflow behavior. */ #ifdef Py_DEBUG assert(_Py_HashSecret_Initialized); #endif if (_PyUnicode_HASH(self) != -1) return _PyUnicode_HASH(self); if (PyUnicode_READY(self) == -1) return -1; len = PyUnicode_GET_LENGTH(self); /* We make the hash of the empty string be 0, rather than using (prefix ^ suffix), since this slightly obfuscates the hash secret */ if (len == 0) { _PyUnicode_HASH(self) = 0; return 0; } x = _Py_HashBytes(PyUnicode_DATA(self), PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self)); _PyUnicode_HASH(self) = x; return x; } PyDoc_STRVAR(index__doc__, "S.index(sub[, start[, end]]) -> int\n\ \n\ Return the lowest index in S where substring sub is found, \n\ such that sub is contained within S[start:end]. Optional\n\ arguments start and end are interpreted as in slice notation.\n\ \n\ Raises ValueError when the substring is not found."); static PyObject * unicode_index(PyObject *self, PyObject *args) { /* initialize variables to prevent gcc warning */ Py_ssize_t result; PyObject *substring = NULL; Py_ssize_t start = 0; Py_ssize_t end = 0; if (!parse_args_finds_unicode("index", args, &substring, &start, &end)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; result = any_find_slice(self, substring, start, end, 1); if (result == -2) return NULL; if (result < 0) { PyErr_SetString(PyExc_ValueError, "substring not found"); return NULL; } return PyLong_FromSsize_t(result); } PyDoc_STRVAR(islower__doc__, "S.islower() -> bool\n\ \n\ Return True if all cased characters in S are lowercase and there is\n\ at least one cased character in S, False otherwise."); static PyObject* unicode_islower(PyObject *self) { Py_ssize_t i, length; int kind; void *data; int cased; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) return PyBool_FromLong( Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0))); /* Special case for empty strings */ if (length == 0) return PyBool_FromLong(0); cased = 0; for (i = 0; i < length; i++) { const Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) return PyBool_FromLong(0); else if (!cased && Py_UNICODE_ISLOWER(ch)) cased = 1; } return PyBool_FromLong(cased); } PyDoc_STRVAR(isupper__doc__, "S.isupper() -> bool\n\ \n\ Return True if all cased characters in S are uppercase and there is\n\ at least one cased character in S, False otherwise."); static PyObject* unicode_isupper(PyObject *self) { Py_ssize_t i, length; int kind; void *data; int cased; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) return PyBool_FromLong( Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0); /* Special case for empty strings */ if (length == 0) return PyBool_FromLong(0); cased = 0; for (i = 0; i < length; i++) { const Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch)) return PyBool_FromLong(0); else if (!cased && Py_UNICODE_ISUPPER(ch)) cased = 1; } return PyBool_FromLong(cased); } PyDoc_STRVAR(istitle__doc__, "S.istitle() -> bool\n\ \n\ Return True if S is a titlecased string and there is at least one\n\ character in S, i.e. upper- and titlecase characters may only\n\ follow uncased characters and lowercase characters only cased ones.\n\ Return False otherwise."); static PyObject* unicode_istitle(PyObject *self) { Py_ssize_t i, length; int kind; void *data; int cased, previous_is_cased; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) { Py_UCS4 ch = PyUnicode_READ(kind, data, 0); return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) || (Py_UNICODE_ISUPPER(ch) != 0)); } /* Special case for empty strings */ if (length == 0) return PyBool_FromLong(0); cased = 0; previous_is_cased = 0; for (i = 0; i < length; i++) { const Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) { if (previous_is_cased) return PyBool_FromLong(0); previous_is_cased = 1; cased = 1; } else if (Py_UNICODE_ISLOWER(ch)) { if (!previous_is_cased) return PyBool_FromLong(0); previous_is_cased = 1; cased = 1; } else previous_is_cased = 0; } return PyBool_FromLong(cased); } PyDoc_STRVAR(isspace__doc__, "S.isspace() -> bool\n\ \n\ Return True if all characters in S are whitespace\n\ and there is at least one character in S, False otherwise."); static PyObject* unicode_isspace(PyObject *self) { Py_ssize_t i, length; int kind; void *data; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) return PyBool_FromLong( Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0))); /* Special case for empty strings */ if (length == 0) return PyBool_FromLong(0); for (i = 0; i < length; i++) { const Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (!Py_UNICODE_ISSPACE(ch)) return PyBool_FromLong(0); } return PyBool_FromLong(1); } PyDoc_STRVAR(isalpha__doc__, "S.isalpha() -> bool\n\ \n\ Return True if all characters in S are alphabetic\n\ and there is at least one character in S, False otherwise."); static PyObject* unicode_isalpha(PyObject *self) { Py_ssize_t i, length; int kind; void *data; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) return PyBool_FromLong( Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0))); /* Special case for empty strings */ if (length == 0) return PyBool_FromLong(0); for (i = 0; i < length; i++) { if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i))) return PyBool_FromLong(0); } return PyBool_FromLong(1); } PyDoc_STRVAR(isalnum__doc__, "S.isalnum() -> bool\n\ \n\ Return True if all characters in S are alphanumeric\n\ and there is at least one character in S, False otherwise."); static PyObject* unicode_isalnum(PyObject *self) { int kind; void *data; Py_ssize_t len, i; if (PyUnicode_READY(self) == -1) return NULL; kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); len = PyUnicode_GET_LENGTH(self); /* Shortcut for single character strings */ if (len == 1) { const Py_UCS4 ch = PyUnicode_READ(kind, data, 0); return PyBool_FromLong(Py_UNICODE_ISALNUM(ch)); } /* Special case for empty strings */ if (len == 0) return PyBool_FromLong(0); for (i = 0; i < len; i++) { const Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (!Py_UNICODE_ISALNUM(ch)) return PyBool_FromLong(0); } return PyBool_FromLong(1); } PyDoc_STRVAR(isdecimal__doc__, "S.isdecimal() -> bool\n\ \n\ Return True if there are only decimal characters in S,\n\ False otherwise."); static PyObject* unicode_isdecimal(PyObject *self) { Py_ssize_t i, length; int kind; void *data; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) return PyBool_FromLong( Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0))); /* Special case for empty strings */ if (length == 0) return PyBool_FromLong(0); for (i = 0; i < length; i++) { if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i))) return PyBool_FromLong(0); } return PyBool_FromLong(1); } PyDoc_STRVAR(isdigit__doc__, "S.isdigit() -> bool\n\ \n\ Return True if all characters in S are digits\n\ and there is at least one character in S, False otherwise."); static PyObject* unicode_isdigit(PyObject *self) { Py_ssize_t i, length; int kind; void *data; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) { const Py_UCS4 ch = PyUnicode_READ(kind, data, 0); return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch)); } /* Special case for empty strings */ if (length == 0) return PyBool_FromLong(0); for (i = 0; i < length; i++) { if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i))) return PyBool_FromLong(0); } return PyBool_FromLong(1); } PyDoc_STRVAR(isnumeric__doc__, "S.isnumeric() -> bool\n\ \n\ Return True if there are only numeric characters in S,\n\ False otherwise."); static PyObject* unicode_isnumeric(PyObject *self) { Py_ssize_t i, length; int kind; void *data; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) return PyBool_FromLong( Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0))); /* Special case for empty strings */ if (length == 0) return PyBool_FromLong(0); for (i = 0; i < length; i++) { if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i))) return PyBool_FromLong(0); } return PyBool_FromLong(1); } int PyUnicode_IsIdentifier(PyObject *self) { int kind; void *data; Py_ssize_t i; Py_UCS4 first; if (PyUnicode_READY(self) == -1) { Py_FatalError("identifier not ready"); return 0; } /* Special case for empty strings */ if (PyUnicode_GET_LENGTH(self) == 0) return 0; kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* PEP 3131 says that the first character must be in XID_Start and subsequent characters in XID_Continue, and for the ASCII range, the 2.x rules apply (i.e start with letters and underscore, continue with letters, digits, underscore). However, given the current definition of XID_Start and XID_Continue, it is sufficient to check just for these, except that _ must be allowed as starting an identifier. */ first = PyUnicode_READ(kind, data, 0); if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */) return 0; for (i = 1; i < PyUnicode_GET_LENGTH(self); i++) if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i))) return 0; return 1; } PyDoc_STRVAR(isidentifier__doc__, "S.isidentifier() -> bool\n\ \n\ Return True if S is a valid identifier according\n\ to the language definition.\n\ \n\ Use keyword.iskeyword() to test for reserved identifiers\n\ such as \"def\" and \"class\".\n"); static PyObject* unicode_isidentifier(PyObject *self) { return PyBool_FromLong(PyUnicode_IsIdentifier(self)); } PyDoc_STRVAR(isprintable__doc__, "S.isprintable() -> bool\n\ \n\ Return True if all characters in S are considered\n\ printable in repr() or S is empty, False otherwise."); static PyObject* unicode_isprintable(PyObject *self) { Py_ssize_t i, length; int kind; void *data; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); /* Shortcut for single character strings */ if (length == 1) return PyBool_FromLong( Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0))); for (i = 0; i < length; i++) { if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) { Py_RETURN_FALSE; } } Py_RETURN_TRUE; } PyDoc_STRVAR(join__doc__, "S.join(iterable) -> str\n\ \n\ Return a string which is the concatenation of the strings in the\n\ iterable. The separator between elements is S."); static PyObject* unicode_join(PyObject *self, PyObject *data) { return PyUnicode_Join(self, data); } static Py_ssize_t unicode_length(PyObject *self) { if (PyUnicode_READY(self) == -1) return -1; return PyUnicode_GET_LENGTH(self); } PyDoc_STRVAR(ljust__doc__, "S.ljust(width[, fillchar]) -> str\n\ \n\ Return S left-justified in a Unicode string of length width. Padding is\n\ done using the specified fill character (default is a space)."); static PyObject * unicode_ljust(PyObject *self, PyObject *args) { Py_ssize_t width; Py_UCS4 fillchar = ' '; if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; if (PyUnicode_GET_LENGTH(self) >= width) return unicode_result_unchanged(self); return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar); } PyDoc_STRVAR(lower__doc__, "S.lower() -> str\n\ \n\ Return a copy of the string S converted to lowercase."); static PyObject* unicode_lower(PyObject *self) { if (PyUnicode_READY(self) == -1) return NULL; if (PyUnicode_IS_ASCII(self)) return ascii_upper_or_lower(self, 1); return case_operation(self, do_lower); } #define LEFTSTRIP 0 #define RIGHTSTRIP 1 #define BOTHSTRIP 2 /* Arrays indexed by above */ static const char * const stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"}; #define STRIPNAME(i) (stripformat[i]+3) /* externally visible for str.strip(unicode) */ PyObject * _PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj) { void *data; int kind; Py_ssize_t i, j, len; BLOOM_MASK sepmask; Py_ssize_t seplen; if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1) return NULL; kind = PyUnicode_KIND(self); data = PyUnicode_DATA(self); len = PyUnicode_GET_LENGTH(self); seplen = PyUnicode_GET_LENGTH(sepobj); sepmask = make_bloom_mask(PyUnicode_KIND(sepobj), PyUnicode_DATA(sepobj), seplen); i = 0; if (striptype != RIGHTSTRIP) { while (i < len) { Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (!BLOOM(sepmask, ch)) break; if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0) break; i++; } } j = len; if (striptype != LEFTSTRIP) { j--; while (j >= i) { Py_UCS4 ch = PyUnicode_READ(kind, data, j); if (!BLOOM(sepmask, ch)) break; if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0) break; j--; } j++; } return PyUnicode_Substring(self, i, j); } PyObject* PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end) { unsigned char *data; int kind; Py_ssize_t length; if (PyUnicode_READY(self) == -1) return NULL; length = PyUnicode_GET_LENGTH(self); end = Py_MIN(end, length); if (start == 0 && end == length) return unicode_result_unchanged(self); if (start < 0 || end < 0) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return NULL; } if (start >= length || end < start) _Py_RETURN_UNICODE_EMPTY(); length = end - start; if (PyUnicode_IS_ASCII(self)) { data = PyUnicode_1BYTE_DATA(self); return _PyUnicode_FromASCII((char*)(data + start), length); } else { kind = PyUnicode_KIND(self); data = PyUnicode_1BYTE_DATA(self); return PyUnicode_FromKindAndData(kind, data + kind * start, length); } } static PyObject * do_strip(PyObject *self, int striptype) { Py_ssize_t len, i, j; if (PyUnicode_READY(self) == -1) return NULL; len = PyUnicode_GET_LENGTH(self); if (PyUnicode_IS_ASCII(self)) { Py_UCS1 *data = PyUnicode_1BYTE_DATA(self); i = 0; if (striptype != RIGHTSTRIP) { while (i < len) { Py_UCS1 ch = data[i]; if (!_Py_ascii_whitespace[ch]) break; i++; } } j = len; if (striptype != LEFTSTRIP) { j--; while (j >= i) { Py_UCS1 ch = data[j]; if (!_Py_ascii_whitespace[ch]) break; j--; } j++; } } else { int kind = PyUnicode_KIND(self); void *data = PyUnicode_DATA(self); i = 0; if (striptype != RIGHTSTRIP) { while (i < len) { Py_UCS4 ch = PyUnicode_READ(kind, data, i); if (!Py_UNICODE_ISSPACE(ch)) break; i++; } } j = len; if (striptype != LEFTSTRIP) { j--; while (j >= i) { Py_UCS4 ch = PyUnicode_READ(kind, data, j); if (!Py_UNICODE_ISSPACE(ch)) break; j--; } j++; } } return PyUnicode_Substring(self, i, j); } static PyObject * do_argstrip(PyObject *self, int striptype, PyObject *args) { PyObject *sep = NULL; if (!PyArg_ParseTuple(args, stripformat[striptype], &sep)) return NULL; if (sep != NULL && sep != Py_None) { if (PyUnicode_Check(sep)) return _PyUnicode_XStrip(self, striptype, sep); else { PyErr_Format(PyExc_TypeError, "%s arg must be None or str", STRIPNAME(striptype)); return NULL; } } return do_strip(self, striptype); } PyDoc_STRVAR(strip__doc__, "S.strip([chars]) -> str\n\ \n\ Return a copy of the string S with leading and trailing\n\ whitespace removed.\n\ If chars is given and not None, remove characters in chars instead."); static PyObject * unicode_strip(PyObject *self, PyObject *args) { if (PyTuple_GET_SIZE(args) == 0) return do_strip(self, BOTHSTRIP); /* Common case */ else return do_argstrip(self, BOTHSTRIP, args); } PyDoc_STRVAR(lstrip__doc__, "S.lstrip([chars]) -> str\n\ \n\ Return a copy of the string S with leading whitespace removed.\n\ If chars is given and not None, remove characters in chars instead."); static PyObject * unicode_lstrip(PyObject *self, PyObject *args) { if (PyTuple_GET_SIZE(args) == 0) return do_strip(self, LEFTSTRIP); /* Common case */ else return do_argstrip(self, LEFTSTRIP, args); } PyDoc_STRVAR(rstrip__doc__, "S.rstrip([chars]) -> str\n\ \n\ Return a copy of the string S with trailing whitespace removed.\n\ If chars is given and not None, remove characters in chars instead."); static PyObject * unicode_rstrip(PyObject *self, PyObject *args) { if (PyTuple_GET_SIZE(args) == 0) return do_strip(self, RIGHTSTRIP); /* Common case */ else return do_argstrip(self, RIGHTSTRIP, args); } static PyObject* unicode_repeat(PyObject *str, Py_ssize_t len) { PyObject *u; Py_ssize_t nchars, n; if (len < 1) _Py_RETURN_UNICODE_EMPTY(); /* no repeat, return original string */ if (len == 1) return unicode_result_unchanged(str); if (PyUnicode_READY(str) == -1) return NULL; if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) { PyErr_SetString(PyExc_OverflowError, "repeated string is too long"); return NULL; } nchars = len * PyUnicode_GET_LENGTH(str); u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str)); if (!u) return NULL; assert(PyUnicode_KIND(u) == PyUnicode_KIND(str)); if (PyUnicode_GET_LENGTH(str) == 1) { const int kind = PyUnicode_KIND(str); const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0); if (kind == PyUnicode_1BYTE_KIND) { void *to = PyUnicode_DATA(u); memset(to, (unsigned char)fill_char, len); } else if (kind == PyUnicode_2BYTE_KIND) { Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u); for (n = 0; n < len; ++n) ucs2[n] = fill_char; } else { Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u); assert(kind == PyUnicode_4BYTE_KIND); for (n = 0; n < len; ++n) ucs4[n] = fill_char; } } else { /* number of characters copied this far */ Py_ssize_t done = PyUnicode_GET_LENGTH(str); const Py_ssize_t char_size = PyUnicode_KIND(str); char *to = (char *) PyUnicode_DATA(u); memcpy(to, PyUnicode_DATA(str), PyUnicode_GET_LENGTH(str) * char_size); while (done < nchars) { n = (done <= nchars-done) ? done : nchars-done; memcpy(to + (done * char_size), to, n * char_size); done += n; } } assert(_PyUnicode_CheckConsistency(u, 1)); return u; } PyObject * PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount) { if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 || ensure_unicode(replstr) < 0) return NULL; return replace(str, substr, replstr, maxcount); } PyDoc_STRVAR(replace__doc__, "S.replace(old, new[, count]) -> str\n\ \n\ Return a copy of S with all occurrences of substring\n\ old replaced by new. If the optional argument count is\n\ given, only the first count occurrences are replaced."); static PyObject* unicode_replace(PyObject *self, PyObject *args) { PyObject *str1; PyObject *str2; Py_ssize_t maxcount = -1; if (!PyArg_ParseTuple(args, "UU|n:replace", &str1, &str2, &maxcount)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; return replace(self, str1, str2, maxcount); } static PyObject * unicode_repr(PyObject *unicode) { PyObject *repr; Py_ssize_t isize; Py_ssize_t osize, squote, dquote, i, o; Py_UCS4 max, quote; int ikind, okind, unchanged; void *idata, *odata; if (PyUnicode_READY(unicode) == -1) return NULL; isize = PyUnicode_GET_LENGTH(unicode); idata = PyUnicode_DATA(unicode); /* Compute length of output, quote characters, and maximum character */ osize = 0; max = 127; squote = dquote = 0; ikind = PyUnicode_KIND(unicode); for (i = 0; i < isize; i++) { Py_UCS4 ch = PyUnicode_READ(ikind, idata, i); Py_ssize_t incr = 1; switch (ch) { case '\'': squote++; break; case '"': dquote++; break; case '\\': case '\t': case '\r': case '\n': incr = 2; break; default: /* Fast-path ASCII */ if (ch < ' ' || ch == 0x7f) incr = 4; /* \xHH */ else if (ch < 0x7f) ; else if (Py_UNICODE_ISPRINTABLE(ch)) max = ch > max ? ch : max; else if (ch < 0x100) incr = 4; /* \xHH */ else if (ch < 0x10000) incr = 6; /* \uHHHH */ else incr = 10; /* \uHHHHHHHH */ } if (osize > PY_SSIZE_T_MAX - incr) { PyErr_SetString(PyExc_OverflowError, "string is too long to generate repr"); return NULL; } osize += incr; } quote = '\''; unchanged = (osize == isize); if (squote) { unchanged = 0; if (dquote) /* Both squote and dquote present. Use squote, and escape them */ osize += squote; else quote = '"'; } osize += 2; /* quotes */ repr = PyUnicode_New(osize, max); if (repr == NULL) return NULL; okind = PyUnicode_KIND(repr); odata = PyUnicode_DATA(repr); PyUnicode_WRITE(okind, odata, 0, quote); PyUnicode_WRITE(okind, odata, osize-1, quote); if (unchanged) { _PyUnicode_FastCopyCharacters(repr, 1, unicode, 0, isize); } else { for (i = 0, o = 1; i < isize; i++) { Py_UCS4 ch = PyUnicode_READ(ikind, idata, i); /* Escape quotes and backslashes */ if ((ch == quote) || (ch == '\\')) { PyUnicode_WRITE(okind, odata, o++, '\\'); PyUnicode_WRITE(okind, odata, o++, ch); continue; } /* Map special whitespace to '\t', \n', '\r' */ if (ch == '\t') { PyUnicode_WRITE(okind, odata, o++, '\\'); PyUnicode_WRITE(okind, odata, o++, 't'); } else if (ch == '\n') { PyUnicode_WRITE(okind, odata, o++, '\\'); PyUnicode_WRITE(okind, odata, o++, 'n'); } else if (ch == '\r') { PyUnicode_WRITE(okind, odata, o++, '\\'); PyUnicode_WRITE(okind, odata, o++, 'r'); } /* Map non-printable US ASCII to '\xhh' */ else if (ch < ' ' || ch == 0x7F) { PyUnicode_WRITE(okind, odata, o++, '\\'); PyUnicode_WRITE(okind, odata, o++, 'x'); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]); } /* Copy ASCII characters as-is */ else if (ch < 0x7F) { PyUnicode_WRITE(okind, odata, o++, ch); } /* Non-ASCII characters */ else { /* Map Unicode whitespace and control characters (categories Z* and C* except ASCII space) */ if (!Py_UNICODE_ISPRINTABLE(ch)) { PyUnicode_WRITE(okind, odata, o++, '\\'); /* Map 8-bit characters to '\xhh' */ if (ch <= 0xff) { PyUnicode_WRITE(okind, odata, o++, 'x'); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]); } /* Map 16-bit characters to '\uxxxx' */ else if (ch <= 0xffff) { PyUnicode_WRITE(okind, odata, o++, 'u'); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]); } /* Map 21-bit characters to '\U00xxxxxx' */ else { PyUnicode_WRITE(okind, odata, o++, 'U'); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]); PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]); } } /* Copy characters as-is */ else { PyUnicode_WRITE(okind, odata, o++, ch); } } } } /* Closing quote already added at the beginning */ assert(_PyUnicode_CheckConsistency(repr, 1)); return repr; } PyDoc_STRVAR(rfind__doc__, "S.rfind(sub[, start[, end]]) -> int\n\ \n\ Return the highest index in S where substring sub is found,\n\ such that sub is contained within S[start:end]. Optional\n\ arguments start and end are interpreted as in slice notation.\n\ \n\ Return -1 on failure."); static PyObject * unicode_rfind(PyObject *self, PyObject *args) { /* initialize variables to prevent gcc warning */ PyObject *substring = NULL; Py_ssize_t start = 0; Py_ssize_t end = 0; Py_ssize_t result; if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; result = any_find_slice(self, substring, start, end, -1); if (result == -2) return NULL; return PyLong_FromSsize_t(result); } PyDoc_STRVAR(rindex__doc__, "S.rindex(sub[, start[, end]]) -> int\n\ \n\ Return the highest index in S where substring sub is found,\n\ such that sub is contained within S[start:end]. Optional\n\ arguments start and end are interpreted as in slice notation.\n\ \n\ Raises ValueError when the substring is not found."); static PyObject * unicode_rindex(PyObject *self, PyObject *args) { /* initialize variables to prevent gcc warning */ PyObject *substring = NULL; Py_ssize_t start = 0; Py_ssize_t end = 0; Py_ssize_t result; if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; result = any_find_slice(self, substring, start, end, -1); if (result == -2) return NULL; if (result < 0) { PyErr_SetString(PyExc_ValueError, "substring not found"); return NULL; } return PyLong_FromSsize_t(result); } PyDoc_STRVAR(rjust__doc__, "S.rjust(width[, fillchar]) -> str\n\ \n\ Return S right-justified in a string of length width. Padding is\n\ done using the specified fill character (default is a space)."); static PyObject * unicode_rjust(PyObject *self, PyObject *args) { Py_ssize_t width; Py_UCS4 fillchar = ' '; if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; if (PyUnicode_GET_LENGTH(self) >= width) return unicode_result_unchanged(self); return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar); } PyObject * PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit) { if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0)) return NULL; return split(s, sep, maxsplit); } PyDoc_STRVAR(split__doc__, "S.split(sep=None, maxsplit=-1) -> list of strings\n\ \n\ Return a list of the words in S, using sep as the\n\ delimiter string. If maxsplit is given, at most maxsplit\n\ splits are done. If sep is not specified or is None, any\n\ whitespace string is a separator and empty strings are\n\ removed from the result."); static PyObject* unicode_split(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"sep", "maxsplit", 0}; PyObject *substring = Py_None; Py_ssize_t maxcount = -1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split", kwlist, &substring, &maxcount)) return NULL; if (substring == Py_None) return split(self, NULL, maxcount); if (PyUnicode_Check(substring)) return split(self, substring, maxcount); PyErr_Format(PyExc_TypeError, "must be str or None, not %.100s", Py_TYPE(substring)->tp_name); return NULL; } PyObject * PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj) { PyObject* out; int kind1, kind2; void *buf1, *buf2; Py_ssize_t len1, len2; if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0) return NULL; kind1 = PyUnicode_KIND(str_obj); kind2 = PyUnicode_KIND(sep_obj); len1 = PyUnicode_GET_LENGTH(str_obj); len2 = PyUnicode_GET_LENGTH(sep_obj); if (kind1 < kind2 || len1 < len2) { _Py_INCREF_UNICODE_EMPTY(); if (!unicode_empty) out = NULL; else { out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty); Py_DECREF(unicode_empty); } return out; } buf1 = PyUnicode_DATA(str_obj); buf2 = PyUnicode_DATA(sep_obj); if (kind2 != kind1) { buf2 = _PyUnicode_AsKind(sep_obj, kind1); if (!buf2) return NULL; } switch (kind1) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj)) out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2); else out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2); break; case PyUnicode_2BYTE_KIND: out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2); break; case PyUnicode_4BYTE_KIND: out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2); break; default: assert(0); out = 0; } if (kind2 != kind1) PyMem_Free(buf2); return out; } PyObject * PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj) { PyObject* out; int kind1, kind2; void *buf1, *buf2; Py_ssize_t len1, len2; if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0) return NULL; kind1 = PyUnicode_KIND(str_obj); kind2 = PyUnicode_KIND(sep_obj); len1 = PyUnicode_GET_LENGTH(str_obj); len2 = PyUnicode_GET_LENGTH(sep_obj); if (kind1 < kind2 || len1 < len2) { _Py_INCREF_UNICODE_EMPTY(); if (!unicode_empty) out = NULL; else { out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj); Py_DECREF(unicode_empty); } return out; } buf1 = PyUnicode_DATA(str_obj); buf2 = PyUnicode_DATA(sep_obj); if (kind2 != kind1) { buf2 = _PyUnicode_AsKind(sep_obj, kind1); if (!buf2) return NULL; } switch (kind1) { case PyUnicode_1BYTE_KIND: if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj)) out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2); else out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2); break; case PyUnicode_2BYTE_KIND: out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2); break; case PyUnicode_4BYTE_KIND: out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2); break; default: assert(0); out = 0; } if (kind2 != kind1) PyMem_Free(buf2); return out; } PyDoc_STRVAR(partition__doc__, "S.partition(sep) -> (head, sep, tail)\n\ \n\ Search for the separator sep in S, and return the part before it,\n\ the separator itself, and the part after it. If the separator is not\n\ found, return S and two empty strings."); static PyObject* unicode_partition(PyObject *self, PyObject *separator) { return PyUnicode_Partition(self, separator); } PyDoc_STRVAR(rpartition__doc__, "S.rpartition(sep) -> (head, sep, tail)\n\ \n\ Search for the separator sep in S, starting at the end of S, and return\n\ the part before it, the separator itself, and the part after it. If the\n\ separator is not found, return two empty strings and S."); static PyObject* unicode_rpartition(PyObject *self, PyObject *separator) { return PyUnicode_RPartition(self, separator); } PyObject * PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit) { if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0)) return NULL; return rsplit(s, sep, maxsplit); } PyDoc_STRVAR(rsplit__doc__, "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\ \n\ Return a list of the words in S, using sep as the\n\ delimiter string, starting at the end of the string and\n\ working to the front. If maxsplit is given, at most maxsplit\n\ splits are done. If sep is not specified, any whitespace string\n\ is a separator."); static PyObject* unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"sep", "maxsplit", 0}; PyObject *substring = Py_None; Py_ssize_t maxcount = -1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit", kwlist, &substring, &maxcount)) return NULL; if (substring == Py_None) return rsplit(self, NULL, maxcount); if (PyUnicode_Check(substring)) return rsplit(self, substring, maxcount); PyErr_Format(PyExc_TypeError, "must be str or None, not %.100s", Py_TYPE(substring)->tp_name); return NULL; } PyDoc_STRVAR(splitlines__doc__, "S.splitlines([keepends]) -> list of strings\n\ \n\ Return a list of the lines in S, breaking at line boundaries.\n\ Line breaks are not included in the resulting list unless keepends\n\ is given and true."); static PyObject* unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"keepends", 0}; int keepends = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines", kwlist, &keepends)) return NULL; return PyUnicode_Splitlines(self, keepends); } static PyObject *unicode_str(PyObject *self) { return unicode_result_unchanged(self); } PyDoc_STRVAR(swapcase__doc__, "S.swapcase() -> str\n\ \n\ Return a copy of S with uppercase characters converted to lowercase\n\ and vice versa."); static PyObject* unicode_swapcase(PyObject *self) { if (PyUnicode_READY(self) == -1) return NULL; return case_operation(self, do_swapcase); } /*[clinic input] @staticmethod str.maketrans as unicode_maketrans x: object y: unicode=NULL z: unicode=NULL / Return a translation table usable for str.translate(). If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result. [clinic start generated code]*/ static PyObject * unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z) /*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/ { PyObject *new = NULL, *key, *value; Py_ssize_t i = 0; int res; new = PyDict_New(); if (!new) return NULL; if (y != NULL) { int x_kind, y_kind, z_kind; void *x_data, *y_data, *z_data; /* x must be a string too, of equal length */ if (!PyUnicode_Check(x)) { PyErr_SetString(PyExc_TypeError, "first maketrans argument must " "be a string if there is a second argument"); goto err; } if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) { PyErr_SetString(PyExc_ValueError, "the first two maketrans " "arguments must have equal length"); goto err; } /* create entries for translating chars in x to those in y */ x_kind = PyUnicode_KIND(x); y_kind = PyUnicode_KIND(y); x_data = PyUnicode_DATA(x); y_data = PyUnicode_DATA(y); for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) { key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i)); if (!key) goto err; value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i)); if (!value) { Py_DECREF(key); goto err; } res = PyDict_SetItem(new, key, value); Py_DECREF(key); Py_DECREF(value); if (res < 0) goto err; } /* create entries for deleting chars in z */ if (z != NULL) { z_kind = PyUnicode_KIND(z); z_data = PyUnicode_DATA(z); for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) { key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i)); if (!key) goto err; res = PyDict_SetItem(new, key, Py_None); Py_DECREF(key); if (res < 0) goto err; } } } else { int kind; void *data; /* x must be a dict */ if (!PyDict_CheckExact(x)) { PyErr_SetString(PyExc_TypeError, "if you give only one argument " "to maketrans it must be a dict"); goto err; } /* copy entries into the new dict, converting string keys to int keys */ while (PyDict_Next(x, &i, &key, &value)) { if (PyUnicode_Check(key)) { /* convert string keys to integer keys */ PyObject *newkey; if (PyUnicode_GET_LENGTH(key) != 1) { PyErr_SetString(PyExc_ValueError, "string keys in translate " "table must be of length 1"); goto err; } kind = PyUnicode_KIND(key); data = PyUnicode_DATA(key); newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0)); if (!newkey) goto err; res = PyDict_SetItem(new, newkey, value); Py_DECREF(newkey); if (res < 0) goto err; } else if (PyLong_Check(key)) { /* just keep integer keys */ if (PyDict_SetItem(new, key, value) < 0) goto err; } else { PyErr_SetString(PyExc_TypeError, "keys in translate table must " "be strings or integers"); goto err; } } } return new; err: Py_DECREF(new); return NULL; } PyDoc_STRVAR(translate__doc__, "S.translate(table) -> str\n\ \n\ Return a copy of the string S in which each character has been mapped\n\ through the given translation table. The table must implement\n\ lookup/indexing via __getitem__, for instance a dictionary or list,\n\ mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\ this operation raises LookupError, the character is left untouched.\n\ Characters mapped to None are deleted."); static PyObject* unicode_translate(PyObject *self, PyObject *table) { return _PyUnicode_TranslateCharmap(self, table, "ignore"); } PyDoc_STRVAR(upper__doc__, "S.upper() -> str\n\ \n\ Return a copy of S converted to uppercase."); static PyObject* unicode_upper(PyObject *self) { if (PyUnicode_READY(self) == -1) return NULL; if (PyUnicode_IS_ASCII(self)) return ascii_upper_or_lower(self, 0); return case_operation(self, do_upper); } PyDoc_STRVAR(zfill__doc__, "S.zfill(width) -> str\n\ \n\ Pad a numeric string S with zeros on the left, to fill a field\n\ of the specified width. The string S is never truncated."); static PyObject * unicode_zfill(PyObject *self, PyObject *args) { Py_ssize_t fill; PyObject *u; Py_ssize_t width; int kind; void *data; Py_UCS4 chr; if (!PyArg_ParseTuple(args, "n:zfill", &width)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; if (PyUnicode_GET_LENGTH(self) >= width) return unicode_result_unchanged(self); fill = width - PyUnicode_GET_LENGTH(self); u = pad(self, fill, 0, '0'); if (u == NULL) return NULL; kind = PyUnicode_KIND(u); data = PyUnicode_DATA(u); chr = PyUnicode_READ(kind, data, fill); if (chr == '+' || chr == '-') { /* move sign to beginning of string */ PyUnicode_WRITE(kind, data, 0, chr); PyUnicode_WRITE(kind, data, fill, '0'); } assert(_PyUnicode_CheckConsistency(u, 1)); return u; } #if 0 static PyObject * unicode__decimal2ascii(PyObject *self) { return PyUnicode_TransformDecimalAndSpaceToASCII(self); } #endif PyDoc_STRVAR(startswith__doc__, "S.startswith(prefix[, start[, end]]) -> bool\n\ \n\ Return True if S starts with the specified prefix, False otherwise.\n\ With optional start, test S beginning at that position.\n\ With optional end, stop comparing S at that position.\n\ prefix can also be a tuple of strings to try."); static PyObject * unicode_startswith(PyObject *self, PyObject *args) { PyObject *subobj; PyObject *substring; Py_ssize_t start = 0; Py_ssize_t end = PY_SSIZE_T_MAX; int result; if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end)) return NULL; if (PyTuple_Check(subobj)) { Py_ssize_t i; for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { substring = PyTuple_GET_ITEM(subobj, i); if (!PyUnicode_Check(substring)) { PyErr_Format(PyExc_TypeError, "tuple for startswith must only contain str, " "not %.100s", Py_TYPE(substring)->tp_name); return NULL; } result = tailmatch(self, substring, start, end, -1); if (result == -1) return NULL; if (result) { Py_RETURN_TRUE; } } /* nothing matched */ Py_RETURN_FALSE; } if (!PyUnicode_Check(subobj)) { PyErr_Format(PyExc_TypeError, "startswith first arg must be str or " "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name); return NULL; } result = tailmatch(self, subobj, start, end, -1); if (result == -1) return NULL; return PyBool_FromLong(result); } PyDoc_STRVAR(endswith__doc__, "S.endswith(suffix[, start[, end]]) -> bool\n\ \n\ Return True if S ends with the specified suffix, False otherwise.\n\ With optional start, test S beginning at that position.\n\ With optional end, stop comparing S at that position.\n\ suffix can also be a tuple of strings to try."); static PyObject * unicode_endswith(PyObject *self, PyObject *args) { PyObject *subobj; PyObject *substring; Py_ssize_t start = 0; Py_ssize_t end = PY_SSIZE_T_MAX; int result; if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end)) return NULL; if (PyTuple_Check(subobj)) { Py_ssize_t i; for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { substring = PyTuple_GET_ITEM(subobj, i); if (!PyUnicode_Check(substring)) { PyErr_Format(PyExc_TypeError, "tuple for endswith must only contain str, " "not %.100s", Py_TYPE(substring)->tp_name); return NULL; } result = tailmatch(self, substring, start, end, +1); if (result == -1) return NULL; if (result) { Py_RETURN_TRUE; } } Py_RETURN_FALSE; } if (!PyUnicode_Check(subobj)) { PyErr_Format(PyExc_TypeError, "endswith first arg must be str or " "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name); return NULL; } result = tailmatch(self, subobj, start, end, +1); if (result == -1) return NULL; return PyBool_FromLong(result); } static inline void _PyUnicodeWriter_Update(_PyUnicodeWriter *writer) { writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer); writer->data = PyUnicode_DATA(writer->buffer); if (!writer->readonly) { writer->kind = PyUnicode_KIND(writer->buffer); writer->size = PyUnicode_GET_LENGTH(writer->buffer); } else { /* use a value smaller than PyUnicode_1BYTE_KIND() so _PyUnicodeWriter_PrepareKind() will copy the buffer. */ writer->kind = PyUnicode_WCHAR_KIND; assert(writer->kind <= PyUnicode_1BYTE_KIND); /* Copy-on-write mode: set buffer size to 0 so * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on * next write. */ writer->size = 0; } } void _PyUnicodeWriter_Init(_PyUnicodeWriter *writer) { bzero(writer, sizeof(*writer)); /* ASCII is the bare minimum */ writer->min_char = 127; /* use a value smaller than PyUnicode_1BYTE_KIND() so _PyUnicodeWriter_PrepareKind() will copy the buffer. */ writer->kind = PyUnicode_WCHAR_KIND; assert(writer->kind <= PyUnicode_1BYTE_KIND); } int _PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer, Py_ssize_t length, Py_UCS4 maxchar) { Py_ssize_t newlen; PyObject *newbuffer; assert(maxchar <= MAX_UNICODE); /* ensure that the _PyUnicodeWriter_Prepare macro was used */ assert((maxchar > writer->maxchar && length >= 0) || length > 0); if (length > PY_SSIZE_T_MAX - writer->pos) { PyErr_NoMemory(); return -1; } newlen = writer->pos + length; maxchar = Py_MAX(maxchar, writer->min_char); if (writer->buffer == NULL) { assert(!writer->readonly); if (writer->overallocate && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) { /* overallocate to limit the number of realloc() */ newlen += newlen / OVERALLOCATE_FACTOR; } if (newlen < writer->min_length) newlen = writer->min_length; writer->buffer = PyUnicode_New(newlen, maxchar); if (writer->buffer == NULL) return -1; } else if (newlen > writer->size) { if (writer->overallocate && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) { /* overallocate to limit the number of realloc() */ newlen += newlen / OVERALLOCATE_FACTOR; } if (newlen < writer->min_length) newlen = writer->min_length; if (maxchar > writer->maxchar || writer->readonly) { /* resize + widen */ maxchar = Py_MAX(maxchar, writer->maxchar); newbuffer = PyUnicode_New(newlen, maxchar); if (newbuffer == NULL) return -1; _PyUnicode_FastCopyCharacters(newbuffer, 0, writer->buffer, 0, writer->pos); Py_DECREF(writer->buffer); writer->readonly = 0; } else { newbuffer = resize_compact(writer->buffer, newlen); if (newbuffer == NULL) return -1; } writer->buffer = newbuffer; } else if (maxchar > writer->maxchar) { assert(!writer->readonly); newbuffer = PyUnicode_New(writer->size, maxchar); if (newbuffer == NULL) return -1; _PyUnicode_FastCopyCharacters(newbuffer, 0, writer->buffer, 0, writer->pos); Py_SETREF(writer->buffer, newbuffer); } _PyUnicodeWriter_Update(writer); return 0; #undef OVERALLOCATE_FACTOR } int _PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer, enum PyUnicode_Kind kind) { Py_UCS4 maxchar; /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */ assert(writer->kind < kind); switch (kind) { case PyUnicode_1BYTE_KIND: maxchar = 0xff; break; case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break; case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break; default: assert(0 && "invalid kind"); return -1; } return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar); } static inline int _PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch) { assert(ch <= MAX_UNICODE); if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0) return -1; PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch); writer->pos++; return 0; } int _PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch) { return _PyUnicodeWriter_WriteCharInline(writer, ch); } int _PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str) { Py_UCS4 maxchar; Py_ssize_t len; if (PyUnicode_READY(str) == -1) return -1; len = PyUnicode_GET_LENGTH(str); if (len == 0) return 0; maxchar = PyUnicode_MAX_CHAR_VALUE(str); if (maxchar > writer->maxchar || len > writer->size - writer->pos) { if (writer->buffer == NULL && !writer->overallocate) { assert(_PyUnicode_CheckConsistency(str, 1)); writer->readonly = 1; Py_INCREF(str); writer->buffer = str; _PyUnicodeWriter_Update(writer); writer->pos += len; return 0; } if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1) return -1; } _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos, str, 0, len); writer->pos += len; return 0; } int _PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str, Py_ssize_t start, Py_ssize_t end) { Py_UCS4 maxchar; Py_ssize_t len; if (PyUnicode_READY(str) == -1) return -1; assert(0 <= start); assert(end <= PyUnicode_GET_LENGTH(str)); assert(start <= end); if (end == 0) return 0; if (start == 0 && end == PyUnicode_GET_LENGTH(str)) return _PyUnicodeWriter_WriteStr(writer, str); if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar) maxchar = _PyUnicode_FindMaxChar(str, start, end); else maxchar = writer->maxchar; len = end - start; if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0) return -1; _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos, str, start, len); writer->pos += len; return 0; } int _PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer, const char *ascii, Py_ssize_t len) { if (len == -1) len = strlen(ascii); assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128); if (writer->buffer == NULL && !writer->overallocate) { PyObject *str; str = _PyUnicode_FromASCII(ascii, len); if (str == NULL) return -1; writer->readonly = 1; writer->buffer = str; _PyUnicodeWriter_Update(writer); writer->pos += len; return 0; } if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1) return -1; switch (writer->kind) { case PyUnicode_1BYTE_KIND: { const Py_UCS1 *str = (const Py_UCS1 *)ascii; Py_UCS1 *data = writer->data; memcpy(data + writer->pos, str, len); break; } case PyUnicode_2BYTE_KIND: { _PyUnicode_CONVERT_BYTES( Py_UCS1, Py_UCS2, ascii, ascii + len, (Py_UCS2 *)writer->data + writer->pos); break; } case PyUnicode_4BYTE_KIND: { _PyUnicode_CONVERT_BYTES( Py_UCS1, Py_UCS4, ascii, ascii + len, (Py_UCS4 *)writer->data + writer->pos); break; } default: assert(0); } writer->pos += len; return 0; } int _PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer, const char *str, Py_ssize_t len) { Py_UCS4 maxchar; maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len); if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1) return -1; unicode_write_cstr(writer->buffer, writer->pos, str, len); writer->pos += len; return 0; } PyObject * _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer) { PyObject *str; if (writer->pos == 0) { Py_CLEAR(writer->buffer); _Py_RETURN_UNICODE_EMPTY(); } str = writer->buffer; writer->buffer = NULL; if (writer->readonly) { assert(PyUnicode_GET_LENGTH(str) == writer->pos); return str; } if (PyUnicode_GET_LENGTH(str) != writer->pos) { PyObject *str2; str2 = resize_compact(str, writer->pos); if (str2 == NULL) { Py_DECREF(str); return NULL; } str = str2; } assert(_PyUnicode_CheckConsistency(str, 1)); return unicode_result_ready(str); } void _PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer) { Py_CLEAR(writer->buffer); } #include "third_party/python/Objects/stringlib/unicode_format.inc" PyDoc_STRVAR(format__doc__, "S.format(*args, **kwargs) -> str\n\ \n\ Return a formatted version of S, using substitutions from args and kwargs.\n\ The substitutions are identified by braces ('{' and '}')."); PyDoc_STRVAR(format_map__doc__, "S.format_map(mapping) -> str\n\ \n\ Return a formatted version of S, using substitutions from mapping.\n\ The substitutions are identified by braces ('{' and '}')."); static PyObject * unicode__format__(PyObject* self, PyObject* args) { PyObject *format_spec; _PyUnicodeWriter writer; int ret; if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) return NULL; if (PyUnicode_READY(self) == -1) return NULL; _PyUnicodeWriter_Init(&writer); ret = _PyUnicode_FormatAdvancedWriter(&writer, self, format_spec, 0, PyUnicode_GET_LENGTH(format_spec)); if (ret == -1) { _PyUnicodeWriter_Dealloc(&writer); return NULL; } return _PyUnicodeWriter_Finish(&writer); } PyDoc_STRVAR(p_format__doc__, "S.__format__(format_spec) -> str\n\ \n\ Return a formatted version of S as described by format_spec."); static PyObject * unicode__sizeof__(PyObject *v) { Py_ssize_t size; /* If it's a compact object, account for base structure + character data. */ if (PyUnicode_IS_COMPACT_ASCII(v)) size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1; else if (PyUnicode_IS_COMPACT(v)) size = sizeof(PyCompactUnicodeObject) + (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v); else { /* If it is a two-block object, account for base object, and for character block if present. */ size = sizeof(PyUnicodeObject); if (_PyUnicode_DATA_ANY(v)) size += (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v); } /* If the wstr pointer is present, account for it unless it is shared with the data pointer. Check if the data is not shared. */ if (_PyUnicode_HAS_WSTR_MEMORY(v)) size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t); if (_PyUnicode_HAS_UTF8_MEMORY(v)) size += PyUnicode_UTF8_LENGTH(v) + 1; return PyLong_FromSsize_t(size); } PyDoc_STRVAR(sizeof__doc__, "S.__sizeof__() -> size of S in memory, in bytes"); static PyObject * unicode_getnewargs(PyObject *v) { PyObject *copy = _PyUnicode_Copy(v); if (!copy) return NULL; return Py_BuildValue("(N)", copy); } static PyMethodDef unicode_methods[] = { {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__}, {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__}, {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__}, {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__}, {"join", (PyCFunction) unicode_join, METH_O, join__doc__}, {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__}, {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__}, {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__}, {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__}, {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__}, {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS | METH_KEYWORDS, expandtabs__doc__}, {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__}, {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__}, {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__}, {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__}, {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__}, {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__}, {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__}, {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__}, {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__}, {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__}, {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__}, {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__}, {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__}, {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__}, {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__}, {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__}, {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__}, {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__}, {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__}, {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__}, {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__}, {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__}, {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__}, {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__}, {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__}, {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__}, {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__}, {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__}, {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__}, {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__}, {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__}, {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__}, {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__}, UNICODE_MAKETRANS_METHODDEF {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__}, #if 0 /* These methods are just used for debugging the implementation. */ {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS}, #endif {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS}, {NULL, NULL} }; static PyObject * unicode_mod(PyObject *v, PyObject *w) { if (!PyUnicode_Check(v)) Py_RETURN_NOTIMPLEMENTED; return PyUnicode_Format(v, w); } static PyNumberMethods unicode_as_number = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ unicode_mod, /*nb_remainder*/ }; static PySequenceMethods unicode_as_sequence = { (lenfunc) unicode_length, /* sq_length */ PyUnicode_Concat, /* sq_concat */ (ssizeargfunc) unicode_repeat, /* sq_repeat */ (ssizeargfunc) unicode_getitem, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ PyUnicode_Contains, /* sq_contains */ }; static PyObject* unicode_subscript(PyObject* self, PyObject* item) { if (PyUnicode_READY(self) == -1) return NULL; if (PyIndex_Check(item)) { Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return NULL; if (i < 0) i += PyUnicode_GET_LENGTH(self); return unicode_getitem(self, i); } else if (PySlice_Check(item)) { Py_ssize_t start, stop, step, slicelength, cur, i; PyObject *result; void *src_data, *dest_data; int src_kind, dest_kind; Py_UCS4 ch, max_char, kind_limit; if (PySlice_Unpack(item, &start, &stop, &step) < 0) { return NULL; } slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self), &start, &stop, step); if (slicelength <= 0) { _Py_RETURN_UNICODE_EMPTY(); } else if (start == 0 && step == 1 && slicelength == PyUnicode_GET_LENGTH(self)) { return unicode_result_unchanged(self); } else if (step == 1) { return PyUnicode_Substring(self, start, start + slicelength); } /* General case */ src_kind = PyUnicode_KIND(self); src_data = PyUnicode_DATA(self); if (!PyUnicode_IS_ASCII(self)) { kind_limit = kind_maxchar_limit(src_kind); max_char = 0; for (cur = start, i = 0; i < slicelength; cur += step, i++) { ch = PyUnicode_READ(src_kind, src_data, cur); if (ch > max_char) { max_char = ch; if (max_char >= kind_limit) break; } } } else max_char = 127; result = PyUnicode_New(slicelength, max_char); if (result == NULL) return NULL; dest_kind = PyUnicode_KIND(result); dest_data = PyUnicode_DATA(result); for (cur = start, i = 0; i < slicelength; cur += step, i++) { Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur); PyUnicode_WRITE(dest_kind, dest_data, i, ch); } assert(_PyUnicode_CheckConsistency(result, 1)); return result; } else { PyErr_SetString(PyExc_TypeError, "string indices must be integers"); return NULL; } } static PyMappingMethods unicode_as_mapping = { (lenfunc)unicode_length, /* mp_length */ (binaryfunc)unicode_subscript, /* mp_subscript */ (objobjargproc)0, /* mp_ass_subscript */ }; /* Helpers for PyUnicode_Format() */ struct unicode_formatter_t { PyObject *args; int args_owned; Py_ssize_t arglen, argidx; PyObject *dict; enum PyUnicode_Kind fmtkind; Py_ssize_t fmtcnt, fmtpos; void *fmtdata; PyObject *fmtstr; _PyUnicodeWriter writer; }; struct unicode_format_arg_t { Py_UCS4 ch; int flags; Py_ssize_t width; int prec; int sign; }; static PyObject * unicode_format_getnextarg(struct unicode_formatter_t *ctx) { Py_ssize_t argidx = ctx->argidx; if (argidx < ctx->arglen) { ctx->argidx++; if (ctx->arglen < 0) return ctx->args; else return PyTuple_GetItem(ctx->args, argidx); } PyErr_SetString(PyExc_TypeError, "not enough arguments for format string"); return NULL; } /* Returns a new reference to a PyUnicode object, or NULL on failure. */ /* Format a float into the writer if the writer is not NULL, or into *p_output otherwise. Return 0 on success, raise an exception and return -1 on error. */ static int formatfloat(PyObject *v, struct unicode_format_arg_t *arg, PyObject **p_output, _PyUnicodeWriter *writer) { char *p; double x; Py_ssize_t len; int prec; int dtoa_flags; x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) return -1; prec = arg->prec; if (prec < 0) prec = 6; if (arg->flags & F_ALT) dtoa_flags = Py_DTSF_ALT; else dtoa_flags = 0; p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL); if (p == NULL) return -1; len = strlen(p); if (writer) { if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) { PyMem_Free(p); return -1; } } else *p_output = _PyUnicode_FromASCII(p, len); PyMem_Free(p); return 0; } /* formatlong() emulates the format codes d, u, o, x and X, and * the F_ALT flag, for Python's long (unbounded) ints. It's not used for * Python's regular ints. * Return value: a new PyUnicodeObject*, or NULL if error. * The output string is of the form * "-"? ("0x" | "0X")? digit+ * "0x"/"0X" are present only for x and X conversions, with F_ALT * set in flags. The case of hex digits will be correct, * There will be at least prec digits, zero-filled on the left if * necessary to get that many. * val object to be converted * flags bitmask of format flags; only F_ALT is looked at * prec minimum number of digits; 0-fill on left if needed * type a character in [duoxX]; u acts the same as d * * CAUTION: o, x and X conversions on regular ints can never * produce a '-' sign, but can for Python's unbounded ints. */ PyObject * _PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type) { PyObject *result = NULL; char *buf; Py_ssize_t i; int sign; /* 1 if '-', else 0 */ int len; /* number of characters */ Py_ssize_t llen; int numdigits; /* len == numnondigits + numdigits */ int numnondigits = 0; /* Avoid exceeding SSIZE_T_MAX */ if (prec > INT_MAX-3) { PyErr_SetString(PyExc_OverflowError, "precision too large"); return NULL; } assert(PyLong_Check(val)); switch (type) { default: assert(!"'type' not in [diuoxX]"); case 'd': case 'i': case 'u': /* int and int subclasses should print numerically when a numeric */ /* format code is used (see issue18780) */ result = PyNumber_ToBase(val, 10); break; case 'o': numnondigits = 2; result = PyNumber_ToBase(val, 8); break; case 'x': case 'X': numnondigits = 2; result = PyNumber_ToBase(val, 16); break; } if (!result) return NULL; assert(unicode_modifiable(result)); assert(PyUnicode_IS_READY(result)); assert(PyUnicode_IS_ASCII(result)); /* To modify the string in-place, there can only be one reference. */ if (Py_REFCNT(result) != 1) { Py_DECREF(result); PyErr_BadInternalCall(); return NULL; } buf = PyUnicode_DATA(result); llen = PyUnicode_GET_LENGTH(result); if (llen > INT_MAX) { Py_DECREF(result); PyErr_SetString(PyExc_ValueError, "string too large in _PyUnicode_FormatLong"); return NULL; } len = (int)llen; sign = buf[0] == '-'; numnondigits += sign; numdigits = len - numnondigits; assert(numdigits > 0); /* Get rid of base marker unless F_ALT */ if (((alt) == 0 && (type == 'o' || type == 'x' || type == 'X'))) { assert(buf[sign] == '0'); assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' || buf[sign+1] == 'o'); numnondigits -= 2; buf += 2; len -= 2; if (sign) buf[0] = '-'; assert(len == numnondigits + numdigits); assert(numdigits > 0); } /* Fill with leading zeroes to meet minimum width. */ if (prec > numdigits) { PyObject *r1 = PyBytes_FromStringAndSize(NULL, numnondigits + prec); char *b1; if (!r1) { Py_DECREF(result); return NULL; } b1 = PyBytes_AS_STRING(r1); for (i = 0; i < numnondigits; ++i) *b1++ = *buf++; for (i = 0; i < prec - numdigits; i++) *b1++ = '0'; for (i = 0; i < numdigits; i++) *b1++ = *buf++; *b1 = '\0'; Py_DECREF(result); result = r1; buf = PyBytes_AS_STRING(result); len = numnondigits + prec; } /* Fix up case for hex conversions. */ if (type == 'X') { /* Need to convert all lower case letters to upper case. and need to convert 0x to 0X (and -0x to -0X). */ for (i = 0; i < len; i++) if (buf[i] >= 'a' && buf[i] <= 'x') buf[i] -= 'a'-'A'; } if (!PyUnicode_Check(result) || buf != PyUnicode_DATA(result)) { PyObject *unicode; unicode = _PyUnicode_FromASCII(buf, len); Py_DECREF(result); result = unicode; } else if (len != PyUnicode_GET_LENGTH(result)) { if (PyUnicode_Resize(&result, len) < 0) Py_CLEAR(result); } return result; } /* Format an integer or a float as an integer. * Return 1 if the number has been formatted into the writer, * 0 if the number has been formatted into *p_output * -1 and raise an exception on error */ static int mainformatlong(PyObject *v, struct unicode_format_arg_t *arg, PyObject **p_output, _PyUnicodeWriter *writer) { PyObject *iobj, *res; char type = (char)arg->ch; if (!PyNumber_Check(v)) goto wrongtype; /* make sure number is a type of integer for o, x, and X */ if (!PyLong_Check(v)) { if (type == 'o' || type == 'x' || type == 'X') { iobj = PyNumber_Index(v); if (iobj == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) goto wrongtype; return -1; } } else { iobj = PyNumber_Long(v); if (iobj == NULL ) { if (PyErr_ExceptionMatches(PyExc_TypeError)) goto wrongtype; return -1; } } assert(PyLong_Check(iobj)); } else { iobj = v; Py_INCREF(iobj); } if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1 && !(arg->flags & (F_SIGN | F_BLANK)) && type != 'X') { /* Fast path */ int alternate = arg->flags & F_ALT; int base; switch(type) { default: assert(0 && "'type' not in [diuoxX]"); case 'd': case 'i': case 'u': base = 10; break; case 'o': base = 8; break; case 'x': case 'X': base = 16; break; } if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) { Py_DECREF(iobj); return -1; } Py_DECREF(iobj); return 1; } res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type); Py_DECREF(iobj); if (res == NULL) return -1; *p_output = res; return 0; wrongtype: switch(type) { case 'o': case 'x': case 'X': PyErr_Format(PyExc_TypeError, "%%%c format: an integer is required, " "not %.200s", type, Py_TYPE(v)->tp_name); break; default: PyErr_Format(PyExc_TypeError, "%%%c format: a number is required, " "not %.200s", type, Py_TYPE(v)->tp_name); break; } return -1; } static Py_UCS4 formatchar(PyObject *v) { /* presume that the buffer is at least 3 characters long */ if (PyUnicode_Check(v)) { if (PyUnicode_GET_LENGTH(v) == 1) { return PyUnicode_READ_CHAR(v, 0); } goto onError; } else { PyObject *iobj; long x; /* make sure number is a type of integer */ if (!PyLong_Check(v)) { iobj = PyNumber_Index(v); if (iobj == NULL) { goto onError; } x = PyLong_AsLong(iobj); Py_DECREF(iobj); } else { x = PyLong_AsLong(v); } if (x == -1 && PyErr_Occurred()) goto onError; if (x < 0 || x > MAX_UNICODE) { PyErr_SetString(PyExc_OverflowError, "%c arg not in range(0x110000)"); return (Py_UCS4) -1; } return (Py_UCS4) x; } onError: PyErr_SetString(PyExc_TypeError, "%c requires int or char"); return (Py_UCS4) -1; } /* Parse options of an argument: flags, width, precision. Handle also "%(name)" syntax. Return 0 if the argument has been formatted into arg->str. Return 1 if the argument has been written into ctx->writer, Raise an exception and return -1 on error. */ static int unicode_format_arg_parse(struct unicode_formatter_t *ctx, struct unicode_format_arg_t *arg) { #define FORMAT_READ(ctx) \ PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos) PyObject *v; if (arg->ch == '(') { /* Get argument value from a dictionary. Example: "%(name)s". */ Py_ssize_t keystart; Py_ssize_t keylen; PyObject *key; int pcount = 1; if (ctx->dict == NULL) { PyErr_SetString(PyExc_TypeError, "format requires a mapping"); return -1; } ++ctx->fmtpos; --ctx->fmtcnt; keystart = ctx->fmtpos; /* Skip over balanced parentheses */ while (pcount > 0 && --ctx->fmtcnt >= 0) { arg->ch = FORMAT_READ(ctx); if (arg->ch == ')') --pcount; else if (arg->ch == '(') ++pcount; ctx->fmtpos++; } keylen = ctx->fmtpos - keystart - 1; if (ctx->fmtcnt < 0 || pcount > 0) { PyErr_SetString(PyExc_ValueError, "incomplete format key"); return -1; } key = PyUnicode_Substring(ctx->fmtstr, keystart, keystart + keylen); if (key == NULL) return -1; if (ctx->args_owned) { ctx->args_owned = 0; Py_DECREF(ctx->args); } ctx->args = PyObject_GetItem(ctx->dict, key); Py_DECREF(key); if (ctx->args == NULL) return -1; ctx->args_owned = 1; ctx->arglen = -1; ctx->argidx = -2; } /* Parse flags. Example: "%+i" => flags=F_SIGN. */ while (--ctx->fmtcnt >= 0) { arg->ch = FORMAT_READ(ctx); ctx->fmtpos++; switch (arg->ch) { case '-': arg->flags |= F_LJUST; continue; case '+': arg->flags |= F_SIGN; continue; case ' ': arg->flags |= F_BLANK; continue; case '#': arg->flags |= F_ALT; continue; case '0': arg->flags |= F_ZERO; continue; } break; } /* Parse width. Example: "%10s" => width=10 */ if (arg->ch == '*') { v = unicode_format_getnextarg(ctx); if (v == NULL) return -1; if (!PyLong_Check(v)) { PyErr_SetString(PyExc_TypeError, "* wants int"); return -1; } arg->width = PyLong_AsSsize_t(v); if (arg->width == -1 && PyErr_Occurred()) return -1; if (arg->width < 0) { arg->flags |= F_LJUST; arg->width = -arg->width; } if (--ctx->fmtcnt >= 0) { arg->ch = FORMAT_READ(ctx); ctx->fmtpos++; } } else if (arg->ch >= '0' && arg->ch <= '9') { arg->width = arg->ch - '0'; while (--ctx->fmtcnt >= 0) { arg->ch = FORMAT_READ(ctx); ctx->fmtpos++; if (arg->ch < '0' || arg->ch > '9') break; /* Since arg->ch is unsigned, the RHS would end up as unsigned, mixing signed and unsigned comparison. Since arg->ch is between '0' and '9', casting to int is safe. */ if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) { PyErr_SetString(PyExc_ValueError, "width too big"); return -1; } arg->width = arg->width*10 + (arg->ch - '0'); } } /* Parse precision. Example: "%.3f" => prec=3 */ if (arg->ch == '.') { arg->prec = 0; if (--ctx->fmtcnt >= 0) { arg->ch = FORMAT_READ(ctx); ctx->fmtpos++; } if (arg->ch == '*') { v = unicode_format_getnextarg(ctx); if (v == NULL) return -1; if (!PyLong_Check(v)) { PyErr_SetString(PyExc_TypeError, "* wants int"); return -1; } arg->prec = _PyLong_AsInt(v); if (arg->prec == -1 && PyErr_Occurred()) return -1; if (arg->prec < 0) arg->prec = 0; if (--ctx->fmtcnt >= 0) { arg->ch = FORMAT_READ(ctx); ctx->fmtpos++; } } else if (arg->ch >= '0' && arg->ch <= '9') { arg->prec = arg->ch - '0'; while (--ctx->fmtcnt >= 0) { arg->ch = FORMAT_READ(ctx); ctx->fmtpos++; if (arg->ch < '0' || arg->ch > '9') break; if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) { PyErr_SetString(PyExc_ValueError, "precision too big"); return -1; } arg->prec = arg->prec*10 + (arg->ch - '0'); } } } /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */ if (ctx->fmtcnt >= 0) { if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') { if (--ctx->fmtcnt >= 0) { arg->ch = FORMAT_READ(ctx); ctx->fmtpos++; } } } if (ctx->fmtcnt < 0) { PyErr_SetString(PyExc_ValueError, "incomplete format"); return -1; } return 0; #undef FORMAT_READ } /* Format one argument. Supported conversion specifiers: - "s", "r", "a": any type - "i", "d", "u": int or float - "o", "x", "X": int - "e", "E", "f", "F", "g", "G": float - "c": int or str (1 character) When possible, the output is written directly into the Unicode writer (ctx->writer). A string is created when padding is required. Return 0 if the argument has been formatted into *p_str, 1 if the argument has been written into ctx->writer, -1 on error. */ static int unicode_format_arg_format(struct unicode_formatter_t *ctx, struct unicode_format_arg_t *arg, PyObject **p_str) { PyObject *v; _PyUnicodeWriter *writer = &ctx->writer; if (ctx->fmtcnt == 0) ctx->writer.overallocate = 0; if (arg->ch == '%') { if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0) return -1; return 1; } v = unicode_format_getnextarg(ctx); if (v == NULL) return -1; switch (arg->ch) { case 's': case 'r': case 'a': if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) { /* Fast path */ if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1) return -1; return 1; } if (PyUnicode_CheckExact(v) && arg->ch == 's') { *p_str = v; Py_INCREF(*p_str); } else { if (arg->ch == 's') *p_str = PyObject_Str(v); else if (arg->ch == 'r') *p_str = PyObject_Repr(v); else *p_str = PyObject_ASCII(v); } break; case 'i': case 'd': case 'u': case 'o': case 'x': case 'X': { int ret = mainformatlong(v, arg, p_str, writer); if (ret != 0) return ret; arg->sign = 1; break; } case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': if (arg->width == -1 && arg->prec == -1 && !(arg->flags & (F_SIGN | F_BLANK))) { /* Fast path */ if (formatfloat(v, arg, NULL, writer) == -1) return -1; return 1; } arg->sign = 1; if (formatfloat(v, arg, p_str, NULL) == -1) return -1; break; case 'c': { Py_UCS4 ch = formatchar(v); if (ch == (Py_UCS4) -1) return -1; if (arg->width == -1 && arg->prec == -1) { /* Fast path */ if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) return -1; return 1; } *p_str = PyUnicode_FromOrdinal(ch); break; } default: PyErr_Format(PyExc_ValueError, "unsupported format character '%c' (0x%x) " "at index %zd", (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?', (int)arg->ch, ctx->fmtpos - 1); return -1; } if (*p_str == NULL) return -1; assert (PyUnicode_Check(*p_str)); return 0; } static int unicode_format_arg_output(struct unicode_formatter_t *ctx, struct unicode_format_arg_t *arg, PyObject *str) { Py_ssize_t len; enum PyUnicode_Kind kind; void *pbuf; Py_ssize_t pindex; Py_UCS4 signchar; Py_ssize_t buflen; Py_UCS4 maxchar; Py_ssize_t sublen; _PyUnicodeWriter *writer = &ctx->writer; Py_UCS4 fill; fill = ' '; if (arg->sign && arg->flags & F_ZERO) fill = '0'; if (PyUnicode_READY(str) == -1) return -1; len = PyUnicode_GET_LENGTH(str); if ((arg->width == -1 || arg->width <= len) && (arg->prec == -1 || arg->prec >= len) && !(arg->flags & (F_SIGN | F_BLANK))) { /* Fast path */ if (_PyUnicodeWriter_WriteStr(writer, str) == -1) return -1; return 0; } /* Truncate the string for "s", "r" and "a" formats if the precision is set */ if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') { if (arg->prec >= 0 && len > arg->prec) len = arg->prec; } /* Adjust sign and width */ kind = PyUnicode_KIND(str); pbuf = PyUnicode_DATA(str); pindex = 0; signchar = '\0'; if (arg->sign) { Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex); if (ch == '-' || ch == '+') { signchar = ch; len--; pindex++; } else if (arg->flags & F_SIGN) signchar = '+'; else if (arg->flags & F_BLANK) signchar = ' '; else arg->sign = 0; } if (arg->width < len) arg->width = len; /* Prepare the writer */ maxchar = writer->maxchar; if (!(arg->flags & F_LJUST)) { if (arg->sign) { if ((arg->width-1) > len) maxchar = Py_MAX(maxchar, fill); } else { if (arg->width > len) maxchar = Py_MAX(maxchar, fill); } } if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) { Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len); maxchar = Py_MAX(maxchar, strmaxchar); } buflen = arg->width; if (arg->sign && len == arg->width) buflen++; if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1) return -1; /* Write the sign if needed */ if (arg->sign) { if (fill != ' ') { PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar); writer->pos += 1; } if (arg->width > len) arg->width--; } /* Write the numeric prefix for "x", "X" and "o" formats if the alternate form is used. For example, write "0x" for the "%#x" format. */ if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) { assert(PyUnicode_READ(kind, pbuf, pindex) == '0'); assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch); if (fill != ' ') { PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0'); PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch); writer->pos += 2; pindex += 2; } arg->width -= 2; if (arg->width < 0) arg->width = 0; len -= 2; } /* Pad left with the fill character if needed */ if (arg->width > len && !(arg->flags & F_LJUST)) { sublen = arg->width - len; FILL(writer->kind, writer->data, fill, writer->pos, sublen); writer->pos += sublen; arg->width = len; } /* If padding with spaces: write sign if needed and/or numeric prefix if the alternate form is used */ if (fill == ' ') { if (arg->sign) { PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar); writer->pos += 1; } if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) { assert(PyUnicode_READ(kind, pbuf, pindex) == '0'); assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch); PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0'); PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch); writer->pos += 2; pindex += 2; } } /* Write characters */ if (len) { _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos, str, pindex, len); writer->pos += len; } /* Pad right with the fill character if needed */ if (arg->width > len) { sublen = arg->width - len; FILL(writer->kind, writer->data, ' ', writer->pos, sublen); writer->pos += sublen; } return 0; } /* Helper of PyUnicode_Format(): format one arg. Return 0 on success, raise an exception and return -1 on error. */ static int unicode_format_arg(struct unicode_formatter_t *ctx) { struct unicode_format_arg_t arg; PyObject *str; int ret; arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos); arg.flags = 0; arg.width = -1; arg.prec = -1; arg.sign = 0; str = NULL; ret = unicode_format_arg_parse(ctx, &arg); if (ret == -1) return -1; ret = unicode_format_arg_format(ctx, &arg, &str); if (ret == -1) return -1; if (ret != 1) { ret = unicode_format_arg_output(ctx, &arg, str); Py_DECREF(str); if (ret == -1) return -1; } if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') { PyErr_SetString(PyExc_TypeError, "not all arguments converted during string formatting"); return -1; } return 0; } PyObject * PyUnicode_Format(PyObject *format, PyObject *args) { struct unicode_formatter_t ctx; if (format == NULL || args == NULL) { PyErr_BadInternalCall(); return NULL; } if (ensure_unicode(format) < 0) return NULL; ctx.fmtstr = format; ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr); ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr); ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr); ctx.fmtpos = 0; _PyUnicodeWriter_Init(&ctx.writer); ctx.writer.min_length = ctx.fmtcnt + 100; ctx.writer.overallocate = 1; if (PyTuple_Check(args)) { ctx.arglen = PyTuple_Size(args); ctx.argidx = 0; } else { ctx.arglen = -1; ctx.argidx = -2; } ctx.args_owned = 0; if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args)) ctx.dict = args; else ctx.dict = NULL; ctx.args = args; while (--ctx.fmtcnt >= 0) { if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') { Py_ssize_t nonfmtpos; nonfmtpos = ctx.fmtpos++; while (ctx.fmtcnt >= 0 && PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') { ctx.fmtpos++; ctx.fmtcnt--; } if (ctx.fmtcnt < 0) { ctx.fmtpos--; ctx.writer.overallocate = 0; } if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr, nonfmtpos, ctx.fmtpos) < 0) goto onError; } else { ctx.fmtpos++; if (unicode_format_arg(&ctx) == -1) goto onError; } } if (ctx.argidx < ctx.arglen && !ctx.dict) { PyErr_SetString(PyExc_TypeError, "not all arguments converted during string formatting"); goto onError; } if (ctx.args_owned) { Py_DECREF(ctx.args); } return _PyUnicodeWriter_Finish(&ctx.writer); onError: _PyUnicodeWriter_Dealloc(&ctx.writer); if (ctx.args_owned) { Py_DECREF(ctx.args); } return NULL; } static PyObject * unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject * unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *x = NULL; static char *kwlist[] = {"object", "encoding", "errors", 0}; char *encoding = NULL; char *errors = NULL; if (type != &PyUnicode_Type) return unicode_subtype_new(type, args, kwds); if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str", kwlist, &x, &encoding, &errors)) return NULL; if (x == NULL) _Py_RETURN_UNICODE_EMPTY(); if (encoding == NULL && errors == NULL) return PyObject_Str(x); else return PyUnicode_FromEncodedObject(x, encoding, errors); } static PyObject * unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *unicode, *self; Py_ssize_t length, char_size; int share_wstr, share_utf8; unsigned int kind; void *data; assert(PyType_IsSubtype(type, &PyUnicode_Type)); unicode = unicode_new(&PyUnicode_Type, args, kwds); if (unicode == NULL) return NULL; assert(_PyUnicode_CHECK(unicode)); if (PyUnicode_READY(unicode) == -1) { Py_DECREF(unicode); return NULL; } self = type->tp_alloc(type, 0); if (self == NULL) { Py_DECREF(unicode); return NULL; } kind = PyUnicode_KIND(unicode); length = PyUnicode_GET_LENGTH(unicode); _PyUnicode_LENGTH(self) = length; #ifdef Py_DEBUG _PyUnicode_HASH(self) = -1; #else _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode); #endif _PyUnicode_STATE(self).interned = 0; _PyUnicode_STATE(self).kind = kind; _PyUnicode_STATE(self).compact = 0; _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii; _PyUnicode_STATE(self).ready = 1; _PyUnicode_WSTR(self) = NULL; _PyUnicode_UTF8_LENGTH(self) = 0; _PyUnicode_UTF8(self) = NULL; _PyUnicode_WSTR_LENGTH(self) = 0; _PyUnicode_DATA_ANY(self) = NULL; share_utf8 = 0; share_wstr = 0; if (kind == PyUnicode_1BYTE_KIND) { char_size = 1; if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128) share_utf8 = 1; } else if (kind == PyUnicode_2BYTE_KIND) { char_size = 2; if (sizeof(wchar_t) == 2) share_wstr = 1; } else { assert(kind == PyUnicode_4BYTE_KIND); char_size = 4; if (sizeof(wchar_t) == 4) share_wstr = 1; } /* Ensure we won't overflow the length. */ if (length > (PY_SSIZE_T_MAX / char_size - 1)) { PyErr_NoMemory(); goto onError; } data = PyObject_MALLOC((length + 1) * char_size); if (data == NULL) { PyErr_NoMemory(); goto onError; } _PyUnicode_DATA_ANY(self) = data; if (share_utf8) { _PyUnicode_UTF8_LENGTH(self) = length; _PyUnicode_UTF8(self) = data; } if (share_wstr) { _PyUnicode_WSTR_LENGTH(self) = length; _PyUnicode_WSTR(self) = (wchar_t *)data; } memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1)); assert(_PyUnicode_CheckConsistency(self, 1)); #ifdef Py_DEBUG _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode); #endif Py_DECREF(unicode); return self; onError: Py_DECREF(unicode); Py_DECREF(self); return NULL; } PyDoc_STRVAR(unicode_doc, "str(object='') -> str\n\ str(bytes_or_buffer[, encoding[, errors]]) -> str\n\ \n\ Create a new string object from the given object. If encoding or\n\ errors is specified, then the object must expose a data buffer\n\ that will be decoded using the given encoding and error handler.\n\ Otherwise, returns the result of object.__str__() (if defined)\n\ or repr(object).\n\ encoding defaults to sys.getdefaultencoding().\n\ errors defaults to 'strict'."); static PyObject *unicode_iter(PyObject *seq); PyTypeObject PyUnicode_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "str", /* tp_name */ sizeof(PyUnicodeObject), /* tp_size */ 0, /* tp_itemsize */ /* Slots */ (destructor)unicode_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ unicode_repr, /* tp_repr */ &unicode_as_number, /* tp_as_number */ &unicode_as_sequence, /* tp_as_sequence */ &unicode_as_mapping, /* tp_as_mapping */ (hashfunc) unicode_hash, /* tp_hash*/ 0, /* tp_call*/ (reprfunc) unicode_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */ unicode_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ PyUnicode_RichCompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ unicode_iter, /* tp_iter */ 0, /* tp_iternext */ unicode_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyBaseObject_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ unicode_new, /* tp_new */ PyObject_Del, /* tp_free */ }; /* Initialize the Unicode implementation */ int _PyUnicode_Init(void) { /* XXX - move this array to unicodectype.c ? */ Py_UCS2 linebreak[] = { 0x000A, /* LINE FEED */ 0x000D, /* CARRIAGE RETURN */ 0x001C, /* FILE SEPARATOR */ 0x001D, /* GROUP SEPARATOR */ 0x001E, /* RECORD SEPARATOR */ 0x0085, /* NEXT LINE */ 0x2028, /* LINE SEPARATOR */ 0x2029, /* PARAGRAPH SEPARATOR */ }; /* Init the implementation */ _Py_INCREF_UNICODE_EMPTY(); if (!unicode_empty) Py_FatalError("Can't create empty string"); Py_DECREF(unicode_empty); if (PyType_Ready(&PyUnicode_Type) < 0) Py_FatalError("Can't initialize 'unicode'"); /* initialize the linebreak bloom filter */ bloom_linebreak = make_bloom_mask( PyUnicode_2BYTE_KIND, linebreak, Py_ARRAY_LENGTH(linebreak)); if (PyType_Ready(&EncodingMapType) < 0) Py_FatalError("Can't initialize encoding map type"); if (PyType_Ready(&PyFieldNameIter_Type) < 0) Py_FatalError("Can't initialize field name iterator type"); if (PyType_Ready(&PyFormatterIter_Type) < 0) Py_FatalError("Can't initialize formatter iter type"); return 0; } /* Finalize the Unicode implementation */ int PyUnicode_ClearFreeList(void) { return 0; } void _PyUnicode_Fini(void) { int i; Py_CLEAR(unicode_empty); for (i = 0; i < 256; i++) Py_CLEAR(unicode_latin1[i]); _PyUnicode_ClearStaticStrings(); (void)PyUnicode_ClearFreeList(); } void PyUnicode_InternInPlace(PyObject **p) { PyObject *s = *p; PyObject *t; #ifdef Py_DEBUG assert(s != NULL); assert(_PyUnicode_CHECK(s)); #else if (s == NULL || !PyUnicode_Check(s)) return; #endif /* If it's a subclass, we don't really know what putting it in the interned dict might do. */ if (!PyUnicode_CheckExact(s)) return; if (PyUnicode_CHECK_INTERNED(s)) return; if (interned == NULL) { interned = PyDict_New(); if (interned == NULL) { PyErr_Clear(); /* Don't leave an exception */ return; } } Py_ALLOW_RECURSION t = PyDict_SetDefault(interned, s, s); Py_END_ALLOW_RECURSION if (t == NULL) { PyErr_Clear(); return; } if (t != s) { Py_INCREF(t); Py_SETREF(*p, t); return; } /* The two references in interned are not counted by refcnt. The deallocator will take care of this */ Py_REFCNT(s) -= 2; _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL; } PyObject * PyUnicode_InternFromString(const char *cp) { PyObject *s = PyUnicode_FromString(cp); if (s == NULL) return NULL; PyUnicode_InternInPlace(&s); return s; } relegated void _Py_ReleaseInternedUnicodeStrings(void) { PyObject *keys; PyObject *s; Py_ssize_t i, n; Py_ssize_t immortal_size = 0, mortal_size = 0; if (interned == NULL || !PyDict_Check(interned)) return; keys = PyDict_Keys(interned); if (keys == NULL || !PyList_Check(keys)) { PyErr_Clear(); return; } /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak detector, interned unicode strings are not forcibly deallocated; rather, we give them their stolen references back, and then clear and DECREF the interned dict. */ n = PyList_GET_SIZE(keys); fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n", n); for (i = 0; i < n; i++) { s = PyList_GET_ITEM(keys, i); if (PyUnicode_READY(s) == -1) { assert(0 && "could not ready string"); fprintf(stderr, "could not ready string\n"); } switch (PyUnicode_CHECK_INTERNED(s)) { case SSTATE_NOT_INTERNED: /* XXX Shouldn't happen */ break; case SSTATE_INTERNED_IMMORTAL: Py_REFCNT(s) += 1; immortal_size += PyUnicode_GET_LENGTH(s); break; case SSTATE_INTERNED_MORTAL: Py_REFCNT(s) += 2; mortal_size += PyUnicode_GET_LENGTH(s); break; default: Py_FatalError("Inconsistent interned string state."); } _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED; } fprintf(stderr, "total size of all interned strings: " "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d " "mortal/immortal\n", mortal_size, immortal_size); Py_DECREF(keys); PyDict_Clear(interned); Py_CLEAR(interned); } /********************* Unicode Iterator **************************/ typedef struct { PyObject_HEAD Py_ssize_t it_index; PyObject *it_seq; /* Set to NULL when iterator is exhausted */ } unicodeiterobject; static void unicodeiter_dealloc(unicodeiterobject *it) { _PyObject_GC_UNTRACK(it); Py_XDECREF(it->it_seq); PyObject_GC_Del(it); } static int unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg) { Py_VISIT(it->it_seq); return 0; } static PyObject * unicodeiter_next(unicodeiterobject *it) { PyObject *seq, *item; assert(it != NULL); seq = it->it_seq; if (seq == NULL) return NULL; assert(_PyUnicode_CHECK(seq)); if (it->it_index < PyUnicode_GET_LENGTH(seq)) { int kind = PyUnicode_KIND(seq); void *data = PyUnicode_DATA(seq); Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index); item = PyUnicode_FromOrdinal(chr); if (item != NULL) ++it->it_index; return item; } it->it_seq = NULL; Py_DECREF(seq); return NULL; } static PyObject * unicodeiter_len(unicodeiterobject *it) { Py_ssize_t len = 0; if (it->it_seq) len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index; return PyLong_FromSsize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * unicodeiter_reduce(unicodeiterobject *it) { if (it->it_seq != NULL) { return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"), it->it_seq, it->it_index); } else { PyObject *u = PyUnicode_FromUnicode(NULL, 0); if (u == NULL) return NULL; return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u); } } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyObject * unicodeiter_setstate(unicodeiterobject *it, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; if (it->it_seq != NULL) { if (index < 0) index = 0; else if (index > PyUnicode_GET_LENGTH(it->it_seq)) index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */ it->it_index = index; } Py_RETURN_NONE; } PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef unicodeiter_methods[] = { {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyUnicodeIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "str_iterator", /* tp_name */ sizeof(unicodeiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)unicodeiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)unicodeiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)unicodeiter_next, /* tp_iternext */ unicodeiter_methods, /* tp_methods */ 0, }; static PyObject * unicode_iter(PyObject *seq) { unicodeiterobject *it; if (!PyUnicode_Check(seq)) { PyErr_BadInternalCall(); return NULL; } if (PyUnicode_READY(seq) == -1) return NULL; it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type); if (it == NULL) return NULL; it->it_index = 0; Py_INCREF(seq); it->it_seq = seq; _PyObject_GC_TRACK(it); return (PyObject *)it; } /* A _string module, to export formatter_parser and formatter_field_name_split to the string.Formatter class implemented in Python. */ static PyMethodDef _string_methods[] = { {"formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_O, PyDoc_STR("split the argument as a field name")}, {"formatter_parser", (PyCFunction) formatter_parser, METH_O, PyDoc_STR("parse the argument as a format string")}, {NULL, NULL} }; static struct PyModuleDef _string_module = { PyModuleDef_HEAD_INIT, "_string", PyDoc_STR("string helper module"), 0, _string_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit__string(void) { return PyModule_Create(&_string_module); }
446,319
14,700
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/codeobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ #define NAME_CHARS \ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" /* Holder for co_extra information */ typedef struct { Py_ssize_t ce_size; void **ce_extras; } _PyCodeObjectExtra; /* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */ static int all_name_chars(PyObject *o) { static char ok_name_char[256]; static const unsigned char *name_chars = (unsigned char *)NAME_CHARS; const unsigned char *s, *e; if (!PyUnicode_IS_ASCII(o)) return 0; if (ok_name_char[*name_chars] == 0) { const unsigned char *p; for (p = name_chars; *p; p++) ok_name_char[*p] = 1; } s = PyUnicode_1BYTE_DATA(o); e = s + PyUnicode_GET_LENGTH(o); while (s != e) { if (ok_name_char[*s++] == 0) return 0; } return 1; } static void intern_strings(PyObject *tuple) { Py_ssize_t i; for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { PyObject *v = PyTuple_GET_ITEM(tuple, i); if (v == NULL || !PyUnicode_CheckExact(v)) { Py_FatalError("non-string found in code slot"); } PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i)); } } /* Intern selected string constants */ static int intern_string_constants(PyObject *tuple) { int modified = 0; Py_ssize_t i; for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) { PyObject *v = PyTuple_GET_ITEM(tuple, i); if (PyUnicode_CheckExact(v)) { if (PyUnicode_READY(v) == -1) { PyErr_Clear(); continue; } if (all_name_chars(v)) { PyObject *w = v; PyUnicode_InternInPlace(&v); if (w != v) { PyTuple_SET_ITEM(tuple, i, v); modified = 1; } } } else if (PyTuple_CheckExact(v)) { intern_string_constants(v); } else if (PyFrozenSet_CheckExact(v)) { PyObject *w = v; PyObject *tmp = PySequence_Tuple(v); if (tmp == NULL) { PyErr_Clear(); continue; } if (intern_string_constants(tmp)) { v = PyFrozenSet_New(tmp); if (v == NULL) { PyErr_Clear(); } else { PyTuple_SET_ITEM(tuple, i, v); Py_DECREF(w); modified = 1; } } Py_DECREF(tmp); } } return modified; } PyCodeObject * PyCode_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab) { PyCodeObject *co; unsigned char *cell2arg = NULL; Py_ssize_t i, n_cellvars, n_varnames, total_args; /* Check argument types */ if (argcount < 0 || kwonlyargcount < 0 || nlocals < 0 || code == NULL || consts == NULL || !PyTuple_Check(consts) || names == NULL || !PyTuple_Check(names) || varnames == NULL || !PyTuple_Check(varnames) || freevars == NULL || !PyTuple_Check(freevars) || cellvars == NULL || !PyTuple_Check(cellvars) || name == NULL || !PyUnicode_Check(name) || filename == NULL || !PyUnicode_Check(filename) || lnotab == NULL || !PyBytes_Check(lnotab) || !PyObject_CheckReadBuffer(code)) { PyErr_BadInternalCall(); return NULL; } /* Ensure that the filename is a ready Unicode string */ if (PyUnicode_READY(filename) < 0) return NULL; intern_strings(names); intern_strings(varnames); intern_strings(freevars); intern_strings(cellvars); intern_string_constants(consts); /* Check for any inner or outer closure references */ n_cellvars = PyTuple_GET_SIZE(cellvars); if (!n_cellvars && !PyTuple_GET_SIZE(freevars)) { flags |= CO_NOFREE; } else { flags &= ~CO_NOFREE; } n_varnames = PyTuple_GET_SIZE(varnames); if (argcount <= n_varnames && kwonlyargcount <= n_varnames) { /* Never overflows. */ total_args = (Py_ssize_t)argcount + (Py_ssize_t)kwonlyargcount + ((flags & CO_VARARGS) != 0) + ((flags & CO_VARKEYWORDS) != 0); } else { total_args = n_varnames + 1; } if (total_args > n_varnames) { PyErr_SetString(PyExc_ValueError, "code: varnames is too small"); return NULL; } /* Create mapping between cells and arguments if needed. */ if (n_cellvars) { Py_ssize_t alloc_size = sizeof(unsigned char) * n_cellvars; bool used_cell2arg = false; cell2arg = PyMem_MALLOC(alloc_size); if (cell2arg == NULL) { PyErr_NoMemory(); return NULL; } memset(cell2arg, CO_CELL_NOT_AN_ARG, alloc_size); /* Find cells which are also arguments. */ for (i = 0; i < n_cellvars; i++) { Py_ssize_t j; PyObject *cell = PyTuple_GET_ITEM(cellvars, i); for (j = 0; j < total_args; j++) { PyObject *arg = PyTuple_GET_ITEM(varnames, j); int cmp = PyUnicode_Compare(cell, arg); if (cmp == -1 && PyErr_Occurred()) { PyMem_FREE(cell2arg); return NULL; } if (cmp == 0) { cell2arg[i] = j; used_cell2arg = true; break; } } } if (!used_cell2arg) { PyMem_FREE(cell2arg); cell2arg = NULL; } } co = PyObject_NEW(PyCodeObject, &PyCode_Type); if (co == NULL) { if (cell2arg) PyMem_FREE(cell2arg); return NULL; } co->co_argcount = argcount; co->co_kwonlyargcount = kwonlyargcount; co->co_nlocals = nlocals; co->co_stacksize = stacksize; co->co_flags = flags; Py_INCREF(code); co->co_code = code; Py_INCREF(consts); co->co_consts = consts; Py_INCREF(names); co->co_names = names; Py_INCREF(varnames); co->co_varnames = varnames; Py_INCREF(freevars); co->co_freevars = freevars; Py_INCREF(cellvars); co->co_cellvars = cellvars; co->co_cell2arg = cell2arg; Py_INCREF(filename); co->co_filename = filename; Py_INCREF(name); co->co_name = name; co->co_firstlineno = firstlineno; Py_INCREF(lnotab); co->co_lnotab = lnotab; co->co_zombieframe = NULL; co->co_weakreflist = NULL; co->co_extra = NULL; return co; } PyCodeObject * PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno) { static PyObject *emptystring = NULL; static PyObject *nulltuple = NULL; PyObject *filename_ob = NULL; PyObject *funcname_ob = NULL; PyCodeObject *result = NULL; if (emptystring == NULL) { emptystring = PyBytes_FromString(""); if (emptystring == NULL) goto failed; } if (nulltuple == NULL) { nulltuple = PyTuple_New(0); if (nulltuple == NULL) goto failed; } funcname_ob = PyUnicode_FromString(funcname); if (funcname_ob == NULL) goto failed; filename_ob = PyUnicode_DecodeFSDefault(filename); if (filename_ob == NULL) goto failed; result = PyCode_New(0, /* argcount */ 0, /* kwonlyargcount */ 0, /* nlocals */ 0, /* stacksize */ 0, /* flags */ emptystring, /* code */ nulltuple, /* consts */ nulltuple, /* names */ nulltuple, /* varnames */ nulltuple, /* freevars */ nulltuple, /* cellvars */ filename_ob, /* filename */ funcname_ob, /* name */ firstlineno, /* firstlineno */ emptystring /* lnotab */ ); failed: Py_XDECREF(funcname_ob); Py_XDECREF(filename_ob); return result; } #define OFF(x) offsetof(PyCodeObject, x) static PyMemberDef code_memberlist[] = { {"co_argcount", T_INT, OFF(co_argcount), READONLY}, {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY}, {"co_nlocals", T_INT, OFF(co_nlocals), READONLY}, {"co_stacksize",T_INT, OFF(co_stacksize), READONLY}, {"co_flags", T_INT, OFF(co_flags), READONLY}, {"co_code", T_OBJECT, OFF(co_code), READONLY}, {"co_consts", T_OBJECT, OFF(co_consts), READONLY}, {"co_names", T_OBJECT, OFF(co_names), READONLY}, {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY}, {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY}, {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY}, {"co_filename", T_OBJECT, OFF(co_filename), READONLY}, {"co_name", T_OBJECT, OFF(co_name), READONLY}, {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY}, {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY}, {NULL} /* Sentinel */ }; /* Helper for code_new: return a shallow copy of a tuple that is guaranteed to contain exact strings, by converting string subclasses to exact strings and complaining if a non-string is found. */ static PyObject* validate_and_copy_tuple(PyObject *tup) { PyObject *newtuple; PyObject *item; Py_ssize_t i, len; len = PyTuple_GET_SIZE(tup); newtuple = PyTuple_New(len); if (newtuple == NULL) return NULL; for (i = 0; i < len; i++) { item = PyTuple_GET_ITEM(tup, i); if (PyUnicode_CheckExact(item)) { Py_INCREF(item); } else if (!PyUnicode_Check(item)) { PyErr_Format( PyExc_TypeError, "name tuples must contain only " "strings, not '%.500s'", item->ob_type->tp_name); Py_DECREF(newtuple); return NULL; } else { item = _PyUnicode_Copy(item); if (item == NULL) { Py_DECREF(newtuple); return NULL; } } PyTuple_SET_ITEM(newtuple, i, item); } return newtuple; } PyDoc_STRVAR(code_doc, "code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\ constants, names, varnames, filename, name, firstlineno,\n\ lnotab[, freevars[, cellvars]])\n\ \n\ Create a code object. Not for the faint of heart."); static PyObject * code_new(PyTypeObject *type, PyObject *args, PyObject *kw) { int argcount; int kwonlyargcount; int nlocals; int stacksize; int flags; PyObject *co = NULL; PyObject *code; PyObject *consts; PyObject *names, *ournames = NULL; PyObject *varnames, *ourvarnames = NULL; PyObject *freevars = NULL, *ourfreevars = NULL; PyObject *cellvars = NULL, *ourcellvars = NULL; PyObject *filename; PyObject *name; int firstlineno; PyObject *lnotab; if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!UUiS|O!O!:code", &argcount, &kwonlyargcount, &nlocals, &stacksize, &flags, &code, &PyTuple_Type, &consts, &PyTuple_Type, &names, &PyTuple_Type, &varnames, &filename, &name, &firstlineno, &lnotab, &PyTuple_Type, &freevars, &PyTuple_Type, &cellvars)) return NULL; if (argcount < 0) { PyErr_SetString( PyExc_ValueError, "code: argcount must not be negative"); goto cleanup; } if (kwonlyargcount < 0) { PyErr_SetString( PyExc_ValueError, "code: kwonlyargcount must not be negative"); goto cleanup; } if (nlocals < 0) { PyErr_SetString( PyExc_ValueError, "code: nlocals must not be negative"); goto cleanup; } ournames = validate_and_copy_tuple(names); if (ournames == NULL) goto cleanup; ourvarnames = validate_and_copy_tuple(varnames); if (ourvarnames == NULL) goto cleanup; if (freevars) ourfreevars = validate_and_copy_tuple(freevars); else ourfreevars = PyTuple_New(0); if (ourfreevars == NULL) goto cleanup; if (cellvars) ourcellvars = validate_and_copy_tuple(cellvars); else ourcellvars = PyTuple_New(0); if (ourcellvars == NULL) goto cleanup; co = (PyObject *)PyCode_New(argcount, kwonlyargcount, nlocals, stacksize, flags, code, consts, ournames, ourvarnames, ourfreevars, ourcellvars, filename, name, firstlineno, lnotab); cleanup: Py_XDECREF(ournames); Py_XDECREF(ourvarnames); Py_XDECREF(ourfreevars); Py_XDECREF(ourcellvars); return co; } static void code_dealloc(PyCodeObject *co) { if (co->co_extra != NULL) { __PyCodeExtraState *state = __PyCodeExtraState_Get(); _PyCodeObjectExtra *co_extra = co->co_extra; for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) { freefunc free_extra = state->co_extra_freefuncs[i]; if (free_extra != NULL) { free_extra(co_extra->ce_extras[i]); } } PyMem_Free(co_extra->ce_extras); PyMem_Free(co_extra); } Py_XDECREF(co->co_code); Py_XDECREF(co->co_consts); Py_XDECREF(co->co_names); Py_XDECREF(co->co_varnames); Py_XDECREF(co->co_freevars); Py_XDECREF(co->co_cellvars); Py_XDECREF(co->co_filename); Py_XDECREF(co->co_name); Py_XDECREF(co->co_lnotab); if (co->co_cell2arg != NULL) PyMem_FREE(co->co_cell2arg); if (co->co_zombieframe != NULL) PyObject_GC_Del(co->co_zombieframe); if (co->co_weakreflist != NULL) PyObject_ClearWeakRefs((PyObject*)co); PyObject_DEL(co); } static PyObject * code_sizeof(PyCodeObject *co, void *unused) { Py_ssize_t res = _PyObject_SIZE(Py_TYPE(co)); _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) co->co_extra; if (co->co_cell2arg != NULL && co->co_cellvars != NULL) res += PyTuple_GET_SIZE(co->co_cellvars) * sizeof(Py_ssize_t); if (co_extra != NULL) res += co_extra->ce_size * sizeof(co_extra->ce_extras[0]); return PyLong_FromSsize_t(res); } static PyObject * code_repr(PyCodeObject *co) { int lineno; if (co->co_firstlineno != 0) lineno = co->co_firstlineno; else lineno = -1; if (co->co_filename && PyUnicode_Check(co->co_filename)) { return PyUnicode_FromFormat( "<code object %U at %p, file \"%U\", line %d>", co->co_name, co, co->co_filename, lineno); } else { return PyUnicode_FromFormat( "<code object %U at %p, file ???, line %d>", co->co_name, co, lineno); } } PyObject* _PyCode_ConstantKey(PyObject *op) { PyObject *key; /* Py_None and Py_Ellipsis are singleton */ if (op == Py_None || op == Py_Ellipsis || PyLong_CheckExact(op) || PyBool_Check(op) || PyBytes_CheckExact(op) || PyUnicode_CheckExact(op) /* code_richcompare() uses _PyCode_ConstantKey() internally */ || PyCode_Check(op)) { key = PyTuple_Pack(2, Py_TYPE(op), op); } else if (PyFloat_CheckExact(op)) { double d = PyFloat_AS_DOUBLE(op); /* all we need is to make the tuple different in either the 0.0 * or -0.0 case from all others, just to avoid the "coercion". */ if (d == 0.0 && copysign(1.0, d) < 0.0) key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None); else key = PyTuple_Pack(2, Py_TYPE(op), op); } else if (PyComplex_CheckExact(op)) { Py_complex z; int real_negzero, imag_negzero; /* For the complex case we must make complex(x, 0.) different from complex(x, -0.) and complex(0., y) different from complex(-0., y), for any x and y. All four complex zeros must be distinguished.*/ z = PyComplex_AsCComplex(op); real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; /* use True, False and None singleton as tags for the real and imag * sign, to make tuples different */ if (real_negzero && imag_negzero) { key = PyTuple_Pack(3, Py_TYPE(op), op, Py_True); } else if (imag_negzero) { key = PyTuple_Pack(3, Py_TYPE(op), op, Py_False); } else if (real_negzero) { key = PyTuple_Pack(3, Py_TYPE(op), op, Py_None); } else { key = PyTuple_Pack(2, Py_TYPE(op), op); } } else if (PyTuple_CheckExact(op)) { Py_ssize_t i, len; PyObject *tuple; len = PyTuple_GET_SIZE(op); tuple = PyTuple_New(len); if (tuple == NULL) return NULL; for (i=0; i < len; i++) { PyObject *item, *item_key; item = PyTuple_GET_ITEM(op, i); item_key = _PyCode_ConstantKey(item); if (item_key == NULL) { Py_DECREF(tuple); return NULL; } PyTuple_SET_ITEM(tuple, i, item_key); } key = PyTuple_Pack(2, tuple, op); Py_DECREF(tuple); } else if (PyFrozenSet_CheckExact(op)) { Py_ssize_t pos = 0; PyObject *item; Py_hash_t hash; Py_ssize_t i, len; PyObject *tuple, *set; len = PySet_GET_SIZE(op); tuple = PyTuple_New(len); if (tuple == NULL) return NULL; i = 0; while (_PySet_NextEntry(op, &pos, &item, &hash)) { PyObject *item_key; item_key = _PyCode_ConstantKey(item); if (item_key == NULL) { Py_DECREF(tuple); return NULL; } assert(i < len); PyTuple_SET_ITEM(tuple, i, item_key); i++; } set = PyFrozenSet_New(tuple); Py_DECREF(tuple); if (set == NULL) return NULL; key = PyTuple_Pack(2, set, op); Py_DECREF(set); return key; } else { /* for other types, use the object identifier as a unique identifier * to ensure that they are seen as unequal. */ PyObject *obj_id = PyLong_FromVoidPtr(op); if (obj_id == NULL) return NULL; key = PyTuple_Pack(2, obj_id, op); Py_DECREF(obj_id); } return key; } static PyObject * code_richcompare(PyObject *self, PyObject *other, int op) { PyCodeObject *co, *cp; int eq; PyObject *consts1, *consts2; PyObject *res; if ((op != Py_EQ && op != Py_NE) || !PyCode_Check(self) || !PyCode_Check(other)) { Py_RETURN_NOTIMPLEMENTED; } co = (PyCodeObject *)self; cp = (PyCodeObject *)other; eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); if (eq <= 0) goto unequal; eq = co->co_argcount == cp->co_argcount; if (!eq) goto unequal; eq = co->co_kwonlyargcount == cp->co_kwonlyargcount; if (!eq) goto unequal; eq = co->co_nlocals == cp->co_nlocals; if (!eq) goto unequal; eq = co->co_flags == cp->co_flags; if (!eq) goto unequal; eq = co->co_firstlineno == cp->co_firstlineno; if (!eq) goto unequal; eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); if (eq <= 0) goto unequal; /* compare constants */ consts1 = _PyCode_ConstantKey(co->co_consts); if (!consts1) return NULL; consts2 = _PyCode_ConstantKey(cp->co_consts); if (!consts2) { Py_DECREF(consts1); return NULL; } eq = PyObject_RichCompareBool(consts1, consts2, Py_EQ); Py_DECREF(consts1); Py_DECREF(consts2); if (eq <= 0) goto unequal; eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); if (eq <= 0) goto unequal; eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); if (eq <= 0) goto unequal; eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ); if (eq <= 0) goto unequal; eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ); if (eq <= 0) goto unequal; if (op == Py_EQ) res = Py_True; else res = Py_False; goto done; unequal: if (eq < 0) return NULL; if (op == Py_NE) res = Py_True; else res = Py_False; done: Py_INCREF(res); return res; } static Py_hash_t code_hash(PyCodeObject *co) { Py_hash_t h, h0, h1, h2, h3, h4, h5, h6; h0 = PyObject_Hash(co->co_name); if (h0 == -1) return -1; h1 = PyObject_Hash(co->co_code); if (h1 == -1) return -1; h2 = PyObject_Hash(co->co_consts); if (h2 == -1) return -1; h3 = PyObject_Hash(co->co_names); if (h3 == -1) return -1; h4 = PyObject_Hash(co->co_varnames); if (h4 == -1) return -1; h5 = PyObject_Hash(co->co_freevars); if (h5 == -1) return -1; h6 = PyObject_Hash(co->co_cellvars); if (h6 == -1) return -1; h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^ co->co_argcount ^ co->co_kwonlyargcount ^ co->co_nlocals ^ co->co_flags; if (h == -1) h = -2; return h; } /* XXX code objects need to participate in GC? */ static struct PyMethodDef code_methods[] = { {"__sizeof__", (PyCFunction)code_sizeof, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyCode_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "code", sizeof(PyCodeObject), 0, (destructor)code_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)code_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)code_hash, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ code_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ code_richcompare, /* tp_richcompare */ offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ code_methods, /* tp_methods */ code_memberlist, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ code_new, /* tp_new */ }; /* Use co_lnotab to compute the line number from a bytecode index, addrq. See lnotab_notes.txt for the details of the lnotab representation. */ int PyCode_Addr2Line(PyCodeObject *co, int addrq) { Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2; unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab); int line = co->co_firstlineno; int addr = 0; while (--size >= 0) { addr += *p++; if (addr > addrq) break; line += (signed char)*p; p++; } return line; } /* Update *bounds to describe the first and one-past-the-last instructions in the same line as lasti. Return the number of that line. */ int _PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds) { Py_ssize_t size; int addr, line; unsigned char* p; p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab); size = PyBytes_GET_SIZE(co->co_lnotab) / 2; addr = 0; line = co->co_firstlineno; assert(line > 0); /* possible optimization: if f->f_lasti == instr_ub (likely to be a common case) then we already know instr_lb -- if we stored the matching value of p somewhere we could skip the first while loop. */ /* See lnotab_notes.txt for the description of co_lnotab. A point to remember: increments to p come in (addr, line) pairs. */ bounds->ap_lower = 0; while (size > 0) { if (addr + *p > lasti) break; addr += *p++; if ((signed char)*p) bounds->ap_lower = addr; line += (signed char)*p; p++; --size; } if (size > 0) { while (--size >= 0) { addr += *p++; if ((signed char)*p) break; p++; } bounds->ap_upper = addr; } else { bounds->ap_upper = INT_MAX; } return line; } int _PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra) { if (!PyCode_Check(code)) { PyErr_BadInternalCall(); return -1; } PyCodeObject *o = (PyCodeObject*) code; _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra*) o->co_extra; if (co_extra == NULL || co_extra->ce_size <= index) { *extra = NULL; return 0; } *extra = co_extra->ce_extras[index]; return 0; } int _PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra) { __PyCodeExtraState *state = __PyCodeExtraState_Get(); if (!PyCode_Check(code) || index < 0 || index >= state->co_extra_user_count) { PyErr_BadInternalCall(); return -1; } PyCodeObject *o = (PyCodeObject*) code; _PyCodeObjectExtra *co_extra = (_PyCodeObjectExtra *) o->co_extra; if (co_extra == NULL) { co_extra = PyMem_Malloc(sizeof(_PyCodeObjectExtra)); if (co_extra == NULL) { return -1; } co_extra->ce_extras = PyMem_Malloc( state->co_extra_user_count * sizeof(void*)); if (co_extra->ce_extras == NULL) { PyMem_Free(co_extra); return -1; } co_extra->ce_size = state->co_extra_user_count; for (Py_ssize_t i = 0; i < co_extra->ce_size; i++) { co_extra->ce_extras[i] = NULL; } o->co_extra = co_extra; } else if (co_extra->ce_size <= index) { void** ce_extras = PyMem_Realloc( co_extra->ce_extras, state->co_extra_user_count * sizeof(void*)); if (ce_extras == NULL) { return -1; } for (Py_ssize_t i = co_extra->ce_size; i < state->co_extra_user_count; i++) { ce_extras[i] = NULL; } co_extra->ce_extras = ce_extras; co_extra->ce_size = state->co_extra_user_count; } if (co_extra->ce_extras[index] != NULL) { freefunc free = state->co_extra_freefuncs[index]; if (free != NULL) { free(co_extra->ce_extras[index]); } } co_extra->ce_extras[index] = extra; return 0; }
30,539
962
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/exceptions.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "libc/errno.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/osdefs.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/tupleobject.h" /* clang-format off */ /* * New exceptions.c written in Iceland by Richard Jones and Georg Brandl. * * Thanks go to Tim Peters and Michael Hudson for debugging. */ /* Compatibility aliases */ PyObject *PyExc_EnvironmentError = NULL; PyObject *PyExc_IOError = NULL; #ifdef MS_WINDOWS PyObject *PyExc_WindowsError = NULL; #endif /* The dict map from errno codes to OSError subclasses */ static PyObject *errnomap = NULL; /* NOTE: If the exception class hierarchy changes, don't forget to update * Lib/test/exception_hierarchy.txt */ /* * BaseException */ static PyObject * BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyBaseExceptionObject *self; self = (PyBaseExceptionObject *)type->tp_alloc(type, 0); if (!self) return NULL; /* the dict is created on the fly in PyObject_GenericSetAttr */ self->dict = NULL; self->traceback = self->cause = self->context = NULL; self->suppress_context = 0; if (args) { self->args = args; Py_INCREF(args); return (PyObject *)self; } self->args = PyTuple_New(0); if (!self->args) { Py_DECREF(self); return NULL; } return (PyObject *)self; } static int BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds) { if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) return -1; Py_INCREF(args); Py_XSETREF(self->args, args); return 0; } static int BaseException_clear(PyBaseExceptionObject *self) { Py_CLEAR(self->dict); Py_CLEAR(self->args); Py_CLEAR(self->traceback); Py_CLEAR(self->cause); Py_CLEAR(self->context); return 0; } static void BaseException_dealloc(PyBaseExceptionObject *self) { _PyObject_GC_UNTRACK(self); BaseException_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); } static int BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg) { Py_VISIT(self->dict); Py_VISIT(self->args); Py_VISIT(self->traceback); Py_VISIT(self->cause); Py_VISIT(self->context); return 0; } static PyObject * BaseException_str(PyBaseExceptionObject *self) { switch (PyTuple_GET_SIZE(self->args)) { case 0: return PyUnicode_FromString(""); case 1: return PyObject_Str(PyTuple_GET_ITEM(self->args, 0)); default: return PyObject_Str(self->args); } } static PyObject * BaseException_repr(PyBaseExceptionObject *self) { const char *name; const char *dot; name = Py_TYPE(self)->tp_name; dot = (const char *) strrchr(name, '.'); if (dot != NULL) name = dot+1; return PyUnicode_FromFormat("%s%R", name, self->args); } /* Pickling support */ static PyObject * BaseException_reduce(PyBaseExceptionObject *self) { if (self->args && self->dict) return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict); else return PyTuple_Pack(2, Py_TYPE(self), self->args); } /* * Needed for backward compatibility, since exceptions used to store * all their attributes in the __dict__. Code is taken from cPickle's * load_build function. */ static PyObject * BaseException_setstate(PyObject *self, PyObject *state) { PyObject *d_key, *d_value; Py_ssize_t i = 0; if (state != Py_None) { if (!PyDict_Check(state)) { PyErr_SetString(PyExc_TypeError, "state is not a dictionary"); return NULL; } while (PyDict_Next(state, &i, &d_key, &d_value)) { if (PyObject_SetAttr(self, d_key, d_value) < 0) return NULL; } } Py_RETURN_NONE; } static PyObject * BaseException_with_traceback(PyObject *self, PyObject *tb) { if (PyException_SetTraceback(self, tb)) return NULL; Py_INCREF(self); return self; } PyDoc_STRVAR(with_traceback_doc, "Exception.with_traceback(tb) --\n\ set self.__traceback__ to tb and return self."); static PyMethodDef BaseException_methods[] = { {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS }, {"__setstate__", (PyCFunction)BaseException_setstate, METH_O }, {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O, with_traceback_doc}, {NULL, NULL, 0, NULL}, }; static PyObject * BaseException_get_args(PyBaseExceptionObject *self, void *Py_UNUSED(ignored)) { if (self->args == NULL) { Py_INCREF(Py_None); return Py_None; } Py_INCREF(self->args); return self->args; } static int BaseException_set_args(PyBaseExceptionObject *self, PyObject *val, void *Py_UNUSED(ignored)) { PyObject *seq; if (val == NULL) { PyErr_SetString(PyExc_TypeError, "args may not be deleted"); return -1; } seq = PySequence_Tuple(val); if (!seq) return -1; Py_XSETREF(self->args, seq); return 0; } static PyObject * BaseException_get_tb(PyBaseExceptionObject *self, void *Py_UNUSED(ignored)) { if (self->traceback == NULL) { Py_INCREF(Py_None); return Py_None; } Py_INCREF(self->traceback); return self->traceback; } static int BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb, void *Py_UNUSED(ignored)) { if (tb == NULL) { PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted"); return -1; } else if (!(tb == Py_None || PyTraceBack_Check(tb))) { PyErr_SetString(PyExc_TypeError, "__traceback__ must be a traceback or None"); return -1; } Py_INCREF(tb); Py_XSETREF(self->traceback, tb); return 0; } static PyObject * BaseException_get_context(PyObject *self, void *Py_UNUSED(ignored)) { PyObject *res = PyException_GetContext(self); if (res) return res; /* new reference already returned above */ Py_RETURN_NONE; } static int BaseException_set_context(PyObject *self, PyObject *arg, void *Py_UNUSED(ignored)) { if (arg == NULL) { PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted"); return -1; } else if (arg == Py_None) { arg = NULL; } else if (!PyExceptionInstance_Check(arg)) { PyErr_SetString(PyExc_TypeError, "exception context must be None " "or derive from BaseException"); return -1; } else { /* PyException_SetContext steals this reference */ Py_INCREF(arg); } PyException_SetContext(self, arg); return 0; } static PyObject * BaseException_get_cause(PyObject *self, void *Py_UNUSED(ignored)) { PyObject *res = PyException_GetCause(self); if (res) return res; /* new reference already returned above */ Py_RETURN_NONE; } static int BaseException_set_cause(PyObject *self, PyObject *arg, void *Py_UNUSED(ignored)) { if (arg == NULL) { PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted"); return -1; } else if (arg == Py_None) { arg = NULL; } else if (!PyExceptionInstance_Check(arg)) { PyErr_SetString(PyExc_TypeError, "exception cause must be None " "or derive from BaseException"); return -1; } else { /* PyException_SetCause steals this reference */ Py_INCREF(arg); } PyException_SetCause(self, arg); return 0; } static PyGetSetDef BaseException_getset[] = { {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, {"args", (getter)BaseException_get_args, (setter)BaseException_set_args}, {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb}, {"__context__", BaseException_get_context, BaseException_set_context, PyDoc_STR("exception context")}, {"__cause__", BaseException_get_cause, BaseException_set_cause, PyDoc_STR("exception cause")}, {NULL}, }; PyObject * PyException_GetTraceback(PyObject *self) { PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self; Py_XINCREF(base_self->traceback); return base_self->traceback; } int PyException_SetTraceback(PyObject *self, PyObject *tb) { return BaseException_set_tb((PyBaseExceptionObject *)self, tb, NULL); } PyObject * PyException_GetCause(PyObject *self) { PyObject *cause = ((PyBaseExceptionObject *)self)->cause; Py_XINCREF(cause); return cause; } /* Steals a reference to cause */ void PyException_SetCause(PyObject *self, PyObject *cause) { ((PyBaseExceptionObject *)self)->suppress_context = 1; Py_XSETREF(((PyBaseExceptionObject *)self)->cause, cause); } PyObject * PyException_GetContext(PyObject *self) { PyObject *context = ((PyBaseExceptionObject *)self)->context; Py_XINCREF(context); return context; } /* Steals a reference to context */ void PyException_SetContext(PyObject *self, PyObject *context) { Py_XSETREF(((PyBaseExceptionObject *)self)->context, context); } static struct PyMemberDef BaseException_members[] = { {"__suppress_context__", T_BOOL, offsetof(PyBaseExceptionObject, suppress_context)}, {NULL} }; static PyTypeObject _PyExc_BaseException = { PyVarObject_HEAD_INIT(NULL, 0) "BaseException", /*tp_name*/ sizeof(PyBaseExceptionObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)BaseException_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /* tp_reserved; */ (reprfunc)BaseException_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ (reprfunc)BaseException_str, /*tp_str*/ PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/ PyDoc_STR("Common base class for all exceptions"), /* tp_doc */ (traverseproc)BaseException_traverse, /* tp_traverse */ (inquiry)BaseException_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ BaseException_methods, /* tp_methods */ BaseException_members, /* tp_members */ BaseException_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */ (initproc)BaseException_init, /* tp_init */ 0, /* tp_alloc */ BaseException_new, /* tp_new */ }; /* the CPython API expects exceptions to be (PyObject *) - both a hold-over from the previous implmentation and also allowing Python objects to be used in the API */ PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException; /* note these macros omit the last semicolon so the macro invocation may * include it and not look strange. */ #define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyVarObject_HEAD_INIT(NULL, 0) \ # EXCNAME, \ sizeof(PyBaseExceptionObject), \ 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, 0, 0, \ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \ (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \ 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \ (initproc)BaseException_init, 0, BaseException_new,\ }; \ PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME #define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyVarObject_HEAD_INIT(NULL, 0) \ # EXCNAME, \ sizeof(Py ## EXCSTORE ## Object), \ 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ 0, 0, 0, 0, 0, \ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \ (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \ 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \ (initproc)EXCSTORE ## _init, 0, 0, \ }; \ PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME #define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \ EXCMETHODS, EXCMEMBERS, EXCGETSET, \ EXCSTR, EXCDOC) \ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyVarObject_HEAD_INIT(NULL, 0) \ # EXCNAME, \ sizeof(Py ## EXCSTORE ## Object), 0, \ (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \ (reprfunc)EXCSTR, 0, 0, 0, \ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \ (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \ EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \ 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \ (initproc)EXCSTORE ## _init, 0, EXCNEW,\ }; \ PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME /* * Exception extends BaseException */ SimpleExtendsException(PyExc_BaseException, Exception, "Common base class for all non-exit exceptions."); /* * TypeError extends Exception */ SimpleExtendsException(PyExc_Exception, TypeError, "Inappropriate argument type."); /* * StopAsyncIteration extends Exception */ SimpleExtendsException(PyExc_Exception, StopAsyncIteration, "Signal the end from iterator.__anext__()."); /* * StopIteration extends Exception */ static PyMemberDef StopIteration_members[] = { {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0, PyDoc_STR("generator return value")}, {NULL} /* Sentinel */ }; static int StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds) { Py_ssize_t size = PyTuple_GET_SIZE(args); PyObject *value; if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) return -1; Py_CLEAR(self->value); if (size > 0) value = PyTuple_GET_ITEM(args, 0); else value = Py_None; Py_INCREF(value); self->value = value; return 0; } static int StopIteration_clear(PyStopIterationObject *self) { Py_CLEAR(self->value); return BaseException_clear((PyBaseExceptionObject *)self); } static void StopIteration_dealloc(PyStopIterationObject *self) { _PyObject_GC_UNTRACK(self); StopIteration_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); } static int StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg) { Py_VISIT(self->value); return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); } ComplexExtendsException( PyExc_Exception, /* base */ StopIteration, /* name */ StopIteration, /* prefix for *_init, etc */ 0, /* new */ 0, /* methods */ StopIteration_members, /* members */ 0, /* getset */ 0, /* str */ "Signal the end from iterator.__next__()." ); /* * GeneratorExit extends BaseException */ SimpleExtendsException(PyExc_BaseException, GeneratorExit, "Request that a generator exit."); /* * SystemExit extends BaseException */ static int SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds) { Py_ssize_t size = PyTuple_GET_SIZE(args); if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) return -1; if (size == 0) return 0; if (size == 1) { Py_INCREF(PyTuple_GET_ITEM(args, 0)); Py_XSETREF(self->code, PyTuple_GET_ITEM(args, 0)); } else { /* size > 1 */ Py_INCREF(args); Py_XSETREF(self->code, args); } return 0; } static int SystemExit_clear(PySystemExitObject *self) { Py_CLEAR(self->code); return BaseException_clear((PyBaseExceptionObject *)self); } static void SystemExit_dealloc(PySystemExitObject *self) { _PyObject_GC_UNTRACK(self); SystemExit_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); } static int SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg) { Py_VISIT(self->code); return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); } static PyMemberDef SystemExit_members[] = { {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0, PyDoc_STR("exception code")}, {NULL} /* Sentinel */ }; ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit, 0, 0, SystemExit_members, 0, 0, "Request to exit from the interpreter."); /* * KeyboardInterrupt extends BaseException */ SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt, "Program interrupted by user."); /* * ImportError extends Exception */ static int ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"name", "path", 0}; PyObject *empty_tuple; PyObject *msg = NULL; PyObject *name = NULL; PyObject *path = NULL; if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1) return -1; empty_tuple = PyTuple_New(0); if (!empty_tuple) return -1; if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OO:ImportError", kwlist, &name, &path)) { Py_DECREF(empty_tuple); return -1; } Py_DECREF(empty_tuple); if (name) { Py_INCREF(name); Py_XSETREF(self->name, name); } if (path) { Py_INCREF(path); Py_XSETREF(self->path, path); } if (PyTuple_GET_SIZE(args) == 1) { msg = PyTuple_GET_ITEM(args, 0); Py_INCREF(msg); Py_XSETREF(self->msg, msg); } return 0; } static int ImportError_clear(PyImportErrorObject *self) { Py_CLEAR(self->msg); Py_CLEAR(self->name); Py_CLEAR(self->path); return BaseException_clear((PyBaseExceptionObject *)self); } static void ImportError_dealloc(PyImportErrorObject *self) { _PyObject_GC_UNTRACK(self); ImportError_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); } static int ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg) { Py_VISIT(self->msg); Py_VISIT(self->name); Py_VISIT(self->path); return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); } static PyObject * ImportError_str(PyImportErrorObject *self) { if (self->msg && PyUnicode_CheckExact(self->msg)) { Py_INCREF(self->msg); return self->msg; } else { return BaseException_str((PyBaseExceptionObject *)self); } } static PyObject * ImportError_getstate(PyImportErrorObject *self) { PyObject *dict = ((PyBaseExceptionObject *)self)->dict; if (self->name || self->path) { _Py_IDENTIFIER(name); _Py_IDENTIFIER(path); dict = dict ? PyDict_Copy(dict) : PyDict_New(); if (dict == NULL) return NULL; if (self->name && _PyDict_SetItemId(dict, &PyId_name, self->name) < 0) { Py_DECREF(dict); return NULL; } if (self->path && _PyDict_SetItemId(dict, &PyId_path, self->path) < 0) { Py_DECREF(dict); return NULL; } return dict; } else if (dict) { Py_INCREF(dict); return dict; } else { Py_RETURN_NONE; } } /* Pickling support */ static PyObject * ImportError_reduce(PyImportErrorObject *self) { PyObject *res; PyObject *args; PyObject *state = ImportError_getstate(self); if (state == NULL) return NULL; args = ((PyBaseExceptionObject *)self)->args; if (state == Py_None) res = PyTuple_Pack(2, Py_TYPE(self), args); else res = PyTuple_Pack(3, Py_TYPE(self), args, state); Py_DECREF(state); return res; } static PyMemberDef ImportError_members[] = { {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0, PyDoc_STR("exception message")}, {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0, PyDoc_STR("module name")}, {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0, PyDoc_STR("module path")}, {NULL} /* Sentinel */ }; static PyMethodDef ImportError_methods[] = { {"__reduce__", (PyCFunction)ImportError_reduce, METH_NOARGS}, {NULL} }; ComplexExtendsException(PyExc_Exception, ImportError, ImportError, 0 /* new */, ImportError_methods, ImportError_members, 0 /* getset */, ImportError_str, "Import can't find module, or can't find name in " "module."); /* * ModuleNotFoundError extends ImportError */ MiddlingExtendsException(PyExc_ImportError, ModuleNotFoundError, ImportError, "Module not found."); /* * OSError extends Exception */ /* Where a function has a single filename, such as open() or some * of the os module functions, PyErr_SetFromErrnoWithFilename() is * called, giving a third argument which is the filename. But, so * that old code using in-place unpacking doesn't break, e.g.: * * except OSError, (errno, strerror): * * we hack args so that it only contains two items. This also * means we need our own __str__() which prints out the filename * when it was supplied. * * (If a function has two filenames, such as rename(), symlink(), * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called, * which allows passing in a second filename.) */ /* This function doesn't cleanup on error, the caller should */ static int oserror_parse_args(PyObject **p_args, PyObject **myerrno, PyObject **strerror, PyObject **filename, PyObject **filename2 #ifdef MS_WINDOWS , PyObject **winerror #endif ) { Py_ssize_t nargs; PyObject *args = *p_args; #ifndef MS_WINDOWS /* * ignored on non-Windows platforms, * but parsed so OSError has a consistent signature */ PyObject *_winerror = NULL; PyObject **winerror = &_winerror; #endif /* MS_WINDOWS */ nargs = PyTuple_GET_SIZE(args); if (nargs >= 2 && nargs <= 5) { if (!PyArg_UnpackTuple(args, "OSError", 2, 5, myerrno, strerror, filename, winerror, filename2)) return -1; #ifdef MS_WINDOWS if (*winerror && PyLong_Check(*winerror)) { long errcode, winerrcode; PyObject *newargs; Py_ssize_t i; winerrcode = PyLong_AsLong(*winerror); if (winerrcode == -1 && PyErr_Occurred()) return -1; /* Set errno to the corresponding POSIX errno (overriding first argument). Windows Socket error codes (>= 10000) have the same value as their POSIX counterparts. */ if (winerrcode < 10000) errcode = winerror_to_errno(winerrcode); else errcode = winerrcode; *myerrno = PyLong_FromLong(errcode); if (!*myerrno) return -1; newargs = PyTuple_New(nargs); if (!newargs) return -1; PyTuple_SET_ITEM(newargs, 0, *myerrno); for (i = 1; i < nargs; i++) { PyObject *val = PyTuple_GET_ITEM(args, i); Py_INCREF(val); PyTuple_SET_ITEM(newargs, i, val); } Py_DECREF(args); args = *p_args = newargs; } #endif /* MS_WINDOWS */ } return 0; } static int oserror_init(PyOSErrorObject *self, PyObject **p_args, PyObject *myerrno, PyObject *strerror, PyObject *filename, PyObject *filename2 #ifdef MS_WINDOWS , PyObject *winerror #endif ) { PyObject *args = *p_args; Py_ssize_t nargs = PyTuple_GET_SIZE(args); /* self->filename will remain Py_None otherwise */ if (filename && filename != Py_None) { if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError && PyNumber_Check(filename)) { /* BlockingIOError's 3rd argument can be the number of * characters written. */ self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError); if (self->written == -1 && PyErr_Occurred()) return -1; } else { Py_INCREF(filename); self->filename = filename; if (filename2 && filename2 != Py_None) { Py_INCREF(filename2); self->filename2 = filename2; } if (nargs >= 2 && nargs <= 5) { /* filename, filename2, and winerror are removed from the args tuple (for compatibility purposes, see test_exceptions.py) */ PyObject *subslice = PyTuple_GetSlice(args, 0, 2); if (!subslice) return -1; Py_DECREF(args); /* replacing args */ *p_args = args = subslice; } } } Py_XINCREF(myerrno); self->myerrno = myerrno; Py_XINCREF(strerror); self->strerror = strerror; #ifdef MS_WINDOWS Py_XINCREF(winerror); self->winerror = winerror; #endif /* Steals the reference to args */ Py_XSETREF(self->args, args); *p_args = args = NULL; return 0; } static PyObject * OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static int OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds); static int oserror_use_init(PyTypeObject *type) { /* When __init__ is defined in an OSError subclass, we want any extraneous argument to __new__ to be ignored. The only reasonable solution, given __new__ takes a variable number of arguments, is to defer arg parsing and initialization to __init__. But when __new__ is overridden as well, it should call our __new__ with the right arguments. (see http://bugs.python.org/issue12555#msg148829 ) */ if (type->tp_init != (initproc) OSError_init && type->tp_new == (newfunc) OSError_new) { assert((PyObject *) type != PyExc_OSError); return 1; } return 0; } static PyObject * OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyOSErrorObject *self = NULL; PyObject *myerrno = NULL, *strerror = NULL; PyObject *filename = NULL, *filename2 = NULL; #ifdef MS_WINDOWS PyObject *winerror = NULL; #endif Py_INCREF(args); if (!oserror_use_init(type)) { if (!_PyArg_NoKeywords(type->tp_name, kwds)) goto error; if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2 #ifdef MS_WINDOWS , &winerror #endif )) goto error; if (myerrno && PyLong_Check(myerrno) && errnomap && (PyObject *) type == PyExc_OSError) { PyObject *newtype; newtype = PyDict_GetItem(errnomap, myerrno); if (newtype) { assert(PyType_Check(newtype)); type = (PyTypeObject *) newtype; } else if (PyErr_Occurred()) goto error; } } self = (PyOSErrorObject *) type->tp_alloc(type, 0); if (!self) goto error; self->dict = NULL; self->traceback = self->cause = self->context = NULL; self->written = -1; if (!oserror_use_init(type)) { if (oserror_init(self, &args, myerrno, strerror, filename, filename2 #ifdef MS_WINDOWS , winerror #endif )) goto error; } else { self->args = PyTuple_New(0); if (self->args == NULL) goto error; } Py_XDECREF(args); return (PyObject *) self; error: Py_XDECREF(args); Py_XDECREF(self); return NULL; } static int OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds) { PyObject *myerrno = NULL, *strerror = NULL; PyObject *filename = NULL, *filename2 = NULL; #ifdef MS_WINDOWS PyObject *winerror = NULL; #endif if (!oserror_use_init(Py_TYPE(self))) /* Everything already done in OSError_new */ return 0; if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds)) return -1; Py_INCREF(args); if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2 #ifdef MS_WINDOWS , &winerror #endif )) goto error; if (oserror_init(self, &args, myerrno, strerror, filename, filename2 #ifdef MS_WINDOWS , winerror #endif )) goto error; return 0; error: Py_DECREF(args); return -1; } static int OSError_clear(PyOSErrorObject *self) { Py_CLEAR(self->myerrno); Py_CLEAR(self->strerror); Py_CLEAR(self->filename); Py_CLEAR(self->filename2); #ifdef MS_WINDOWS Py_CLEAR(self->winerror); #endif return BaseException_clear((PyBaseExceptionObject *)self); } static void OSError_dealloc(PyOSErrorObject *self) { _PyObject_GC_UNTRACK(self); OSError_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); } static int OSError_traverse(PyOSErrorObject *self, visitproc visit, void *arg) { Py_VISIT(self->myerrno); Py_VISIT(self->strerror); Py_VISIT(self->filename); Py_VISIT(self->filename2); #ifdef MS_WINDOWS Py_VISIT(self->winerror); #endif return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); } static PyObject * OSError_str(PyOSErrorObject *self) { #define OR_NONE(x) ((x)?(x):Py_None) #ifdef MS_WINDOWS /* If available, winerror has the priority over myerrno */ if (self->winerror && self->filename) { if (self->filename2) { return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R", OR_NONE(self->winerror), OR_NONE(self->strerror), self->filename, self->filename2); } else { return PyUnicode_FromFormat("[WinError %S] %S: %R", OR_NONE(self->winerror), OR_NONE(self->strerror), self->filename); } } if (self->winerror && self->strerror) return PyUnicode_FromFormat("[WinError %S] %S", self->winerror ? self->winerror: Py_None, self->strerror ? self->strerror: Py_None); #endif if (self->filename) { if (self->filename2) { return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R", OR_NONE(self->myerrno), OR_NONE(self->strerror), self->filename, self->filename2); } else { return PyUnicode_FromFormat("[Errno %S] %S: %R", OR_NONE(self->myerrno), OR_NONE(self->strerror), self->filename); } } if (self->myerrno && self->strerror) return PyUnicode_FromFormat("[Errno %S] %S", self->myerrno, self->strerror); return BaseException_str((PyBaseExceptionObject *)self); } static PyObject * OSError_reduce(PyOSErrorObject *self) { PyObject *args = self->args; PyObject *res = NULL, *tmp; /* self->args is only the first two real arguments if there was a * file name given to OSError. */ if (PyTuple_GET_SIZE(args) == 2 && self->filename) { Py_ssize_t size = self->filename2 ? 5 : 3; args = PyTuple_New(size); if (!args) return NULL; tmp = PyTuple_GET_ITEM(self->args, 0); Py_INCREF(tmp); PyTuple_SET_ITEM(args, 0, tmp); tmp = PyTuple_GET_ITEM(self->args, 1); Py_INCREF(tmp); PyTuple_SET_ITEM(args, 1, tmp); Py_INCREF(self->filename); PyTuple_SET_ITEM(args, 2, self->filename); if (self->filename2) { /* * This tuple is essentially used as OSError(*args). * So, to recreate filename2, we need to pass in * winerror as well. */ Py_INCREF(Py_None); PyTuple_SET_ITEM(args, 3, Py_None); /* filename2 */ Py_INCREF(self->filename2); PyTuple_SET_ITEM(args, 4, self->filename2); } } else Py_INCREF(args); if (self->dict) res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict); else res = PyTuple_Pack(2, Py_TYPE(self), args); Py_DECREF(args); return res; } static PyObject * OSError_written_get(PyOSErrorObject *self, void *context) { if (self->written == -1) { PyErr_SetString(PyExc_AttributeError, "characters_written"); return NULL; } return PyLong_FromSsize_t(self->written); } static int OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context) { Py_ssize_t n; n = PyNumber_AsSsize_t(arg, PyExc_ValueError); if (n == -1 && PyErr_Occurred()) return -1; self->written = n; return 0; } static PyMemberDef OSError_members[] = { {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0, PyDoc_STR("POSIX exception code")}, {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0, PyDoc_STR("exception strerror")}, {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0, PyDoc_STR("exception filename")}, {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0, PyDoc_STR("second exception filename")}, #ifdef MS_WINDOWS {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0, PyDoc_STR("Win32 exception code")}, #endif {NULL} /* Sentinel */ }; static PyMethodDef OSError_methods[] = { {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS}, {NULL} }; static PyGetSetDef OSError_getset[] = { {"characters_written", (getter) OSError_written_get, (setter) OSError_written_set, NULL}, {NULL} }; ComplexExtendsException(PyExc_Exception, OSError, OSError, OSError_new, OSError_methods, OSError_members, OSError_getset, OSError_str, "Base class for I/O related errors."); /* * Various OSError subclasses */ MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError, "I/O operation would block."); MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError, "Connection error."); MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError, "Child process error."); MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError, "Broken pipe."); MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError, "Connection aborted."); MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError, "Connection refused."); MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError, "Connection reset."); MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError, "File already exists."); MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError, "File not found."); MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError, "Operation doesn't work on directories."); MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError, "Operation only works on directories."); MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError, "Interrupted by signal."); MiddlingExtendsException(PyExc_OSError, PermissionError, OSError, "Not enough permissions."); MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError, "Process not found."); MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError, "Timeout expired."); /* * EOFError extends Exception */ SimpleExtendsException(PyExc_Exception, EOFError, "Read beyond end of file."); /* * RuntimeError extends Exception */ SimpleExtendsException(PyExc_Exception, RuntimeError, "Unspecified run-time error."); /* * RecursionError extends RuntimeError */ SimpleExtendsException(PyExc_RuntimeError, RecursionError, "Recursion limit exceeded."); /* * NotImplementedError extends RuntimeError */ SimpleExtendsException(PyExc_RuntimeError, NotImplementedError, "Method or function hasn't been implemented yet."); /* * NameError extends Exception */ SimpleExtendsException(PyExc_Exception, NameError, "Name not found globally."); /* * UnboundLocalError extends NameError */ SimpleExtendsException(PyExc_NameError, UnboundLocalError, "Local name referenced but not bound to a value."); /* * AttributeError extends Exception */ SimpleExtendsException(PyExc_Exception, AttributeError, "Attribute not found."); /* * SyntaxError extends Exception */ /* Helper function to customize error message for some syntax errors */ static int _report_missing_parentheses(PySyntaxErrorObject *self); static int SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds) { PyObject *info = NULL; Py_ssize_t lenargs = PyTuple_GET_SIZE(args); if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) return -1; if (lenargs >= 1) { Py_INCREF(PyTuple_GET_ITEM(args, 0)); Py_XSETREF(self->msg, PyTuple_GET_ITEM(args, 0)); } if (lenargs == 2) { info = PyTuple_GET_ITEM(args, 1); info = PySequence_Tuple(info); if (!info) return -1; if (PyTuple_GET_SIZE(info) != 4) { /* not a very good error message, but it's what Python 2.4 gives */ PyErr_SetString(PyExc_IndexError, "tuple index out of range"); Py_DECREF(info); return -1; } Py_INCREF(PyTuple_GET_ITEM(info, 0)); Py_XSETREF(self->filename, PyTuple_GET_ITEM(info, 0)); Py_INCREF(PyTuple_GET_ITEM(info, 1)); Py_XSETREF(self->lineno, PyTuple_GET_ITEM(info, 1)); Py_INCREF(PyTuple_GET_ITEM(info, 2)); Py_XSETREF(self->offset, PyTuple_GET_ITEM(info, 2)); Py_INCREF(PyTuple_GET_ITEM(info, 3)); Py_XSETREF(self->text, PyTuple_GET_ITEM(info, 3)); Py_DECREF(info); /* * Issue #21669: Custom error for 'print' & 'exec' as statements * * Only applies to SyntaxError instances, not to subclasses such * as TabError or IndentationError (see issue #31161) */ if ((PyObject*)Py_TYPE(self) == PyExc_SyntaxError && self->text && PyUnicode_Check(self->text) && _report_missing_parentheses(self) < 0) { return -1; } } return 0; } static int SyntaxError_clear(PySyntaxErrorObject *self) { Py_CLEAR(self->msg); Py_CLEAR(self->filename); Py_CLEAR(self->lineno); Py_CLEAR(self->offset); Py_CLEAR(self->text); Py_CLEAR(self->print_file_and_line); return BaseException_clear((PyBaseExceptionObject *)self); } static void SyntaxError_dealloc(PySyntaxErrorObject *self) { _PyObject_GC_UNTRACK(self); SyntaxError_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); } static int SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg) { Py_VISIT(self->msg); Py_VISIT(self->filename); Py_VISIT(self->lineno); Py_VISIT(self->offset); Py_VISIT(self->text); Py_VISIT(self->print_file_and_line); return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); } /* This is called "my_basename" instead of just "basename" to avoid name conflicts with glibc; basename is already prototyped if _GNU_SOURCE is defined, and Python does define that. */ static PyObject* my_basename(PyObject *name) { Py_ssize_t i, size, offset; int kind; void *data; if (PyUnicode_READY(name)) return NULL; kind = PyUnicode_KIND(name); data = PyUnicode_DATA(name); size = PyUnicode_GET_LENGTH(name); offset = 0; for(i=0; i < size; i++) { if (PyUnicode_READ(kind, data, i) == SEP) offset = i + 1; } if (offset != 0) return PyUnicode_Substring(name, offset, size); else { Py_INCREF(name); return name; } } static PyObject * SyntaxError_str(PySyntaxErrorObject *self) { int have_lineno = 0; PyObject *filename; PyObject *result; /* Below, we always ignore overflow errors, just printing -1. Still, we cannot allow an OverflowError to be raised, so we need to call PyLong_AsLongAndOverflow. */ int overflow; /* XXX -- do all the additional formatting with filename and lineno here */ if (self->filename && PyUnicode_Check(self->filename)) { filename = my_basename(self->filename); if (filename == NULL) return NULL; } else { filename = NULL; } have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno); if (!filename && !have_lineno) return PyObject_Str(self->msg ? self->msg : Py_None); if (filename && have_lineno) result = PyUnicode_FromFormat("%S (%U, line %ld)", self->msg ? self->msg : Py_None, filename, PyLong_AsLongAndOverflow(self->lineno, &overflow)); else if (filename) result = PyUnicode_FromFormat("%S (%U)", self->msg ? self->msg : Py_None, filename); else /* only have_lineno */ result = PyUnicode_FromFormat("%S (line %ld)", self->msg ? self->msg : Py_None, PyLong_AsLongAndOverflow(self->lineno, &overflow)); Py_XDECREF(filename); return result; } static PyMemberDef SyntaxError_members[] = { {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0, PyDoc_STR("exception msg")}, {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0, PyDoc_STR("exception filename")}, {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0, PyDoc_STR("exception lineno")}, {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0, PyDoc_STR("exception offset")}, {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0, PyDoc_STR("exception text")}, {"print_file_and_line", T_OBJECT, offsetof(PySyntaxErrorObject, print_file_and_line), 0, PyDoc_STR("exception print_file_and_line")}, {NULL} /* Sentinel */ }; ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError, 0, 0, SyntaxError_members, 0, SyntaxError_str, "Invalid syntax."); /* * IndentationError extends SyntaxError */ MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError, "Improper indentation."); /* * TabError extends IndentationError */ MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError, "Improper mixture of spaces and tabs."); /* * LookupError extends Exception */ SimpleExtendsException(PyExc_Exception, LookupError, "Base class for lookup errors."); /* * IndexError extends LookupError */ SimpleExtendsException(PyExc_LookupError, IndexError, "Sequence index out of range."); /* * KeyError extends LookupError */ static PyObject * KeyError_str(PyBaseExceptionObject *self) { /* If args is a tuple of exactly one item, apply repr to args[0]. This is done so that e.g. the exception raised by {}[''] prints KeyError: '' rather than the confusing KeyError alone. The downside is that if KeyError is raised with an explanatory string, that string will be displayed in quotes. Too bad. If args is anything else, use the default BaseException__str__(). */ if (PyTuple_GET_SIZE(self->args) == 1) { return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0)); } return BaseException_str(self); } ComplexExtendsException(PyExc_LookupError, KeyError, BaseException, 0, 0, 0, 0, KeyError_str, "Mapping key not found."); /* * ValueError extends Exception */ SimpleExtendsException(PyExc_Exception, ValueError, "Inappropriate argument value (of correct type)."); /* * UnicodeError extends ValueError */ SimpleExtendsException(PyExc_ValueError, UnicodeError, "Unicode related error."); static PyObject * get_string(PyObject *attr, const char *name) { if (!attr) { PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name); return NULL; } if (!PyBytes_Check(attr)) { PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name); return NULL; } Py_INCREF(attr); return attr; } static PyObject * get_unicode(PyObject *attr, const char *name) { if (!attr) { PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name); return NULL; } if (!PyUnicode_Check(attr)) { PyErr_Format(PyExc_TypeError, "%.200s attribute must be unicode", name); return NULL; } Py_INCREF(attr); return attr; } static int set_unicodefromstring(PyObject **attr, const char *value) { PyObject *obj = PyUnicode_FromString(value); if (!obj) return -1; Py_XSETREF(*attr, obj); return 0; } PyObject * PyUnicodeEncodeError_GetEncoding(PyObject *exc) { return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding"); } PyObject * PyUnicodeDecodeError_GetEncoding(PyObject *exc) { return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding"); } PyObject * PyUnicodeEncodeError_GetObject(PyObject *exc) { return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object"); } PyObject * PyUnicodeDecodeError_GetObject(PyObject *exc) { return get_string(((PyUnicodeErrorObject *)exc)->object, "object"); } PyObject * PyUnicodeTranslateError_GetObject(PyObject *exc) { return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object"); } int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) { Py_ssize_t size; PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object, "object"); if (!obj) return -1; *start = ((PyUnicodeErrorObject *)exc)->start; size = PyUnicode_GET_LENGTH(obj); if (*start<0) *start = 0; /*XXX check for values <0*/ if (*start>=size) *start = size-1; Py_DECREF(obj); return 0; } int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) { Py_ssize_t size; PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object"); if (!obj) return -1; size = PyBytes_GET_SIZE(obj); *start = ((PyUnicodeErrorObject *)exc)->start; if (*start<0) *start = 0; if (*start>=size) *start = size-1; Py_DECREF(obj); return 0; } int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) { return PyUnicodeEncodeError_GetStart(exc, start); } int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start) { ((PyUnicodeErrorObject *)exc)->start = start; return 0; } int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start) { ((PyUnicodeErrorObject *)exc)->start = start; return 0; } int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start) { ((PyUnicodeErrorObject *)exc)->start = start; return 0; } int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end) { Py_ssize_t size; PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object, "object"); if (!obj) return -1; *end = ((PyUnicodeErrorObject *)exc)->end; size = PyUnicode_GET_LENGTH(obj); if (*end<1) *end = 1; if (*end>size) *end = size; Py_DECREF(obj); return 0; } int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end) { Py_ssize_t size; PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object"); if (!obj) return -1; size = PyBytes_GET_SIZE(obj); *end = ((PyUnicodeErrorObject *)exc)->end; if (*end<1) *end = 1; if (*end>size) *end = size; Py_DECREF(obj); return 0; } int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start) { return PyUnicodeEncodeError_GetEnd(exc, start); } int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end) { ((PyUnicodeErrorObject *)exc)->end = end; return 0; } int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end) { ((PyUnicodeErrorObject *)exc)->end = end; return 0; } int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end) { ((PyUnicodeErrorObject *)exc)->end = end; return 0; } PyObject * PyUnicodeEncodeError_GetReason(PyObject *exc) { return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason"); } PyObject * PyUnicodeDecodeError_GetReason(PyObject *exc) { return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason"); } PyObject * PyUnicodeTranslateError_GetReason(PyObject *exc) { return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason"); } int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason) { return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason, reason); } int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason) { return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason, reason); } int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason) { return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason, reason); } static int UnicodeError_clear(PyUnicodeErrorObject *self) { Py_CLEAR(self->encoding); Py_CLEAR(self->object); Py_CLEAR(self->reason); return BaseException_clear((PyBaseExceptionObject *)self); } static void UnicodeError_dealloc(PyUnicodeErrorObject *self) { _PyObject_GC_UNTRACK(self); UnicodeError_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); } static int UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg) { Py_VISIT(self->encoding); Py_VISIT(self->object); Py_VISIT(self->reason); return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); } static PyMemberDef UnicodeError_members[] = { {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0, PyDoc_STR("exception encoding")}, {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0, PyDoc_STR("exception object")}, {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0, PyDoc_STR("exception start")}, {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0, PyDoc_STR("exception end")}, {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0, PyDoc_STR("exception reason")}, {NULL} /* Sentinel */ }; /* * UnicodeEncodeError extends UnicodeError */ static int UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds) { PyUnicodeErrorObject *err; if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) return -1; err = (PyUnicodeErrorObject *)self; Py_CLEAR(err->encoding); Py_CLEAR(err->object); Py_CLEAR(err->reason); if (!PyArg_ParseTuple(args, "O!O!nnO!", &PyUnicode_Type, &err->encoding, &PyUnicode_Type, &err->object, &err->start, &err->end, &PyUnicode_Type, &err->reason)) { err->encoding = err->object = err->reason = NULL; return -1; } if (PyUnicode_READY(err->object) < -1) { err->encoding = NULL; return -1; } Py_INCREF(err->encoding); Py_INCREF(err->object); Py_INCREF(err->reason); return 0; } static PyObject * UnicodeEncodeError_str(PyObject *self) { PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self; PyObject *result = NULL; PyObject *reason_str = NULL; PyObject *encoding_str = NULL; if (!uself->object) /* Not properly initialized. */ return PyUnicode_FromString(""); /* Get reason and encoding as strings, which they might not be if they've been modified after we were constructed. */ reason_str = PyObject_Str(uself->reason); if (reason_str == NULL) goto done; encoding_str = PyObject_Str(uself->encoding); if (encoding_str == NULL) goto done; if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) { Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start); const char *fmt; if (badchar <= 0xff) fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U"; else if (badchar <= 0xffff) fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U"; else fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U"; result = PyUnicode_FromFormat( fmt, encoding_str, (int)badchar, uself->start, reason_str); } else { result = PyUnicode_FromFormat( "'%U' codec can't encode characters in position %zd-%zd: %U", encoding_str, uself->start, uself->end-1, reason_str); } done: Py_XDECREF(reason_str); Py_XDECREF(encoding_str); return result; } static PyTypeObject _PyExc_UnicodeEncodeError = { PyVarObject_HEAD_INIT(NULL, 0) "UnicodeEncodeError", sizeof(PyUnicodeErrorObject), 0, (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (reprfunc)UnicodeEncodeError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse, (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), (initproc)UnicodeEncodeError_init, 0, BaseException_new, }; PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError; PyObject * PyUnicodeEncodeError_Create( const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) { return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns", encoding, object, length, start, end, reason); } /* * UnicodeDecodeError extends UnicodeError */ static int UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds) { PyUnicodeErrorObject *ude; if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) return -1; ude = (PyUnicodeErrorObject *)self; Py_CLEAR(ude->encoding); Py_CLEAR(ude->object); Py_CLEAR(ude->reason); if (!PyArg_ParseTuple(args, "O!OnnO!", &PyUnicode_Type, &ude->encoding, &ude->object, &ude->start, &ude->end, &PyUnicode_Type, &ude->reason)) { ude->encoding = ude->object = ude->reason = NULL; return -1; } Py_INCREF(ude->encoding); Py_INCREF(ude->object); Py_INCREF(ude->reason); if (!PyBytes_Check(ude->object)) { Py_buffer view; if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0) goto error; Py_XSETREF(ude->object, PyBytes_FromStringAndSize(view.buf, view.len)); PyBuffer_Release(&view); if (!ude->object) goto error; } return 0; error: Py_CLEAR(ude->encoding); Py_CLEAR(ude->object); Py_CLEAR(ude->reason); return -1; } static PyObject * UnicodeDecodeError_str(PyObject *self) { PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self; PyObject *result = NULL; PyObject *reason_str = NULL; PyObject *encoding_str = NULL; if (!uself->object) /* Not properly initialized. */ return PyUnicode_FromString(""); /* Get reason and encoding as strings, which they might not be if they've been modified after we were constructed. */ reason_str = PyObject_Str(uself->reason); if (reason_str == NULL) goto done; encoding_str = PyObject_Str(uself->encoding); if (encoding_str == NULL) goto done; if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) { int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff); result = PyUnicode_FromFormat( "'%U' codec can't decode byte 0x%02x in position %zd: %U", encoding_str, byte, uself->start, reason_str); } else { result = PyUnicode_FromFormat( "'%U' codec can't decode bytes in position %zd-%zd: %U", encoding_str, uself->start, uself->end-1, reason_str ); } done: Py_XDECREF(reason_str); Py_XDECREF(encoding_str); return result; } static PyTypeObject _PyExc_UnicodeDecodeError = { PyVarObject_HEAD_INIT(NULL, 0) "UnicodeDecodeError", sizeof(PyUnicodeErrorObject), 0, (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (reprfunc)UnicodeDecodeError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse, (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), (initproc)UnicodeDecodeError_init, 0, BaseException_new, }; PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError; PyObject * PyUnicodeDecodeError_Create( const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) { return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns", encoding, object, length, start, end, reason); } /* * UnicodeTranslateError extends UnicodeError */ static int UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args, PyObject *kwds) { if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) return -1; Py_CLEAR(self->object); Py_CLEAR(self->reason); if (!PyArg_ParseTuple(args, "O!nnO!", &PyUnicode_Type, &self->object, &self->start, &self->end, &PyUnicode_Type, &self->reason)) { self->object = self->reason = NULL; return -1; } Py_INCREF(self->object); Py_INCREF(self->reason); return 0; } static PyObject * UnicodeTranslateError_str(PyObject *self) { PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self; PyObject *result = NULL; PyObject *reason_str = NULL; if (!uself->object) /* Not properly initialized. */ return PyUnicode_FromString(""); /* Get reason as a string, which it might not be if it's been modified after we were constructed. */ reason_str = PyObject_Str(uself->reason); if (reason_str == NULL) goto done; if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) { Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start); const char *fmt; if (badchar <= 0xff) fmt = "can't translate character '\\x%02x' in position %zd: %U"; else if (badchar <= 0xffff) fmt = "can't translate character '\\u%04x' in position %zd: %U"; else fmt = "can't translate character '\\U%08x' in position %zd: %U"; result = PyUnicode_FromFormat( fmt, (int)badchar, uself->start, reason_str ); } else { result = PyUnicode_FromFormat( "can't translate characters in position %zd-%zd: %U", uself->start, uself->end-1, reason_str ); } done: Py_XDECREF(reason_str); return result; } static PyTypeObject _PyExc_UnicodeTranslateError = { PyVarObject_HEAD_INIT(NULL, 0) "UnicodeTranslateError", sizeof(PyUnicodeErrorObject), 0, (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (reprfunc)UnicodeTranslateError_str, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse, (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members, 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict), (initproc)UnicodeTranslateError_init, 0, BaseException_new, }; PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError; /* Deprecated. */ PyObject * PyUnicodeTranslateError_Create( const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason) { return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns", object, length, start, end, reason); } PyObject * _PyUnicodeTranslateError_Create( PyObject *object, Py_ssize_t start, Py_ssize_t end, const char *reason) { return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns", object, start, end, reason); } /* * AssertionError extends Exception */ SimpleExtendsException(PyExc_Exception, AssertionError, "Assertion failed."); /* * ArithmeticError extends Exception */ SimpleExtendsException(PyExc_Exception, ArithmeticError, "Base class for arithmetic errors."); /* * FloatingPointError extends ArithmeticError */ SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError, "Floating point operation failed."); /* * OverflowError extends ArithmeticError */ SimpleExtendsException(PyExc_ArithmeticError, OverflowError, "Result too large to be represented."); /* * ZeroDivisionError extends ArithmeticError */ SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError, "Second argument to a division or modulo operation was zero."); /* * SystemError extends Exception */ SimpleExtendsException(PyExc_Exception, SystemError, "Internal error in the Python interpreter.\n" "\n" "Please report this to the Python maintainer, along with the traceback,\n" "the Python version, and the hardware/OS platform and version."); /* * ReferenceError extends Exception */ SimpleExtendsException(PyExc_Exception, ReferenceError, "Weak ref proxy used after referent went away."); /* * MemoryError extends Exception */ #define MEMERRORS_SAVE 16 static PyBaseExceptionObject *memerrors_freelist = NULL; static int memerrors_numfree = 0; static PyObject * MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyBaseExceptionObject *self; if (type != (PyTypeObject *) PyExc_MemoryError) return BaseException_new(type, args, kwds); if (memerrors_freelist == NULL) return BaseException_new(type, args, kwds); /* Fetch object from freelist and revive it */ self = memerrors_freelist; self->args = PyTuple_New(0); /* This shouldn't happen since the empty tuple is persistent */ if (self->args == NULL) return NULL; memerrors_freelist = (PyBaseExceptionObject *) self->dict; memerrors_numfree--; self->dict = NULL; _Py_NewReference((PyObject *)self); _PyObject_GC_TRACK(self); return (PyObject *)self; } static void MemoryError_dealloc(PyBaseExceptionObject *self) { _PyObject_GC_UNTRACK(self); BaseException_clear(self); if (memerrors_numfree >= MEMERRORS_SAVE) Py_TYPE(self)->tp_free((PyObject *)self); else { self->dict = (PyObject *) memerrors_freelist; memerrors_freelist = self; memerrors_numfree++; } } static void preallocate_memerrors(void) { /* We create enough MemoryErrors and then decref them, which will fill up the freelist. */ int i; PyObject *errors[MEMERRORS_SAVE]; for (i = 0; i < MEMERRORS_SAVE; i++) { errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError, NULL, NULL); if (!errors[i]) Py_FatalError("Could not preallocate MemoryError object"); } for (i = 0; i < MEMERRORS_SAVE; i++) { Py_DECREF(errors[i]); } } static void free_preallocated_memerrors(void) { while (memerrors_freelist != NULL) { PyObject *self = (PyObject *) memerrors_freelist; memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict; Py_TYPE(self)->tp_free((PyObject *)self); } } static PyTypeObject _PyExc_MemoryError = { PyVarObject_HEAD_INIT(NULL, 0) "MemoryError", sizeof(PyBaseExceptionObject), 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse, (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception, 0, 0, 0, offsetof(PyBaseExceptionObject, dict), (initproc)BaseException_init, 0, MemoryError_new }; PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError; /* * BufferError extends Exception */ SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error."); /* Warning category docstrings */ /* * Warning extends Exception */ SimpleExtendsException(PyExc_Exception, Warning, "Base class for warning categories."); /* * UserWarning extends Warning */ SimpleExtendsException(PyExc_Warning, UserWarning, "Base class for warnings generated by user code."); /* * DeprecationWarning extends Warning */ SimpleExtendsException(PyExc_Warning, DeprecationWarning, "Base class for warnings about deprecated features."); /* * PendingDeprecationWarning extends Warning */ SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning, "Base class for warnings about features which will be deprecated\n" "in the future."); /* * SyntaxWarning extends Warning */ SimpleExtendsException(PyExc_Warning, SyntaxWarning, "Base class for warnings about dubious syntax."); /* * RuntimeWarning extends Warning */ SimpleExtendsException(PyExc_Warning, RuntimeWarning, "Base class for warnings about dubious runtime behavior."); /* * FutureWarning extends Warning */ SimpleExtendsException(PyExc_Warning, FutureWarning, "Base class for warnings about constructs that will change semantically\n" "in the future."); /* * ImportWarning extends Warning */ SimpleExtendsException(PyExc_Warning, ImportWarning, "Base class for warnings about probable mistakes in module imports"); /* * UnicodeWarning extends Warning */ SimpleExtendsException(PyExc_Warning, UnicodeWarning, "Base class for warnings about Unicode related problems, mostly\n" "related to conversion problems."); /* * BytesWarning extends Warning */ SimpleExtendsException(PyExc_Warning, BytesWarning, "Base class for warnings about bytes and buffer related problems, mostly\n" "related to conversion from str or comparing to str."); /* * ResourceWarning extends Warning */ SimpleExtendsException(PyExc_Warning, ResourceWarning, "Base class for warnings about resource usage."); #define PRE_INIT(TYPE) \ if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \ if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \ Py_FatalError("exceptions bootstrapping error."); \ Py_INCREF(PyExc_ ## TYPE); \ } #define POST_INIT(TYPE) \ if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \ Py_FatalError("Module dictionary insertion problem."); #define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \ Py_XDECREF(PyExc_ ## NAME); \ PyExc_ ## NAME = PyExc_ ## TYPE; \ if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \ Py_FatalError("Module dictionary insertion problem."); #define ADD_ERRNO(TYPE, CODE) { \ PyObject *_code = PyLong_FromLong(CODE); \ assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \ if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \ Py_FatalError("errmap insertion problem."); \ Py_DECREF(_code); \ } #ifdef MS_WINDOWS #include <winsock2.h> /* The following constants were added to errno.h in VS2010 but have preferred WSA equivalents. */ #undef EADDRINUSE #undef EADDRNOTAVAIL #undef EAFNOSUPPORT #undef EALREADY #undef ECONNABORTED #undef ECONNREFUSED #undef ECONNRESET #undef EDESTADDRREQ #undef EHOSTUNREACH #undef EINPROGRESS #undef EISCONN #undef ELOOP #undef EMSGSIZE #undef ENETDOWN #undef ENETRESET #undef ENETUNREACH #undef ENOBUFS #undef ENOPROTOOPT #undef ENOTCONN #undef ENOTSOCK #undef EOPNOTSUPP #undef EPROTONOSUPPORT #undef EPROTOTYPE #undef ETIMEDOUT #undef EWOULDBLOCK #if defined(WSAEALREADY) && !defined(EALREADY) #define EALREADY WSAEALREADY #endif #if defined(WSAECONNABORTED) && !defined(ECONNABORTED) #define ECONNABORTED WSAECONNABORTED #endif #if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED) #define ECONNREFUSED WSAECONNREFUSED #endif #if defined(WSAECONNRESET) && !defined(ECONNRESET) #define ECONNRESET WSAECONNRESET #endif #if defined(WSAEINPROGRESS) && !defined(EINPROGRESS) #define EINPROGRESS WSAEINPROGRESS #endif #if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN) #define ESHUTDOWN WSAESHUTDOWN #endif #if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT) #define ETIMEDOUT WSAETIMEDOUT #endif #if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK) #define EWOULDBLOCK WSAEWOULDBLOCK #endif #endif /* MS_WINDOWS */ void _PyExc_Init(PyObject *bltinmod) { PyObject *bdict; PRE_INIT(BaseException) PRE_INIT(Exception) PRE_INIT(TypeError) PRE_INIT(StopAsyncIteration) PRE_INIT(StopIteration) PRE_INIT(GeneratorExit) PRE_INIT(SystemExit) PRE_INIT(KeyboardInterrupt) PRE_INIT(ImportError) PRE_INIT(ModuleNotFoundError) PRE_INIT(OSError) PRE_INIT(EOFError) PRE_INIT(RuntimeError) PRE_INIT(RecursionError) PRE_INIT(NotImplementedError) PRE_INIT(NameError) PRE_INIT(UnboundLocalError) PRE_INIT(AttributeError) PRE_INIT(SyntaxError) PRE_INIT(IndentationError) PRE_INIT(TabError) PRE_INIT(LookupError) PRE_INIT(IndexError) PRE_INIT(KeyError) PRE_INIT(ValueError) PRE_INIT(UnicodeError) PRE_INIT(UnicodeEncodeError) PRE_INIT(UnicodeDecodeError) PRE_INIT(UnicodeTranslateError) PRE_INIT(AssertionError) PRE_INIT(ArithmeticError) PRE_INIT(FloatingPointError) PRE_INIT(OverflowError) PRE_INIT(ZeroDivisionError) PRE_INIT(SystemError) PRE_INIT(ReferenceError) PRE_INIT(BufferError) PRE_INIT(MemoryError) PRE_INIT(BufferError) PRE_INIT(Warning) PRE_INIT(UserWarning) PRE_INIT(DeprecationWarning) PRE_INIT(PendingDeprecationWarning) PRE_INIT(SyntaxWarning) PRE_INIT(RuntimeWarning) PRE_INIT(FutureWarning) PRE_INIT(ImportWarning) PRE_INIT(UnicodeWarning) PRE_INIT(BytesWarning) PRE_INIT(ResourceWarning) /* OSError subclasses */ PRE_INIT(ConnectionError); PRE_INIT(BlockingIOError); PRE_INIT(BrokenPipeError); PRE_INIT(ChildProcessError); PRE_INIT(ConnectionAbortedError); PRE_INIT(ConnectionRefusedError); PRE_INIT(ConnectionResetError); PRE_INIT(FileExistsError); PRE_INIT(FileNotFoundError); PRE_INIT(IsADirectoryError); PRE_INIT(NotADirectoryError); PRE_INIT(InterruptedError); PRE_INIT(PermissionError); PRE_INIT(ProcessLookupError); PRE_INIT(TimeoutError); bdict = PyModule_GetDict(bltinmod); if (bdict == NULL) Py_FatalError("exceptions bootstrapping error."); POST_INIT(BaseException) POST_INIT(Exception) POST_INIT(TypeError) POST_INIT(StopAsyncIteration) POST_INIT(StopIteration) POST_INIT(GeneratorExit) POST_INIT(SystemExit) POST_INIT(KeyboardInterrupt) POST_INIT(ImportError) POST_INIT(ModuleNotFoundError) POST_INIT(OSError) INIT_ALIAS(EnvironmentError, OSError) INIT_ALIAS(IOError, OSError) #ifdef MS_WINDOWS INIT_ALIAS(WindowsError, OSError) #endif POST_INIT(EOFError) POST_INIT(RuntimeError) POST_INIT(RecursionError) POST_INIT(NotImplementedError) POST_INIT(NameError) POST_INIT(UnboundLocalError) POST_INIT(AttributeError) POST_INIT(SyntaxError) POST_INIT(IndentationError) POST_INIT(TabError) POST_INIT(LookupError) POST_INIT(IndexError) POST_INIT(KeyError) POST_INIT(ValueError) POST_INIT(UnicodeError) POST_INIT(UnicodeEncodeError) POST_INIT(UnicodeDecodeError) POST_INIT(UnicodeTranslateError) POST_INIT(AssertionError) POST_INIT(ArithmeticError) POST_INIT(FloatingPointError) POST_INIT(OverflowError) POST_INIT(ZeroDivisionError) POST_INIT(SystemError) POST_INIT(ReferenceError) POST_INIT(BufferError) POST_INIT(MemoryError) POST_INIT(BufferError) POST_INIT(Warning) POST_INIT(UserWarning) POST_INIT(DeprecationWarning) POST_INIT(PendingDeprecationWarning) POST_INIT(SyntaxWarning) POST_INIT(RuntimeWarning) POST_INIT(FutureWarning) POST_INIT(ImportWarning) POST_INIT(UnicodeWarning) POST_INIT(BytesWarning) POST_INIT(ResourceWarning) if (!errnomap) { errnomap = PyDict_New(); if (!errnomap) Py_FatalError("Cannot allocate map from errnos to OSError subclasses"); } /* OSError subclasses */ POST_INIT(ConnectionError); POST_INIT(BlockingIOError); ADD_ERRNO(BlockingIOError, EAGAIN); ADD_ERRNO(BlockingIOError, EALREADY); ADD_ERRNO(BlockingIOError, EINPROGRESS); ADD_ERRNO(BlockingIOError, EWOULDBLOCK); POST_INIT(BrokenPipeError); ADD_ERRNO(BrokenPipeError, EPIPE); #ifdef ESHUTDOWN ADD_ERRNO(BrokenPipeError, ESHUTDOWN); #endif POST_INIT(ChildProcessError); ADD_ERRNO(ChildProcessError, ECHILD); POST_INIT(ConnectionAbortedError); ADD_ERRNO(ConnectionAbortedError, ECONNABORTED); POST_INIT(ConnectionRefusedError); ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED); POST_INIT(ConnectionResetError); ADD_ERRNO(ConnectionResetError, ECONNRESET); POST_INIT(FileExistsError); ADD_ERRNO(FileExistsError, EEXIST); POST_INIT(FileNotFoundError); ADD_ERRNO(FileNotFoundError, ENOENT); POST_INIT(IsADirectoryError); ADD_ERRNO(IsADirectoryError, EISDIR); POST_INIT(NotADirectoryError); ADD_ERRNO(NotADirectoryError, ENOTDIR); POST_INIT(InterruptedError); ADD_ERRNO(InterruptedError, EINTR); POST_INIT(PermissionError); ADD_ERRNO(PermissionError, EACCES); ADD_ERRNO(PermissionError, EPERM); POST_INIT(ProcessLookupError); ADD_ERRNO(ProcessLookupError, ESRCH); POST_INIT(TimeoutError); ADD_ERRNO(TimeoutError, ETIMEDOUT); preallocate_memerrors(); } void _PyExc_Fini(void) { free_preallocated_memerrors(); Py_CLEAR(errnomap); } /* Helper to do the equivalent of "raise X from Y" in C, but always using * the current exception rather than passing one in. * * We currently limit this to *only* exceptions that use the BaseException * tp_init and tp_new methods, since we can be reasonably sure we can wrap * those correctly without losing data and without losing backwards * compatibility. * * We also aim to rule out *all* exceptions that might be storing additional * state, whether by having a size difference relative to BaseException, * additional arguments passed in during construction or by having a * non-empty instance dict. * * We need to be very careful with what we wrap, since changing types to * a broader exception type would be backwards incompatible for * existing codecs, and with different init or new method implementations * may either not support instantiation with PyErr_Format or lose * information when instantiated that way. * * XXX (ncoghlan): This could be made more comprehensive by exploiting the * fact that exceptions are expected to support pickling. If more builtin * exceptions (e.g. AttributeError) start to be converted to rich * exceptions with additional attributes, that's probably a better approach * to pursue over adding special cases for particular stateful subclasses. * * Returns a borrowed reference to the new exception (if any), NULL if the * existing exception was left in place. */ PyObject * _PyErr_TrySetFromCause(const char *format, ...) { PyObject* msg_prefix; PyObject *exc, *val, *tb; PyTypeObject *caught_type; PyObject **dictptr; PyObject *instance_args; Py_ssize_t num_args, caught_type_size, base_exc_size; PyObject *new_exc, *new_val, *new_tb; va_list vargs; int same_basic_size; PyErr_Fetch(&exc, &val, &tb); caught_type = (PyTypeObject *)exc; /* Ensure type info indicates no extra state is stored at the C level * and that the type can be reinstantiated using PyErr_Format */ caught_type_size = caught_type->tp_basicsize; base_exc_size = _PyExc_BaseException.tp_basicsize; same_basic_size = ( caught_type_size == base_exc_size || (PyType_SUPPORTS_WEAKREFS(caught_type) && (caught_type_size == base_exc_size + (Py_ssize_t)sizeof(PyObject *)) ) ); if (caught_type->tp_init != (initproc)BaseException_init || caught_type->tp_new != BaseException_new || !same_basic_size || caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) { /* We can't be sure we can wrap this safely, since it may contain * more state than just the exception type. Accordingly, we just * leave it alone. */ PyErr_Restore(exc, val, tb); return NULL; } /* Check the args are empty or contain a single string */ PyErr_NormalizeException(&exc, &val, &tb); instance_args = ((PyBaseExceptionObject *)val)->args; num_args = PyTuple_GET_SIZE(instance_args); if (num_args > 1 || (num_args == 1 && !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) { /* More than 1 arg, or the one arg we do have isn't a string */ PyErr_Restore(exc, val, tb); return NULL; } /* Ensure the instance dict is also empty */ dictptr = _PyObject_GetDictPtr(val); if (dictptr != NULL && *dictptr != NULL && PyObject_Length(*dictptr) > 0) { /* While we could potentially copy a non-empty instance dictionary * to the replacement exception, for now we take the more * conservative path of leaving exceptions with attributes set * alone. */ PyErr_Restore(exc, val, tb); return NULL; } /* For exceptions that we can wrap safely, we chain the original * exception to a new one of the exact same type with an * error message that mentions the additional details and the * original exception. * * It would be nice to wrap OSError and various other exception * types as well, but that's quite a bit trickier due to the extra * state potentially stored on OSError instances. */ /* Ensure the traceback is set correctly on the existing exception */ if (tb != NULL) { PyException_SetTraceback(val, tb); Py_DECREF(tb); } #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, format); #else va_start(vargs); #endif msg_prefix = PyUnicode_FromFormatV(format, vargs); va_end(vargs); if (msg_prefix == NULL) { Py_DECREF(exc); Py_DECREF(val); return NULL; } PyErr_Format(exc, "%U (%s: %S)", msg_prefix, Py_TYPE(val)->tp_name, val); Py_DECREF(exc); Py_DECREF(msg_prefix); PyErr_Fetch(&new_exc, &new_val, &new_tb); PyErr_NormalizeException(&new_exc, &new_val, &new_tb); PyException_SetCause(new_val, val); PyErr_Restore(new_exc, new_val, new_tb); return new_val; } /* To help with migration from Python 2, SyntaxError.__init__ applies some * heuristics to try to report a more meaningful exception when print and * exec are used like statements. * * The heuristics are currently expected to detect the following cases: * - top level statement * - statement in a nested suite * - trailing section of a one line complex statement * * They're currently known not to trigger: * - after a semi-colon * * The error message can be a bit odd in cases where the "arguments" are * completely illegal syntactically, but that isn't worth the hassle of * fixing. * * We also can't do anything about cases that are legal Python 3 syntax * but mean something entirely different from what they did in Python 2 * (omitting the arguments entirely, printing items preceded by a unary plus * or minus, using the stream redirection syntax). */ // Static helper for setting legacy print error message static int _set_legacy_print_statement_msg(PySyntaxErrorObject *self, Py_ssize_t start) { // PRINT_OFFSET is to remove the `print ` prefix from the data. const int PRINT_OFFSET = 6; const int STRIP_BOTH = 2; Py_ssize_t start_pos = start + PRINT_OFFSET; Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text); Py_UCS4 semicolon = ';'; Py_ssize_t end_pos = PyUnicode_FindChar(self->text, semicolon, start_pos, text_len, 1); if (end_pos < -1) { return -1; } else if (end_pos == -1) { end_pos = text_len; } PyObject *data = PyUnicode_Substring(self->text, start_pos, end_pos); if (data == NULL) { return -1; } PyObject *strip_sep_obj = PyUnicode_FromString(" \t\r\n"); if (strip_sep_obj == NULL) { Py_DECREF(data); return -1; } PyObject *new_data = _PyUnicode_XStrip(data, STRIP_BOTH, strip_sep_obj); Py_DECREF(data); Py_DECREF(strip_sep_obj); if (new_data == NULL) { return -1; } // gets the modified text_len after stripping `print ` text_len = PyUnicode_GET_LENGTH(new_data); const char *maybe_end_arg = ""; if (text_len > 0 && PyUnicode_READ_CHAR(new_data, text_len-1) == ',') { maybe_end_arg = " end=\" \""; } PyObject *error_msg = PyUnicode_FromFormat( "Missing parentheses in call to 'print'. Did you mean print(%U%s)?", new_data, maybe_end_arg ); Py_DECREF(new_data); if (error_msg == NULL) return -1; Py_XSETREF(self->msg, error_msg); return 1; } static int _check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start) { /* Return values: * -1: an error occurred * 0: nothing happened * 1: the check triggered & the error message was changed */ static PyObject *print_prefix = NULL; static PyObject *exec_prefix = NULL; Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text); int kind = PyUnicode_KIND(self->text); void *data = PyUnicode_DATA(self->text); /* Ignore leading whitespace */ while (start < text_len) { Py_UCS4 ch = PyUnicode_READ(kind, data, start); if (!Py_UNICODE_ISSPACE(ch)) break; start++; } /* Checking against an empty or whitespace-only part of the string */ if (start == text_len) { return 0; } /* Check for legacy print statements */ if (print_prefix == NULL) { print_prefix = PyUnicode_InternFromString("print "); if (print_prefix == NULL) { return -1; } } if (PyUnicode_Tailmatch(self->text, print_prefix, start, text_len, -1)) { return _set_legacy_print_statement_msg(self, start); } /* Check for legacy exec statements */ if (exec_prefix == NULL) { exec_prefix = PyUnicode_InternFromString("exec "); if (exec_prefix == NULL) { return -1; } } if (PyUnicode_Tailmatch(self->text, exec_prefix, start, text_len, -1)) { Py_XSETREF(self->msg, PyUnicode_FromString("Missing parentheses in call to 'exec'")); return 1; } /* Fall back to the default error message */ return 0; } static int _report_missing_parentheses(PySyntaxErrorObject *self) { Py_UCS4 left_paren = 40; Py_ssize_t left_paren_index; Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text); int legacy_check_result = 0; /* Skip entirely if there is an opening parenthesis */ left_paren_index = PyUnicode_FindChar(self->text, left_paren, 0, text_len, 1); if (left_paren_index < -1) { return -1; } if (left_paren_index != -1) { /* Use default error message for any line with an opening paren */ return 0; } /* Handle the simple statement case */ legacy_check_result = _check_for_legacy_statements(self, 0); if (legacy_check_result < 0) { return -1; } if (legacy_check_result == 0) { /* Handle the one-line complex statement case */ Py_UCS4 colon = 58; Py_ssize_t colon_index; colon_index = PyUnicode_FindChar(self->text, colon, 0, text_len, 1); if (colon_index < -1) { return -1; } if (colon_index >= 0 && colon_index < text_len) { /* Check again, starting from just after the colon */ if (_check_for_legacy_statements(self, colon_index+1) < 0) { return -1; } } } return 0; }
89,536
3,026
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/memoryobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/memoryobject.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pystrhex.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ /****************************************************************************/ /* ManagedBuffer Object */ /****************************************************************************/ /* ManagedBuffer Object: --------------------- The purpose of this object is to facilitate the handling of chained memoryviews that have the same underlying exporting object. PEP-3118 allows the underlying object to change while a view is exported. This could lead to unexpected results when constructing a new memoryview from an existing memoryview. Rather than repeatedly redirecting buffer requests to the original base object, all chained memoryviews use a single buffer snapshot. This snapshot is generated by the constructor _PyManagedBuffer_FromObject(). Ownership rules: ---------------- The master buffer inside a managed buffer is filled in by the original base object. shape, strides, suboffsets and format are read-only for all consumers. A memoryview's buffer is a private copy of the exporter's buffer. shape, strides and suboffsets belong to the memoryview and are thus writable. If a memoryview itself exports several buffers via memory_getbuf(), all buffer copies share shape, strides and suboffsets. In this case, the arrays are NOT writable. Reference count assumptions: ---------------------------- The 'obj' member of a Py_buffer must either be NULL or refer to the exporting base object. In the Python codebase, all getbufferprocs return a new reference to view.obj (example: bytes_buffer_getbuffer()). PyBuffer_Release() decrements view.obj (if non-NULL), so the releasebufferprocs must NOT decrement view.obj. */ #define CHECK_MBUF_RELEASED(mbuf) \ if (((_PyManagedBufferObject *)mbuf)->flags&_Py_MANAGED_BUFFER_RELEASED) { \ PyErr_SetString(PyExc_ValueError, \ "operation forbidden on released memoryview object"); \ return NULL; \ } static inline _PyManagedBufferObject * mbuf_alloc(void) { _PyManagedBufferObject *mbuf; mbuf = (_PyManagedBufferObject *) PyObject_GC_New(_PyManagedBufferObject, &_PyManagedBuffer_Type); if (mbuf == NULL) return NULL; mbuf->flags = 0; mbuf->exports = 0; mbuf->master.obj = NULL; _PyObject_GC_TRACK(mbuf); return mbuf; } static PyObject * _PyManagedBuffer_FromObject(PyObject *base) { _PyManagedBufferObject *mbuf; mbuf = mbuf_alloc(); if (mbuf == NULL) return NULL; if (PyObject_GetBuffer(base, &mbuf->master, PyBUF_FULL_RO) < 0) { mbuf->master.obj = NULL; Py_DECREF(mbuf); return NULL; } return (PyObject *)mbuf; } static void mbuf_release(_PyManagedBufferObject *self) { if (self->flags&_Py_MANAGED_BUFFER_RELEASED) return; /* NOTE: at this point self->exports can still be > 0 if this function is called from mbuf_clear() to break up a reference cycle. */ self->flags |= _Py_MANAGED_BUFFER_RELEASED; /* PyBuffer_Release() decrements master->obj and sets it to NULL. */ _PyObject_GC_UNTRACK(self); PyBuffer_Release(&self->master); } static void mbuf_dealloc(_PyManagedBufferObject *self) { assert(self->exports == 0); mbuf_release(self); if (self->flags&_Py_MANAGED_BUFFER_FREE_FORMAT) PyMem_Free(self->master.format); PyObject_GC_Del(self); } static int mbuf_traverse(_PyManagedBufferObject *self, visitproc visit, void *arg) { Py_VISIT(self->master.obj); return 0; } static int mbuf_clear(_PyManagedBufferObject *self) { assert(self->exports >= 0); mbuf_release(self); return 0; } PyTypeObject _PyManagedBuffer_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "managedbuffer", sizeof(_PyManagedBufferObject), 0, (destructor)mbuf_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)mbuf_traverse, /* tp_traverse */ (inquiry)mbuf_clear /* tp_clear */ }; /****************************************************************************/ /* MemoryView Object */ /****************************************************************************/ /* In the process of breaking reference cycles mbuf_release() can be called before memory_release(). */ #define BASE_INACCESSIBLE(mv) \ (((PyMemoryViewObject *)mv)->flags&_Py_MEMORYVIEW_RELEASED || \ ((PyMemoryViewObject *)mv)->mbuf->flags&_Py_MANAGED_BUFFER_RELEASED) #define CHECK_RELEASED(mv) \ if (BASE_INACCESSIBLE(mv)) { \ PyErr_SetString(PyExc_ValueError, \ "operation forbidden on released memoryview object"); \ return NULL; \ } #define CHECK_RELEASED_INT(mv) \ if (BASE_INACCESSIBLE(mv)) { \ PyErr_SetString(PyExc_ValueError, \ "operation forbidden on released memoryview object"); \ return -1; \ } #define CHECK_LIST_OR_TUPLE(v) \ if (!PyList_Check(v) && !PyTuple_Check(v)) { \ PyErr_SetString(PyExc_TypeError, \ #v " must be a list or a tuple"); \ return NULL; \ } #define VIEW_ADDR(mv) (&((PyMemoryViewObject *)mv)->view) /* Check for the presence of suboffsets in the first dimension. */ #define HAVE_PTR(suboffsets, dim) (suboffsets && suboffsets[dim] >= 0) /* Adjust ptr if suboffsets are present. */ #define ADJUST_PTR(ptr, suboffsets, dim) \ (HAVE_PTR(suboffsets, dim) ? *((char**)ptr) + suboffsets[dim] : ptr) /* Memoryview buffer properties */ #define MV_C_CONTIGUOUS(flags) (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C)) #define MV_F_CONTIGUOUS(flags) \ (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_FORTRAN)) #define MV_ANY_CONTIGUOUS(flags) \ (flags&(_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN)) /* Fast contiguity test. Caller must ensure suboffsets==NULL and ndim==1. */ #define MV_CONTIGUOUS_NDIM1(view) \ ((view)->shape[0] == 1 || (view)->strides[0] == (view)->itemsize) /* getbuffer() requests */ #define REQ_INDIRECT(flags) ((flags&PyBUF_INDIRECT) == PyBUF_INDIRECT) #define REQ_C_CONTIGUOUS(flags) ((flags&PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) #define REQ_F_CONTIGUOUS(flags) ((flags&PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) #define REQ_ANY_CONTIGUOUS(flags) ((flags&PyBUF_ANY_CONTIGUOUS) == PyBUF_ANY_CONTIGUOUS) #define REQ_STRIDES(flags) ((flags&PyBUF_STRIDES) == PyBUF_STRIDES) #define REQ_SHAPE(flags) ((flags&PyBUF_ND) == PyBUF_ND) #define REQ_WRITABLE(flags) (flags&PyBUF_WRITABLE) #define REQ_FORMAT(flags) (flags&PyBUF_FORMAT) PyDoc_STRVAR(memory_doc, "memoryview(object)\n--\n\ \n\ Create a new memoryview object which references the given object."); /**************************************************************************/ /* Copy memoryview buffers */ /**************************************************************************/ /* The functions in this section take a source and a destination buffer with the same logical structure: format, itemsize, ndim and shape are identical, with ndim > 0. NOTE: All buffers are assumed to have PyBUF_FULL information, which is the case for memoryviews! */ /* Assumptions: ndim >= 1. The macro tests for a corner case that should perhaps be explicitly forbidden in the PEP. */ #define HAVE_SUBOFFSETS_IN_LAST_DIM(view) \ (view->suboffsets && view->suboffsets[dest->ndim-1] >= 0) static inline int last_dim_is_contiguous(const Py_buffer *dest, const Py_buffer *src) { assert(dest->ndim > 0 && src->ndim > 0); return (!HAVE_SUBOFFSETS_IN_LAST_DIM(dest) && !HAVE_SUBOFFSETS_IN_LAST_DIM(src) && dest->strides[dest->ndim-1] == dest->itemsize && src->strides[src->ndim-1] == src->itemsize); } /* This is not a general function for determining format equivalence. It is used in copy_single() and copy_buffer() to weed out non-matching formats. Skipping the '@' character is specifically used in slice assignments, where the lvalue is already known to have a single character format. This is a performance hack that could be rewritten (if properly benchmarked). */ static inline int equiv_format(const Py_buffer *dest, const Py_buffer *src) { const char *dfmt, *sfmt; assert(dest->format && src->format); dfmt = dest->format[0] == '@' ? dest->format+1 : dest->format; sfmt = src->format[0] == '@' ? src->format+1 : src->format; if (strcmp(dfmt, sfmt) != 0 || dest->itemsize != src->itemsize) { return 0; } return 1; } /* Two shapes are equivalent if they are either equal or identical up to a zero element at the same position. For example, in NumPy arrays the shapes [1, 0, 5] and [1, 0, 7] are equivalent. */ static inline int equiv_shape(const Py_buffer *dest, const Py_buffer *src) { int i; if (dest->ndim != src->ndim) return 0; for (i = 0; i < dest->ndim; i++) { if (dest->shape[i] != src->shape[i]) return 0; if (dest->shape[i] == 0) break; } return 1; } /* Check that the logical structure of the destination and source buffers is identical. */ static int equiv_structure(const Py_buffer *dest, const Py_buffer *src) { if (!equiv_format(dest, src) || !equiv_shape(dest, src)) { PyErr_SetString(PyExc_ValueError, "memoryview assignment: lvalue and rvalue have different " "structures"); return 0; } return 1; } /* Base case for recursive multi-dimensional copying. Contiguous arrays are copied with very little overhead. Assumptions: ndim == 1, mem == NULL or sizeof(mem) == shape[0] * itemsize. */ static void copy_base(const Py_ssize_t *shape, Py_ssize_t itemsize, char *dptr, const Py_ssize_t *dstrides, const Py_ssize_t *dsuboffsets, char *sptr, const Py_ssize_t *sstrides, const Py_ssize_t *ssuboffsets, char *mem) { if (mem == NULL) { /* contiguous */ Py_ssize_t size = shape[0] * itemsize; if (dptr + size < sptr || sptr + size < dptr) memcpy(dptr, sptr, size); /* no overlapping */ else memmove(dptr, sptr, size); } else { char *p; Py_ssize_t i; for (i=0, p=mem; i < shape[0]; p+=itemsize, sptr+=sstrides[0], i++) { char *xsptr = ADJUST_PTR(sptr, ssuboffsets, 0); memcpy(p, xsptr, itemsize); } for (i=0, p=mem; i < shape[0]; p+=itemsize, dptr+=dstrides[0], i++) { char *xdptr = ADJUST_PTR(dptr, dsuboffsets, 0); memcpy(xdptr, p, itemsize); } } } /* Recursively copy a source buffer to a destination buffer. The two buffers have the same ndim, shape and itemsize. */ static void copy_rec(const Py_ssize_t *shape, Py_ssize_t ndim, Py_ssize_t itemsize, char *dptr, const Py_ssize_t *dstrides, const Py_ssize_t *dsuboffsets, char *sptr, const Py_ssize_t *sstrides, const Py_ssize_t *ssuboffsets, char *mem) { Py_ssize_t i; assert(ndim >= 1); if (ndim == 1) { copy_base(shape, itemsize, dptr, dstrides, dsuboffsets, sptr, sstrides, ssuboffsets, mem); return; } for (i = 0; i < shape[0]; dptr+=dstrides[0], sptr+=sstrides[0], i++) { char *xdptr = ADJUST_PTR(dptr, dsuboffsets, 0); char *xsptr = ADJUST_PTR(sptr, ssuboffsets, 0); copy_rec(shape+1, ndim-1, itemsize, xdptr, dstrides+1, dsuboffsets ? dsuboffsets+1 : NULL, xsptr, sstrides+1, ssuboffsets ? ssuboffsets+1 : NULL, mem); } } /* Faster copying of one-dimensional arrays. */ static int copy_single(Py_buffer *dest, Py_buffer *src) { char *mem = NULL; assert(dest->ndim == 1); if (!equiv_structure(dest, src)) return -1; if (!last_dim_is_contiguous(dest, src)) { mem = PyMem_Malloc(dest->shape[0] * dest->itemsize); if (mem == NULL) { PyErr_NoMemory(); return -1; } } copy_base(dest->shape, dest->itemsize, dest->buf, dest->strides, dest->suboffsets, src->buf, src->strides, src->suboffsets, mem); if (mem) PyMem_Free(mem); return 0; } /* Recursively copy src to dest. Both buffers must have the same basic structure. Copying is atomic, the function never fails with a partial copy. */ static int copy_buffer(Py_buffer *dest, Py_buffer *src) { char *mem = NULL; assert(dest->ndim > 0); if (!equiv_structure(dest, src)) return -1; if (!last_dim_is_contiguous(dest, src)) { mem = PyMem_Malloc(dest->shape[dest->ndim-1] * dest->itemsize); if (mem == NULL) { PyErr_NoMemory(); return -1; } } copy_rec(dest->shape, dest->ndim, dest->itemsize, dest->buf, dest->strides, dest->suboffsets, src->buf, src->strides, src->suboffsets, mem); if (mem) PyMem_Free(mem); return 0; } /* Initialize strides for a C-contiguous array. */ static inline void init_strides_from_shape(Py_buffer *view) { Py_ssize_t i; assert(view->ndim > 0); view->strides[view->ndim-1] = view->itemsize; for (i = view->ndim-2; i >= 0; i--) view->strides[i] = view->strides[i+1] * view->shape[i+1]; } /* Initialize strides for a Fortran-contiguous array. */ static inline void init_fortran_strides_from_shape(Py_buffer *view) { Py_ssize_t i; assert(view->ndim > 0); view->strides[0] = view->itemsize; for (i = 1; i < view->ndim; i++) view->strides[i] = view->strides[i-1] * view->shape[i-1]; } /* Copy src to a contiguous representation. order is one of 'C', 'F' (Fortran) or 'A' (Any). Assumptions: src has PyBUF_FULL information, src->ndim >= 1, len(mem) == src->len. */ static int buffer_to_contiguous(char *mem, Py_buffer *src, char order) { Py_buffer dest; Py_ssize_t *strides; int ret; assert(src->ndim >= 1); assert(src->shape != NULL); assert(src->strides != NULL); strides = PyMem_Malloc(src->ndim * (sizeof *src->strides)); if (strides == NULL) { PyErr_NoMemory(); return -1; } /* initialize dest */ dest = *src; dest.buf = mem; /* shape is constant and shared: the logical representation of the array is unaltered. */ /* The physical representation determined by strides (and possibly suboffsets) may change. */ dest.strides = strides; if (order == 'C' || order == 'A') { init_strides_from_shape(&dest); } else { init_fortran_strides_from_shape(&dest); } dest.suboffsets = NULL; ret = copy_buffer(&dest, src); PyMem_Free(strides); return ret; } /****************************************************************************/ /* Constructors */ /****************************************************************************/ /* Initialize values that are shared with the managed buffer. */ static inline void init_shared_values(Py_buffer *dest, const Py_buffer *src) { dest->obj = src->obj; dest->buf = src->buf; dest->len = src->len; dest->itemsize = src->itemsize; dest->readonly = src->readonly; dest->format = src->format ? src->format : "B"; dest->internal = src->internal; } /* Copy shape and strides. Reconstruct missing values. */ static void init_shape_strides(Py_buffer *dest, const Py_buffer *src) { Py_ssize_t i; if (src->ndim == 0) { dest->shape = NULL; dest->strides = NULL; return; } if (src->ndim == 1) { dest->shape[0] = src->shape ? src->shape[0] : src->len / src->itemsize; dest->strides[0] = src->strides ? src->strides[0] : src->itemsize; return; } for (i = 0; i < src->ndim; i++) dest->shape[i] = src->shape[i]; if (src->strides) { for (i = 0; i < src->ndim; i++) dest->strides[i] = src->strides[i]; } else { init_strides_from_shape(dest); } } static inline void init_suboffsets(Py_buffer *dest, const Py_buffer *src) { Py_ssize_t i; if (src->suboffsets == NULL) { dest->suboffsets = NULL; return; } for (i = 0; i < src->ndim; i++) dest->suboffsets[i] = src->suboffsets[i]; } /* len = product(shape) * itemsize */ static inline void init_len(Py_buffer *view) { Py_ssize_t i, len; len = 1; for (i = 0; i < view->ndim; i++) len *= view->shape[i]; len *= view->itemsize; view->len = len; } /* Initialize memoryview buffer properties. */ static void init_flags(PyMemoryViewObject *mv) { const Py_buffer *view = &mv->view; int flags = 0; switch (view->ndim) { case 0: flags |= (_Py_MEMORYVIEW_SCALAR|_Py_MEMORYVIEW_C| _Py_MEMORYVIEW_FORTRAN); break; case 1: if (MV_CONTIGUOUS_NDIM1(view)) flags |= (_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN); break; default: if (PyBuffer_IsContiguous(view, 'C')) flags |= _Py_MEMORYVIEW_C; if (PyBuffer_IsContiguous(view, 'F')) flags |= _Py_MEMORYVIEW_FORTRAN; break; } if (view->suboffsets) { flags |= _Py_MEMORYVIEW_PIL; flags &= ~(_Py_MEMORYVIEW_C|_Py_MEMORYVIEW_FORTRAN); } mv->flags = flags; } /* Allocate a new memoryview and perform basic initialization. New memoryviews are exclusively created through the mbuf_add functions. */ static inline PyMemoryViewObject * memory_alloc(int ndim) { PyMemoryViewObject *mv; mv = (PyMemoryViewObject *) PyObject_GC_NewVar(PyMemoryViewObject, &PyMemoryView_Type, 3*ndim); if (mv == NULL) return NULL; mv->mbuf = NULL; mv->hash = -1; mv->flags = 0; mv->exports = 0; mv->view.ndim = ndim; mv->view.shape = mv->ob_array; mv->view.strides = mv->ob_array + ndim; mv->view.suboffsets = mv->ob_array + 2 * ndim; mv->weakreflist = NULL; _PyObject_GC_TRACK(mv); return mv; } /* Return a new memoryview that is registered with mbuf. If src is NULL, use mbuf->master as the underlying buffer. Otherwise, use src. The new memoryview has full buffer information: shape and strides are always present, suboffsets as needed. Arrays are copied to the memoryview's ob_array field. */ static PyObject * mbuf_add_view(_PyManagedBufferObject *mbuf, const Py_buffer *src) { PyMemoryViewObject *mv; Py_buffer *dest; if (src == NULL) src = &mbuf->master; if (src->ndim > PyBUF_MAX_NDIM) { PyErr_SetString(PyExc_ValueError, "memoryview: number of dimensions must not exceed " Py_STRINGIFY(PyBUF_MAX_NDIM)); return NULL; } mv = memory_alloc(src->ndim); if (mv == NULL) return NULL; dest = &mv->view; init_shared_values(dest, src); init_shape_strides(dest, src); init_suboffsets(dest, src); init_flags(mv); mv->mbuf = mbuf; Py_INCREF(mbuf); mbuf->exports++; return (PyObject *)mv; } /* Register an incomplete view: shape, strides, suboffsets and flags still need to be initialized. Use 'ndim' instead of src->ndim to determine the size of the memoryview's ob_array. Assumption: ndim <= PyBUF_MAX_NDIM. */ static PyObject * mbuf_add_incomplete_view(_PyManagedBufferObject *mbuf, const Py_buffer *src, int ndim) { PyMemoryViewObject *mv; Py_buffer *dest; if (src == NULL) src = &mbuf->master; assert(ndim <= PyBUF_MAX_NDIM); mv = memory_alloc(ndim); if (mv == NULL) return NULL; dest = &mv->view; init_shared_values(dest, src); mv->mbuf = mbuf; Py_INCREF(mbuf); mbuf->exports++; return (PyObject *)mv; } /* Expose a raw memory area as a view of contiguous bytes. flags can be PyBUF_READ or PyBUF_WRITE. view->format is set to "B" (unsigned bytes). The memoryview has complete buffer information. */ PyObject * PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags) { _PyManagedBufferObject *mbuf; PyObject *mv; int readonly; assert(mem != NULL); assert(flags == PyBUF_READ || flags == PyBUF_WRITE); mbuf = mbuf_alloc(); if (mbuf == NULL) return NULL; readonly = (flags == PyBUF_WRITE) ? 0 : 1; (void)PyBuffer_FillInfo(&mbuf->master, NULL, mem, size, readonly, PyBUF_FULL_RO); mv = mbuf_add_view(mbuf, NULL); Py_DECREF(mbuf); return mv; } /* Create a memoryview from a given Py_buffer. For simple byte views, PyMemoryView_FromMemory() should be used instead. This function is the only entry point that can create a master buffer without full information. Because of this fact init_shape_strides() must be able to reconstruct missing values. */ PyObject * PyMemoryView_FromBuffer(Py_buffer *info) { _PyManagedBufferObject *mbuf; PyObject *mv; if (info->buf == NULL) { PyErr_SetString(PyExc_ValueError, "PyMemoryView_FromBuffer(): info->buf must not be NULL"); return NULL; } mbuf = mbuf_alloc(); if (mbuf == NULL) return NULL; /* info->obj is either NULL or a borrowed reference. This reference should not be decremented in PyBuffer_Release(). */ mbuf->master = *info; mbuf->master.obj = NULL; mv = mbuf_add_view(mbuf, NULL); Py_DECREF(mbuf); return mv; } /* Create a memoryview from an object that implements the buffer protocol. If the object is a memoryview, the new memoryview must be registered with the same managed buffer. Otherwise, a new managed buffer is created. */ PyObject * PyMemoryView_FromObject(PyObject *v) { _PyManagedBufferObject *mbuf; if (PyMemoryView_Check(v)) { PyMemoryViewObject *mv = (PyMemoryViewObject *)v; CHECK_RELEASED(mv); return mbuf_add_view(mv->mbuf, &mv->view); } else if (PyObject_CheckBuffer(v)) { PyObject *ret; mbuf = (_PyManagedBufferObject *)_PyManagedBuffer_FromObject(v); if (mbuf == NULL) return NULL; ret = mbuf_add_view(mbuf, NULL); Py_DECREF(mbuf); return ret; } PyErr_Format(PyExc_TypeError, "memoryview: a bytes-like object is required, not '%.200s'", Py_TYPE(v)->tp_name); return NULL; } /* Copy the format string from a base object that might vanish. */ static int mbuf_copy_format(_PyManagedBufferObject *mbuf, const char *fmt) { if (fmt != NULL) { char *cp = PyMem_Malloc(strlen(fmt)+1); if (cp == NULL) { PyErr_NoMemory(); return -1; } mbuf->master.format = strcpy(cp, fmt); mbuf->flags |= _Py_MANAGED_BUFFER_FREE_FORMAT; } return 0; } /* Return a memoryview that is based on a contiguous copy of src. Assumptions: src has PyBUF_FULL_RO information, src->ndim > 0. Ownership rules: 1) As usual, the returned memoryview has a private copy of src->shape, src->strides and src->suboffsets. 2) src->format is copied to the master buffer and released in mbuf_dealloc(). The releasebufferproc of the bytes object is NULL, so it does not matter that mbuf_release() passes the altered format pointer to PyBuffer_Release(). */ static PyObject * memory_from_contiguous_copy(Py_buffer *src, char order) { _PyManagedBufferObject *mbuf; PyMemoryViewObject *mv; PyObject *bytes; Py_buffer *dest; int i; assert(src->ndim > 0); assert(src->shape != NULL); bytes = PyBytes_FromStringAndSize(NULL, src->len); if (bytes == NULL) return NULL; mbuf = (_PyManagedBufferObject *)_PyManagedBuffer_FromObject(bytes); Py_DECREF(bytes); if (mbuf == NULL) return NULL; if (mbuf_copy_format(mbuf, src->format) < 0) { Py_DECREF(mbuf); return NULL; } mv = (PyMemoryViewObject *)mbuf_add_incomplete_view(mbuf, NULL, src->ndim); Py_DECREF(mbuf); if (mv == NULL) return NULL; dest = &mv->view; /* shared values are initialized correctly except for itemsize */ dest->itemsize = src->itemsize; /* shape and strides */ for (i = 0; i < src->ndim; i++) { dest->shape[i] = src->shape[i]; } if (order == 'C' || order == 'A') { init_strides_from_shape(dest); } else { init_fortran_strides_from_shape(dest); } /* suboffsets */ dest->suboffsets = NULL; /* flags */ init_flags(mv); if (copy_buffer(dest, src) < 0) { Py_DECREF(mv); return NULL; } return (PyObject *)mv; } /* Return a new memoryview object based on a contiguous exporter with buffertype={PyBUF_READ, PyBUF_WRITE} and order={'C', 'F'ortran, or 'A'ny}. The logical structure of the input and output buffers is the same (i.e. tolist(input) == tolist(output)), but the physical layout in memory can be explicitly chosen. As usual, if buffertype=PyBUF_WRITE, the exporter's buffer must be writable, otherwise it may be writable or read-only. If the exporter is already contiguous with the desired target order, the memoryview will be directly based on the exporter. Otherwise, if the buffertype is PyBUF_READ, the memoryview will be based on a new bytes object. If order={'C', 'A'ny}, use 'C' order, 'F'ortran order otherwise. */ PyObject * PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order) { PyMemoryViewObject *mv; PyObject *ret; Py_buffer *view; assert(buffertype == PyBUF_READ || buffertype == PyBUF_WRITE); assert(order == 'C' || order == 'F' || order == 'A'); mv = (PyMemoryViewObject *)PyMemoryView_FromObject(obj); if (mv == NULL) return NULL; view = &mv->view; if (buffertype == PyBUF_WRITE && view->readonly) { PyErr_SetString(PyExc_BufferError, "underlying buffer is not writable"); Py_DECREF(mv); return NULL; } if (PyBuffer_IsContiguous(view, order)) return (PyObject *)mv; if (buffertype == PyBUF_WRITE) { PyErr_SetString(PyExc_BufferError, "writable contiguous buffer requested " "for a non-contiguous object."); Py_DECREF(mv); return NULL; } ret = memory_from_contiguous_copy(view, order); Py_DECREF(mv); return ret; } static PyObject * memory_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) { PyObject *obj; static char *kwlist[] = {"object", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:memoryview", kwlist, &obj)) { return NULL; } return PyMemoryView_FromObject(obj); } /****************************************************************************/ /* Previously in abstract.c */ /****************************************************************************/ typedef struct { Py_buffer view; Py_ssize_t array[1]; } Py_buffer_full; int PyBuffer_ToContiguous(void *buf, Py_buffer *src, Py_ssize_t len, char order) { Py_buffer_full *fb = NULL; int ret; assert(order == 'C' || order == 'F' || order == 'A'); if (len != src->len) { PyErr_SetString(PyExc_ValueError, "PyBuffer_ToContiguous: len != view->len"); return -1; } if (PyBuffer_IsContiguous(src, order)) { memcpy((char *)buf, src->buf, len); return 0; } /* buffer_to_contiguous() assumes PyBUF_FULL */ fb = PyMem_Malloc(sizeof *fb + 3 * src->ndim * (sizeof *fb->array)); if (fb == NULL) { PyErr_NoMemory(); return -1; } fb->view.ndim = src->ndim; fb->view.shape = fb->array; fb->view.strides = fb->array + src->ndim; fb->view.suboffsets = fb->array + 2 * src->ndim; init_shared_values(&fb->view, src); init_shape_strides(&fb->view, src); init_suboffsets(&fb->view, src); src = &fb->view; ret = buffer_to_contiguous(buf, src, order); PyMem_Free(fb); return ret; } /****************************************************************************/ /* Release/GC management */ /****************************************************************************/ /* Inform the managed buffer that this particular memoryview will not access the underlying buffer again. If no other memoryviews are registered with the managed buffer, the underlying buffer is released instantly and marked as inaccessible for both the memoryview and the managed buffer. This function fails if the memoryview itself has exported buffers. */ static int _memory_release(PyMemoryViewObject *self) { if (self->flags & _Py_MEMORYVIEW_RELEASED) return 0; if (self->exports == 0) { self->flags |= _Py_MEMORYVIEW_RELEASED; assert(self->mbuf->exports > 0); if (--self->mbuf->exports == 0) mbuf_release(self->mbuf); return 0; } if (self->exports > 0) { PyErr_Format(PyExc_BufferError, "memoryview has %zd exported buffer%s", self->exports, self->exports==1 ? "" : "s"); return -1; } Py_FatalError("_memory_release(): negative export count"); return -1; } static PyObject * memory_release(PyMemoryViewObject *self, PyObject *noargs) { if (_memory_release(self) < 0) return NULL; Py_RETURN_NONE; } static void memory_dealloc(PyMemoryViewObject *self) { assert(self->exports == 0); _PyObject_GC_UNTRACK(self); (void)_memory_release(self); Py_CLEAR(self->mbuf); if (self->weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *) self); PyObject_GC_Del(self); } static int memory_traverse(PyMemoryViewObject *self, visitproc visit, void *arg) { Py_VISIT(self->mbuf); return 0; } static int memory_clear(PyMemoryViewObject *self) { (void)_memory_release(self); Py_CLEAR(self->mbuf); return 0; } static PyObject * memory_enter(PyObject *self, PyObject *args) { CHECK_RELEASED(self); Py_INCREF(self); return self; } static PyObject * memory_exit(PyObject *self, PyObject *args) { return memory_release((PyMemoryViewObject *)self, NULL); } /****************************************************************************/ /* Casting format and shape */ /****************************************************************************/ #define IS_BYTE_FORMAT(f) (f == 'b' || f == 'B' || f == 'c') static inline Py_ssize_t get_native_fmtchar(char *result, const char *fmt) { Py_ssize_t size = -1; if (fmt[0] == '@') fmt++; switch (fmt[0]) { case 'c': case 'b': case 'B': size = sizeof(char); break; case 'h': case 'H': size = sizeof(short); break; case 'i': case 'I': size = sizeof(int); break; case 'l': case 'L': size = sizeof(long); break; case 'q': case 'Q': size = sizeof(long long); break; case 'n': case 'N': size = sizeof(Py_ssize_t); break; case 'f': size = sizeof(float); break; case 'd': size = sizeof(double); break; case '?': size = sizeof(_Bool); break; case 'P': size = sizeof(void *); break; } if (size > 0 && fmt[1] == '\0') { *result = fmt[0]; return size; } return -1; } static inline const char * get_native_fmtstr(const char *fmt) { int at = 0; if (fmt[0] == '@') { at = 1; fmt++; } if (fmt[0] == '\0' || fmt[1] != '\0') { return NULL; } #define RETURN(s) do { return at ? "@" s : s; } while (0) switch (fmt[0]) { case 'c': RETURN("c"); case 'b': RETURN("b"); case 'B': RETURN("B"); case 'h': RETURN("h"); case 'H': RETURN("H"); case 'i': RETURN("i"); case 'I': RETURN("I"); case 'l': RETURN("l"); case 'L': RETURN("L"); case 'q': RETURN("q"); case 'Q': RETURN("Q"); case 'n': RETURN("n"); case 'N': RETURN("N"); case 'f': RETURN("f"); case 'd': RETURN("d"); case '?': RETURN("?"); case 'P': RETURN("P"); } return NULL; } /* Cast a memoryview's data type to 'format'. The input array must be C-contiguous. At least one of input-format, output-format must have byte size. The output array is 1-D, with the same byte length as the input array. Thus, view->len must be a multiple of the new itemsize. */ static int cast_to_1D(PyMemoryViewObject *mv, PyObject *format) { Py_buffer *view = &mv->view; PyObject *asciifmt; char srcchar, destchar; Py_ssize_t itemsize; int ret = -1; assert(view->ndim >= 1); assert(Py_SIZE(mv) == 3*view->ndim); assert(view->shape == mv->ob_array); assert(view->strides == mv->ob_array + view->ndim); assert(view->suboffsets == mv->ob_array + 2*view->ndim); asciifmt = PyUnicode_AsASCIIString(format); if (asciifmt == NULL) return ret; itemsize = get_native_fmtchar(&destchar, PyBytes_AS_STRING(asciifmt)); if (itemsize < 0) { PyErr_SetString(PyExc_ValueError, "memoryview: destination format must be a native single " "character format prefixed with an optional '@'"); goto out; } if ((get_native_fmtchar(&srcchar, view->format) < 0 || !IS_BYTE_FORMAT(srcchar)) && !IS_BYTE_FORMAT(destchar)) { PyErr_SetString(PyExc_TypeError, "memoryview: cannot cast between two non-byte formats"); goto out; } if (view->len % itemsize) { PyErr_SetString(PyExc_TypeError, "memoryview: length is not a multiple of itemsize"); goto out; } view->format = (char *)get_native_fmtstr(PyBytes_AS_STRING(asciifmt)); if (view->format == NULL) { /* NOT_REACHED: get_native_fmtchar() already validates the format. */ PyErr_SetString(PyExc_RuntimeError, "memoryview: internal error"); goto out; } view->itemsize = itemsize; view->ndim = 1; view->shape[0] = view->len / view->itemsize; view->strides[0] = view->itemsize; view->suboffsets = NULL; init_flags(mv); ret = 0; out: Py_DECREF(asciifmt); return ret; } /* The memoryview must have space for 3*len(seq) elements. */ static Py_ssize_t copy_shape(Py_ssize_t *shape, const PyObject *seq, Py_ssize_t ndim, Py_ssize_t itemsize) { Py_ssize_t x, i; Py_ssize_t len = itemsize; for (i = 0; i < ndim; i++) { PyObject *tmp = PySequence_Fast_GET_ITEM(seq, i); if (!PyLong_Check(tmp)) { PyErr_SetString(PyExc_TypeError, "memoryview.cast(): elements of shape must be integers"); return -1; } x = PyLong_AsSsize_t(tmp); if (x == -1 && PyErr_Occurred()) { return -1; } if (x <= 0) { /* In general elements of shape may be 0, but not for casting. */ PyErr_Format(PyExc_ValueError, "memoryview.cast(): elements of shape must be integers > 0"); return -1; } if (x > PY_SSIZE_T_MAX / len) { PyErr_Format(PyExc_ValueError, "memoryview.cast(): product(shape) > SSIZE_MAX"); return -1; } len *= x; shape[i] = x; } return len; } /* Cast a 1-D array to a new shape. The result array will be C-contiguous. If the result array does not have exactly the same byte length as the input array, raise ValueError. */ static int cast_to_ND(PyMemoryViewObject *mv, const PyObject *shape, int ndim) { Py_buffer *view = &mv->view; Py_ssize_t len; assert(view->ndim == 1); /* ndim from cast_to_1D() */ assert(Py_SIZE(mv) == 3*(ndim==0?1:ndim)); /* ndim of result array */ assert(view->shape == mv->ob_array); assert(view->strides == mv->ob_array + (ndim==0?1:ndim)); assert(view->suboffsets == NULL); view->ndim = ndim; if (view->ndim == 0) { view->shape = NULL; view->strides = NULL; len = view->itemsize; } else { len = copy_shape(view->shape, shape, ndim, view->itemsize); if (len < 0) return -1; init_strides_from_shape(view); } if (view->len != len) { PyErr_SetString(PyExc_TypeError, "memoryview: product(shape) * itemsize != buffer size"); return -1; } init_flags(mv); return 0; } static int zero_in_shape(PyMemoryViewObject *mv) { Py_buffer *view = &mv->view; Py_ssize_t i; for (i = 0; i < view->ndim; i++) if (view->shape[i] == 0) return 1; return 0; } /* Cast a copy of 'self' to a different view. The input view must be C-contiguous. The function always casts the input view to a 1-D output according to 'format'. At least one of input-format, output-format must have byte size. If 'shape' is given, the 1-D view from the previous step will be cast to a C-contiguous view with new shape and strides. All casts must result in views that will have the exact byte size of the original input. Otherwise, an error is raised. */ static PyObject * memory_cast(PyMemoryViewObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"format", "shape", NULL}; PyMemoryViewObject *mv = NULL; PyObject *shape = NULL; PyObject *format; Py_ssize_t ndim = 1; CHECK_RELEASED(self); if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist, &format, &shape)) { return NULL; } if (!PyUnicode_Check(format)) { PyErr_SetString(PyExc_TypeError, "memoryview: format argument must be a string"); return NULL; } if (!MV_C_CONTIGUOUS(self->flags)) { PyErr_SetString(PyExc_TypeError, "memoryview: casts are restricted to C-contiguous views"); return NULL; } if ((shape || self->view.ndim != 1) && zero_in_shape(self)) { PyErr_SetString(PyExc_TypeError, "memoryview: cannot cast view with zeros in shape or strides"); return NULL; } if (shape) { CHECK_LIST_OR_TUPLE(shape) ndim = PySequence_Fast_GET_SIZE(shape); if (ndim > PyBUF_MAX_NDIM) { PyErr_SetString(PyExc_ValueError, "memoryview: number of dimensions must not exceed " Py_STRINGIFY(PyBUF_MAX_NDIM)); return NULL; } if (self->view.ndim != 1 && ndim != 1) { PyErr_SetString(PyExc_TypeError, "memoryview: cast must be 1D -> ND or ND -> 1D"); return NULL; } } mv = (PyMemoryViewObject *) mbuf_add_incomplete_view(self->mbuf, &self->view, ndim==0 ? 1 : (int)ndim); if (mv == NULL) return NULL; if (cast_to_1D(mv, format) < 0) goto error; if (shape && cast_to_ND(mv, shape, (int)ndim) < 0) goto error; return (PyObject *)mv; error: Py_DECREF(mv); return NULL; } /**************************************************************************/ /* getbuffer */ /**************************************************************************/ static int memory_getbuf(PyMemoryViewObject *self, Py_buffer *view, int flags) { Py_buffer *base = &self->view; int baseflags = self->flags; CHECK_RELEASED_INT(self); /* start with complete information */ *view = *base; view->obj = NULL; if (REQ_WRITABLE(flags) && base->readonly) { PyErr_SetString(PyExc_BufferError, "memoryview: underlying buffer is not writable"); return -1; } if (!REQ_FORMAT(flags)) { /* NULL indicates that the buffer's data type has been cast to 'B'. view->itemsize is the _previous_ itemsize. If shape is present, the equality product(shape) * itemsize = len still holds at this point. The equality calcsize(format) = itemsize does _not_ hold from here on! */ view->format = NULL; } if (REQ_C_CONTIGUOUS(flags) && !MV_C_CONTIGUOUS(baseflags)) { PyErr_SetString(PyExc_BufferError, "memoryview: underlying buffer is not C-contiguous"); return -1; } if (REQ_F_CONTIGUOUS(flags) && !MV_F_CONTIGUOUS(baseflags)) { PyErr_SetString(PyExc_BufferError, "memoryview: underlying buffer is not Fortran contiguous"); return -1; } if (REQ_ANY_CONTIGUOUS(flags) && !MV_ANY_CONTIGUOUS(baseflags)) { PyErr_SetString(PyExc_BufferError, "memoryview: underlying buffer is not contiguous"); return -1; } if (!REQ_INDIRECT(flags) && (baseflags & _Py_MEMORYVIEW_PIL)) { PyErr_SetString(PyExc_BufferError, "memoryview: underlying buffer requires suboffsets"); return -1; } if (!REQ_STRIDES(flags)) { if (!MV_C_CONTIGUOUS(baseflags)) { PyErr_SetString(PyExc_BufferError, "memoryview: underlying buffer is not C-contiguous"); return -1; } view->strides = NULL; } if (!REQ_SHAPE(flags)) { /* PyBUF_SIMPLE or PyBUF_WRITABLE: at this point buf is C-contiguous, so base->buf = ndbuf->data. */ if (view->format != NULL) { /* PyBUF_SIMPLE|PyBUF_FORMAT and PyBUF_WRITABLE|PyBUF_FORMAT do not make sense. */ PyErr_Format(PyExc_BufferError, "memoryview: cannot cast to unsigned bytes if the format flag " "is present"); return -1; } /* product(shape) * itemsize = len and calcsize(format) = itemsize do _not_ hold from here on! */ view->ndim = 1; view->shape = NULL; } view->obj = (PyObject *)self; Py_INCREF(view->obj); self->exports++; return 0; } static void memory_releasebuf(PyMemoryViewObject *self, Py_buffer *view) { self->exports--; return; /* PyBuffer_Release() decrements view->obj after this function returns. */ } /* Buffer methods */ static PyBufferProcs memory_as_buffer = { (getbufferproc)memory_getbuf, /* bf_getbuffer */ (releasebufferproc)memory_releasebuf, /* bf_releasebuffer */ }; /****************************************************************************/ /* Optimized pack/unpack for all native format specifiers */ /****************************************************************************/ /* Fix exceptions: 1) Include format string in the error message. 2) OverflowError -> ValueError. 3) The error message from PyNumber_Index() is not ideal. */ static int type_error_int(const char *fmt) { PyErr_Format(PyExc_TypeError, "memoryview: invalid type for format '%s'", fmt); return -1; } static int value_error_int(const char *fmt) { PyErr_Format(PyExc_ValueError, "memoryview: invalid value for format '%s'", fmt); return -1; } static int fix_error_int(const char *fmt) { assert(PyErr_Occurred()); if (PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); return type_error_int(fmt); } else if (PyErr_ExceptionMatches(PyExc_OverflowError) || PyErr_ExceptionMatches(PyExc_ValueError)) { PyErr_Clear(); return value_error_int(fmt); } return -1; } /* Accept integer objects or objects with an __index__() method. */ static long pylong_as_ld(PyObject *item) { PyObject *tmp; long ld; tmp = PyNumber_Index(item); if (tmp == NULL) return -1; ld = PyLong_AsLong(tmp); Py_DECREF(tmp); return ld; } static unsigned long pylong_as_lu(PyObject *item) { PyObject *tmp; unsigned long lu; tmp = PyNumber_Index(item); if (tmp == NULL) return (unsigned long)-1; lu = PyLong_AsUnsignedLong(tmp); Py_DECREF(tmp); return lu; } static long long pylong_as_lld(PyObject *item) { PyObject *tmp; long long lld; tmp = PyNumber_Index(item); if (tmp == NULL) return -1; lld = PyLong_AsLongLong(tmp); Py_DECREF(tmp); return lld; } static unsigned long long pylong_as_llu(PyObject *item) { PyObject *tmp; unsigned long long llu; tmp = PyNumber_Index(item); if (tmp == NULL) return (unsigned long long)-1; llu = PyLong_AsUnsignedLongLong(tmp); Py_DECREF(tmp); return llu; } static Py_ssize_t pylong_as_zd(PyObject *item) { PyObject *tmp; Py_ssize_t zd; tmp = PyNumber_Index(item); if (tmp == NULL) return -1; zd = PyLong_AsSsize_t(tmp); Py_DECREF(tmp); return zd; } static size_t pylong_as_zu(PyObject *item) { PyObject *tmp; size_t zu; tmp = PyNumber_Index(item); if (tmp == NULL) return (size_t)-1; zu = PyLong_AsSize_t(tmp); Py_DECREF(tmp); return zu; } /* Timings with the ndarray from _testbuffer.c indicate that using the struct module is around 15x slower than the two functions below. */ #define UNPACK_SINGLE(dest, ptr, type) \ do { \ type x; \ memcpy((char *)&x, ptr, sizeof x); \ dest = x; \ } while (0) /* Unpack a single item. 'fmt' can be any native format character in struct module syntax. This function is very sensitive to small changes. With this layout gcc automatically generates a fast jump table. */ static inline PyObject * unpack_single(const char *ptr, const char *fmt) { unsigned long long llu; unsigned long lu; size_t zu; long long lld; long ld; Py_ssize_t zd; double d; unsigned char uc; void *p; switch (fmt[0]) { /* signed integers and fast path for 'B' */ case 'B': uc = *((unsigned char *)ptr); goto convert_uc; case 'b': ld = *((signed char *)ptr); goto convert_ld; case 'h': UNPACK_SINGLE(ld, ptr, short); goto convert_ld; case 'i': UNPACK_SINGLE(ld, ptr, int); goto convert_ld; case 'l': UNPACK_SINGLE(ld, ptr, long); goto convert_ld; /* boolean */ case '?': UNPACK_SINGLE(ld, ptr, _Bool); goto convert_bool; /* unsigned integers */ case 'H': UNPACK_SINGLE(lu, ptr, unsigned short); goto convert_lu; case 'I': UNPACK_SINGLE(lu, ptr, unsigned int); goto convert_lu; case 'L': UNPACK_SINGLE(lu, ptr, unsigned long); goto convert_lu; /* native 64-bit */ case 'q': UNPACK_SINGLE(lld, ptr, long long); goto convert_lld; case 'Q': UNPACK_SINGLE(llu, ptr, unsigned long long); goto convert_llu; /* ssize_t and size_t */ case 'n': UNPACK_SINGLE(zd, ptr, Py_ssize_t); goto convert_zd; case 'N': UNPACK_SINGLE(zu, ptr, size_t); goto convert_zu; /* floats */ case 'f': UNPACK_SINGLE(d, ptr, float); goto convert_double; case 'd': UNPACK_SINGLE(d, ptr, double); goto convert_double; /* bytes object */ case 'c': goto convert_bytes; /* pointer */ case 'P': UNPACK_SINGLE(p, ptr, void *); goto convert_pointer; /* default */ default: goto err_format; } convert_uc: /* PyLong_FromUnsignedLong() is slower */ return PyLong_FromLong(uc); convert_ld: return PyLong_FromLong(ld); convert_lu: return PyLong_FromUnsignedLong(lu); convert_lld: return PyLong_FromLongLong(lld); convert_llu: return PyLong_FromUnsignedLongLong(llu); convert_zd: return PyLong_FromSsize_t(zd); convert_zu: return PyLong_FromSize_t(zu); convert_double: return PyFloat_FromDouble(d); convert_bool: return PyBool_FromLong(ld); convert_bytes: return PyBytes_FromStringAndSize(ptr, 1); convert_pointer: return PyLong_FromVoidPtr(p); err_format: PyErr_Format(PyExc_NotImplementedError, "memoryview: format %s not supported", fmt); return NULL; } #define PACK_SINGLE(ptr, src, type) \ do { \ type x; \ x = (type)src; \ memcpy(ptr, (char *)&x, sizeof x); \ } while (0) /* Pack a single item. 'fmt' can be any native format character in struct module syntax. */ static int pack_single(char *ptr, PyObject *item, const char *fmt) { unsigned long long llu; unsigned long lu; size_t zu; long long lld; long ld; Py_ssize_t zd; double d; void *p; switch (fmt[0]) { /* signed integers */ case 'b': case 'h': case 'i': case 'l': ld = pylong_as_ld(item); if (ld == -1 && PyErr_Occurred()) goto err_occurred; switch (fmt[0]) { case 'b': if (ld < SCHAR_MIN || ld > SCHAR_MAX) goto err_range; *((signed char *)ptr) = (signed char)ld; break; case 'h': if (ld < SHRT_MIN || ld > SHRT_MAX) goto err_range; PACK_SINGLE(ptr, ld, short); break; case 'i': if (ld < INT_MIN || ld > INT_MAX) goto err_range; PACK_SINGLE(ptr, ld, int); break; default: /* 'l' */ PACK_SINGLE(ptr, ld, long); break; } break; /* unsigned integers */ case 'B': case 'H': case 'I': case 'L': lu = pylong_as_lu(item); if (lu == (unsigned long)-1 && PyErr_Occurred()) goto err_occurred; switch (fmt[0]) { case 'B': if (lu > UCHAR_MAX) goto err_range; *((unsigned char *)ptr) = (unsigned char)lu; break; case 'H': if (lu > USHRT_MAX) goto err_range; PACK_SINGLE(ptr, lu, unsigned short); break; case 'I': if (lu > UINT_MAX) goto err_range; PACK_SINGLE(ptr, lu, unsigned int); break; default: /* 'L' */ PACK_SINGLE(ptr, lu, unsigned long); break; } break; /* native 64-bit */ case 'q': lld = pylong_as_lld(item); if (lld == -1 && PyErr_Occurred()) goto err_occurred; PACK_SINGLE(ptr, lld, long long); break; case 'Q': llu = pylong_as_llu(item); if (llu == (unsigned long long)-1 && PyErr_Occurred()) goto err_occurred; PACK_SINGLE(ptr, llu, unsigned long long); break; /* ssize_t and size_t */ case 'n': zd = pylong_as_zd(item); if (zd == -1 && PyErr_Occurred()) goto err_occurred; PACK_SINGLE(ptr, zd, Py_ssize_t); break; case 'N': zu = pylong_as_zu(item); if (zu == (size_t)-1 && PyErr_Occurred()) goto err_occurred; PACK_SINGLE(ptr, zu, size_t); break; /* floats */ case 'f': case 'd': d = PyFloat_AsDouble(item); if (d == -1.0 && PyErr_Occurred()) goto err_occurred; if (fmt[0] == 'f') { PACK_SINGLE(ptr, d, float); } else { PACK_SINGLE(ptr, d, double); } break; /* bool */ case '?': ld = PyObject_IsTrue(item); if (ld < 0) return -1; /* preserve original error */ PACK_SINGLE(ptr, ld, _Bool); break; /* bytes object */ case 'c': if (!PyBytes_Check(item)) return type_error_int(fmt); if (PyBytes_GET_SIZE(item) != 1) return value_error_int(fmt); *ptr = PyBytes_AS_STRING(item)[0]; break; /* pointer */ case 'P': p = PyLong_AsVoidPtr(item); if (p == NULL && PyErr_Occurred()) goto err_occurred; PACK_SINGLE(ptr, p, void *); break; /* default */ default: goto err_format; } return 0; err_occurred: return fix_error_int(fmt); err_range: return value_error_int(fmt); err_format: PyErr_Format(PyExc_NotImplementedError, "memoryview: format %s not supported", fmt); return -1; } /****************************************************************************/ /* unpack using the struct module */ /****************************************************************************/ /* For reasonable performance it is necessary to cache all objects required for unpacking. An unpacker can handle the format passed to unpack_from(). Invariant: All pointer fields of the struct should either be NULL or valid pointers. */ struct unpacker { PyObject *unpack_from; /* Struct.unpack_from(format) */ PyObject *mview; /* cached memoryview */ char *item; /* buffer for mview */ Py_ssize_t itemsize; /* len(item) */ }; static struct unpacker * unpacker_new(void) { struct unpacker *x = PyMem_Malloc(sizeof *x); if (x == NULL) { PyErr_NoMemory(); return NULL; } x->unpack_from = NULL; x->mview = NULL; x->item = NULL; x->itemsize = 0; return x; } static void unpacker_free(struct unpacker *x) { if (x) { Py_XDECREF(x->unpack_from); Py_XDECREF(x->mview); PyMem_Free(x->item); PyMem_Free(x); } } /* Return a new unpacker for the given format. */ static struct unpacker * struct_get_unpacker(const char *fmt, Py_ssize_t itemsize) { PyObject *structmodule; /* XXX cache these two */ PyObject *Struct = NULL; /* XXX in globals? */ PyObject *structobj = NULL; PyObject *format = NULL; struct unpacker *x = NULL; structmodule = PyImport_ImportModule("struct"); if (structmodule == NULL) return NULL; Struct = PyObject_GetAttrString(structmodule, "Struct"); Py_DECREF(structmodule); if (Struct == NULL) return NULL; x = unpacker_new(); if (x == NULL) goto error; format = PyBytes_FromString(fmt); if (format == NULL) goto error; structobj = PyObject_CallFunctionObjArgs(Struct, format, NULL); if (structobj == NULL) goto error; x->unpack_from = PyObject_GetAttrString(structobj, "unpack_from"); if (x->unpack_from == NULL) goto error; x->item = PyMem_Malloc(itemsize); if (x->item == NULL) { PyErr_NoMemory(); goto error; } x->itemsize = itemsize; x->mview = PyMemoryView_FromMemory(x->item, itemsize, PyBUF_WRITE); if (x->mview == NULL) goto error; out: Py_XDECREF(Struct); Py_XDECREF(format); Py_XDECREF(structobj); return x; error: unpacker_free(x); x = NULL; goto out; } /* unpack a single item */ static PyObject * struct_unpack_single(const char *ptr, struct unpacker *x) { PyObject *v; memcpy(x->item, ptr, x->itemsize); v = PyObject_CallFunctionObjArgs(x->unpack_from, x->mview, NULL); if (v == NULL) return NULL; if (PyTuple_GET_SIZE(v) == 1) { PyObject *tmp = PyTuple_GET_ITEM(v, 0); Py_INCREF(tmp); Py_DECREF(v); return tmp; } return v; } /****************************************************************************/ /* Representations */ /****************************************************************************/ /* allow explicit form of native format */ static inline const char * adjust_fmt(const Py_buffer *view) { const char *fmt; fmt = (view->format[0] == '@') ? view->format+1 : view->format; if (fmt[0] && fmt[1] == '\0') return fmt; PyErr_Format(PyExc_NotImplementedError, "memoryview: unsupported format %s", view->format); return NULL; } /* Base case for multi-dimensional unpacking. Assumption: ndim == 1. */ static PyObject * tolist_base(const char *ptr, const Py_ssize_t *shape, const Py_ssize_t *strides, const Py_ssize_t *suboffsets, const char *fmt) { PyObject *lst, *item; Py_ssize_t i; lst = PyList_New(shape[0]); if (lst == NULL) return NULL; for (i = 0; i < shape[0]; ptr+=strides[0], i++) { const char *xptr = ADJUST_PTR(ptr, suboffsets, 0); item = unpack_single(xptr, fmt); if (item == NULL) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, item); } return lst; } /* Unpack a multi-dimensional array into a nested list. Assumption: ndim >= 1. */ static PyObject * tolist_rec(const char *ptr, Py_ssize_t ndim, const Py_ssize_t *shape, const Py_ssize_t *strides, const Py_ssize_t *suboffsets, const char *fmt) { PyObject *lst, *item; Py_ssize_t i; assert(ndim >= 1); assert(shape != NULL); assert(strides != NULL); if (ndim == 1) return tolist_base(ptr, shape, strides, suboffsets, fmt); lst = PyList_New(shape[0]); if (lst == NULL) return NULL; for (i = 0; i < shape[0]; ptr+=strides[0], i++) { const char *xptr = ADJUST_PTR(ptr, suboffsets, 0); item = tolist_rec(xptr, ndim-1, shape+1, strides+1, suboffsets ? suboffsets+1 : NULL, fmt); if (item == NULL) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, item); } return lst; } /* Return a list representation of the memoryview. Currently only buffers with native format strings are supported. */ static PyObject * memory_tolist(PyMemoryViewObject *mv, PyObject *noargs) { const Py_buffer *view = &(mv->view); const char *fmt; CHECK_RELEASED(mv); fmt = adjust_fmt(view); if (fmt == NULL) return NULL; if (view->ndim == 0) { return unpack_single(view->buf, fmt); } else if (view->ndim == 1) { return tolist_base(view->buf, view->shape, view->strides, view->suboffsets, fmt); } else { return tolist_rec(view->buf, view->ndim, view->shape, view->strides, view->suboffsets, fmt); } } static PyObject * memory_tobytes(PyMemoryViewObject *self, PyObject *dummy) { Py_buffer *src = VIEW_ADDR(self); PyObject *bytes = NULL; CHECK_RELEASED(self); if (MV_C_CONTIGUOUS(self->flags)) { return PyBytes_FromStringAndSize(src->buf, src->len); } bytes = PyBytes_FromStringAndSize(NULL, src->len); if (bytes == NULL) return NULL; if (buffer_to_contiguous(PyBytes_AS_STRING(bytes), src, 'C') < 0) { Py_DECREF(bytes); return NULL; } return bytes; } static PyObject * memory_hex(PyMemoryViewObject *self, PyObject *dummy) { Py_buffer *src = VIEW_ADDR(self); PyObject *bytes; PyObject *ret; CHECK_RELEASED(self); if (MV_C_CONTIGUOUS(self->flags)) { return _Py_strhex(src->buf, src->len); } bytes = memory_tobytes(self, dummy); if (bytes == NULL) return NULL; ret = _Py_strhex(PyBytes_AS_STRING(bytes), Py_SIZE(bytes)); Py_DECREF(bytes); return ret; } static PyObject * memory_repr(PyMemoryViewObject *self) { if (self->flags & _Py_MEMORYVIEW_RELEASED) return PyUnicode_FromFormat("<released memory at %p>", self); else return PyUnicode_FromFormat("<memory at %p>", self); } /**************************************************************************/ /* Indexing and slicing */ /**************************************************************************/ static char * lookup_dimension(Py_buffer *view, char *ptr, int dim, Py_ssize_t index) { Py_ssize_t nitems; /* items in the given dimension */ assert(view->shape); assert(view->strides); nitems = view->shape[dim]; if (index < 0) { index += nitems; } if (index < 0 || index >= nitems) { PyErr_Format(PyExc_IndexError, "index out of bounds on dimension %d", dim + 1); return NULL; } ptr += view->strides[dim] * index; ptr = ADJUST_PTR(ptr, view->suboffsets, dim); return ptr; } /* Get the pointer to the item at index. */ static char * ptr_from_index(Py_buffer *view, Py_ssize_t index) { char *ptr = (char *)view->buf; return lookup_dimension(view, ptr, 0, index); } /* Get the pointer to the item at tuple. */ static char * ptr_from_tuple(Py_buffer *view, PyObject *tup) { char *ptr = (char *)view->buf; Py_ssize_t dim, nindices = PyTuple_GET_SIZE(tup); if (nindices > view->ndim) { PyErr_Format(PyExc_TypeError, "cannot index %zd-dimension view with %zd-element tuple", view->ndim, nindices); return NULL; } for (dim = 0; dim < nindices; dim++) { Py_ssize_t index; index = PyNumber_AsSsize_t(PyTuple_GET_ITEM(tup, dim), PyExc_IndexError); if (index == -1 && PyErr_Occurred()) return NULL; ptr = lookup_dimension(view, ptr, (int)dim, index); if (ptr == NULL) return NULL; } return ptr; } /* Return the item at index. In a one-dimensional view, this is an object with the type specified by view->format. Otherwise, the item is a sub-view. The function is used in memory_subscript() and memory_as_sequence. */ static PyObject * memory_item(PyMemoryViewObject *self, Py_ssize_t index) { Py_buffer *view = &(self->view); const char *fmt; CHECK_RELEASED(self); fmt = adjust_fmt(view); if (fmt == NULL) return NULL; if (view->ndim == 0) { PyErr_SetString(PyExc_TypeError, "invalid indexing of 0-dim memory"); return NULL; } if (view->ndim == 1) { char *ptr = ptr_from_index(view, index); if (ptr == NULL) return NULL; return unpack_single(ptr, fmt); } PyErr_SetString(PyExc_NotImplementedError, "multi-dimensional sub-views are not implemented"); return NULL; } /* Return the item at position *key* (a tuple of indices). */ static PyObject * memory_item_multi(PyMemoryViewObject *self, PyObject *tup) { Py_buffer *view = &(self->view); const char *fmt; Py_ssize_t nindices = PyTuple_GET_SIZE(tup); char *ptr; CHECK_RELEASED(self); fmt = adjust_fmt(view); if (fmt == NULL) return NULL; if (nindices < view->ndim) { PyErr_SetString(PyExc_NotImplementedError, "sub-views are not implemented"); return NULL; } ptr = ptr_from_tuple(view, tup); if (ptr == NULL) return NULL; return unpack_single(ptr, fmt); } static inline int init_slice(Py_buffer *base, PyObject *key, int dim) { Py_ssize_t start, stop, step, slicelength; if (PySlice_Unpack(key, &start, &stop, &step) < 0) { return -1; } slicelength = PySlice_AdjustIndices(base->shape[dim], &start, &stop, step); if (base->suboffsets == NULL || dim == 0) { adjust_buf: base->buf = (char *)base->buf + base->strides[dim] * start; } else { Py_ssize_t n = dim-1; while (n >= 0 && base->suboffsets[n] < 0) n--; if (n < 0) goto adjust_buf; /* all suboffsets are negative */ base->suboffsets[n] = base->suboffsets[n] + base->strides[dim] * start; } base->shape[dim] = slicelength; base->strides[dim] = base->strides[dim] * step; return 0; } static int is_multislice(PyObject *key) { Py_ssize_t size, i; if (!PyTuple_Check(key)) return 0; size = PyTuple_GET_SIZE(key); if (size == 0) return 0; for (i = 0; i < size; i++) { PyObject *x = PyTuple_GET_ITEM(key, i); if (!PySlice_Check(x)) return 0; } return 1; } static Py_ssize_t is_multiindex(PyObject *key) { Py_ssize_t size, i; if (!PyTuple_Check(key)) return 0; size = PyTuple_GET_SIZE(key); for (i = 0; i < size; i++) { PyObject *x = PyTuple_GET_ITEM(key, i); if (!PyIndex_Check(x)) return 0; } return 1; } /* mv[obj] returns an object holding the data for one element if obj fully indexes the memoryview or another memoryview object if it does not. 0-d memoryview objects can be referenced using mv[...] or mv[()] but not with anything else. */ static PyObject * memory_subscript(PyMemoryViewObject *self, PyObject *key) { Py_buffer *view; view = &(self->view); CHECK_RELEASED(self); if (view->ndim == 0) { if (PyTuple_Check(key) && PyTuple_GET_SIZE(key) == 0) { const char *fmt = adjust_fmt(view); if (fmt == NULL) return NULL; return unpack_single(view->buf, fmt); } else if (key == Py_Ellipsis) { Py_INCREF(self); return (PyObject *)self; } else { PyErr_SetString(PyExc_TypeError, "invalid indexing of 0-dim memory"); return NULL; } } if (PyIndex_Check(key)) { Py_ssize_t index; index = PyNumber_AsSsize_t(key, PyExc_IndexError); if (index == -1 && PyErr_Occurred()) return NULL; return memory_item(self, index); } else if (PySlice_Check(key)) { PyMemoryViewObject *sliced; sliced = (PyMemoryViewObject *)mbuf_add_view(self->mbuf, view); if (sliced == NULL) return NULL; if (init_slice(&sliced->view, key, 0) < 0) { Py_DECREF(sliced); return NULL; } init_len(&sliced->view); init_flags(sliced); return (PyObject *)sliced; } else if (is_multiindex(key)) { return memory_item_multi(self, key); } else if (is_multislice(key)) { PyErr_SetString(PyExc_NotImplementedError, "multi-dimensional slicing is not implemented"); return NULL; } PyErr_SetString(PyExc_TypeError, "memoryview: invalid slice key"); return NULL; } static int memory_ass_sub(PyMemoryViewObject *self, PyObject *key, PyObject *value) { Py_buffer *view = &(self->view); Py_buffer src; const char *fmt; char *ptr; CHECK_RELEASED_INT(self); fmt = adjust_fmt(view); if (fmt == NULL) return -1; if (view->readonly) { PyErr_SetString(PyExc_TypeError, "cannot modify read-only memory"); return -1; } if (value == NULL) { PyErr_SetString(PyExc_TypeError, "cannot delete memory"); return -1; } if (view->ndim == 0) { if (key == Py_Ellipsis || (PyTuple_Check(key) && PyTuple_GET_SIZE(key)==0)) { ptr = (char *)view->buf; return pack_single(ptr, value, fmt); } else { PyErr_SetString(PyExc_TypeError, "invalid indexing of 0-dim memory"); return -1; } } if (PyIndex_Check(key)) { Py_ssize_t index; if (1 < view->ndim) { PyErr_SetString(PyExc_NotImplementedError, "sub-views are not implemented"); return -1; } index = PyNumber_AsSsize_t(key, PyExc_IndexError); if (index == -1 && PyErr_Occurred()) return -1; ptr = ptr_from_index(view, index); if (ptr == NULL) return -1; return pack_single(ptr, value, fmt); } /* one-dimensional: fast path */ if (PySlice_Check(key) && view->ndim == 1) { Py_buffer dest; /* sliced view */ Py_ssize_t arrays[3]; int ret = -1; /* rvalue must be an exporter */ if (PyObject_GetBuffer(value, &src, PyBUF_FULL_RO) < 0) return ret; dest = *view; dest.shape = &arrays[0]; dest.shape[0] = view->shape[0]; dest.strides = &arrays[1]; dest.strides[0] = view->strides[0]; if (view->suboffsets) { dest.suboffsets = &arrays[2]; dest.suboffsets[0] = view->suboffsets[0]; } if (init_slice(&dest, key, 0) < 0) goto end_block; dest.len = dest.shape[0] * dest.itemsize; ret = copy_single(&dest, &src); end_block: PyBuffer_Release(&src); return ret; } if (is_multiindex(key)) { char *ptr; if (PyTuple_GET_SIZE(key) < view->ndim) { PyErr_SetString(PyExc_NotImplementedError, "sub-views are not implemented"); return -1; } ptr = ptr_from_tuple(view, key); if (ptr == NULL) return -1; return pack_single(ptr, value, fmt); } if (PySlice_Check(key) || is_multislice(key)) { /* Call memory_subscript() to produce a sliced lvalue, then copy rvalue into lvalue. This is already implemented in _testbuffer.c. */ PyErr_SetString(PyExc_NotImplementedError, "memoryview slice assignments are currently restricted " "to ndim = 1"); return -1; } PyErr_SetString(PyExc_TypeError, "memoryview: invalid slice key"); return -1; } static Py_ssize_t memory_length(PyMemoryViewObject *self) { CHECK_RELEASED_INT(self); return self->view.ndim == 0 ? 1 : self->view.shape[0]; } /* As mapping */ static PyMappingMethods memory_as_mapping = { (lenfunc)memory_length, /* mp_length */ (binaryfunc)memory_subscript, /* mp_subscript */ (objobjargproc)memory_ass_sub, /* mp_ass_subscript */ }; /* As sequence */ static PySequenceMethods memory_as_sequence = { (lenfunc)memory_length, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ (ssizeargfunc)memory_item, /* sq_item */ }; /**************************************************************************/ /* Comparisons */ /**************************************************************************/ #define MV_COMPARE_EX -1 /* exception */ #define MV_COMPARE_NOT_IMPL -2 /* not implemented */ /* Translate a StructError to "not equal". Preserve other exceptions. */ static int fix_struct_error_int(void) { assert(PyErr_Occurred()); /* XXX Cannot get at StructError directly? */ if (PyErr_ExceptionMatches(PyExc_ImportError) || PyErr_ExceptionMatches(PyExc_MemoryError)) { return MV_COMPARE_EX; } /* StructError: invalid or unknown format -> not equal */ PyErr_Clear(); return 0; } /* Unpack and compare single items of p and q using the struct module. */ static int struct_unpack_cmp(const char *p, const char *q, struct unpacker *unpack_p, struct unpacker *unpack_q) { PyObject *v, *w; int ret; /* At this point any exception from the struct module should not be StructError, since both formats have been accepted already. */ v = struct_unpack_single(p, unpack_p); if (v == NULL) return MV_COMPARE_EX; w = struct_unpack_single(q, unpack_q); if (w == NULL) { Py_DECREF(v); return MV_COMPARE_EX; } /* MV_COMPARE_EX == -1: exceptions are preserved */ ret = PyObject_RichCompareBool(v, w, Py_EQ); Py_DECREF(v); Py_DECREF(w); return ret; } /* Unpack and compare single items of p and q. If both p and q have the same single element native format, the comparison uses a fast path (gcc creates a jump table and converts memcpy into simple assignments on x86/x64). Otherwise, the comparison is delegated to the struct module, which is 30-60x slower. */ #define CMP_SINGLE(p, q, type) \ do { \ type x; \ type y; \ memcpy((char *)&x, p, sizeof x); \ memcpy((char *)&y, q, sizeof y); \ equal = (x == y); \ } while (0) static inline int unpack_cmp(const char *p, const char *q, char fmt, struct unpacker *unpack_p, struct unpacker *unpack_q) { int equal; switch (fmt) { /* signed integers and fast path for 'B' */ case 'B': return *((unsigned char *)p) == *((unsigned char *)q); case 'b': return *((signed char *)p) == *((signed char *)q); case 'h': CMP_SINGLE(p, q, short); return equal; case 'i': CMP_SINGLE(p, q, int); return equal; case 'l': CMP_SINGLE(p, q, long); return equal; /* boolean */ case '?': CMP_SINGLE(p, q, _Bool); return equal; /* unsigned integers */ case 'H': CMP_SINGLE(p, q, unsigned short); return equal; case 'I': CMP_SINGLE(p, q, unsigned int); return equal; case 'L': CMP_SINGLE(p, q, unsigned long); return equal; /* native 64-bit */ case 'q': CMP_SINGLE(p, q, long long); return equal; case 'Q': CMP_SINGLE(p, q, unsigned long long); return equal; /* ssize_t and size_t */ case 'n': CMP_SINGLE(p, q, Py_ssize_t); return equal; case 'N': CMP_SINGLE(p, q, size_t); return equal; /* floats */ /* XXX DBL_EPSILON? */ case 'f': CMP_SINGLE(p, q, float); return equal; case 'd': CMP_SINGLE(p, q, double); return equal; /* bytes object */ case 'c': return *p == *q; /* pointer */ case 'P': CMP_SINGLE(p, q, void *); return equal; /* use the struct module */ case '_': assert(unpack_p); assert(unpack_q); return struct_unpack_cmp(p, q, unpack_p, unpack_q); } /* NOT REACHED */ PyErr_SetString(PyExc_RuntimeError, "memoryview: internal error in richcompare"); return MV_COMPARE_EX; } /* Base case for recursive array comparisons. Assumption: ndim == 1. */ static int cmp_base(const char *p, const char *q, const Py_ssize_t *shape, const Py_ssize_t *pstrides, const Py_ssize_t *psuboffsets, const Py_ssize_t *qstrides, const Py_ssize_t *qsuboffsets, char fmt, struct unpacker *unpack_p, struct unpacker *unpack_q) { Py_ssize_t i; int equal; for (i = 0; i < shape[0]; p+=pstrides[0], q+=qstrides[0], i++) { const char *xp = ADJUST_PTR(p, psuboffsets, 0); const char *xq = ADJUST_PTR(q, qsuboffsets, 0); equal = unpack_cmp(xp, xq, fmt, unpack_p, unpack_q); if (equal <= 0) return equal; } return 1; } /* Recursively compare two multi-dimensional arrays that have the same logical structure. Assumption: ndim >= 1. */ static int cmp_rec(const char *p, const char *q, Py_ssize_t ndim, const Py_ssize_t *shape, const Py_ssize_t *pstrides, const Py_ssize_t *psuboffsets, const Py_ssize_t *qstrides, const Py_ssize_t *qsuboffsets, char fmt, struct unpacker *unpack_p, struct unpacker *unpack_q) { Py_ssize_t i; int equal; assert(ndim >= 1); assert(shape != NULL); assert(pstrides != NULL); assert(qstrides != NULL); if (ndim == 1) { return cmp_base(p, q, shape, pstrides, psuboffsets, qstrides, qsuboffsets, fmt, unpack_p, unpack_q); } for (i = 0; i < shape[0]; p+=pstrides[0], q+=qstrides[0], i++) { const char *xp = ADJUST_PTR(p, psuboffsets, 0); const char *xq = ADJUST_PTR(q, qsuboffsets, 0); equal = cmp_rec(xp, xq, ndim-1, shape+1, pstrides+1, psuboffsets ? psuboffsets+1 : NULL, qstrides+1, qsuboffsets ? qsuboffsets+1 : NULL, fmt, unpack_p, unpack_q); if (equal <= 0) return equal; } return 1; } static PyObject * memory_richcompare(PyObject *v, PyObject *w, int op) { PyObject *res; Py_buffer wbuf, *vv; Py_buffer *ww = NULL; struct unpacker *unpack_v = NULL; struct unpacker *unpack_w = NULL; char vfmt, wfmt; int equal = MV_COMPARE_NOT_IMPL; if (op != Py_EQ && op != Py_NE) goto result; /* Py_NotImplemented */ assert(PyMemoryView_Check(v)); if (BASE_INACCESSIBLE(v)) { equal = (v == w); goto result; } vv = VIEW_ADDR(v); if (PyMemoryView_Check(w)) { if (BASE_INACCESSIBLE(w)) { equal = (v == w); goto result; } ww = VIEW_ADDR(w); } else { if (PyObject_GetBuffer(w, &wbuf, PyBUF_FULL_RO) < 0) { PyErr_Clear(); goto result; /* Py_NotImplemented */ } ww = &wbuf; } if (!equiv_shape(vv, ww)) { PyErr_Clear(); equal = 0; goto result; } /* Use fast unpacking for identical primitive C type formats. */ if (get_native_fmtchar(&vfmt, vv->format) < 0) vfmt = '_'; if (get_native_fmtchar(&wfmt, ww->format) < 0) wfmt = '_'; if (vfmt == '_' || wfmt == '_' || vfmt != wfmt) { /* Use struct module unpacking. NOTE: Even for equal format strings, memcmp() cannot be used for item comparison since it would give incorrect results in the case of NaNs or uninitialized padding bytes. */ vfmt = '_'; unpack_v = struct_get_unpacker(vv->format, vv->itemsize); if (unpack_v == NULL) { equal = fix_struct_error_int(); goto result; } unpack_w = struct_get_unpacker(ww->format, ww->itemsize); if (unpack_w == NULL) { equal = fix_struct_error_int(); goto result; } } if (vv->ndim == 0) { equal = unpack_cmp(vv->buf, ww->buf, vfmt, unpack_v, unpack_w); } else if (vv->ndim == 1) { equal = cmp_base(vv->buf, ww->buf, vv->shape, vv->strides, vv->suboffsets, ww->strides, ww->suboffsets, vfmt, unpack_v, unpack_w); } else { equal = cmp_rec(vv->buf, ww->buf, vv->ndim, vv->shape, vv->strides, vv->suboffsets, ww->strides, ww->suboffsets, vfmt, unpack_v, unpack_w); } result: if (equal < 0) { if (equal == MV_COMPARE_NOT_IMPL) res = Py_NotImplemented; else /* exception */ res = NULL; } else if ((equal && op == Py_EQ) || (!equal && op == Py_NE)) res = Py_True; else res = Py_False; if (ww == &wbuf) PyBuffer_Release(ww); unpacker_free(unpack_v); unpacker_free(unpack_w); Py_XINCREF(res); return res; } /**************************************************************************/ /* Hash */ /**************************************************************************/ static Py_hash_t memory_hash(PyMemoryViewObject *self) { if (self->hash == -1) { Py_buffer *view = &self->view; char *mem = view->buf; Py_ssize_t ret; char fmt; CHECK_RELEASED_INT(self); if (!view->readonly) { PyErr_SetString(PyExc_ValueError, "cannot hash writable memoryview object"); return -1; } ret = get_native_fmtchar(&fmt, view->format); if (ret < 0 || !IS_BYTE_FORMAT(fmt)) { PyErr_SetString(PyExc_ValueError, "memoryview: hashing is restricted to formats 'B', 'b' or 'c'"); return -1; } if (view->obj != NULL && PyObject_Hash(view->obj) == -1) { /* Keep the original error message */ return -1; } if (!MV_C_CONTIGUOUS(self->flags)) { mem = PyMem_Malloc(view->len); if (mem == NULL) { PyErr_NoMemory(); return -1; } if (buffer_to_contiguous(mem, view, 'C') < 0) { PyMem_Free(mem); return -1; } } /* Can't fail */ self->hash = _Py_HashBytes(mem, view->len); if (mem != view->buf) PyMem_Free(mem); } return self->hash; } /**************************************************************************/ /* getters */ /**************************************************************************/ static PyObject * _IntTupleFromSsizet(int len, Py_ssize_t *vals) { int i; PyObject *o; PyObject *intTuple; if (vals == NULL) return PyTuple_New(0); intTuple = PyTuple_New(len); if (!intTuple) return NULL; for (i=0; i<len; i++) { o = PyLong_FromSsize_t(vals[i]); if (!o) { Py_DECREF(intTuple); return NULL; } PyTuple_SET_ITEM(intTuple, i, o); } return intTuple; } static PyObject * memory_obj_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { Py_buffer *view = &self->view; CHECK_RELEASED(self); if (view->obj == NULL) { Py_RETURN_NONE; } Py_INCREF(view->obj); return view->obj; } static PyObject * memory_nbytes_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { CHECK_RELEASED(self); return PyLong_FromSsize_t(self->view.len); } static PyObject * memory_format_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { CHECK_RELEASED(self); return PyUnicode_FromString(self->view.format); } static PyObject * memory_itemsize_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { CHECK_RELEASED(self); return PyLong_FromSsize_t(self->view.itemsize); } static PyObject * memory_shape_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { CHECK_RELEASED(self); return _IntTupleFromSsizet(self->view.ndim, self->view.shape); } static PyObject * memory_strides_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { CHECK_RELEASED(self); return _IntTupleFromSsizet(self->view.ndim, self->view.strides); } static PyObject * memory_suboffsets_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { CHECK_RELEASED(self); return _IntTupleFromSsizet(self->view.ndim, self->view.suboffsets); } static PyObject * memory_readonly_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { CHECK_RELEASED(self); return PyBool_FromLong(self->view.readonly); } static PyObject * memory_ndim_get(PyMemoryViewObject *self, void *Py_UNUSED(ignored)) { CHECK_RELEASED(self); return PyLong_FromLong(self->view.ndim); } static PyObject * memory_c_contiguous(PyMemoryViewObject *self, PyObject *dummy) { CHECK_RELEASED(self); return PyBool_FromLong(MV_C_CONTIGUOUS(self->flags)); } static PyObject * memory_f_contiguous(PyMemoryViewObject *self, PyObject *dummy) { CHECK_RELEASED(self); return PyBool_FromLong(MV_F_CONTIGUOUS(self->flags)); } static PyObject * memory_contiguous(PyMemoryViewObject *self, PyObject *dummy) { CHECK_RELEASED(self); return PyBool_FromLong(MV_ANY_CONTIGUOUS(self->flags)); } PyDoc_STRVAR(memory_obj_doc, "The underlying object of the memoryview."); PyDoc_STRVAR(memory_nbytes_doc, "The amount of space in bytes that the array would use in\n" " a contiguous representation."); PyDoc_STRVAR(memory_readonly_doc, "A bool indicating whether the memory is read only."); PyDoc_STRVAR(memory_itemsize_doc, "The size in bytes of each element of the memoryview."); PyDoc_STRVAR(memory_format_doc, "A string containing the format (in struct module style)\n" " for each element in the view."); PyDoc_STRVAR(memory_ndim_doc, "An integer indicating how many dimensions of a multi-dimensional\n" " array the memory represents."); PyDoc_STRVAR(memory_shape_doc, "A tuple of ndim integers giving the shape of the memory\n" " as an N-dimensional array."); PyDoc_STRVAR(memory_strides_doc, "A tuple of ndim integers giving the size in bytes to access\n" " each element for each dimension of the array."); PyDoc_STRVAR(memory_suboffsets_doc, "A tuple of integers used internally for PIL-style arrays."); PyDoc_STRVAR(memory_c_contiguous_doc, "A bool indicating whether the memory is C contiguous."); PyDoc_STRVAR(memory_f_contiguous_doc, "A bool indicating whether the memory is Fortran contiguous."); PyDoc_STRVAR(memory_contiguous_doc, "A bool indicating whether the memory is contiguous."); static PyGetSetDef memory_getsetlist[] = { {"obj", (getter)memory_obj_get, NULL, memory_obj_doc}, {"nbytes", (getter)memory_nbytes_get, NULL, memory_nbytes_doc}, {"readonly", (getter)memory_readonly_get, NULL, memory_readonly_doc}, {"itemsize", (getter)memory_itemsize_get, NULL, memory_itemsize_doc}, {"format", (getter)memory_format_get, NULL, memory_format_doc}, {"ndim", (getter)memory_ndim_get, NULL, memory_ndim_doc}, {"shape", (getter)memory_shape_get, NULL, memory_shape_doc}, {"strides", (getter)memory_strides_get, NULL, memory_strides_doc}, {"suboffsets", (getter)memory_suboffsets_get, NULL, memory_suboffsets_doc}, {"c_contiguous", (getter)memory_c_contiguous, NULL, memory_c_contiguous_doc}, {"f_contiguous", (getter)memory_f_contiguous, NULL, memory_f_contiguous_doc}, {"contiguous", (getter)memory_contiguous, NULL, memory_contiguous_doc}, {NULL, NULL, NULL, NULL}, }; PyDoc_STRVAR(memory_release_doc, "release($self, /)\n--\n\ \n\ Release the underlying buffer exposed by the memoryview object."); PyDoc_STRVAR(memory_tobytes_doc, "tobytes($self, /)\n--\n\ \n\ Return the data in the buffer as a byte string."); PyDoc_STRVAR(memory_hex_doc, "hex($self, /)\n--\n\ \n\ Return the data in the buffer as a string of hexadecimal numbers."); PyDoc_STRVAR(memory_tolist_doc, "tolist($self, /)\n--\n\ \n\ Return the data in the buffer as a list of elements."); PyDoc_STRVAR(memory_cast_doc, "cast($self, /, format, *, shape)\n--\n\ \n\ Cast a memoryview to a new format or shape."); static PyMethodDef memory_methods[] = { {"release", (PyCFunction)memory_release, METH_NOARGS, memory_release_doc}, {"tobytes", (PyCFunction)memory_tobytes, METH_NOARGS, memory_tobytes_doc}, {"hex", (PyCFunction)memory_hex, METH_NOARGS, memory_hex_doc}, {"tolist", (PyCFunction)memory_tolist, METH_NOARGS, memory_tolist_doc}, {"cast", (PyCFunction)memory_cast, METH_VARARGS|METH_KEYWORDS, memory_cast_doc}, {"__enter__", memory_enter, METH_NOARGS, NULL}, {"__exit__", memory_exit, METH_VARARGS, NULL}, {NULL, NULL} }; PyTypeObject PyMemoryView_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "memoryview", /* tp_name */ offsetof(PyMemoryViewObject, ob_array), /* tp_basicsize */ sizeof(Py_ssize_t), /* tp_itemsize */ (destructor)memory_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)memory_repr, /* tp_repr */ 0, /* tp_as_number */ &memory_as_sequence, /* tp_as_sequence */ &memory_as_mapping, /* tp_as_mapping */ (hashfunc)memory_hash, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &memory_as_buffer, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ memory_doc, /* tp_doc */ (traverseproc)memory_traverse, /* tp_traverse */ (inquiry)memory_clear, /* tp_clear */ memory_richcompare, /* tp_richcompare */ offsetof(PyMemoryViewObject, weakreflist),/* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ memory_methods, /* tp_methods */ 0, /* tp_members */ memory_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ memory_new, /* tp_new */ };
92,589
3,134
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/unicodeobject-deadcode.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "libc/assert.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ #define _PyUnicode_STATE(op) \ (((PyASCIIObject *)(op))->state) int ensure_unicode(PyObject *); PyObject *unicode_result(PyObject *); int unicode_check_modifiable(PyObject *); PyObject *unicode_encode_ucs1(PyObject *, const char *, const Py_UCS4); PyObject *_PyUnicode_TranslateCharmap(PyObject *, PyObject *, const char *); /* The max unicode value is always 0x10FFFF while using the PEP-393 API. This function is kept for backward compatibility with the old API. */ Py_UNICODE PyUnicode_GetMax(void) { #ifdef Py_UNICODE_WIDE return 0x10FFFF; #else /* This is actually an illegal character, so it should not be passed to unichr. */ return 0xFFFF; #endif } PyObject * PyUnicode_AsDecodedObject(PyObject *unicode, const char *encoding, const char *errors) { if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } if (PyErr_WarnEx(PyExc_DeprecationWarning, "PyUnicode_AsDecodedObject() is deprecated; " "use PyCodec_Decode() to decode from str", 1) < 0) return NULL; if (encoding == NULL) encoding = PyUnicode_GetDefaultEncoding(); /* Decode via the codec registry */ return PyCodec_Decode(unicode, encoding, errors); } PyObject * PyUnicode_AsDecodedUnicode(PyObject *unicode, const char *encoding, const char *errors) { PyObject *v; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); goto onError; } if (PyErr_WarnEx(PyExc_DeprecationWarning, "PyUnicode_AsDecodedUnicode() is deprecated; " "use PyCodec_Decode() to decode from str to str", 1) < 0) return NULL; if (encoding == NULL) encoding = PyUnicode_GetDefaultEncoding(); /* Decode via the codec registry */ v = PyCodec_Decode(unicode, encoding, errors); if (v == NULL) goto onError; if (!PyUnicode_Check(v)) { PyErr_Format(PyExc_TypeError, "'%.400s' decoder returned '%.400s' instead of 'str'; " "use codecs.decode() to decode to arbitrary types", encoding, Py_TYPE(unicode)->tp_name); Py_DECREF(v); goto onError; } return unicode_result(v); onError: return NULL; } PyObject * PyUnicode_AsEncodedObject(PyObject *unicode, const char *encoding, const char *errors) { PyObject *v; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); goto onError; } if (PyErr_WarnEx(PyExc_DeprecationWarning, "PyUnicode_AsEncodedObject() is deprecated; " "use PyUnicode_AsEncodedString() to encode from str to bytes " "or PyCodec_Encode() for generic encoding", 1) < 0) return NULL; if (encoding == NULL) encoding = PyUnicode_GetDefaultEncoding(); /* Encode via the codec registry */ v = PyCodec_Encode(unicode, encoding, errors); if (v == NULL) goto onError; return v; onError: return NULL; } PyObject * PyUnicode_AsEncodedUnicode(PyObject *unicode, const char *encoding, const char *errors) { PyObject *v; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); goto onError; } if (PyErr_WarnEx(PyExc_DeprecationWarning, "PyUnicode_AsEncodedUnicode() is deprecated; " "use PyCodec_Encode() to encode from str to str", 1) < 0) return NULL; if (encoding == NULL) encoding = PyUnicode_GetDefaultEncoding(); /* Encode via the codec registry */ v = PyCodec_Encode(unicode, encoding, errors); if (v == NULL) goto onError; if (!PyUnicode_Check(v)) { PyErr_Format(PyExc_TypeError, "'%.400s' encoder returned '%.400s' instead of 'str'; " "use codecs.encode() to encode to arbitrary types", encoding, Py_TYPE(v)->tp_name); Py_DECREF(v); goto onError; } return v; onError: return NULL; } wchar_t * _PyUnicode_AsWideCharString(PyObject *unicode) { const wchar_t *wstr; wchar_t *buffer; Py_ssize_t buflen; if (unicode == NULL) { PyErr_BadInternalCall(); return NULL; } wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen); if (wstr == NULL) { return NULL; } if (wcslen(wstr) != (size_t)buflen) { PyErr_SetString(PyExc_ValueError, "embedded null character"); return NULL; } buffer = PyMem_NEW(wchar_t, buflen + 1); if (buffer == NULL) { PyErr_NoMemory(); return NULL; } memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t)); return buffer; } const Py_UNICODE * _PyUnicode_AsUnicode(PyObject *unicode) { Py_ssize_t size; const Py_UNICODE *wstr; wstr = PyUnicode_AsUnicodeAndSize(unicode, &size); if (wstr && wcslen(wstr) != (size_t)size) { PyErr_SetString(PyExc_ValueError, "embedded null character"); return NULL; } return wstr; } Py_ssize_t PyUnicode_GetSize(PyObject *unicode) { if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); goto onError; } return PyUnicode_GET_SIZE(unicode); onError: return -1; } int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch) { if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) { PyErr_BadArgument(); return -1; } assert(PyUnicode_IS_READY(unicode)); if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return -1; } if (unicode_check_modifiable(unicode)) return -1; if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) { PyErr_SetString(PyExc_ValueError, "character out of range"); return -1; } PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode), index, ch); return 0; } /* Deprecated */ PyObject * PyUnicode_EncodeLatin1(const Py_UNICODE *p, Py_ssize_t size, const char *errors) { PyObject *result; PyObject *unicode = PyUnicode_FromUnicode(p, size); if (unicode == NULL) return NULL; result = unicode_encode_ucs1(unicode, errors, 256); Py_DECREF(unicode); return result; } /* Deprecated */ PyObject * PyUnicode_EncodeASCII(const Py_UNICODE *p, Py_ssize_t size, const char *errors) { PyObject *result; PyObject *unicode = PyUnicode_FromUnicode(p, size); if (unicode == NULL) return NULL; result = unicode_encode_ucs1(unicode, errors, 128); Py_DECREF(unicode); return result; } PyObject * PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors) { PyObject *v, *unicode; unicode = PyUnicode_FromUnicode(s, size); if (unicode == NULL) return NULL; v = PyUnicode_AsEncodedString(unicode, encoding, errors); Py_DECREF(unicode); return v; } /* Deprecated */ PyObject * PyUnicode_EncodeCharmap(const Py_UNICODE *p, Py_ssize_t size, PyObject *mapping, const char *errors) { PyObject *result; PyObject *unicode = PyUnicode_FromUnicode(p, size); if (unicode == NULL) return NULL; result = _PyUnicode_EncodeCharmap(unicode, mapping, errors); Py_DECREF(unicode); return result; } /* Deprecated. Use PyUnicode_Translate instead. */ PyObject * PyUnicode_TranslateCharmap(const Py_UNICODE *p, Py_ssize_t size, PyObject *mapping, const char *errors) { PyObject *result; PyObject *unicode = PyUnicode_FromUnicode(p, size); if (!unicode) return NULL; result = _PyUnicode_TranslateCharmap(unicode, mapping, errors); Py_DECREF(unicode); return result; } void PyUnicode_InternImmortal(PyObject **p) { PyUnicode_InternInPlace(p); if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) { _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL; Py_INCREF(*p); } } Py_UNICODE* Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2) { Py_UNICODE *u = s1; while ((*u++ = *s2++)); return s1; } Py_UNICODE* Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n) { Py_UNICODE *u = s1; while ((*u++ = *s2++)) if (n-- == 0) break; return s1; } Py_UNICODE* Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2) { Py_UNICODE *u1 = s1; u1 += Py_UNICODE_strlen(u1); Py_UNICODE_strcpy(u1, s2); return s1; } int Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2) { while (*s1 && *s2 && *s1 == *s2) s1++, s2++; if (*s1 && *s2) return (*s1 < *s2) ? -1 : +1; if (*s1) return 1; if (*s2) return -1; return 0; } int Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n) { Py_UNICODE u1, u2; for (; n != 0; n--) { u1 = *s1; u2 = *s2; if (u1 != u2) return (u1 < u2) ? -1 : +1; if (u1 == '\0') return 0; s1++; s2++; } return 0; } Py_UNICODE* Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c) { const Py_UNICODE *p; for (p = s; *p; p++) if (*p == c) return (Py_UNICODE*)p; return NULL; } Py_UNICODE* Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c) { const Py_UNICODE *p; p = s + Py_UNICODE_strlen(s); while (p != s) { p--; if (*p == c) return (Py_UNICODE*)p; } return NULL; } size_t Py_UNICODE_strlen(const Py_UNICODE *u) { int res = 0; while(*u++) res++; return res; } Py_UNICODE* PyUnicode_AsUnicodeCopy(PyObject *unicode) { Py_UNICODE *u, *copy; Py_ssize_t len, size; if (!PyUnicode_Check(unicode)) { PyErr_BadArgument(); return NULL; } u = PyUnicode_AsUnicodeAndSize(unicode, &len); if (u == NULL) return NULL; /* Ensure we won't overflow the size. */ if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) { PyErr_NoMemory(); return NULL; } size = len + 1; /* copy the null character */ size *= sizeof(Py_UNICODE); copy = PyMem_Malloc(size); if (copy == NULL) { PyErr_NoMemory(); return NULL; } memcpy(copy, u, size); return copy; }
12,073
432
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/weakrefobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/weakrefobject.h" #include "third_party/quickjs/quickjs.h" /* clang-format off */ #define GET_WEAKREFS_LISTPTR(o) \ ((PyWeakReference **) PyObject_GET_WEAKREFS_LISTPTR(o)) Py_ssize_t _PyWeakref_GetWeakrefCount(PyWeakReference *head) { Py_ssize_t count = 0; while (head != NULL) { ++count; head = head->wr_next; } return count; } static void init_weakref(PyWeakReference *self, PyObject *ob, PyObject *callback) { self->hash = -1; self->wr_object = ob; self->wr_prev = NULL; self->wr_next = NULL; Py_XINCREF(callback); self->wr_callback = callback; } static PyWeakReference * new_weakref(PyObject *ob, PyObject *callback) { PyWeakReference *result; result = PyObject_GC_New(PyWeakReference, &_PyWeakref_RefType); if (result) { init_weakref(result, ob, callback); PyObject_GC_Track(result); } return result; } /* This function clears the passed-in reference and removes it from the * list of weak references for the referent. This is the only code that * removes an item from the doubly-linked list of weak references for an * object; it is also responsible for clearing the callback slot. */ static void clear_weakref(PyWeakReference *self) { PyObject *callback = self->wr_callback; if (self->wr_object != Py_None) { PyWeakReference **list = GET_WEAKREFS_LISTPTR(self->wr_object); if (*list == self) /* If 'self' is the end of the list (and thus self->wr_next == NULL) then the weakref list itself (and thus the value of *list) will end up being set to NULL. */ *list = self->wr_next; self->wr_object = Py_None; if (self->wr_prev != NULL) self->wr_prev->wr_next = self->wr_next; if (self->wr_next != NULL) self->wr_next->wr_prev = self->wr_prev; self->wr_prev = NULL; self->wr_next = NULL; } if (callback != NULL) { Py_DECREF(callback); self->wr_callback = NULL; } } /* Cyclic gc uses this to *just* clear the passed-in reference, leaving * the callback intact and uncalled. It must be possible to call self's * tp_dealloc() after calling this, so self has to be left in a sane enough * state for that to work. We expect tp_dealloc to decref the callback * then. The reason for not letting clear_weakref() decref the callback * right now is that if the callback goes away, that may in turn trigger * another callback (if a weak reference to the callback exists) -- running * arbitrary Python code in the middle of gc is a disaster. The convolution * here allows gc to delay triggering such callbacks until the world is in * a sane state again. */ void _PyWeakref_ClearRef(PyWeakReference *self) { PyObject *callback; assert(self != NULL); assert(PyWeakref_Check(self)); /* Preserve and restore the callback around clear_weakref. */ callback = self->wr_callback; self->wr_callback = NULL; clear_weakref(self); self->wr_callback = callback; } static void weakref_dealloc(PyObject *self) { PyObject_GC_UnTrack(self); clear_weakref((PyWeakReference *) self); Py_TYPE(self)->tp_free(self); } static int gc_traverse(PyWeakReference *self, visitproc visit, void *arg) { Py_VISIT(self->wr_callback); return 0; } static int gc_clear(PyWeakReference *self) { clear_weakref(self); return 0; } static PyObject * weakref_call(PyWeakReference *self, PyObject *args, PyObject *kw) { static char *kwlist[] = {NULL}; if (PyArg_ParseTupleAndKeywords(args, kw, ":__call__", kwlist)) { PyObject *object = PyWeakref_GET_OBJECT(self); Py_INCREF(object); return (object); } return NULL; } static Py_hash_t weakref_hash(PyWeakReference *self) { if (self->hash != -1) return self->hash; if (PyWeakref_GET_OBJECT(self) == Py_None) { PyErr_SetString(PyExc_TypeError, "weak object has gone away"); return -1; } self->hash = PyObject_Hash(PyWeakref_GET_OBJECT(self)); return self->hash; } static PyObject * weakref_repr(PyWeakReference *self) { PyObject *name, *repr; _Py_IDENTIFIER(__name__); if (PyWeakref_GET_OBJECT(self) == Py_None) return PyUnicode_FromFormat("<weakref at %p; dead>", self); name = _PyObject_GetAttrId(PyWeakref_GET_OBJECT(self), &PyId___name__); if (name == NULL || !PyUnicode_Check(name)) { if (name == NULL) PyErr_Clear(); repr = PyUnicode_FromFormat( "<weakref at %p; to '%s' at %p>", self, Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, PyWeakref_GET_OBJECT(self)); } else { repr = PyUnicode_FromFormat( "<weakref at %p; to '%s' at %p (%U)>", self, Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name, PyWeakref_GET_OBJECT(self), name); } Py_XDECREF(name); return repr; } /* Weak references only support equality, not ordering. Two weak references are equal if the underlying objects are equal. If the underlying object has gone away, they are equal if they are identical. */ static PyObject * weakref_richcompare(PyWeakReference* self, PyWeakReference* other, int op) { if ((op != Py_EQ && op != Py_NE) || !PyWeakref_Check(self) || !PyWeakref_Check(other)) { Py_RETURN_NOTIMPLEMENTED; } if (PyWeakref_GET_OBJECT(self) == Py_None || PyWeakref_GET_OBJECT(other) == Py_None) { int res = (self == other); if (op == Py_NE) res = !res; if (res) Py_RETURN_TRUE; else Py_RETURN_FALSE; } return PyObject_RichCompare(PyWeakref_GET_OBJECT(self), PyWeakref_GET_OBJECT(other), op); } /* Given the head of an object's list of weak references, extract the * two callback-less refs (ref and proxy). Used to determine if the * shared references exist and to determine the back link for newly * inserted references. */ static void get_basic_refs(PyWeakReference *head, PyWeakReference **refp, PyWeakReference **proxyp) { *refp = NULL; *proxyp = NULL; if (head != NULL && head->wr_callback == NULL) { /* We need to be careful that the "basic refs" aren't subclasses of the main types. That complicates this a little. */ if (PyWeakref_CheckRefExact(head)) { *refp = head; head = head->wr_next; } if (head != NULL && head->wr_callback == NULL && PyWeakref_CheckProxy(head)) { *proxyp = head; /* head = head->wr_next; */ } } } /* Insert 'newref' in the list after 'prev'. Both must be non-NULL. */ static void insert_after(PyWeakReference *newref, PyWeakReference *prev) { newref->wr_prev = prev; newref->wr_next = prev->wr_next; if (prev->wr_next != NULL) prev->wr_next->wr_prev = newref; prev->wr_next = newref; } /* Insert 'newref' at the head of the list; 'list' points to the variable * that stores the head. */ static void insert_head(PyWeakReference *newref, PyWeakReference **list) { PyWeakReference *next = *list; newref->wr_prev = NULL; newref->wr_next = next; if (next != NULL) next->wr_prev = newref; *list = newref; } static int parse_weakref_init_args(const char *funcname, PyObject *args, PyObject *kwargs, PyObject **obp, PyObject **callbackp) { return PyArg_UnpackTuple(args, funcname, 1, 2, obp, callbackp); } static PyObject * weakref___new__(PyTypeObject *type, PyObject *args, PyObject *kwargs) { PyWeakReference *self = NULL; PyObject *ob, *callback = NULL; if (parse_weakref_init_args("__new__", args, kwargs, &ob, &callback)) { PyWeakReference *ref, *proxy; PyWeakReference **list; if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } if (callback == Py_None) callback = NULL; list = GET_WEAKREFS_LISTPTR(ob); get_basic_refs(*list, &ref, &proxy); if (callback == NULL && type == &_PyWeakref_RefType) { if (ref != NULL) { /* We can re-use an existing reference. */ Py_INCREF(ref); return (PyObject *)ref; } } /* We have to create a new reference. */ /* Note: the tp_alloc() can trigger cyclic GC, so the weakref list on ob can be mutated. This means that the ref and proxy pointers we got back earlier may have been collected, so we need to compute these values again before we use them. */ self = (PyWeakReference *) (type->tp_alloc(type, 0)); if (self != NULL) { init_weakref(self, ob, callback); if (callback == NULL && type == &_PyWeakref_RefType) { insert_head(self, list); } else { PyWeakReference *prev; get_basic_refs(*list, &ref, &proxy); prev = (proxy == NULL) ? ref : proxy; if (prev == NULL) insert_head(self, list); else insert_after(self, prev); } } } return (PyObject *)self; } static int weakref___init__(PyObject *self, PyObject *args, PyObject *kwargs) { PyObject *tmp; if (!_PyArg_NoKeywords("ref()", kwargs)) return -1; if (parse_weakref_init_args("__init__", args, kwargs, &tmp, &tmp)) return 0; else return -1; } static PyMemberDef weakref_members[] = { {"__callback__", T_OBJECT, offsetof(PyWeakReference, wr_callback), READONLY}, {NULL} /* Sentinel */ }; PyTypeObject _PyWeakref_RefType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "weakref", sizeof(PyWeakReference), 0, weakref_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ (reprfunc)weakref_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ (hashfunc)weakref_hash, /*tp_hash*/ (ternaryfunc)weakref_call, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ (traverseproc)gc_traverse, /*tp_traverse*/ (inquiry)gc_clear, /*tp_clear*/ (richcmpfunc)weakref_richcompare, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ 0, /*tp_methods*/ weakref_members, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ weakref___init__, /*tp_init*/ PyType_GenericAlloc, /*tp_alloc*/ weakref___new__, /*tp_new*/ PyObject_GC_Del, /*tp_free*/ }; static int proxy_checkref(PyWeakReference *proxy) { if (PyWeakref_GET_OBJECT(proxy) == Py_None) { PyErr_SetString(PyExc_ReferenceError, "weakly-referenced object no longer exists"); return 0; } return 1; } /* If a parameter is a proxy, check that it is still "live" and wrap it, * replacing the original value with the raw object. Raises ReferenceError * if the param is a dead proxy. */ #define UNWRAP(o) \ if (PyWeakref_CheckProxy(o)) { \ if (!proxy_checkref((PyWeakReference *)o)) \ return NULL; \ o = PyWeakref_GET_OBJECT(o); \ } #define UNWRAP_I(o) \ if (PyWeakref_CheckProxy(o)) { \ if (!proxy_checkref((PyWeakReference *)o)) \ return -1; \ o = PyWeakref_GET_OBJECT(o); \ } #define WRAP_UNARY(method, generic) \ static PyObject * \ method(PyObject *proxy) { \ UNWRAP(proxy); \ return generic(proxy); \ } #define WRAP_BINARY(method, generic) \ static PyObject * \ method(PyObject *x, PyObject *y) { \ UNWRAP(x); \ UNWRAP(y); \ return generic(x, y); \ } /* Note that the third arg needs to be checked for NULL since the tp_call * slot can receive NULL for this arg. */ #define WRAP_TERNARY(method, generic) \ static PyObject * \ method(PyObject *proxy, PyObject *v, PyObject *w) { \ UNWRAP(proxy); \ UNWRAP(v); \ if (w != NULL) \ UNWRAP(w); \ return generic(proxy, v, w); \ } #define WRAP_METHOD(method, special) \ static PyObject * \ method(PyObject *proxy) { \ _Py_IDENTIFIER(special); \ UNWRAP(proxy); \ return _PyObject_CallMethodId(proxy, &PyId_##special, NULL); \ } /* direct slots */ WRAP_BINARY(proxy_getattr, PyObject_GetAttr) WRAP_UNARY(proxy_str, PyObject_Str) WRAP_TERNARY(proxy_call, PyEval_CallObjectWithKeywords) static PyObject * proxy_repr(PyWeakReference *proxy) { return PyUnicode_FromFormat( "<weakproxy at %p to %s at %p>", proxy, Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name, PyWeakref_GET_OBJECT(proxy)); } static int proxy_setattr(PyWeakReference *proxy, PyObject *name, PyObject *value) { if (!proxy_checkref(proxy)) return -1; return PyObject_SetAttr(PyWeakref_GET_OBJECT(proxy), name, value); } static PyObject * proxy_richcompare(PyObject *proxy, PyObject *v, int op) { UNWRAP(proxy); UNWRAP(v); return PyObject_RichCompare(proxy, v, op); } /* number slots */ WRAP_BINARY(proxy_add, PyNumber_Add) WRAP_BINARY(proxy_sub, PyNumber_Subtract) WRAP_BINARY(proxy_mul, PyNumber_Multiply) WRAP_BINARY(proxy_floor_div, PyNumber_FloorDivide) WRAP_BINARY(proxy_true_div, PyNumber_TrueDivide) WRAP_BINARY(proxy_mod, PyNumber_Remainder) WRAP_BINARY(proxy_divmod, PyNumber_Divmod) WRAP_TERNARY(proxy_pow, PyNumber_Power) WRAP_UNARY(proxy_neg, PyNumber_Negative) WRAP_UNARY(proxy_pos, PyNumber_Positive) WRAP_UNARY(proxy_abs, PyNumber_Absolute) WRAP_UNARY(proxy_invert, PyNumber_Invert) WRAP_BINARY(proxy_lshift, PyNumber_Lshift) WRAP_BINARY(proxy_rshift, PyNumber_Rshift) WRAP_BINARY(proxy_and, PyNumber_And) WRAP_BINARY(proxy_xor, PyNumber_Xor) WRAP_BINARY(proxy_or, PyNumber_Or) WRAP_UNARY(proxy_int, PyNumber_Long) WRAP_UNARY(proxy_float, PyNumber_Float) WRAP_BINARY(proxy_iadd, PyNumber_InPlaceAdd) WRAP_BINARY(proxy_isub, PyNumber_InPlaceSubtract) WRAP_BINARY(proxy_imul, PyNumber_InPlaceMultiply) WRAP_BINARY(proxy_ifloor_div, PyNumber_InPlaceFloorDivide) WRAP_BINARY(proxy_itrue_div, PyNumber_InPlaceTrueDivide) WRAP_BINARY(proxy_imod, PyNumber_InPlaceRemainder) WRAP_TERNARY(proxy_ipow, PyNumber_InPlacePower) WRAP_BINARY(proxy_ilshift, PyNumber_InPlaceLshift) WRAP_BINARY(proxy_irshift, PyNumber_InPlaceRshift) WRAP_BINARY(proxy_iand, PyNumber_InPlaceAnd) WRAP_BINARY(proxy_ixor, PyNumber_InPlaceXor) WRAP_BINARY(proxy_ior, PyNumber_InPlaceOr) WRAP_UNARY(proxy_index, PyNumber_Index) static int proxy_bool(PyWeakReference *proxy) { PyObject *o = PyWeakref_GET_OBJECT(proxy); if (!proxy_checkref(proxy)) return -1; return PyObject_IsTrue(o); } static void proxy_dealloc(PyWeakReference *self) { if (self->wr_callback != NULL) PyObject_GC_UnTrack((PyObject *)self); clear_weakref(self); PyObject_GC_Del(self); } /* sequence slots */ static int proxy_contains(PyWeakReference *proxy, PyObject *value) { if (!proxy_checkref(proxy)) return -1; return PySequence_Contains(PyWeakref_GET_OBJECT(proxy), value); } /* mapping slots */ static Py_ssize_t proxy_length(PyWeakReference *proxy) { if (!proxy_checkref(proxy)) return -1; return PyObject_Length(PyWeakref_GET_OBJECT(proxy)); } WRAP_BINARY(proxy_getitem, PyObject_GetItem) static int proxy_setitem(PyWeakReference *proxy, PyObject *key, PyObject *value) { if (!proxy_checkref(proxy)) return -1; if (value == NULL) return PyObject_DelItem(PyWeakref_GET_OBJECT(proxy), key); else return PyObject_SetItem(PyWeakref_GET_OBJECT(proxy), key, value); } /* iterator slots */ static PyObject * proxy_iter(PyWeakReference *proxy) { if (!proxy_checkref(proxy)) return NULL; return PyObject_GetIter(PyWeakref_GET_OBJECT(proxy)); } static PyObject * proxy_iternext(PyWeakReference *proxy) { if (!proxy_checkref(proxy)) return NULL; return PyIter_Next(PyWeakref_GET_OBJECT(proxy)); } WRAP_METHOD(proxy_bytes, __bytes__) static PyMethodDef proxy_methods[] = { {"__bytes__", (PyCFunction)proxy_bytes, METH_NOARGS}, {NULL, NULL} }; static PyNumberMethods proxy_as_number = { proxy_add, /*nb_add*/ proxy_sub, /*nb_subtract*/ proxy_mul, /*nb_multiply*/ proxy_mod, /*nb_remainder*/ proxy_divmod, /*nb_divmod*/ proxy_pow, /*nb_power*/ proxy_neg, /*nb_negative*/ proxy_pos, /*nb_positive*/ proxy_abs, /*nb_absolute*/ (inquiry)proxy_bool, /*nb_bool*/ proxy_invert, /*nb_invert*/ proxy_lshift, /*nb_lshift*/ proxy_rshift, /*nb_rshift*/ proxy_and, /*nb_and*/ proxy_xor, /*nb_xor*/ proxy_or, /*nb_or*/ proxy_int, /*nb_int*/ 0, /*nb_reserved*/ proxy_float, /*nb_float*/ proxy_iadd, /*nb_inplace_add*/ proxy_isub, /*nb_inplace_subtract*/ proxy_imul, /*nb_inplace_multiply*/ proxy_imod, /*nb_inplace_remainder*/ proxy_ipow, /*nb_inplace_power*/ proxy_ilshift, /*nb_inplace_lshift*/ proxy_irshift, /*nb_inplace_rshift*/ proxy_iand, /*nb_inplace_and*/ proxy_ixor, /*nb_inplace_xor*/ proxy_ior, /*nb_inplace_or*/ proxy_floor_div, /*nb_floor_divide*/ proxy_true_div, /*nb_true_divide*/ proxy_ifloor_div, /*nb_inplace_floor_divide*/ proxy_itrue_div, /*nb_inplace_true_divide*/ proxy_index, /*nb_index*/ }; static PySequenceMethods proxy_as_sequence = { (lenfunc)proxy_length, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ 0, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ (objobjproc)proxy_contains, /* sq_contains */ }; static PyMappingMethods proxy_as_mapping = { (lenfunc)proxy_length, /*mp_length*/ proxy_getitem, /*mp_subscript*/ (objobjargproc)proxy_setitem, /*mp_ass_subscript*/ }; PyTypeObject _PyWeakref_ProxyType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "weakproxy", sizeof(PyWeakReference), 0, /* methods */ (destructor)proxy_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)proxy_repr, /* tp_repr */ &proxy_as_number, /* tp_as_number */ &proxy_as_sequence, /* tp_as_sequence */ &proxy_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ proxy_str, /* tp_str */ proxy_getattr, /* tp_getattro */ (setattrofunc)proxy_setattr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ (inquiry)gc_clear, /* tp_clear */ proxy_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)proxy_iter, /* tp_iter */ (iternextfunc)proxy_iternext, /* tp_iternext */ proxy_methods, /* tp_methods */ }; PyTypeObject _PyWeakref_CallableProxyType = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "weakcallableproxy", sizeof(PyWeakReference), 0, /* methods */ (destructor)proxy_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (unaryfunc)proxy_repr, /* tp_repr */ &proxy_as_number, /* tp_as_number */ &proxy_as_sequence, /* tp_as_sequence */ &proxy_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ proxy_call, /* tp_call */ proxy_str, /* tp_str */ proxy_getattr, /* tp_getattro */ (setattrofunc)proxy_setattr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ (inquiry)gc_clear, /* tp_clear */ proxy_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)proxy_iter, /* tp_iter */ (iternextfunc)proxy_iternext, /* tp_iternext */ }; PyObject * PyWeakref_NewRef(PyObject *ob, PyObject *callback) { PyWeakReference *result = NULL; PyWeakReference **list; PyWeakReference *ref, *proxy; if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } list = GET_WEAKREFS_LISTPTR(ob); get_basic_refs(*list, &ref, &proxy); if (callback == Py_None) callback = NULL; if (callback == NULL) /* return existing weak reference if it exists */ result = ref; if (result != NULL) Py_INCREF(result); else { /* Note: new_weakref() can trigger cyclic GC, so the weakref list on ob can be mutated. This means that the ref and proxy pointers we got back earlier may have been collected, so we need to compute these values again before we use them. */ result = new_weakref(ob, callback); if (result != NULL) { get_basic_refs(*list, &ref, &proxy); if (callback == NULL) { if (ref == NULL) insert_head(result, list); else { /* Someone else added a ref without a callback during GC. Return that one instead of this one to avoid violating the invariants of the list of weakrefs for ob. */ Py_DECREF(result); Py_INCREF(ref); result = ref; } } else { PyWeakReference *prev; prev = (proxy == NULL) ? ref : proxy; if (prev == NULL) insert_head(result, list); else insert_after(result, prev); } } } return (PyObject *) result; } PyObject * PyWeakref_NewProxy(PyObject *ob, PyObject *callback) { PyWeakReference *result = NULL; PyWeakReference **list; PyWeakReference *ref, *proxy; if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) { PyErr_Format(PyExc_TypeError, "cannot create weak reference to '%s' object", Py_TYPE(ob)->tp_name); return NULL; } list = GET_WEAKREFS_LISTPTR(ob); get_basic_refs(*list, &ref, &proxy); if (callback == Py_None) callback = NULL; if (callback == NULL) /* attempt to return an existing weak reference if it exists */ result = proxy; if (result != NULL) Py_INCREF(result); else { /* Note: new_weakref() can trigger cyclic GC, so the weakref list on ob can be mutated. This means that the ref and proxy pointers we got back earlier may have been collected, so we need to compute these values again before we use them. */ result = new_weakref(ob, callback); if (result != NULL) { PyWeakReference *prev; if (PyCallable_Check(ob)) Py_TYPE(result) = &_PyWeakref_CallableProxyType; else Py_TYPE(result) = &_PyWeakref_ProxyType; get_basic_refs(*list, &ref, &proxy); if (callback == NULL) { if (proxy != NULL) { /* Someone else added a proxy without a callback during GC. Return that one instead of this one to avoid violating the invariants of the list of weakrefs for ob. */ Py_DECREF(result); Py_INCREF(result = proxy); goto skip_insert; } prev = ref; } else prev = (proxy == NULL) ? ref : proxy; if (prev == NULL) insert_head(result, list); else insert_after(result, prev); skip_insert: ; } } return (PyObject *) result; } PyObject * PyWeakref_GetObject(PyObject *ref) { if (ref == NULL || !PyWeakref_Check(ref)) { PyErr_BadInternalCall(); return NULL; } return PyWeakref_GET_OBJECT(ref); } /* Note that there's an inlined copy-paste of handle_callback() in gcmodule.c's * handle_weakrefs(). */ static void handle_callback(PyWeakReference *ref, PyObject *callback) { PyObject *cbresult = PyObject_CallFunctionObjArgs(callback, ref, NULL); if (cbresult == NULL) PyErr_WriteUnraisable(callback); else Py_DECREF(cbresult); } /* This function is called by the tp_dealloc handler to clear weak references. * * This iterates through the weak references for 'object' and calls callbacks * for those references which have one. It returns when all callbacks have * been attempted. */ void PyObject_ClearWeakRefs(PyObject *object) { PyWeakReference **list; if (object == NULL || !PyType_SUPPORTS_WEAKREFS(Py_TYPE(object)) || object->ob_refcnt != 0) { PyErr_BadInternalCall(); return; } list = GET_WEAKREFS_LISTPTR(object); /* Remove the callback-less basic and proxy references */ if (*list != NULL && (*list)->wr_callback == NULL) { clear_weakref(*list); if (*list != NULL && (*list)->wr_callback == NULL) clear_weakref(*list); } if (*list != NULL) { PyWeakReference *current = *list; Py_ssize_t count = _PyWeakref_GetWeakrefCount(current); PyObject *err_type, *err_value, *err_tb; PyErr_Fetch(&err_type, &err_value, &err_tb); if (count == 1) { PyObject *callback = current->wr_callback; current->wr_callback = NULL; clear_weakref(current); if (callback != NULL) { if (((PyObject *)current)->ob_refcnt > 0) handle_callback(current, callback); Py_DECREF(callback); } } else { PyObject *tuple; Py_ssize_t i = 0; tuple = PyTuple_New(count * 2); if (tuple == NULL) { _PyErr_ChainExceptions(err_type, err_value, err_tb); return; } for (i = 0; i < count; ++i) { PyWeakReference *next = current->wr_next; if (((PyObject *)current)->ob_refcnt > 0) { Py_INCREF(current); PyTuple_SET_ITEM(tuple, i * 2, (PyObject *) current); PyTuple_SET_ITEM(tuple, i * 2 + 1, current->wr_callback); } else { Py_DECREF(current->wr_callback); } current->wr_callback = NULL; clear_weakref(current); current = next; } for (i = 0; i < count; ++i) { PyObject *callback = PyTuple_GET_ITEM(tuple, i * 2 + 1); /* The tuple may have slots left to NULL */ if (callback != NULL) { PyObject *item = PyTuple_GET_ITEM(tuple, i * 2); handle_callback((PyWeakReference *)item, callback); } } Py_DECREF(tuple); } assert(!PyErr_Occurred()); PyErr_Restore(err_type, err_value, err_tb); } }
31,402
974
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/unicodectype.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Modules/unicodedata.h" #include "third_party/python/Modules/unicodedata_unidata.h" /* clang-format off */ /* * Unicode character type helpers. * * Written by Marc-Andre Lemburg ([email protected]). * Modified for Python 2.0 by Fredrik Lundh ([email protected]) * * Copyright (c) Corporation for National Research Initiatives. */ #define ALPHA_MASK 0x01 #define DECIMAL_MASK 0x02 #define DIGIT_MASK 0x04 #define LOWER_MASK 0x08 #define LINEBREAK_MASK 0x10 #define SPACE_MASK 0x20 #define TITLE_MASK 0x40 #define UPPER_MASK 0x80 #define XID_START_MASK 0x100 #define XID_CONTINUE_MASK 0x200 #define PRINTABLE_MASK 0x400 #define NUMERIC_MASK 0x800 #define CASE_IGNORABLE_MASK 0x1000 #define CASED_MASK 0x2000 #define EXTENDED_CASE_MASK 0x4000 static const _PyUnicode_TypeRecord * _PyUnicode_GetTypeRecord(Py_UCS4 c) { int i, k; if (c >= 0x110000) { i = 0; } else { k = _PyUnicode_TypeRecordsShift; i = _PyUnicode_TypeRecordsIndex1[(c >> k)]; i = _PyUnicode_TypeRecordsIndex2[(i << k) + (c & ((1 << k) - 1))]; } return &_PyUnicode_TypeRecords[i]; } /* Returns the titlecase Unicode characters corresponding to ch or just ch if no titlecase mapping is known. */ Py_UCS4 _PyUnicode_ToTitlecase(Py_UCS4 ch) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); if (ctype->flags & EXTENDED_CASE_MASK) return _PyUnicode_ExtendedCase[ctype->title & 0xFFFF]; return ch + ctype->title; } /* Returns 1 for Unicode characters having the category 'Lt', 0 otherwise. */ int _PyUnicode_IsTitlecase(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & TITLE_MASK); } /* Returns 1 for Unicode characters having the XID_Start property, 0 otherwise. */ int _PyUnicode_IsXidStart(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & XID_START_MASK); } /* Returns 1 for Unicode characters having the XID_Continue property, 0 otherwise. */ int _PyUnicode_IsXidContinue(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & XID_CONTINUE_MASK); } /* Returns the integer decimal (0-9) for Unicode characters having this property, -1 otherwise. */ int _PyUnicode_ToDecimalDigit(Py_UCS4 ch) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); return (ctype->flags & DECIMAL_MASK) ? ctype->decimal : -1; } int _PyUnicode_IsDecimalDigit(Py_UCS4 ch) { if (_PyUnicode_ToDecimalDigit(ch) < 0) return 0; return 1; } /* Returns the integer digit (0-9) for Unicode characters having this property, -1 otherwise. */ int _PyUnicode_ToDigit(Py_UCS4 ch) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); return (ctype->flags & DIGIT_MASK) ? ctype->digit : -1; } int _PyUnicode_IsDigit(Py_UCS4 ch) { if (_PyUnicode_ToDigit(ch) < 0) return 0; return 1; } /* Returns the numeric value as double for Unicode characters having this property, -1.0 otherwise. */ int _PyUnicode_IsNumeric(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & NUMERIC_MASK); } /* Returns 1 for Unicode characters to be hex-escaped when repr()ed, 0 otherwise. All characters except those characters defined in the Unicode character database as following categories are considered printable. * Cc (Other, Control) * Cf (Other, Format) * Cs (Other, Surrogate) * Co (Other, Private Use) * Cn (Other, Not Assigned) * Zl Separator, Line ('\u2028', LINE SEPARATOR) * Zp Separator, Paragraph ('\u2029', PARAGRAPH SEPARATOR) * Zs (Separator, Space) other than ASCII space('\x20'). */ int _PyUnicode_IsPrintable(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & PRINTABLE_MASK); } /* Returns 1 for Unicode characters having the category 'Ll', 0 otherwise. */ int _PyUnicode_IsLowercase(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & LOWER_MASK); } /* Returns 1 for Unicode characters having the category 'Lu', 0 otherwise. */ int _PyUnicode_IsUppercase(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & UPPER_MASK); } /* Returns the uppercase Unicode characters corresponding to ch or just ch if no uppercase mapping is known. */ Py_UCS4 _PyUnicode_ToUppercase(Py_UCS4 ch) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); if (ctype->flags & EXTENDED_CASE_MASK) return _PyUnicode_ExtendedCase[ctype->upper & 0xFFFF]; return ch + ctype->upper; } /* Returns the lowercase Unicode characters corresponding to ch or just ch if no lowercase mapping is known. */ Py_UCS4 _PyUnicode_ToLowercase(Py_UCS4 ch) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); if (ctype->flags & EXTENDED_CASE_MASK) return _PyUnicode_ExtendedCase[ctype->lower & 0xFFFF]; return ch + ctype->lower; } int _PyUnicode_ToLowerFull(Py_UCS4 ch, Py_UCS4 *res) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); if (ctype->flags & EXTENDED_CASE_MASK) { int index = ctype->lower & 0xFFFF; int n = ctype->lower >> 24; int i; for (i = 0; i < n; i++) res[i] = _PyUnicode_ExtendedCase[index + i]; return n; } res[0] = ch + ctype->lower; return 1; } int _PyUnicode_ToTitleFull(Py_UCS4 ch, Py_UCS4 *res) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); if (ctype->flags & EXTENDED_CASE_MASK) { int index = ctype->title & 0xFFFF; int n = ctype->title >> 24; int i; for (i = 0; i < n; i++) res[i] = _PyUnicode_ExtendedCase[index + i]; return n; } res[0] = ch + ctype->title; return 1; } int _PyUnicode_ToUpperFull(Py_UCS4 ch, Py_UCS4 *res) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); if (ctype->flags & EXTENDED_CASE_MASK) { int index = ctype->upper & 0xFFFF; int n = ctype->upper >> 24; int i; for (i = 0; i < n; i++) res[i] = _PyUnicode_ExtendedCase[index + i]; return n; } res[0] = ch + ctype->upper; return 1; } int _PyUnicode_ToFoldedFull(Py_UCS4 ch, Py_UCS4 *res) { const _PyUnicode_TypeRecord *ctype = _PyUnicode_GetTypeRecord(ch); if (ctype->flags & EXTENDED_CASE_MASK && (ctype->lower >> 20) & 7) { int index = (ctype->lower & 0xFFFF) + (ctype->lower >> 24); int n = (ctype->lower >> 20) & 7; int i; for (i = 0; i < n; i++) res[i] = _PyUnicode_ExtendedCase[index + i]; return n; } return _PyUnicode_ToLowerFull(ch, res); } int _PyUnicode_IsCased(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & CASED_MASK); } int _PyUnicode_IsCaseIgnorable(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & CASE_IGNORABLE_MASK); } /* Returns 1 for Unicode characters having the category 'Ll', 'Lu', 'Lt', 'Lo' or 'Lm', 0 otherwise. */ int _PyUnicode_IsAlpha(Py_UCS4 ch) { return !!(_PyUnicode_GetTypeRecord(ch)->flags & ALPHA_MASK); }
8,062
246
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/frameobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/cellobject.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/genobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/opcode.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/tupleobject.h" /* clang-format off */ #define OFF(x) offsetof(PyFrameObject, x) static PyMemberDef frame_memberlist[] = { {"f_back", T_OBJECT, OFF(f_back), READONLY}, {"f_code", T_OBJECT, OFF(f_code), READONLY}, {"f_builtins", T_OBJECT, OFF(f_builtins), READONLY}, {"f_globals", T_OBJECT, OFF(f_globals), READONLY}, {"f_lasti", T_INT, OFF(f_lasti), READONLY}, {NULL} /* Sentinel */ }; static PyObject * frame_getlocals(PyFrameObject *f, void *closure) { if (PyFrame_FastToLocalsWithError(f) < 0) return NULL; Py_INCREF(f->f_locals); return f->f_locals; } int PyFrame_GetLineNumber(PyFrameObject *f) { if (f->f_trace) return f->f_lineno; else return PyCode_Addr2Line(f->f_code, f->f_lasti); } static PyObject * frame_getlineno(PyFrameObject *f, void *closure) { return PyLong_FromLong(PyFrame_GetLineNumber(f)); } /* Setter for f_lineno - you can set f_lineno from within a trace function in * order to jump to a given line of code, subject to some restrictions. Most * lines are OK to jump to because they don't make any assumptions about the * state of the stack (obvious because you could remove the line and the code * would still work without any stack errors), but there are some constructs * that limit jumping: * * o Lines with an 'except' statement on them can't be jumped to, because * they expect an exception to be on the top of the stack. * o Lines that live in a 'finally' block can't be jumped from or to, since * the END_FINALLY expects to clean up the stack after the 'try' block. * o 'try'/'for'/'while' blocks can't be jumped into because the blockstack * needs to be set up before their code runs, and for 'for' loops the * iterator needs to be on the stack. * o Jumps cannot be made from within a trace function invoked with a * 'return' or 'exception' event since the eval loop has been exited at * that time. */ static int frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno, void *Py_UNUSED(ignored)) { int new_lineno = 0; /* The new value of f_lineno */ long l_new_lineno; int overflow; int new_lasti = 0; /* The new value of f_lasti */ int new_iblock = 0; /* The new value of f_iblock */ unsigned char *code = NULL; /* The bytecode for the frame... */ Py_ssize_t code_len = 0; /* ...and its length */ unsigned char *lnotab = NULL; /* Iterating over co_lnotab */ Py_ssize_t lnotab_len = 0; /* (ditto) */ int offset = 0; /* (ditto) */ int line = 0; /* (ditto) */ int addr = 0; /* (ditto) */ int min_addr = 0; /* Scanning the SETUPs and POPs */ int max_addr = 0; /* (ditto) */ int delta_iblock = 0; /* (ditto) */ int min_delta_iblock = 0; /* (ditto) */ int min_iblock = 0; /* (ditto) */ int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */ int new_lasti_setup_addr = 0; /* (ditto) */ int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */ int in_finally[CO_MAXBLOCKS]; /* (ditto) */ int blockstack_top = 0; /* (ditto) */ unsigned char setup_op = 0; /* (ditto) */ /* f_lineno must be an integer. */ if (!PyLong_CheckExact(p_new_lineno)) { PyErr_SetString(PyExc_ValueError, "lineno must be an integer"); return -1; } /* Upon the 'call' trace event of a new frame, f->f_lasti is -1 and * f->f_trace is NULL, check first on the first condition. * Forbidding jumps from the 'call' event of a new frame is a side effect * of allowing to set f_lineno only from trace functions. */ if (f->f_lasti == -1) { PyErr_Format(PyExc_ValueError, "can't jump from the 'call' trace event of a new frame"); return -1; } /* You can only do this from within a trace function, not via * _getframe or similar hackery. */ if (!f->f_trace) { PyErr_Format(PyExc_ValueError, "f_lineno can only be set by a trace function"); return -1; } /* Forbid jumps upon a 'return' trace event (except after executing a * YIELD_VALUE or YIELD_FROM opcode, f_stacktop is not NULL in that case) * and upon an 'exception' trace event. * Jumps from 'call' trace events have already been forbidden above for new * frames, so this check does not change anything for 'call' events. */ if (f->f_stacktop == NULL) { PyErr_SetString(PyExc_ValueError, "can only jump from a 'line' trace event"); return -1; } /* Fail if the line comes before the start of the code block. */ l_new_lineno = PyLong_AsLongAndOverflow(p_new_lineno, &overflow); if (overflow #if SIZEOF_LONG > SIZEOF_INT || l_new_lineno > INT_MAX || l_new_lineno < INT_MIN #endif ) { PyErr_SetString(PyExc_ValueError, "lineno out of range"); return -1; } new_lineno = (int)l_new_lineno; if (new_lineno < f->f_code->co_firstlineno) { PyErr_Format(PyExc_ValueError, "line %d comes before the current code block", new_lineno); return -1; } else if (new_lineno == f->f_code->co_firstlineno) { new_lasti = 0; new_lineno = f->f_code->co_firstlineno; } else { /* Find the bytecode offset for the start of the given * line, or the first code-owning line after it. */ char *tmp; PyBytes_AsStringAndSize(f->f_code->co_lnotab, &tmp, &lnotab_len); lnotab = (unsigned char *) tmp; addr = 0; line = f->f_code->co_firstlineno; new_lasti = -1; for (offset = 0; offset < lnotab_len; offset += 2) { addr += lnotab[offset]; line += (signed char)lnotab[offset+1]; if (line >= new_lineno) { new_lasti = addr; new_lineno = line; break; } } } /* If we didn't reach the requested line, return an error. */ if (new_lasti == -1) { PyErr_Format(PyExc_ValueError, "line %d comes after the current code block", new_lineno); return -1; } /* We're now ready to look at the bytecode. */ PyBytes_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len); /* The trace function is called with a 'return' trace event after the * execution of a yield statement. */ assert(f->f_lasti != -1); if (code[f->f_lasti] == YIELD_VALUE || code[f->f_lasti] == YIELD_FROM) { PyErr_SetString(PyExc_ValueError, "can't jump from a yield statement"); return -1; } min_addr = Py_MIN(new_lasti, f->f_lasti); max_addr = Py_MAX(new_lasti, f->f_lasti); /* You can't jump onto a line with an 'except' statement on it - * they expect to have an exception on the top of the stack, which * won't be true if you jump to them. They always start with code * that either pops the exception using POP_TOP (plain 'except:' * lines do this) or duplicates the exception on the stack using * DUP_TOP (if there's an exception type specified). See compile.c, * 'com_try_except' for the full details. There aren't any other * cases (AFAIK) where a line's code can start with DUP_TOP or * POP_TOP, but if any ever appear, they'll be subject to the same * restriction (but with a different error message). */ if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) { PyErr_SetString(PyExc_ValueError, "can't jump to 'except' line as there's no exception"); return -1; } /* You can't jump into or out of a 'finally' block because the 'try' * block leaves something on the stack for the END_FINALLY to clean * up. So we walk the bytecode, maintaining a simulated blockstack. * When we reach the old or new address and it's in a 'finally' block * we note the address of the corresponding SETUP_FINALLY. The jump * is only legal if neither address is in a 'finally' block or * they're both in the same one. 'blockstack' is a stack of the * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks * whether we're in a 'finally' block at each blockstack level. */ f_lasti_setup_addr = -1; new_lasti_setup_addr = -1; bzero(blockstack, sizeof(blockstack)); bzero(in_finally, sizeof(in_finally)); blockstack_top = 0; for (addr = 0; addr < code_len; addr += sizeof(_Py_CODEUNIT)) { unsigned char op = code[addr]; switch (op) { case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: case SETUP_ASYNC_WITH: blockstack[blockstack_top++] = addr; in_finally[blockstack_top-1] = 0; break; case POP_BLOCK: assert(blockstack_top > 0); setup_op = code[blockstack[blockstack_top-1]]; if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH || setup_op == SETUP_ASYNC_WITH) { in_finally[blockstack_top-1] = 1; } else { blockstack_top--; } break; case END_FINALLY: /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist * in the bytecode but don't correspond to an actual * 'finally' block. (If blockstack_top is 0, we must * be seeing such an END_FINALLY.) */ if (blockstack_top > 0) { setup_op = code[blockstack[blockstack_top-1]]; if (setup_op == SETUP_FINALLY || setup_op == SETUP_WITH || setup_op == SETUP_ASYNC_WITH) { blockstack_top--; } } break; } /* For the addresses we're interested in, see whether they're * within a 'finally' block and if so, remember the address * of the SETUP_FINALLY. */ if (addr == new_lasti || addr == f->f_lasti) { int i = 0; int setup_addr = -1; for (i = blockstack_top-1; i >= 0; i--) { if (in_finally[i]) { setup_addr = blockstack[i]; break; } } if (setup_addr != -1) { if (addr == new_lasti) { new_lasti_setup_addr = setup_addr; } if (addr == f->f_lasti) { f_lasti_setup_addr = setup_addr; } } } } /* Verify that the blockstack tracking code didn't get lost. */ assert(blockstack_top == 0); /* After all that, are we jumping into / out of a 'finally' block? */ if (new_lasti_setup_addr != f_lasti_setup_addr) { PyErr_SetString(PyExc_ValueError, "can't jump into or out of a 'finally' block"); return -1; } /* Police block-jumping (you can't jump into the middle of a block) * and ensure that the blockstack finishes up in a sensible state (by * popping any blocks we're jumping out of). We look at all the * blockstack operations between the current position and the new * one, and keep track of how many blocks we drop out of on the way. * By also keeping track of the lowest blockstack position we see, we * can tell whether the jump goes into any blocks without coming out * again - in that case we raise an exception below. */ delta_iblock = 0; for (addr = min_addr; addr < max_addr; addr += sizeof(_Py_CODEUNIT)) { unsigned char op = code[addr]; switch (op) { case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: case SETUP_WITH: case SETUP_ASYNC_WITH: delta_iblock++; break; case POP_BLOCK: delta_iblock--; break; } min_delta_iblock = Py_MIN(min_delta_iblock, delta_iblock); } /* Derive the absolute iblock values from the deltas. */ min_iblock = f->f_iblock + min_delta_iblock; if (new_lasti > f->f_lasti) { /* Forwards jump. */ new_iblock = f->f_iblock + delta_iblock; } else { /* Backwards jump. */ new_iblock = f->f_iblock - delta_iblock; } /* Are we jumping into a block? */ if (new_iblock > min_iblock) { PyErr_SetString(PyExc_ValueError, "can't jump into the middle of a block"); return -1; } /* Pop any blocks that we're jumping out of. */ while (f->f_iblock > new_iblock) { PyTryBlock *b = &f->f_blockstack[--f->f_iblock]; while ((f->f_stacktop - f->f_valuestack) > b->b_level) { PyObject *v = (*--f->f_stacktop); Py_DECREF(v); } if (b->b_type == SETUP_FINALLY && code[b->b_handler] == WITH_CLEANUP_START) { /* Pop the exit function. */ PyObject *v = (*--f->f_stacktop); Py_DECREF(v); } } /* Finally set the new f_lineno and f_lasti and return OK. */ f->f_lineno = new_lineno; f->f_lasti = new_lasti; return 0; } static PyObject * frame_gettrace(PyFrameObject *f, void *closure) { PyObject* trace = f->f_trace; if (trace == NULL) trace = Py_None; Py_INCREF(trace); return trace; } static int frame_settrace(PyFrameObject *f, PyObject* v, void *closure) { /* We rely on f_lineno being accurate when f_trace is set. */ f->f_lineno = PyFrame_GetLineNumber(f); if (v == Py_None) v = NULL; Py_XINCREF(v); Py_XSETREF(f->f_trace, v); return 0; } static PyGetSetDef frame_getsetlist[] = { {"f_locals", (getter)frame_getlocals, NULL, NULL}, {"f_lineno", (getter)frame_getlineno, (setter)frame_setlineno, NULL}, {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL}, {0} }; /* Stack frames are allocated and deallocated at a considerable rate. In an attempt to improve the speed of function calls, we: 1. Hold a single "zombie" frame on each code object. This retains the allocated and initialised frame object from an invocation of the code object. The zombie is reanimated the next time we need a frame object for that code object. Doing this saves the malloc/ realloc required when using a free_list frame that isn't the correct size. It also saves some field initialisation. In zombie mode, no field of PyFrameObject holds a reference, but the following fields are still valid: * ob_type, ob_size, f_code, f_valuestack; * f_locals, f_trace, f_exc_type, f_exc_value, f_exc_traceback are NULL; * f_localsplus does not require re-allocation and the local variables in f_localsplus are NULL. 2. We also maintain a separate free list of stack frames (just like floats are allocated in a special way -- see floatobject.c). When a stack frame is on the free list, only the following members have a meaning: ob_type == &Frametype f_back next item on free list, or NULL f_stacksize size of value stack ob_size size of localsplus Note that the value and block stacks are preserved -- this can save another malloc() call or two (and two free() calls as well!). Also note that, unlike for integers, each frame object is a malloc'ed object in its own right -- it is only the actual calls to malloc() that we are trying to save here, not the administration. After all, while a typical program may make millions of calls, a call depth of more than 20 or 30 is probably already exceptional unless the program contains run-away recursion. I hope. Later, PyFrame_MAXFREELIST was added to bound the # of frames saved on free_list. Else programs creating lots of cyclic trash involving frames could provoke free_list into growing without bound. */ static int numfree; static PyFrameObject *free_list; #define PyFrame_MAXFREELIST 200 static void _Py_HOT_FUNCTION frame_dealloc(PyFrameObject *restrict f) { PyObject **p, **valuestack; PyCodeObject *co; if (_PyObject_GC_IS_TRACKED(f)) _PyObject_GC_UNTRACK(f); Py_TRASHCAN_SAFE_BEGIN(f) /* Kill all local variables */ valuestack = f->f_valuestack; for (p = f->f_localsplus; p < valuestack; p++) Py_CLEAR(*p); /* Free stack */ if (UNLIKELY(f->f_stacktop != NULL)) { /* 0% taken */ for (p = valuestack; p < f->f_stacktop; p++) Py_XDECREF(*p); } Py_XDECREF(f->f_back); Py_DECREF(f->f_builtins); Py_DECREF(f->f_globals); Py_CLEAR(f->f_locals); Py_CLEAR(f->f_trace); Py_CLEAR(f->f_exc_type); Py_CLEAR(f->f_exc_value); Py_CLEAR(f->f_exc_traceback); co = f->f_code; if (co->co_zombieframe == NULL) co->co_zombieframe = f; else if (numfree < PyFrame_MAXFREELIST) { ++numfree; f->f_back = free_list; free_list = f; } else PyObject_GC_Del(f); Py_DECREF(co); Py_TRASHCAN_SAFE_END(f) } static int frame_traverse(PyFrameObject *f, visitproc visit, void *arg) { PyObject **fastlocals, **p; Py_ssize_t i, slots; Py_VISIT(f->f_back); Py_VISIT(f->f_code); Py_VISIT(f->f_builtins); Py_VISIT(f->f_globals); Py_VISIT(f->f_locals); Py_VISIT(f->f_trace); Py_VISIT(f->f_exc_type); Py_VISIT(f->f_exc_value); Py_VISIT(f->f_exc_traceback); /* locals */ slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); fastlocals = f->f_localsplus; for (i = slots; --i >= 0; ++fastlocals) Py_VISIT(*fastlocals); /* stack */ if (f->f_stacktop != NULL) { for (p = f->f_valuestack; p < f->f_stacktop; p++) Py_VISIT(*p); } return 0; } static int frame_tp_clear(PyFrameObject *f) { PyObject **fastlocals, **p, **oldtop; Py_ssize_t i, slots; /* Before anything else, make sure that this frame is clearly marked * as being defunct! Else, e.g., a generator reachable from this * frame may also point to this frame, believe itself to still be * active, and try cleaning up this frame again. */ oldtop = f->f_stacktop; f->f_stacktop = NULL; f->f_executing = 0; Py_CLEAR(f->f_exc_type); Py_CLEAR(f->f_exc_value); Py_CLEAR(f->f_exc_traceback); Py_CLEAR(f->f_trace); /* locals */ slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars); fastlocals = f->f_localsplus; for (i = slots; --i >= 0; ++fastlocals) Py_CLEAR(*fastlocals); /* stack */ if (oldtop != NULL) { for (p = f->f_valuestack; p < oldtop; p++) Py_CLEAR(*p); } return 0; } static PyObject * frame_clear(PyFrameObject *f) { if (f->f_executing) { PyErr_SetString(PyExc_RuntimeError, "cannot clear an executing frame"); return NULL; } if (f->f_gen) { _PyGen_Finalize(f->f_gen); assert(f->f_gen == NULL); } (void)frame_tp_clear(f); Py_RETURN_NONE; } PyDoc_STRVAR(clear__doc__, "F.clear(): clear most references held by the frame"); static PyObject * frame_sizeof(PyFrameObject *f) { Py_ssize_t res, extras, ncells, nfrees; ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars); nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars); extras = f->f_code->co_stacksize + f->f_code->co_nlocals + ncells + nfrees; /* subtract one as it is already included in PyFrameObject */ res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *); return PyLong_FromSsize_t(res); } PyDoc_STRVAR(sizeof__doc__, "F.__sizeof__() -> size of F in memory, in bytes"); static PyMethodDef frame_methods[] = { {"clear", (PyCFunction)frame_clear, METH_NOARGS, clear__doc__}, {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS, sizeof__doc__}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyFrame_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "frame", sizeof(PyFrameObject), sizeof(PyObject *), (destructor)frame_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)frame_traverse, /* tp_traverse */ (inquiry)frame_tp_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ frame_methods, /* tp_methods */ frame_memberlist, /* tp_members */ frame_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ }; _Py_IDENTIFIER(__builtins__); int _PyFrame_Init() { /* Before, PyId___builtins__ was a string created explicitly in this function. Now there is nothing to initialize anymore, but the function is kept for backward compatibility. */ return 1; } PyFrameObject* _Py_HOT_FUNCTION _PyFrame_New_NoTrack(PyThreadState *tstate, PyCodeObject *code, PyObject *globals, PyObject *locals) { PyFrameObject *back = tstate->frame; PyFrameObject *f; PyObject *builtins; Py_ssize_t i; #ifdef Py_DEBUG if (code == NULL || globals == NULL || !PyDict_Check(globals) || (locals != NULL && !PyMapping_Check(locals))) { PyErr_BadInternalCall(); return NULL; } #endif if (back == NULL || back->f_globals != globals) { builtins = _PyDict_GetItemId(globals, &PyId___builtins__); if (builtins) { if (PyModule_Check(builtins)) { builtins = PyModule_GetDict(builtins); assert(builtins != NULL); } } if (builtins == NULL) { /* No builtins! Make up a minimal one Give them 'None', at least. */ builtins = PyDict_New(); if (builtins == NULL || PyDict_SetItemString( builtins, "None", Py_None) < 0) return NULL; } else Py_INCREF(builtins); } else { /* If we share the globals, we share the builtins. Save a lookup and a call. */ builtins = back->f_builtins; assert(builtins != NULL); Py_INCREF(builtins); } if (code->co_zombieframe != NULL) { f = code->co_zombieframe; code->co_zombieframe = NULL; _Py_NewReference((PyObject *)f); assert(f->f_code == code); } else { Py_ssize_t extras, ncells, nfrees; ncells = PyTuple_GET_SIZE(code->co_cellvars); nfrees = PyTuple_GET_SIZE(code->co_freevars); extras = code->co_stacksize + code->co_nlocals + ncells + nfrees; if (free_list == NULL) { f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras); if (f == NULL) { Py_DECREF(builtins); return NULL; } } else { assert(numfree > 0); --numfree; f = free_list; free_list = free_list->f_back; if (Py_SIZE(f) < extras) { PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras); if (new_f == NULL) { PyObject_GC_Del(f); Py_DECREF(builtins); return NULL; } f = new_f; } _Py_NewReference((PyObject *)f); } f->f_code = code; extras = code->co_nlocals + ncells + nfrees; f->f_valuestack = f->f_localsplus + extras; for (i=0; i<extras; i++) f->f_localsplus[i] = NULL; f->f_locals = NULL; f->f_trace = NULL; f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; } f->f_stacktop = f->f_valuestack; f->f_builtins = builtins; Py_XINCREF(back); f->f_back = back; Py_INCREF(code); Py_INCREF(globals); f->f_globals = globals; /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == (CO_NEWLOCALS | CO_OPTIMIZED)) ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */ else if (code->co_flags & CO_NEWLOCALS) { locals = PyDict_New(); if (locals == NULL) { Py_DECREF(f); return NULL; } f->f_locals = locals; } else { if (locals == NULL) locals = globals; Py_INCREF(locals); f->f_locals = locals; } f->f_lasti = -1; f->f_lineno = code->co_firstlineno; f->f_iblock = 0; f->f_executing = 0; f->f_gen = NULL; return f; } PyFrameObject* PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals, PyObject *locals) { PyFrameObject *f = _PyFrame_New_NoTrack(tstate, code, globals, locals); if (f) _PyObject_GC_TRACK(f); return f; } /* Block management */ void PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level) { PyTryBlock *b; if (f->f_iblock >= CO_MAXBLOCKS) Py_FatalError("XXX block stack overflow"); b = &f->f_blockstack[f->f_iblock++]; b->b_type = type; b->b_level = level; b->b_handler = handler; } PyTryBlock * PyFrame_BlockPop(PyFrameObject *f) { PyTryBlock *b; if (f->f_iblock <= 0) Py_FatalError("XXX block stack underflow"); b = &f->f_blockstack[--f->f_iblock]; return b; } /* Convert between "fast" version of locals and dictionary version. map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, the variable is deleted from dict. If deref is true, then the values being copied are cell variables and the value is extracted from the cell variable before being put in dict. */ static int map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, int deref) { Py_ssize_t j; assert(PyTuple_Check(map)); assert(PyDict_Check(dict)); assert(PyTuple_Size(map) >= nmap); for (j = nmap; --j >= 0; ) { PyObject *key = PyTuple_GET_ITEM(map, j); PyObject *value = values[j]; assert(PyUnicode_Check(key)); if (deref && value != NULL) { assert(PyCell_Check(value)); value = PyCell_GET(value); } if (value == NULL) { if (PyObject_DelItem(dict, key) != 0) { if (PyErr_ExceptionMatches(PyExc_KeyError)) PyErr_Clear(); else return -1; } } else { if (PyObject_SetItem(dict, key, value) != 0) return -1; } } return 0; } /* Copy values from the "locals" dict into the fast locals. dict is an input argument containing string keys representing variables names and arbitrary PyObject* as values. map and values are input arguments. map is a tuple of strings. values is an array of PyObject*. At index i, map[i] is the name of the variable with value values[i]. The function copies the first nmap variable from map/values into dict. If values[i] is NULL, the variable is deleted from dict. If deref is true, then the values being copied are cell variables and the value is extracted from the cell variable before being put in dict. If clear is true, then variables in map but not in dict are set to NULL in map; if clear is false, variables missing in dict are ignored. Exceptions raised while modifying the dict are silently ignored, because there is no good way to report them. */ static void dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values, int deref, int clear) { Py_ssize_t j; assert(PyTuple_Check(map)); assert(PyDict_Check(dict)); assert(PyTuple_Size(map) >= nmap); for (j = nmap; --j >= 0; ) { PyObject *key = PyTuple_GET_ITEM(map, j); PyObject *value = PyObject_GetItem(dict, key); assert(PyUnicode_Check(key)); /* We only care about NULLs if clear is true. */ if (value == NULL) { PyErr_Clear(); if (!clear) continue; } if (deref) { assert(PyCell_Check(values[j])); if (PyCell_GET(values[j]) != value) { if (PyCell_Set(values[j], value) < 0) PyErr_Clear(); } } else if (values[j] != value) { Py_XINCREF(value); Py_XSETREF(values[j], value); } Py_XDECREF(value); } } int PyFrame_FastToLocalsWithError(PyFrameObject *f) { /* Merge fast locals into f->f_locals */ PyObject *locals, *map; PyObject **fast; PyCodeObject *co; Py_ssize_t j; Py_ssize_t ncells, nfreevars; if (f == NULL) { PyErr_BadInternalCall(); return -1; } locals = f->f_locals; if (locals == NULL) { locals = f->f_locals = PyDict_New(); if (locals == NULL) return -1; } co = f->f_code; map = co->co_varnames; if (!PyTuple_Check(map)) { PyErr_Format(PyExc_SystemError, "co_varnames must be a tuple, not %s", Py_TYPE(map)->tp_name); return -1; } fast = f->f_localsplus; j = PyTuple_GET_SIZE(map); if (j > co->co_nlocals) j = co->co_nlocals; if (co->co_nlocals) { if (map_to_dict(map, j, locals, fast, 0) < 0) return -1; } ncells = PyTuple_GET_SIZE(co->co_cellvars); nfreevars = PyTuple_GET_SIZE(co->co_freevars); if (ncells || nfreevars) { if (map_to_dict(co->co_cellvars, ncells, locals, fast + co->co_nlocals, 1)) return -1; /* If the namespace is unoptimized, then one of the following cases applies: 1. It does not contain free variables, because it uses import * or is a top-level namespace. 2. It is a class namespace. We don't want to accidentally copy free variables into the locals dict used by the class. */ if (co->co_flags & CO_OPTIMIZED) { if (map_to_dict(co->co_freevars, nfreevars, locals, fast + co->co_nlocals + ncells, 1) < 0) return -1; } } return 0; } void PyFrame_FastToLocals(PyFrameObject *f) { int res; assert(!PyErr_Occurred()); res = PyFrame_FastToLocalsWithError(f); if (res < 0) PyErr_Clear(); } void PyFrame_LocalsToFast(PyFrameObject *f, int clear) { /* Merge f->f_locals into fast locals */ PyObject *locals, *map; PyObject **fast; PyObject *error_type, *error_value, *error_traceback; PyCodeObject *co; Py_ssize_t j; Py_ssize_t ncells, nfreevars; if (f == NULL) return; locals = f->f_locals; co = f->f_code; map = co->co_varnames; if (locals == NULL) return; if (!PyTuple_Check(map)) return; PyErr_Fetch(&error_type, &error_value, &error_traceback); fast = f->f_localsplus; j = PyTuple_GET_SIZE(map); if (j > co->co_nlocals) j = co->co_nlocals; if (co->co_nlocals) dict_to_map(co->co_varnames, j, locals, fast, 0, clear); ncells = PyTuple_GET_SIZE(co->co_cellvars); nfreevars = PyTuple_GET_SIZE(co->co_freevars); if (ncells || nfreevars) { dict_to_map(co->co_cellvars, ncells, locals, fast + co->co_nlocals, 1, clear); /* Same test as in PyFrame_FastToLocals() above. */ if (co->co_flags & CO_OPTIMIZED) { dict_to_map(co->co_freevars, nfreevars, locals, fast + co->co_nlocals + ncells, 1, clear); } } PyErr_Restore(error_type, error_value, error_traceback); } /* Clear out the free list */ int PyFrame_ClearFreeList(void) { int freelist_size = numfree; while (free_list != NULL) { PyFrameObject *f = free_list; free_list = free_list->f_back; PyObject_GC_Del(f); --numfree; } assert(numfree == 0); return freelist_size; } void PyFrame_Fini(void) { (void)PyFrame_ClearFreeList(); } /* Print summary info about the state of the optimized allocator */ void _PyFrame_DebugMallocStats(FILE *out) { _PyDebugAllocatorStats(out, "free PyFrameObject", numfree, sizeof(PyFrameObject)); }
36,360
1,063
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/bytes_methods.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytes_methods.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" /* clang-format off */ PyDoc_STRVAR_shared(_Py_isspace__doc__, "B.isspace() -> bool\n\ \n\ Return True if all characters in B are whitespace\n\ and there is at least one character in B, False otherwise."); PyObject* _Py_bytes_isspace(const char *cptr, Py_ssize_t len) { const unsigned char *p = (unsigned char *) cptr; const unsigned char *e; /* Shortcut for single character strings */ if (len == 1 && Py_ISSPACE(*p)) Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { if (!Py_ISSPACE(*p)) Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyDoc_STRVAR_shared(_Py_isalpha__doc__, "B.isalpha() -> bool\n\ \n\ Return True if all characters in B are alphabetic\n\ and there is at least one character in B, False otherwise."); PyObject* _Py_bytes_isalpha(const char *cptr, Py_ssize_t len) { const unsigned char *p = (unsigned char *) cptr; const unsigned char *e; /* Shortcut for single character strings */ if (len == 1 && Py_ISALPHA(*p)) Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { if (!Py_ISALPHA(*p)) Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyDoc_STRVAR_shared(_Py_isalnum__doc__, "B.isalnum() -> bool\n\ \n\ Return True if all characters in B are alphanumeric\n\ and there is at least one character in B, False otherwise."); PyObject* _Py_bytes_isalnum(const char *cptr, Py_ssize_t len) { const unsigned char *p = (unsigned char *) cptr; const unsigned char *e; /* Shortcut for single character strings */ if (len == 1 && Py_ISALNUM(*p)) Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { if (!Py_ISALNUM(*p)) Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyDoc_STRVAR_shared(_Py_isdigit__doc__, "B.isdigit() -> bool\n\ \n\ Return True if all characters in B are digits\n\ and there is at least one character in B, False otherwise."); PyObject* _Py_bytes_isdigit(const char *cptr, Py_ssize_t len) { const unsigned char *p = (unsigned char *) cptr; const unsigned char *e; /* Shortcut for single character strings */ if (len == 1 && Py_ISDIGIT(*p)) Py_RETURN_TRUE; /* Special case for empty strings */ if (len == 0) Py_RETURN_FALSE; e = p + len; for (; p < e; p++) { if (!Py_ISDIGIT(*p)) Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyDoc_STRVAR_shared(_Py_islower__doc__, "B.islower() -> bool\n\ \n\ Return True if all cased characters in B are lowercase and there is\n\ at least one cased character in B, False otherwise."); PyObject* _Py_bytes_islower(const char *cptr, Py_ssize_t len) { const unsigned char *p = (unsigned char *) cptr; const unsigned char *e; int cased; /* Shortcut for single character strings */ if (len == 1) return PyBool_FromLong(Py_ISLOWER(*p)); /* Special case for empty strings */ if (len == 0) Py_RETURN_FALSE; e = p + len; cased = 0; for (; p < e; p++) { if (Py_ISUPPER(*p)) Py_RETURN_FALSE; else if (!cased && Py_ISLOWER(*p)) cased = 1; } return PyBool_FromLong(cased); } PyDoc_STRVAR_shared(_Py_isupper__doc__, "B.isupper() -> bool\n\ \n\ Return True if all cased characters in B are uppercase and there is\n\ at least one cased character in B, False otherwise."); PyObject* _Py_bytes_isupper(const char *cptr, Py_ssize_t len) { const unsigned char *p = (unsigned char *) cptr; const unsigned char *e; int cased; /* Shortcut for single character strings */ if (len == 1) return PyBool_FromLong(Py_ISUPPER(*p)); /* Special case for empty strings */ if (len == 0) Py_RETURN_FALSE; e = p + len; cased = 0; for (; p < e; p++) { if (Py_ISLOWER(*p)) Py_RETURN_FALSE; else if (!cased && Py_ISUPPER(*p)) cased = 1; } return PyBool_FromLong(cased); } PyDoc_STRVAR_shared(_Py_istitle__doc__, "B.istitle() -> bool\n\ \n\ Return True if B is a titlecased string and there is at least one\n\ character in B, i.e. uppercase characters may only follow uncased\n\ characters and lowercase characters only cased ones. Return False\n\ otherwise."); PyObject* _Py_bytes_istitle(const char *cptr, Py_ssize_t len) { const unsigned char *p = (unsigned char *) cptr; const unsigned char *e; int cased, previous_is_cased; /* Shortcut for single character strings */ if (len == 1) return PyBool_FromLong(Py_ISUPPER(*p)); /* Special case for empty strings */ if (len == 0) Py_RETURN_FALSE; e = p + len; cased = 0; previous_is_cased = 0; for (; p < e; p++) { const unsigned char ch = *p; if (Py_ISUPPER(ch)) { if (previous_is_cased) Py_RETURN_FALSE; previous_is_cased = 1; cased = 1; } else if (Py_ISLOWER(ch)) { if (!previous_is_cased) Py_RETURN_FALSE; previous_is_cased = 1; cased = 1; } else previous_is_cased = 0; } return PyBool_FromLong(cased); } PyDoc_STRVAR_shared(_Py_lower__doc__, "B.lower() -> copy of B\n\ \n\ Return a copy of B with all ASCII characters converted to lowercase."); void _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len) { Py_ssize_t i; for (i = 0; i < len; i++) { result[i] = Py_TOLOWER((unsigned char) cptr[i]); } } PyDoc_STRVAR_shared(_Py_upper__doc__, "B.upper() -> copy of B\n\ \n\ Return a copy of B with all ASCII characters converted to uppercase."); void _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len) { Py_ssize_t i; for (i = 0; i < len; i++) { result[i] = Py_TOUPPER((unsigned char) cptr[i]); } } PyDoc_STRVAR_shared(_Py_title__doc__, "B.title() -> copy of B\n\ \n\ Return a titlecased version of B, i.e. ASCII words start with uppercase\n\ characters, all remaining cased characters have lowercase."); void _Py_bytes_title(char *result, const char *s, Py_ssize_t len) { Py_ssize_t i; int previous_is_cased = 0; for (i = 0; i < len; i++) { int c = Py_CHARMASK(*s++); if (Py_ISLOWER(c)) { if (!previous_is_cased) c = Py_TOUPPER(c); previous_is_cased = 1; } else if (Py_ISUPPER(c)) { if (previous_is_cased) c = Py_TOLOWER(c); previous_is_cased = 1; } else previous_is_cased = 0; *result++ = c; } } PyDoc_STRVAR_shared(_Py_capitalize__doc__, "B.capitalize() -> copy of B\n\ \n\ Return a copy of B with only its first character capitalized (ASCII)\n\ and the rest lower-cased."); void _Py_bytes_capitalize(char *result, const char *s, Py_ssize_t len) { Py_ssize_t i; if (0 < len) { int c = Py_CHARMASK(*s++); if (Py_ISLOWER(c)) *result = Py_TOUPPER(c); else *result = c; result++; } for (i = 1; i < len; i++) { int c = Py_CHARMASK(*s++); if (Py_ISUPPER(c)) *result = Py_TOLOWER(c); else *result = c; result++; } } PyDoc_STRVAR_shared(_Py_swapcase__doc__, "B.swapcase() -> copy of B\n\ \n\ Return a copy of B with uppercase ASCII characters converted\n\ to lowercase ASCII and vice versa."); void _Py_bytes_swapcase(char *result, const char *s, Py_ssize_t len) { Py_ssize_t i; for (i = 0; i < len; i++) { int c = Py_CHARMASK(*s++); if (Py_ISLOWER(c)) { *result = Py_TOUPPER(c); } else if (Py_ISUPPER(c)) { *result = Py_TOLOWER(c); } else *result = c; result++; } } PyDoc_STRVAR_shared(_Py_maketrans__doc__, "B.maketrans(frm, to) -> translation table\n\ \n\ Return a translation table (a bytes object of length 256) suitable\n\ for use in the bytes or bytearray translate method where each byte\n\ in frm is mapped to the byte at the same position in to.\n\ The bytes objects frm and to must be of the same length."); PyObject * _Py_bytes_maketrans(Py_buffer *frm, Py_buffer *to) { PyObject *res = NULL; Py_ssize_t i; char *p; if (frm->len != to->len) { PyErr_Format(PyExc_ValueError, "maketrans arguments must have same length"); return NULL; } res = PyBytes_FromStringAndSize(NULL, 256); if (!res) return NULL; p = PyBytes_AS_STRING(res); for (i = 0; i < 256; i++) p[i] = (char) i; for (i = 0; i < frm->len; i++) { p[((unsigned char *)frm->buf)[i]] = ((char *)to->buf)[i]; } return res; } #define FASTSEARCH fastsearch #define STRINGLIB(F) stringlib_##F #define STRINGLIB_CHAR char #define STRINGLIB_SIZEOF_CHAR 1 #include "third_party/python/Objects/stringlib/fastsearch.inc" #include "third_party/python/Objects/stringlib/count.inc" #include "third_party/python/Objects/stringlib/find.inc" /* Wraps stringlib_parse_args_finds() and additionally checks whether the first argument is an integer in range(0, 256). If this is the case, writes the integer value to the byte parameter and sets subobj to NULL. Otherwise, sets the first argument to subobj and doesn't touch byte. The other parameters are similar to those of stringlib_parse_args_finds(). */ Py_LOCAL_INLINE(int) parse_args_finds_byte(const char *function_name, PyObject *args, PyObject **subobj, char *byte, Py_ssize_t *start, Py_ssize_t *end) { PyObject *tmp_subobj; Py_ssize_t ival; PyObject *err; if(!stringlib_parse_args_finds(function_name, args, &tmp_subobj, start, end)) return 0; if (!PyNumber_Check(tmp_subobj)) { *subobj = tmp_subobj; return 1; } ival = PyNumber_AsSsize_t(tmp_subobj, PyExc_OverflowError); if (ival == -1) { err = PyErr_Occurred(); if (err && !PyErr_GivenExceptionMatches(err, PyExc_OverflowError)) { PyErr_Clear(); *subobj = tmp_subobj; return 1; } } if (ival < 0 || ival > 255) { PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); return 0; } *subobj = NULL; *byte = (char)ival; return 1; } /* helper macro to fixup start/end slice values */ #define ADJUST_INDICES(start, end, len) \ if (end > len) \ end = len; \ else if (end < 0) { \ end += len; \ if (end < 0) \ end = 0; \ } \ if (start < 0) { \ start += len; \ if (start < 0) \ start = 0; \ } Py_LOCAL_INLINE(Py_ssize_t) find_internal(const char *str, Py_ssize_t len, const char *function_name, PyObject *args, int dir) { PyObject *subobj; char byte; Py_buffer subbuf; const char *sub; Py_ssize_t sub_len; Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; Py_ssize_t res; if (!parse_args_finds_byte(function_name, args, &subobj, &byte, &start, &end)) return -2; if (subobj) { if (PyObject_GetBuffer(subobj, &subbuf, PyBUF_SIMPLE) != 0) return -2; sub = subbuf.buf; sub_len = subbuf.len; } else { sub = &byte; sub_len = 1; } ADJUST_INDICES(start, end, len); if (end - start < sub_len) res = -1; else if (sub_len == 1) { if (dir > 0) res = stringlib_find_char( str + start, end - start, *sub); else res = stringlib_rfind_char( str + start, end - start, *sub); if (res >= 0) res += start; } else { if (dir > 0) res = stringlib_find_slice( str, len, sub, sub_len, start, end); else res = stringlib_rfind_slice( str, len, sub, sub_len, start, end); } if (subobj) PyBuffer_Release(&subbuf); return res; } PyDoc_STRVAR_shared(_Py_find__doc__, "B.find(sub[, start[, end]]) -> int\n\ \n\ Return the lowest index in B where subsection sub is found,\n\ such that sub is contained within B[start,end]. Optional\n\ arguments start and end are interpreted as in slice notation.\n\ \n\ Return -1 on failure."); PyObject * _Py_bytes_find(const char *str, Py_ssize_t len, PyObject *args) { Py_ssize_t result = find_internal(str, len, "find", args, +1); if (result == -2) return NULL; return PyLong_FromSsize_t(result); } PyDoc_STRVAR_shared(_Py_index__doc__, "B.index(sub[, start[, end]]) -> int\n\ \n\ Return the lowest index in B where subsection sub is found,\n\ such that sub is contained within B[start,end]. Optional\n\ arguments start and end are interpreted as in slice notation.\n\ \n\ Raises ValueError when the subsection is not found."); PyObject * _Py_bytes_index(const char *str, Py_ssize_t len, PyObject *args) { Py_ssize_t result = find_internal(str, len, "index", args, +1); if (result == -2) return NULL; if (result == -1) { PyErr_SetString(PyExc_ValueError, "subsection not found"); return NULL; } return PyLong_FromSsize_t(result); } PyDoc_STRVAR_shared(_Py_rfind__doc__, "B.rfind(sub[, start[, end]]) -> int\n\ \n\ Return the highest index in B where subsection sub is found,\n\ such that sub is contained within B[start,end]. Optional\n\ arguments start and end are interpreted as in slice notation.\n\ \n\ Return -1 on failure."); PyObject * _Py_bytes_rfind(const char *str, Py_ssize_t len, PyObject *args) { Py_ssize_t result = find_internal(str, len, "rfind", args, -1); if (result == -2) return NULL; return PyLong_FromSsize_t(result); } PyDoc_STRVAR_shared(_Py_rindex__doc__, "B.rindex(sub[, start[, end]]) -> int\n\ \n\ Return the highest index in B where subsection sub is found,\n\ such that sub is contained within B[start,end]. Optional\n\ arguments start and end are interpreted as in slice notation.\n\ \n\ Raise ValueError when the subsection is not found."); PyObject * _Py_bytes_rindex(const char *str, Py_ssize_t len, PyObject *args) { Py_ssize_t result = find_internal(str, len, "rindex", args, -1); if (result == -2) return NULL; if (result == -1) { PyErr_SetString(PyExc_ValueError, "subsection not found"); return NULL; } return PyLong_FromSsize_t(result); } PyDoc_STRVAR_shared(_Py_count__doc__, "B.count(sub[, start[, end]]) -> int\n\ \n\ Return the number of non-overlapping occurrences of subsection sub in\n\ bytes B[start:end]. Optional arguments start and end are interpreted\n\ as in slice notation."); PyObject * _Py_bytes_count(const char *str, Py_ssize_t len, PyObject *args) { PyObject *sub_obj; const char *sub; Py_ssize_t sub_len; char byte; Py_ssize_t start = 0, end = PY_SSIZE_T_MAX; Py_buffer vsub; PyObject *count_obj; if (!parse_args_finds_byte("count", args, &sub_obj, &byte, &start, &end)) return NULL; if (sub_obj) { if (PyObject_GetBuffer(sub_obj, &vsub, PyBUF_SIMPLE) != 0) return NULL; sub = vsub.buf; sub_len = vsub.len; } else { sub = &byte; sub_len = 1; } ADJUST_INDICES(start, end, len); count_obj = PyLong_FromSsize_t( stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX) ); if (sub_obj) PyBuffer_Release(&vsub); return count_obj; } int _Py_bytes_contains(const char *str, Py_ssize_t len, PyObject *arg) { Py_ssize_t ival = PyNumber_AsSsize_t(arg, NULL); if (ival == -1 && PyErr_Occurred()) { Py_buffer varg; Py_ssize_t pos; PyErr_Clear(); if (PyObject_GetBuffer(arg, &varg, PyBUF_SIMPLE) != 0) return -1; pos = stringlib_find(str, len, varg.buf, varg.len, 0); PyBuffer_Release(&varg); return pos >= 0; } if (ival < 0 || ival >= 256) { PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); return -1; } return memchr(str, (int) ival, len) != NULL; } /* Matches the end (direction >= 0) or start (direction < 0) of the buffer * against substr, using the start and end arguments. Returns * -1 on error, 0 if not found and 1 if found. */ static int tailmatch(const char *str, Py_ssize_t len, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction) { Py_buffer sub_view = {NULL, NULL}; const char *sub; Py_ssize_t slen; if (PyBytes_Check(substr)) { sub = PyBytes_AS_STRING(substr); slen = PyBytes_GET_SIZE(substr); } else { if (PyObject_GetBuffer(substr, &sub_view, PyBUF_SIMPLE) != 0) return -1; sub = sub_view.buf; slen = sub_view.len; } ADJUST_INDICES(start, end, len); if (direction < 0) { /* startswith */ if (start + slen > len) goto notfound; } else { /* endswith */ if (end - start < slen || start > len) goto notfound; if (end - slen > start) start = end - slen; } if (end - start < slen) goto notfound; if (bcmp(str + start, sub, slen) != 0) goto notfound; PyBuffer_Release(&sub_view); return 1; notfound: PyBuffer_Release(&sub_view); return 0; } static PyObject * _Py_bytes_tailmatch(const char *str, Py_ssize_t len, const char *function_name, PyObject *args, int direction) { Py_ssize_t start = 0; Py_ssize_t end = PY_SSIZE_T_MAX; PyObject *subobj; int result; if (!stringlib_parse_args_finds(function_name, args, &subobj, &start, &end)) return NULL; if (PyTuple_Check(subobj)) { Py_ssize_t i; for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) { result = tailmatch(str, len, PyTuple_GET_ITEM(subobj, i), start, end, direction); if (result == -1) return NULL; else if (result) { Py_RETURN_TRUE; } } Py_RETURN_FALSE; } result = tailmatch(str, len, subobj, start, end, direction); if (result == -1) { if (PyErr_ExceptionMatches(PyExc_TypeError)) PyErr_Format(PyExc_TypeError, "%s first arg must be bytes or a tuple of bytes, " "not %s", function_name, Py_TYPE(subobj)->tp_name); return NULL; } else return PyBool_FromLong(result); } PyDoc_STRVAR_shared(_Py_startswith__doc__, "B.startswith(prefix[, start[, end]]) -> bool\n\ \n\ Return True if B starts with the specified prefix, False otherwise.\n\ With optional start, test B beginning at that position.\n\ With optional end, stop comparing B at that position.\n\ prefix can also be a tuple of bytes to try."); PyObject * _Py_bytes_startswith(const char *str, Py_ssize_t len, PyObject *args) { return _Py_bytes_tailmatch(str, len, "startswith", args, -1); } PyDoc_STRVAR_shared(_Py_endswith__doc__, "B.endswith(suffix[, start[, end]]) -> bool\n\ \n\ Return True if B ends with the specified suffix, False otherwise.\n\ With optional start, test B beginning at that position.\n\ With optional end, stop comparing B at that position.\n\ suffix can also be a tuple of bytes to try."); PyObject * _Py_bytes_endswith(const char *str, Py_ssize_t len, PyObject *args) { return _Py_bytes_tailmatch(str, len, "endswith", args, +1); } PyDoc_STRVAR_shared(_Py_expandtabs__doc__, "B.expandtabs(tabsize=8) -> copy of B\n\ \n\ Return a copy of B where all tab characters are expanded using spaces.\n\ If tabsize is not given, a tab size of 8 characters is assumed."); PyDoc_STRVAR_shared(_Py_ljust__doc__, "B.ljust(width[, fillchar]) -> copy of B\n" "\n" "Return B left justified in a string of length width. Padding is\n" "done using the specified fill character (default is a space)."); PyDoc_STRVAR_shared(_Py_rjust__doc__, "B.rjust(width[, fillchar]) -> copy of B\n" "\n" "Return B right justified in a string of length width. Padding is\n" "done using the specified fill character (default is a space)"); PyDoc_STRVAR_shared(_Py_center__doc__, "B.center(width[, fillchar]) -> copy of B\n" "\n" "Return B centered in a string of length width. Padding is\n" "done using the specified fill character (default is a space)."); PyDoc_STRVAR_shared(_Py_zfill__doc__, "B.zfill(width) -> copy of B\n" "\n" "Pad a numeric string B with zeros on the left, to fill a field\n" "of the specified width. B is never truncated.");
22,751
835
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/README
Source files for various builtin objects
41
2
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/descrobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ /* Descriptors -- a new, flexible way to describe attributes */ static void descr_dealloc(PyDescrObject *descr) { _PyObject_GC_UNTRACK(descr); Py_XDECREF(descr->d_type); Py_XDECREF(descr->d_name); Py_XDECREF(descr->d_qualname); PyObject_GC_Del(descr); } static PyObject * descr_name(PyDescrObject *descr) { if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) return descr->d_name; return NULL; } static PyObject * descr_repr(PyDescrObject *descr, const char *format) { PyObject *name = NULL; if (descr->d_name != NULL && PyUnicode_Check(descr->d_name)) name = descr->d_name; return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name); } static PyObject * method_repr(PyMethodDescrObject *descr) { return descr_repr((PyDescrObject *)descr, "<method '%V' of '%s' objects>"); } static PyObject * member_repr(PyMemberDescrObject *descr) { return descr_repr((PyDescrObject *)descr, "<member '%V' of '%s' objects>"); } static PyObject * getset_repr(PyGetSetDescrObject *descr) { return descr_repr((PyDescrObject *)descr, "<attribute '%V' of '%s' objects>"); } static PyObject * wrapperdescr_repr(PyWrapperDescrObject *descr) { return descr_repr((PyDescrObject *)descr, "<slot wrapper '%V' of '%s' objects>"); } static int descr_check(PyDescrObject *descr, PyObject *obj, PyObject **pres) { if (obj == NULL) { Py_INCREF(descr); *pres = (PyObject *)descr; return 1; } if (!PyObject_TypeCheck(obj, descr->d_type)) { PyErr_Format(PyExc_TypeError, "descriptor '%V' for '%s' objects " "doesn't apply to '%s' object", descr_name((PyDescrObject *)descr), "?", descr->d_type->tp_name, obj->ob_type->tp_name); *pres = NULL; return 1; } return 0; } static PyObject * classmethod_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { /* Ensure a valid type. Class methods ignore obj. */ if (type == NULL) { if (obj != NULL) type = (PyObject *)obj->ob_type; else { /* Wot - no type?! */ PyErr_Format(PyExc_TypeError, "descriptor '%V' for type '%s' " "needs either an object or a type", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name); return NULL; } } if (!PyType_Check(type)) { PyErr_Format(PyExc_TypeError, "descriptor '%V' for type '%s' " "needs a type, not a '%s' as arg 2", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name, type->ob_type->tp_name); return NULL; } if (!PyType_IsSubtype((PyTypeObject *)type, PyDescr_TYPE(descr))) { PyErr_Format(PyExc_TypeError, "descriptor '%V' for type '%s' " "doesn't apply to type '%s'", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name, ((PyTypeObject *)type)->tp_name); return NULL; } return PyCFunction_NewEx(descr->d_method, type, NULL); } static PyObject * method_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type) { PyObject *res; if (descr_check((PyDescrObject *)descr, obj, &res)) return res; return PyCFunction_NewEx(descr->d_method, obj, NULL); } static PyObject * member_get(PyMemberDescrObject *descr, PyObject *obj, PyObject *type) { PyObject *res; if (descr_check((PyDescrObject *)descr, obj, &res)) return res; return PyMember_GetOne((char *)obj, descr->d_member); } static PyObject * getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyObject *type) { PyObject *res; if (descr_check((PyDescrObject *)descr, obj, &res)) return res; if (descr->d_getset->get != NULL) return descr->d_getset->get(obj, descr->d_getset->closure); PyErr_Format(PyExc_AttributeError, "attribute '%V' of '%.100s' objects is not readable", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name); return NULL; } static PyObject * wrapperdescr_get(PyWrapperDescrObject *descr, PyObject *obj, PyObject *type) { PyObject *res; if (descr_check((PyDescrObject *)descr, obj, &res)) return res; return PyWrapper_New((PyObject *)descr, obj); } static int descr_setcheck(PyDescrObject *descr, PyObject *obj, PyObject *value, int *pres) { assert(obj != NULL); if (!PyObject_TypeCheck(obj, descr->d_type)) { PyErr_Format(PyExc_TypeError, "descriptor '%V' for '%.100s' objects " "doesn't apply to '%.100s' object", descr_name(descr), "?", descr->d_type->tp_name, obj->ob_type->tp_name); *pres = -1; return 1; } return 0; } static int member_set(PyMemberDescrObject *descr, PyObject *obj, PyObject *value) { int res; if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) return res; return PyMember_SetOne((char *)obj, descr->d_member, value); } static int getset_set(PyGetSetDescrObject *descr, PyObject *obj, PyObject *value) { int res; if (descr_setcheck((PyDescrObject *)descr, obj, value, &res)) return res; if (descr->d_getset->set != NULL) return descr->d_getset->set(obj, value, descr->d_getset->closure); PyErr_Format(PyExc_AttributeError, "attribute '%V' of '%.100s' objects is not writable", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name); return -1; } static PyObject * methoddescr_call(PyMethodDescrObject *descr, PyObject *args, PyObject *kwargs) { Py_ssize_t nargs; PyObject *self, *result; /* Make sure that the first argument is acceptable as 'self' */ assert(PyTuple_Check(args)); nargs = PyTuple_GET_SIZE(args); if (nargs < 1) { PyErr_Format(PyExc_TypeError, "descriptor '%V' of '%.100s' " "object needs an argument", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name); return NULL; } self = PyTuple_GET_ITEM(args, 0); if (!_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self), (PyObject *)PyDescr_TYPE(descr))) { PyErr_Format(PyExc_TypeError, "descriptor '%V' " "requires a '%.100s' object " "but received a '%.100s'", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name, self->ob_type->tp_name); return NULL; } result = _PyMethodDef_RawFastCallDict(descr->d_method, self, &PyTuple_GET_ITEM(args, 1), nargs - 1, kwargs); result = _Py_CheckFunctionResult((PyObject *)descr, result, NULL); return result; } // same to methoddescr_call(), but use FASTCALL convention. PyObject * _PyMethodDescr_FastCallKeywords(PyObject *descrobj, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames) { assert(Py_TYPE(descrobj) == &PyMethodDescr_Type); PyMethodDescrObject *descr = (PyMethodDescrObject *)descrobj; PyObject *self, *result; /* Make sure that the first argument is acceptable as 'self' */ if (nargs < 1) { PyErr_Format(PyExc_TypeError, "descriptor '%V' of '%.100s' " "object needs an argument", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name); return NULL; } self = args[0]; if (!_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self), (PyObject *)PyDescr_TYPE(descr))) { PyErr_Format(PyExc_TypeError, "descriptor '%V' " "requires a '%.100s' object " "but received a '%.100s'", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name, self->ob_type->tp_name); return NULL; } result = _PyMethodDef_RawFastCallKeywords(descr->d_method, self, args+1, nargs-1, kwnames); result = _Py_CheckFunctionResult((PyObject *)descr, result, NULL); return result; } static PyObject * classmethoddescr_call(PyMethodDescrObject *descr, PyObject *args, PyObject *kwds) { Py_ssize_t argc; PyObject *self, *func, *result, **stack; /* Make sure that the first argument is acceptable as 'self' */ assert(PyTuple_Check(args)); argc = PyTuple_GET_SIZE(args); if (argc < 1) { PyErr_Format(PyExc_TypeError, "descriptor '%V' of '%.100s' " "object needs an argument", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name); return NULL; } self = PyTuple_GET_ITEM(args, 0); if (!PyType_Check(self)) { PyErr_Format(PyExc_TypeError, "descriptor '%V' requires a type " "but received a '%.100s'", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name, self->ob_type->tp_name); return NULL; } if (!PyType_IsSubtype((PyTypeObject *)self, PyDescr_TYPE(descr))) { PyErr_Format(PyExc_TypeError, "descriptor '%V' " "requires a subtype of '%.100s' " "but received '%.100s", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name, self->ob_type->tp_name); return NULL; } func = PyCFunction_NewEx(descr->d_method, self, NULL); if (func == NULL) return NULL; stack = &PyTuple_GET_ITEM(args, 1); result = _PyObject_FastCallDict(func, stack, argc - 1, kwds); Py_DECREF(func); return result; } static PyObject * wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds) { Py_ssize_t argc; PyObject *self, *func, *result, **stack; /* Make sure that the first argument is acceptable as 'self' */ assert(PyTuple_Check(args)); argc = PyTuple_GET_SIZE(args); if (argc < 1) { PyErr_Format(PyExc_TypeError, "descriptor '%V' of '%.100s' " "object needs an argument", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name); return NULL; } self = PyTuple_GET_ITEM(args, 0); if (!_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self), (PyObject *)PyDescr_TYPE(descr))) { PyErr_Format(PyExc_TypeError, "descriptor '%V' " "requires a '%.100s' object " "but received a '%.100s'", descr_name((PyDescrObject *)descr), "?", PyDescr_TYPE(descr)->tp_name, self->ob_type->tp_name); return NULL; } func = PyWrapper_New((PyObject *)descr, self); if (func == NULL) return NULL; stack = &PyTuple_GET_ITEM(args, 1); result = _PyObject_FastCallDict(func, stack, argc - 1, kwds); Py_DECREF(func); return result; } static PyObject * method_get_doc(PyMethodDescrObject *descr, void *closure) { return _PyType_GetDocFromInternalDoc(descr->d_method->ml_name, descr->d_method->ml_doc); } static PyObject * method_get_text_signature(PyMethodDescrObject *descr, void *closure) { return _PyType_GetTextSignatureFromInternalDoc(descr->d_method->ml_name, descr->d_method->ml_doc); } static PyObject * calculate_qualname(PyDescrObject *descr) { PyObject *type_qualname, *res; _Py_IDENTIFIER(__qualname__); if (descr->d_name == NULL || !PyUnicode_Check(descr->d_name)) { PyErr_SetString(PyExc_TypeError, "<descriptor>.__name__ is not a unicode object"); return NULL; } type_qualname = _PyObject_GetAttrId((PyObject *)descr->d_type, &PyId___qualname__); if (type_qualname == NULL) return NULL; if (!PyUnicode_Check(type_qualname)) { PyErr_SetString(PyExc_TypeError, "<descriptor>.__objclass__." "__qualname__ is not a unicode object"); Py_XDECREF(type_qualname); return NULL; } res = PyUnicode_FromFormat("%S.%S", type_qualname, descr->d_name); Py_DECREF(type_qualname); return res; } static PyObject * descr_get_qualname(PyDescrObject *descr, void *Py_UNUSED(ignored)) { if (descr->d_qualname == NULL) descr->d_qualname = calculate_qualname(descr); Py_XINCREF(descr->d_qualname); return descr->d_qualname; } static PyObject * descr_reduce(PyDescrObject *descr) { _Py_IDENTIFIER(getattr); return Py_BuildValue("N(OO)", _PyEval_GetBuiltinId(&PyId_getattr), PyDescr_TYPE(descr), PyDescr_NAME(descr)); } static PyMethodDef descr_methods[] = { {"__reduce__", (PyCFunction)descr_reduce, METH_NOARGS, NULL}, {NULL, NULL} }; static PyMemberDef descr_members[] = { {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY}, {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY}, {0} }; static PyGetSetDef method_getset[] = { {"__doc__", (getter)method_get_doc}, {"__qualname__", (getter)descr_get_qualname}, {"__text_signature__", (getter)method_get_text_signature}, {0} }; static PyObject * member_get_doc(PyMemberDescrObject *descr, void *closure) { if (descr->d_member->doc == NULL) { Py_INCREF(Py_None); return Py_None; } return PyUnicode_FromString(descr->d_member->doc); } static PyGetSetDef member_getset[] = { {"__doc__", (getter)member_get_doc}, {"__qualname__", (getter)descr_get_qualname}, {0} }; static PyObject * getset_get_doc(PyGetSetDescrObject *descr, void *closure) { if (descr->d_getset->doc == NULL) { Py_INCREF(Py_None); return Py_None; } return PyUnicode_FromString(descr->d_getset->doc); } static PyGetSetDef getset_getset[] = { {"__doc__", (getter)getset_get_doc}, {"__qualname__", (getter)descr_get_qualname}, {0} }; static PyObject * wrapperdescr_get_doc(PyWrapperDescrObject *descr, void *closure) { return _PyType_GetDocFromInternalDoc(descr->d_base->name, descr->d_base->doc); } static PyObject * wrapperdescr_get_text_signature(PyWrapperDescrObject *descr, void *closure) { return _PyType_GetTextSignatureFromInternalDoc(descr->d_base->name, descr->d_base->doc); } static PyGetSetDef wrapperdescr_getset[] = { {"__doc__", (getter)wrapperdescr_get_doc}, {"__qualname__", (getter)descr_get_qualname}, {"__text_signature__", (getter)wrapperdescr_get_text_signature}, {0} }; static int descr_traverse(PyObject *self, visitproc visit, void *arg) { PyDescrObject *descr = (PyDescrObject *)self; Py_VISIT(descr->d_type); return 0; } PyTypeObject PyMethodDescr_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "method_descriptor", sizeof(PyMethodDescrObject), 0, (destructor)descr_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)method_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)methoddescr_call, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ descr_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ descr_methods, /* tp_methods */ descr_members, /* tp_members */ method_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ (descrgetfunc)method_get, /* tp_descr_get */ 0, /* tp_descr_set */ }; /* This is for METH_CLASS in C, not for "f = classmethod(f)" in Python! */ PyTypeObject PyClassMethodDescr_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "classmethod_descriptor", sizeof(PyMethodDescrObject), 0, (destructor)descr_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)method_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)classmethoddescr_call, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ descr_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ descr_methods, /* tp_methods */ descr_members, /* tp_members */ method_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ (descrgetfunc)classmethod_get, /* tp_descr_get */ 0, /* tp_descr_set */ }; PyTypeObject PyMemberDescr_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "member_descriptor", sizeof(PyMemberDescrObject), 0, (destructor)descr_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)member_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ descr_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ descr_methods, /* tp_methods */ descr_members, /* tp_members */ member_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ (descrgetfunc)member_get, /* tp_descr_get */ (descrsetfunc)member_set, /* tp_descr_set */ }; PyTypeObject PyGetSetDescr_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "getset_descriptor", sizeof(PyGetSetDescrObject), 0, (destructor)descr_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)getset_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ descr_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ descr_members, /* tp_members */ getset_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ (descrgetfunc)getset_get, /* tp_descr_get */ (descrsetfunc)getset_set, /* tp_descr_set */ }; PyTypeObject PyWrapperDescr_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "wrapper_descriptor", sizeof(PyWrapperDescrObject), 0, (destructor)descr_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)wrapperdescr_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)wrapperdescr_call, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ descr_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ descr_methods, /* tp_methods */ descr_members, /* tp_members */ wrapperdescr_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ (descrgetfunc)wrapperdescr_get, /* tp_descr_get */ 0, /* tp_descr_set */ }; static PyDescrObject * descr_new(PyTypeObject *descrtype, PyTypeObject *type, const char *name) { PyDescrObject *descr; descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0); if (descr != NULL) { Py_XINCREF(type); descr->d_type = type; descr->d_name = PyUnicode_InternFromString(name); if (descr->d_name == NULL) { Py_DECREF(descr); descr = NULL; } else { descr->d_qualname = NULL; } } return descr; } PyObject * PyDescr_NewMethod(PyTypeObject *type, PyMethodDef *method) { PyMethodDescrObject *descr; descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type, type, method->ml_name); if (descr != NULL) descr->d_method = method; return (PyObject *)descr; } PyObject * PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) { PyMethodDescrObject *descr; descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type, type, method->ml_name); if (descr != NULL) descr->d_method = method; return (PyObject *)descr; } PyObject * PyDescr_NewMember(PyTypeObject *type, PyMemberDef *member) { PyMemberDescrObject *descr; descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type, type, member->name); if (descr != NULL) descr->d_member = member; return (PyObject *)descr; } PyObject * PyDescr_NewGetSet(PyTypeObject *type, PyGetSetDef *getset) { PyGetSetDescrObject *descr; descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type, type, getset->name); if (descr != NULL) descr->d_getset = getset; return (PyObject *)descr; } PyObject * PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped) { PyWrapperDescrObject *descr; descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type, type, base->name); if (descr != NULL) { descr->d_base = base; descr->d_wrapped = wrapped; } return (PyObject *)descr; } /* --- mappingproxy: read-only proxy for mappings --- */ /* This has no reason to be in this file except that adding new files is a bit of a pain */ typedef struct { PyObject_HEAD PyObject *mapping; } mappingproxyobject; static Py_ssize_t mappingproxy_len(mappingproxyobject *pp) { return PyObject_Size(pp->mapping); } static PyObject * mappingproxy_getitem(mappingproxyobject *pp, PyObject *key) { return PyObject_GetItem(pp->mapping, key); } static PyMappingMethods mappingproxy_as_mapping = { (lenfunc)mappingproxy_len, /* mp_length */ (binaryfunc)mappingproxy_getitem, /* mp_subscript */ 0, /* mp_ass_subscript */ }; static int mappingproxy_contains(mappingproxyobject *pp, PyObject *key) { if (PyDict_CheckExact(pp->mapping)) return PyDict_Contains(pp->mapping, key); else return PySequence_Contains(pp->mapping, key); } static PySequenceMethods mappingproxy_as_sequence = { 0, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ 0, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)mappingproxy_contains, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; static PyObject * mappingproxy_get(mappingproxyobject *pp, PyObject *args) { PyObject *key, *def = Py_None; _Py_IDENTIFIER(get); if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def)) return NULL; return _PyObject_CallMethodId(pp->mapping, &PyId_get, "(OO)", key, def); } static PyObject * mappingproxy_keys(mappingproxyobject *pp) { _Py_IDENTIFIER(keys); return _PyObject_CallMethodId(pp->mapping, &PyId_keys, NULL); } static PyObject * mappingproxy_values(mappingproxyobject *pp) { _Py_IDENTIFIER(values); return _PyObject_CallMethodId(pp->mapping, &PyId_values, NULL); } static PyObject * mappingproxy_items(mappingproxyobject *pp) { _Py_IDENTIFIER(items); return _PyObject_CallMethodId(pp->mapping, &PyId_items, NULL); } static PyObject * mappingproxy_copy(mappingproxyobject *pp) { _Py_IDENTIFIER(copy); return _PyObject_CallMethodId(pp->mapping, &PyId_copy, NULL); } /* WARNING: mappingproxy methods must not give access to the underlying mapping */ static PyMethodDef mappingproxy_methods[] = { {"get", (PyCFunction)mappingproxy_get, METH_VARARGS, PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d." " d defaults to None.")}, {"keys", (PyCFunction)mappingproxy_keys, METH_NOARGS, PyDoc_STR("D.keys() -> list of D's keys")}, {"values", (PyCFunction)mappingproxy_values, METH_NOARGS, PyDoc_STR("D.values() -> list of D's values")}, {"items", (PyCFunction)mappingproxy_items, METH_NOARGS, PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")}, {"copy", (PyCFunction)mappingproxy_copy, METH_NOARGS, PyDoc_STR("D.copy() -> a shallow copy of D")}, {0} }; static void mappingproxy_dealloc(mappingproxyobject *pp) { _PyObject_GC_UNTRACK(pp); Py_DECREF(pp->mapping); PyObject_GC_Del(pp); } static PyObject * mappingproxy_getiter(mappingproxyobject *pp) { return PyObject_GetIter(pp->mapping); } static PyObject * mappingproxy_str(mappingproxyobject *pp) { return PyObject_Str(pp->mapping); } static PyObject * mappingproxy_repr(mappingproxyobject *pp) { return PyUnicode_FromFormat("mappingproxy(%R)", pp->mapping); } static int mappingproxy_traverse(PyObject *self, visitproc visit, void *arg) { mappingproxyobject *pp = (mappingproxyobject *)self; Py_VISIT(pp->mapping); return 0; } static PyObject * mappingproxy_richcompare(mappingproxyobject *v, PyObject *w, int op) { return PyObject_RichCompare(v->mapping, w, op); } static int mappingproxy_check_mapping(PyObject *mapping) { if (!PyMapping_Check(mapping) || PyList_Check(mapping) || PyTuple_Check(mapping)) { PyErr_Format(PyExc_TypeError, "mappingproxy() argument must be a mapping, not %s", Py_TYPE(mapping)->tp_name); return -1; } return 0; } static PyObject* mappingproxy_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"mapping", NULL}; PyObject *mapping; mappingproxyobject *mappingproxy; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:mappingproxy", kwlist, &mapping)) return NULL; if (mappingproxy_check_mapping(mapping) == -1) return NULL; mappingproxy = PyObject_GC_New(mappingproxyobject, &PyDictProxy_Type); if (mappingproxy == NULL) return NULL; Py_INCREF(mapping); mappingproxy->mapping = mapping; _PyObject_GC_TRACK(mappingproxy); return (PyObject *)mappingproxy; } PyTypeObject PyDictProxy_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "mappingproxy", /* tp_name */ sizeof(mappingproxyobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)mappingproxy_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)mappingproxy_repr, /* tp_repr */ 0, /* tp_as_number */ &mappingproxy_as_sequence, /* tp_as_sequence */ &mappingproxy_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)mappingproxy_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ mappingproxy_traverse, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)mappingproxy_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)mappingproxy_getiter, /* tp_iter */ 0, /* tp_iternext */ mappingproxy_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ mappingproxy_new, /* tp_new */ }; PyObject * PyDictProxy_New(PyObject *mapping) { mappingproxyobject *pp; if (mappingproxy_check_mapping(mapping) == -1) return NULL; pp = PyObject_GC_New(mappingproxyobject, &PyDictProxy_Type); if (pp != NULL) { Py_INCREF(mapping); pp->mapping = mapping; _PyObject_GC_TRACK(pp); } return (PyObject *)pp; } /* --- Wrapper object for "slot" methods --- */ /* This has no reason to be in this file except that adding new files is a bit of a pain */ typedef struct { PyObject_HEAD PyWrapperDescrObject *descr; PyObject *self; } wrapperobject; #define Wrapper_Check(v) (Py_TYPE(v) == &_PyMethodWrapper_Type) static void wrapper_dealloc(wrapperobject *wp) { PyObject_GC_UnTrack(wp); Py_TRASHCAN_SAFE_BEGIN(wp) Py_XDECREF(wp->descr); Py_XDECREF(wp->self); PyObject_GC_Del(wp); Py_TRASHCAN_SAFE_END(wp) } #define TEST_COND(cond) ((cond) ? Py_True : Py_False) static PyObject * wrapper_richcompare(PyObject *a, PyObject *b, int op) { intptr_t result; PyObject *v; PyWrapperDescrObject *a_descr, *b_descr; assert(a != NULL && b != NULL); /* both arguments should be wrapperobjects */ if (!Wrapper_Check(a) || !Wrapper_Check(b)) { v = Py_NotImplemented; Py_INCREF(v); return v; } /* compare by descriptor address; if the descriptors are the same, compare by the objects they're bound to */ a_descr = ((wrapperobject *)a)->descr; b_descr = ((wrapperobject *)b)->descr; if (a_descr == b_descr) { a = ((wrapperobject *)a)->self; b = ((wrapperobject *)b)->self; return PyObject_RichCompare(a, b, op); } result = a_descr - b_descr; switch (op) { case Py_EQ: v = TEST_COND(result == 0); break; case Py_NE: v = TEST_COND(result != 0); break; case Py_LE: v = TEST_COND(result <= 0); break; case Py_GE: v = TEST_COND(result >= 0); break; case Py_LT: v = TEST_COND(result < 0); break; case Py_GT: v = TEST_COND(result > 0); break; default: PyErr_BadArgument(); return NULL; } Py_INCREF(v); return v; } static Py_hash_t wrapper_hash(wrapperobject *wp) { Py_hash_t x, y; x = _Py_HashPointer(wp->descr); if (x == -1) return -1; y = PyObject_Hash(wp->self); if (y == -1) return -1; x = x ^ y; if (x == -1) x = -2; return x; } static PyObject * wrapper_repr(wrapperobject *wp) { return PyUnicode_FromFormat("<method-wrapper '%s' of %s object at %p>", wp->descr->d_base->name, wp->self->ob_type->tp_name, wp->self); } static PyObject * wrapper_reduce(wrapperobject *wp) { _Py_IDENTIFIER(getattr); return Py_BuildValue("N(OO)", _PyEval_GetBuiltinId(&PyId_getattr), wp->self, PyDescr_NAME(wp->descr)); } static PyMethodDef wrapper_methods[] = { {"__reduce__", (PyCFunction)wrapper_reduce, METH_NOARGS, NULL}, {NULL, NULL} }; static PyMemberDef wrapper_members[] = { {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY}, {0} }; static PyObject * wrapper_objclass(wrapperobject *wp, void *Py_UNUSED(ignored)) { PyObject *c = (PyObject *)PyDescr_TYPE(wp->descr); Py_INCREF(c); return c; } static PyObject * wrapper_name(wrapperobject *wp, void *Py_UNUSED(ignored)) { const char *s = wp->descr->d_base->name; return PyUnicode_FromString(s); } static PyObject * wrapper_doc(wrapperobject *wp, void *Py_UNUSED(ignored)) { return _PyType_GetDocFromInternalDoc(wp->descr->d_base->name, wp->descr->d_base->doc); } static PyObject * wrapper_text_signature(wrapperobject *wp, void *Py_UNUSED(ignored)) { return _PyType_GetTextSignatureFromInternalDoc(wp->descr->d_base->name, wp->descr->d_base->doc); } static PyObject * wrapper_qualname(wrapperobject *wp, void *Py_UNUSED(ignored)) { return descr_get_qualname((PyDescrObject *)wp->descr, NULL); } static PyGetSetDef wrapper_getsets[] = { {"__objclass__", (getter)wrapper_objclass}, {"__name__", (getter)wrapper_name}, {"__qualname__", (getter)wrapper_qualname}, {"__doc__", (getter)wrapper_doc}, {"__text_signature__", (getter)wrapper_text_signature}, {0} }; static PyObject * wrapper_call(wrapperobject *wp, PyObject *args, PyObject *kwds) { wrapperfunc wrapper = wp->descr->d_base->wrapper; PyObject *self = wp->self; if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) { wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper; return (*wk)(self, args, wp->descr->d_wrapped, kwds); } if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) { PyErr_Format(PyExc_TypeError, "wrapper %s doesn't take keyword arguments", wp->descr->d_base->name); return NULL; } return (*wrapper)(self, args, wp->descr->d_wrapped); } static int wrapper_traverse(PyObject *self, visitproc visit, void *arg) { wrapperobject *wp = (wrapperobject *)self; Py_VISIT(wp->descr); Py_VISIT(wp->self); return 0; } PyTypeObject _PyMethodWrapper_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "method-wrapper", /* tp_name */ sizeof(wrapperobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)wrapper_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)wrapper_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)wrapper_hash, /* tp_hash */ (ternaryfunc)wrapper_call, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ wrapper_traverse, /* tp_traverse */ 0, /* tp_clear */ wrapper_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ wrapper_methods, /* tp_methods */ wrapper_members, /* tp_members */ wrapper_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ }; PyObject * PyWrapper_New(PyObject *d, PyObject *self) { wrapperobject *wp; PyWrapperDescrObject *descr; assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type)); descr = (PyWrapperDescrObject *)d; assert(_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self), (PyObject *)PyDescr_TYPE(descr))); wp = PyObject_GC_New(wrapperobject, &_PyMethodWrapper_Type); if (wp != NULL) { Py_INCREF(descr); wp->descr = descr; Py_INCREF(self); wp->self = self; _PyObject_GC_TRACK(wp); } return (PyObject *)wp; } /* A built-in 'property' type */ /* class property(object): def __init__(self, fget=None, fset=None, fdel=None, doc=None): if doc is None and fget is not None and hasattr(fget, "__doc__"): doc = fget.__doc__ self.__get = fget self.__set = fset self.__del = fdel self.__doc__ = doc def __get__(self, inst, type=None): if inst is None: return self if self.__get is None: raise AttributeError, "unreadable attribute" return self.__get(inst) def __set__(self, inst, value): if self.__set is None: raise AttributeError, "can't set attribute" return self.__set(inst, value) def __delete__(self, inst): if self.__del is None: raise AttributeError, "can't delete attribute" return self.__del(inst) */ typedef struct { PyObject_HEAD PyObject *prop_get; PyObject *prop_set; PyObject *prop_del; PyObject *prop_doc; int getter_doc; } propertyobject; static PyObject * property_copy(PyObject *, PyObject *, PyObject *, PyObject *); static PyMemberDef property_members[] = { {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY}, {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY}, {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY}, {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), 0}, {0} }; PyDoc_STRVAR(getter_doc, "Descriptor to change the getter on a property."); static PyObject * property_getter(PyObject *self, PyObject *getter) { return property_copy(self, getter, NULL, NULL); } PyDoc_STRVAR(setter_doc, "Descriptor to change the setter on a property."); static PyObject * property_setter(PyObject *self, PyObject *setter) { return property_copy(self, NULL, setter, NULL); } PyDoc_STRVAR(deleter_doc, "Descriptor to change the deleter on a property."); static PyObject * property_deleter(PyObject *self, PyObject *deleter) { return property_copy(self, NULL, NULL, deleter); } static PyMethodDef property_methods[] = { {"getter", property_getter, METH_O, getter_doc}, {"setter", property_setter, METH_O, setter_doc}, {"deleter", property_deleter, METH_O, deleter_doc}, {0} }; static void property_dealloc(PyObject *self) { propertyobject *gs = (propertyobject *)self; _PyObject_GC_UNTRACK(self); Py_XDECREF(gs->prop_get); Py_XDECREF(gs->prop_set); Py_XDECREF(gs->prop_del); Py_XDECREF(gs->prop_doc); self->ob_type->tp_free(self); } static PyObject * property_descr_get(PyObject *self, PyObject *obj, PyObject *type) { static PyObject * volatile cached_args = NULL; PyObject *args; PyObject *ret; propertyobject *gs = (propertyobject *)self; if (obj == NULL || obj == Py_None) { Py_INCREF(self); return self; } if (gs->prop_get == NULL) { PyErr_SetString(PyExc_AttributeError, "unreadable attribute"); return NULL; } args = cached_args; cached_args = NULL; if (!args) { args = PyTuple_New(1); if (!args) return NULL; _PyObject_GC_UNTRACK(args); } Py_INCREF(obj); PyTuple_SET_ITEM(args, 0, obj); ret = PyObject_Call(gs->prop_get, args, NULL); if (cached_args == NULL && Py_REFCNT(args) == 1) { assert(Py_SIZE(args) == 1); assert(PyTuple_GET_ITEM(args, 0) == obj); cached_args = args; Py_DECREF(obj); } else { assert(Py_REFCNT(args) >= 1); _PyObject_GC_TRACK(args); Py_DECREF(args); } return ret; } static int property_descr_set(PyObject *self, PyObject *obj, PyObject *value) { propertyobject *gs = (propertyobject *)self; PyObject *func, *res; if (value == NULL) func = gs->prop_del; else func = gs->prop_set; if (func == NULL) { PyErr_SetString(PyExc_AttributeError, value == NULL ? "can't delete attribute" : "can't set attribute"); return -1; } if (value == NULL) res = PyObject_CallFunctionObjArgs(func, obj, NULL); else res = PyObject_CallFunctionObjArgs(func, obj, value, NULL); if (res == NULL) return -1; Py_DECREF(res); return 0; } static PyObject * property_copy(PyObject *old, PyObject *get, PyObject *set, PyObject *del) { propertyobject *pold = (propertyobject *)old; PyObject *new, *type, *doc; type = PyObject_Type(old); if (type == NULL) return NULL; if (get == NULL || get == Py_None) { Py_XDECREF(get); get = pold->prop_get ? pold->prop_get : Py_None; } if (set == NULL || set == Py_None) { Py_XDECREF(set); set = pold->prop_set ? pold->prop_set : Py_None; } if (del == NULL || del == Py_None) { Py_XDECREF(del); del = pold->prop_del ? pold->prop_del : Py_None; } if (pold->getter_doc && get != Py_None) { /* make _init use __doc__ from getter */ doc = Py_None; } else { doc = pold->prop_doc ? pold->prop_doc : Py_None; } new = PyObject_CallFunction(type, "OOOO", get, set, del, doc); Py_DECREF(type); if (new == NULL) return NULL; return new; } static int property_init(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL; static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0}; propertyobject *prop = (propertyobject *)self; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property", kwlist, &get, &set, &del, &doc)) return -1; if (get == Py_None) get = NULL; if (set == Py_None) set = NULL; if (del == Py_None) del = NULL; Py_XINCREF(get); Py_XINCREF(set); Py_XINCREF(del); Py_XINCREF(doc); Py_XSETREF(prop->prop_get, get); Py_XSETREF(prop->prop_set, set); Py_XSETREF(prop->prop_del, del); Py_XSETREF(prop->prop_doc, doc); prop->getter_doc = 0; /* if no docstring given and the getter has one, use that one */ if ((doc == NULL || doc == Py_None) && get != NULL) { _Py_IDENTIFIER(__doc__); PyObject *get_doc = _PyObject_GetAttrId(get, &PyId___doc__); if (get_doc) { if (Py_TYPE(self) == &PyProperty_Type) { Py_XSETREF(prop->prop_doc, get_doc); } else { /* If this is a property subclass, put __doc__ in dict of the subclass instance instead, otherwise it gets shadowed by __doc__ in the class's dict. */ int err = _PyObject_SetAttrId(self, &PyId___doc__, get_doc); Py_DECREF(get_doc); if (err < 0) return -1; } prop->getter_doc = 1; } else if (PyErr_ExceptionMatches(PyExc_Exception)) { PyErr_Clear(); } else { return -1; } } return 0; } static PyObject * property_get___isabstractmethod__(propertyobject *prop, void *closure) { int res = _PyObject_IsAbstract(prop->prop_get); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } res = _PyObject_IsAbstract(prop->prop_set); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } res = _PyObject_IsAbstract(prop->prop_del); if (res == -1) { return NULL; } else if (res) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyGetSetDef property_getsetlist[] = { {"__isabstractmethod__", (getter)property_get___isabstractmethod__, NULL, NULL, NULL}, {NULL} /* Sentinel */ }; PyDoc_STRVAR(property_doc, "property(fget=None, fset=None, fdel=None, doc=None) -> property attribute\n" "\n" "fget is a function to be used for getting an attribute value, and likewise\n" "fset is a function for setting, and fdel a function for del'ing, an\n" "attribute. Typical use is to define a managed attribute x:\n\n" "class C(object):\n" " def getx(self): return self._x\n" " def setx(self, value): self._x = value\n" " def delx(self): del self._x\n" " x = property(getx, setx, delx, \"I'm the 'x' property.\")\n" "\n" "Decorators make defining new properties or modifying existing ones easy:\n\n" "class C(object):\n" " @property\n" " def x(self):\n" " \"I am the 'x' property.\"\n" " return self._x\n" " @x.setter\n" " def x(self, value):\n" " self._x = value\n" " @x.deleter\n" " def x(self):\n" " del self._x\n" ); static int property_traverse(PyObject *self, visitproc visit, void *arg) { propertyobject *pp = (propertyobject *)self; Py_VISIT(pp->prop_get); Py_VISIT(pp->prop_set); Py_VISIT(pp->prop_del); Py_VISIT(pp->prop_doc); return 0; } static int property_clear(PyObject *self) { propertyobject *pp = (propertyobject *)self; Py_CLEAR(pp->prop_doc); return 0; } PyTypeObject PyProperty_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "property", /* tp_name */ sizeof(propertyobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ property_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ property_doc, /* tp_doc */ property_traverse, /* tp_traverse */ (inquiry)property_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ property_methods, /* tp_methods */ property_members, /* tp_members */ property_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ property_descr_get, /* tp_descr_get */ property_descr_set, /* tp_descr_set */ 0, /* tp_dictoffset */ property_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ };
57,904
1,693
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/obmalloc.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/intrin/bits.h" #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/fmt/fmt.h" #include "libc/intrin/asan.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "third_party/dlmalloc/dlmalloc.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ /* Python's malloc wrappers (see pymem.h) */ #undef uint #define uint unsigned int /* assuming >= 16 bits */ /* Forward declaration */ #if IsModeDbg() static void *_PyMem_DebugRawMalloc(void *, size_t); static void *_PyMem_DebugRawCalloc(void *, size_t, size_t); static void *_PyMem_DebugRawRealloc(void *, void *, size_t); static void _PyMem_DebugRawFree(void *, void *); static void *_PyMem_DebugMalloc(void *, size_t); static void *_PyMem_DebugCalloc(void *, size_t, size_t); static void *_PyMem_DebugRealloc(void *, void *, size_t); static void _PyMem_DebugFree(void *, void *); #endif static void _PyObject_DebugDumpAddress(const void *); static void _PyMem_DebugCheckAddress(char, const void *); #if defined(__has_feature) /* Clang */ # if __has_feature(address_sanitizer) /* is ASAN enabled? */ # define _Py_NO_ADDRESS_SAFETY_ANALYSIS \ __attribute__((no_address_safety_analysis)) # endif # if __has_feature(thread_sanitizer) /* is TSAN enabled? */ # define _Py_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread)) # endif # if __has_feature(memory_sanitizer) /* is MSAN enabled? */ # define _Py_NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory)) # endif #elif defined(__GNUC__) # if defined(__SANITIZE_ADDRESS__) /* GCC 4.8+, is ASAN enabled? */ # define _Py_NO_ADDRESS_SAFETY_ANALYSIS \ __attribute__((no_address_safety_analysis)) # endif // TSAN is supported since GCC 4.8, but __SANITIZE_THREAD__ macro // is provided only since GCC 7. # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # define _Py_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread)) # endif #endif #ifndef _Py_NO_ADDRESS_SAFETY_ANALYSIS # define _Py_NO_ADDRESS_SAFETY_ANALYSIS #endif #ifndef _Py_NO_SANITIZE_THREAD # define _Py_NO_SANITIZE_THREAD #endif #ifndef _Py_NO_SANITIZE_MEMORY # define _Py_NO_SANITIZE_MEMORY #endif #ifdef WITH_PYMALLOC #define ARENAS_USE_MMAP /* Forward declaration */ static void* _PyObject_Malloc(void *ctx, size_t size); static void* _PyObject_Calloc(void *ctx, size_t nelem, size_t elsize); static void _PyObject_Free(void *ctx, void *p); static void* _PyObject_Realloc(void *ctx, void *ptr, size_t size); #else /* in MODE=asan, no pymalloc, so use macro */ #define _PyObject_Malloc(ctx, size) _PyMem_RawMalloc((ctx), (size)) #define _PyObject_Calloc(ctx, nelem, elsize) _PyMem_RawCalloc((ctx), (nelem), (elsize)) #define _PyObject_Realloc(ctx, ptr, size) _PyMem_RawRealloc((ctx), (ptr), (size)) #define _PyObject_Free(ctx, p) _PyMem_RawFree((ctx), (p)) #endif static inline void * _PyMem_RawMalloc(void *ctx, size_t size) { #ifdef __COSMOPOLITAN__ #ifdef __SANITIZE_ADDRESS__ return __asan_memalign(16, size); #else return dlmalloc(size); #endif #else /* PyMem_RawMalloc(0) means malloc(1). Some systems would return NULL for malloc(0), which would be treated as an error. Some platforms would return a pointer with no memory behind it, which would break pymalloc. To solve these problems, allocate an extra byte. */ if (size == 0) size = 1; return malloc(size); #endif } static inline void * _PyMem_RawCalloc(void *ctx, size_t nelem, size_t elsize) { #ifdef __COSMOPOLITAN__ #ifdef __SANITIZE_ADDRESS__ return __asan_calloc(nelem, elsize); #else return dlcalloc(nelem, elsize); #endif #else /* PyMem_RawCalloc(0, 0) means calloc(1, 1). Some systems would return NULL for calloc(0, 0), which would be treated as an error. Some platforms would return a pointer with no memory behind it, which would break pymalloc. To solve these problems, allocate an extra byte. */ if (nelem == 0 || elsize == 0) { nelem = 1; elsize = 1; } return calloc(nelem, elsize); #endif } static inline void * _PyMem_RawRealloc(void *ctx, void *ptr, size_t size) { if (size == 0) size = 1; #ifdef __COSMOPOLITAN__ #ifdef __SANITIZE_ADDRESS__ return __asan_realloc(ptr, size); #else return dlrealloc(ptr, size); #endif #else return realloc(ptr, size); #endif } static inline void _PyMem_RawFree(void *ctx, void *ptr) { #ifdef __COSMOPOLITAN__ #ifdef __SANITIZE_ADDRESS__ __asan_free(ptr); #else dlfree(ptr); #endif #else free(ptr); #endif } #ifdef MS_WINDOWS static void * _PyObject_ArenaVirtualAlloc(void *ctx, size_t size) { return VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); } static void _PyObject_ArenaVirtualFree(void *ctx, void *ptr, size_t size) { VirtualFree(ptr, 0, MEM_RELEASE); } #elif defined(ARENAS_USE_MMAP) static void * _PyObject_ArenaMmap(void *ctx, size_t size) { #ifdef __COSMOPOLITAN__ return _mapanon(size); #else void *ptr; ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (ptr == MAP_FAILED) return NULL; assert(ptr != NULL); return ptr; #endif } static void _PyObject_ArenaMunmap(void *ctx, void *ptr, size_t size) { munmap(ptr, size); } #else static inline void * _PyObject_ArenaMalloc(void *ctx, size_t size) { return malloc(size); } static inline void _PyObject_ArenaFree(void *ctx, void *ptr, size_t size) { free(ptr); } #endif #if IsModeDbg() #define PYRAW_FUNCS _PyMem_RawMalloc, _PyMem_RawCalloc, _PyMem_RawRealloc, _PyMem_RawFree #ifdef WITH_PYMALLOC # define PYOBJ_FUNCS _PyObject_Malloc, _PyObject_Calloc, _PyObject_Realloc, _PyObject_Free #else # define PYOBJ_FUNCS PYRAW_FUNCS #endif #define PYMEM_FUNCS PYOBJ_FUNCS typedef struct { /* We tag each block with an API ID in order to tag API violations */ char api_id; PyMemAllocatorEx alloc; } debug_alloc_api_t; static struct { debug_alloc_api_t raw; debug_alloc_api_t mem; debug_alloc_api_t obj; } _PyMem_Debug = { {'r', {NULL, PYRAW_FUNCS}}, {'m', {NULL, PYMEM_FUNCS}}, {'o', {NULL, PYOBJ_FUNCS}} }; #define PYRAWDBG_FUNCS \ _PyMem_DebugRawMalloc, _PyMem_DebugRawCalloc, _PyMem_DebugRawRealloc, _PyMem_DebugRawFree #define PYDBG_FUNCS \ _PyMem_DebugMalloc, _PyMem_DebugCalloc, _PyMem_DebugRealloc, _PyMem_DebugFree static PyMemAllocatorEx _PyMem_Raw = { #ifdef Py_DEBUG &_PyMem_Debug.raw, PYRAWDBG_FUNCS #else NULL, PYRAW_FUNCS #endif }; static PyMemAllocatorEx _PyMem = { #ifdef Py_DEBUG &_PyMem_Debug.mem, PYDBG_FUNCS #else NULL, PYMEM_FUNCS #endif }; static PyMemAllocatorEx _PyObject = { #ifdef Py_DEBUG &_PyMem_Debug.obj, PYDBG_FUNCS #else NULL, PYOBJ_FUNCS #endif }; int _PyMem_SetupAllocators(const char *opt) { if (opt == NULL || *opt == '\0') { /* PYTHONMALLOC is empty or is not set or ignored (-E/-I command line options): use default allocators */ #ifdef Py_DEBUG # ifdef WITH_PYMALLOC opt = "pymalloc_debug"; # else opt = "malloc_debug"; # endif #else /* !Py_DEBUG */ # ifdef WITH_PYMALLOC opt = "pymalloc"; # else opt = "malloc"; # endif #endif } if (strcmp(opt, "debug") == 0) { PyMem_SetupDebugHooks(); } else if (strcmp(opt, "malloc") == 0 || strcmp(opt, "malloc_debug") == 0) { PyMemAllocatorEx alloc = {NULL, PYRAW_FUNCS}; PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc); PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc); PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc); if (strcmp(opt, "malloc_debug") == 0) PyMem_SetupDebugHooks(); } #ifdef WITH_PYMALLOC else if (strcmp(opt, "pymalloc") == 0 || strcmp(opt, "pymalloc_debug") == 0) { PyMemAllocatorEx raw_alloc = {NULL, PYRAW_FUNCS}; PyMemAllocatorEx mem_alloc = {NULL, PYMEM_FUNCS}; PyMemAllocatorEx obj_alloc = {NULL, PYOBJ_FUNCS}; PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &raw_alloc); PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &mem_alloc); PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &obj_alloc); if (strcmp(opt, "pymalloc_debug") == 0) PyMem_SetupDebugHooks(); } #endif else { /* unknown allocator */ return -1; } return 0; } #undef PYRAW_FUNCS #undef PYMEM_FUNCS #undef PYOBJ_FUNCS #undef PYRAWDBG_FUNCS #undef PYDBG_FUNCS static PyObjectArenaAllocator _PyObject_Arena = {NULL, #ifdef MS_WINDOWS _PyObject_ArenaVirtualAlloc, _PyObject_ArenaVirtualFree #elif defined(ARENAS_USE_MMAP) _PyObject_ArenaMmap, _PyObject_ArenaMunmap #else _PyObject_ArenaMalloc, _PyObject_ArenaFree #endif }; #ifdef WITH_PYMALLOC static int _PyMem_DebugEnabled(void) { return (_PyObject.malloc == _PyMem_DebugMalloc); } int _PyMem_PymallocEnabled(void) { if (_PyMem_DebugEnabled()) { return (_PyMem_Debug.obj.alloc.malloc == _PyObject_Malloc); } else { return (_PyObject.malloc == _PyObject_Malloc); } } #endif void PyMem_SetupDebugHooks(void) { PyMemAllocatorEx alloc; alloc.malloc = _PyMem_DebugRawMalloc; alloc.calloc = _PyMem_DebugRawCalloc; alloc.realloc = _PyMem_DebugRawRealloc; alloc.free = _PyMem_DebugRawFree; if (_PyMem_Raw.malloc != _PyMem_DebugRawMalloc) { alloc.ctx = &_PyMem_Debug.raw; PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &_PyMem_Debug.raw.alloc); PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &alloc); } alloc.malloc = _PyMem_DebugMalloc; alloc.calloc = _PyMem_DebugCalloc; alloc.realloc = _PyMem_DebugRealloc; alloc.free = _PyMem_DebugFree; if (_PyMem.malloc != _PyMem_DebugMalloc) { alloc.ctx = &_PyMem_Debug.mem; PyMem_GetAllocator(PYMEM_DOMAIN_MEM, &_PyMem_Debug.mem.alloc); PyMem_SetAllocator(PYMEM_DOMAIN_MEM, &alloc); } if (_PyObject.malloc != _PyMem_DebugMalloc) { alloc.ctx = &_PyMem_Debug.obj; PyMem_GetAllocator(PYMEM_DOMAIN_OBJ, &_PyMem_Debug.obj.alloc); PyMem_SetAllocator(PYMEM_DOMAIN_OBJ, &alloc); } } void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator) { switch(domain) { case PYMEM_DOMAIN_RAW: *allocator = _PyMem_Raw; break; case PYMEM_DOMAIN_MEM: *allocator = _PyMem; break; case PYMEM_DOMAIN_OBJ: *allocator = _PyObject; break; default: /* unknown domain: set all attributes to NULL */ allocator->ctx = NULL; allocator->malloc = NULL; allocator->calloc = NULL; allocator->realloc = NULL; allocator->free = NULL; } } void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator) { switch(domain) { case PYMEM_DOMAIN_RAW: _PyMem_Raw = *allocator; break; case PYMEM_DOMAIN_MEM: _PyMem = *allocator; break; case PYMEM_DOMAIN_OBJ: _PyObject = *allocator; break; /* ignore unknown domain */ } } void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator) { *allocator = _PyObject_Arena; } void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator) { _PyObject_Arena = *allocator; } #endif void * PyMem_RawMalloc(size_t size) { /* * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes. * Most python internals blindly use a signed Py_ssize_t to track * things without checking for overflows or negatives. * As size_t is unsigned, checking for size < 0 is not required. */ if (size > (size_t)PY_SSIZE_T_MAX) return NULL; #if IsModeDbg() return _PyMem_Raw.malloc(_PyMem_Raw.ctx, size); #else return _PyMem_RawMalloc(NULL, size); #endif } void * PyMem_RawCalloc(size_t nelem, size_t elsize) { /* see PyMem_RawMalloc() */ if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize) return NULL; #if IsModeDbg() return _PyMem_Raw.calloc(_PyMem_Raw.ctx, nelem, elsize); #else return _PyMem_RawCalloc(NULL, nelem, elsize); #endif } void* PyMem_RawRealloc(void *ptr, size_t new_size) { /* see PyMem_RawMalloc() */ if (new_size > (size_t)PY_SSIZE_T_MAX) return NULL; #if IsModeDbg() return _PyMem_Raw.realloc(_PyMem_Raw.ctx, ptr, new_size); #else return _PyMem_RawRealloc(NULL, ptr, new_size); #endif } void PyMem_RawFree(void *ptr) { #if IsModeDbg() _PyMem_Raw.free(_PyMem_Raw.ctx, ptr); #else _PyMem_RawFree(NULL, ptr); #endif } void * PyMem_Malloc(size_t size) { /* see PyMem_RawMalloc() */ if (size > (size_t)PY_SSIZE_T_MAX) return NULL; #if IsModeDbg() return _PyMem.malloc(_PyMem.ctx, size); #else return _PyObject_Malloc(NULL, size); #endif } void * PyMem_Calloc(size_t nelem, size_t elsize) { /* see PyMem_RawMalloc() */ if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize) return NULL; #if IsModeDbg() return _PyMem.calloc(_PyMem.ctx, nelem, elsize); #else return _PyObject_Calloc(NULL, nelem, elsize); #endif } void * PyMem_Realloc(void *ptr, size_t new_size) { /* see PyMem_RawMalloc() */ if (new_size > (size_t)PY_SSIZE_T_MAX) return NULL; #if IsModeDbg() return _PyMem.realloc(_PyMem.ctx, ptr, new_size); #else return _PyObject_Realloc(NULL, ptr, new_size); #endif } void (PyMem_Free)(void *ptr) { #if IsModeDbg() _PyMem.free(_PyMem.ctx, ptr); #else return _PyObject_Free(NULL, ptr); #endif } char * _PyMem_RawStrdup(const char *str) { size_t size; char *copy; size = strlen(str) + 1; copy = PyMem_RawMalloc(size); if (copy == NULL) return NULL; memcpy(copy, str, size); return copy; } char * _PyMem_Strdup(const char *str) { size_t size; char *copy; size = strlen(str) + 1; copy = PyMem_Malloc(size); if (copy == NULL) return NULL; memcpy(copy, str, size); return copy; } void * (PyObject_Malloc)(size_t size) { /* see PyMem_RawMalloc() */ if (size > (size_t)PY_SSIZE_T_MAX) return NULL; #if IsModeDbg() return _PyObject.malloc(_PyObject.ctx, size); #else return _PyObject_Malloc(NULL, size); #endif } void * PyObject_Calloc(size_t nelem, size_t elsize) { /* see PyMem_RawMalloc() */ if (elsize != 0 && nelem > (size_t)PY_SSIZE_T_MAX / elsize) return NULL; #if IsModeDbg() return _PyObject.calloc(_PyObject.ctx, nelem, elsize); #else return _PyObject_Calloc(NULL, nelem, elsize); #endif } void * PyObject_Realloc(void *ptr, size_t new_size) { /* see PyMem_RawMalloc() */ if (new_size > (size_t)PY_SSIZE_T_MAX) return NULL; #if IsModeDbg() return _PyObject.realloc(_PyObject.ctx, ptr, new_size); #else return _PyObject_Realloc(NULL, ptr, new_size); #endif } void PyObject_Free(void *ptr) { #if IsModeDbg() _PyObject.free(_PyObject.ctx, ptr); #else return _PyObject_Free(NULL, ptr); #endif } #ifdef WITH_PYMALLOC #ifdef WITH_VALGRIND #include <valgrind/valgrind.h> /* If we're using GCC, use __builtin_expect() to reduce overhead of the valgrind checks */ #if defined(__GNUC__) && (__GNUC__ > 2) && defined(__OPTIMIZE__) # define UNLIKELY(value) __builtin_expect((value), 0) #else # define UNLIKELY(value) (value) #endif /* -1 indicates that we haven't checked that we're running on valgrind yet. */ static int running_on_valgrind = -1; #endif /* An object allocator for Python. Here is an introduction to the layers of the Python memory architecture, showing where the object allocator is actually used (layer +2), It is called for every object allocation and deallocation (PyObject_New/Del), unless the object-specific allocators implement a proprietary allocation scheme (ex.: ints use a simple free list). This is also the place where the cyclic garbage collector operates selectively on container objects. Object-specific allocators _____ ______ ______ ________ [ int ] [ dict ] [ list ] ... [ string ] Python core | +3 | <----- Object-specific memory -----> | <-- Non-object memory --> | _______________________________ | | [ Python's object allocator ] | | +2 | ####### Object memory ####### | <------ Internal buffers ------> | ______________________________________________________________ | [ Python's raw memory allocator (PyMem_ API) ] | +1 | <----- Python memory (under PyMem manager's control) ------> | | __________________________________________________________________ [ Underlying general-purpose allocator (ex: C library malloc) ] 0 | <------ Virtual memory allocated for the python process -------> | ========================================================================= _______________________________________________________________________ [ OS-specific Virtual Memory Manager (VMM) ] -1 | <--- Kernel dynamic storage allocation & management (page-based) ---> | __________________________________ __________________________________ [ ] [ ] -2 | <-- Physical memory: ROM/RAM --> | | <-- Secondary storage (swap) --> | */ /*==========================================================================*/ /* A fast, special-purpose memory allocator for small blocks, to be used on top of a general-purpose malloc -- heavily based on previous art. */ /* Vladimir Marangozov -- August 2000 */ /* * "Memory management is where the rubber meets the road -- if we do the wrong * thing at any level, the results will not be good. And if we don't make the * levels work well together, we are in serious trouble." (1) * * (1) Paul R. Wilson, Mark S. Johnstone, Michael Neely, and David Boles, * "Dynamic Storage Allocation: A Survey and Critical Review", * in Proc. 1995 Int'l. Workshop on Memory Management, September 1995. */ /* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */ /*==========================================================================*/ /* * Allocation strategy abstract: * * For small requests, the allocator sub-allocates <Big> blocks of memory. * Requests greater than SMALL_REQUEST_THRESHOLD bytes are routed to the * system's allocator. * * Small requests are grouped in size classes spaced 8 bytes apart, due * to the required valid alignment of the returned address. Requests of * a particular size are serviced from memory pools of 4K (one VMM page). * Pools are fragmented on demand and contain free lists of blocks of one * particular size class. In other words, there is a fixed-size allocator * for each size class. Free pools are shared by the different allocators * thus minimizing the space reserved for a particular size class. * * This allocation strategy is a variant of what is known as "simple * segregated storage based on array of free lists". The main drawback of * simple segregated storage is that we might end up with lot of reserved * memory for the different free lists, which degenerate in time. To avoid * this, we partition each free list in pools and we share dynamically the * reserved space between all free lists. This technique is quite efficient * for memory intensive programs which allocate mainly small-sized blocks. * * For small requests we have the following table: * * Request in bytes Size of allocated block Size class idx * ---------------------------------------------------------------- * 1-8 8 0 * 9-16 16 1 * 17-24 24 2 * 25-32 32 3 * 33-40 40 4 * 41-48 48 5 * 49-56 56 6 * 57-64 64 7 * 65-72 72 8 * ... ... ... * 497-504 504 62 * 505-512 512 63 * * 0, SMALL_REQUEST_THRESHOLD + 1 and up: routed to the underlying * allocator. */ /*==========================================================================*/ /* * -- Main tunable settings section -- */ /* * Alignment of addresses returned to the user. 8-bytes alignment works * on most current architectures (with 32-bit or 64-bit address busses). * The alignment value is also used for grouping small requests in size * classes spaced ALIGNMENT bytes apart. * * You shouldn't change this unless you know what you are doing. */ #define ALIGNMENT 8 /* must be 2^N */ #define ALIGNMENT_SHIFT 3 /* Return the number of bytes in size class I, as a uint. */ #define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT) /* * Max size threshold below which malloc requests are considered to be * small enough in order to use preallocated memory pools. You can tune * this value according to your application behaviour and memory needs. * * Note: a size threshold of 512 guarantees that newly created dictionaries * will be allocated from preallocated memory pools on 64-bit. * * The following invariants must hold: * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 512 * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT * * Although not required, for better performance and space efficiency, * it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2. */ #define SMALL_REQUEST_THRESHOLD 512 #define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT) /* * The system's VMM page size can be obtained on most unices with a * getpagesize() call or deduced from various header files. To make * things simpler, we assume that it is 4K, which is OK for most systems. * It is probably better if this is the native page size, but it doesn't * have to be. In theory, if SYSTEM_PAGE_SIZE is larger than the native page * size, then `POOL_ADDR(p)->arenaindex' could rarely cause a segmentation * violation fault. 4K is apparently OK for all the platforms that python * currently targets. */ #define SYSTEM_PAGE_SIZE (4 * 1024) #define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1) /* * Maximum amount of memory managed by the allocator for small requests. */ #ifdef WITH_MEMORY_LIMITS #ifndef SMALL_MEMORY_LIMIT #define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */ #endif #endif /* * The allocator sub-allocates <Big> blocks of memory (called arenas) aligned * on a page boundary. This is a reserved virtual address space for the * current process (obtained through a malloc()/mmap() call). In no way this * means that the memory arenas will be used entirely. A malloc(<Big>) is * usually an address range reservation for <Big> bytes, unless all pages within * this space are referenced subsequently. So malloc'ing big blocks and not * using them does not mean "wasting memory". It's an addressable range * wastage... * * Arenas are allocated with mmap() on systems supporting anonymous memory * mappings to reduce heap fragmentation. */ #define ARENA_SIZE (256 << 10) /* 256KB */ #ifdef WITH_MEMORY_LIMITS #define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE) #endif /* * Size of the pools used for small blocks. Should be a power of 2, * between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k. */ #define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */ #define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK /* * -- End of tunable settings section -- */ /*==========================================================================*/ /* * Locking * * To reduce lock contention, it would probably be better to refine the * crude function locking with per size class locking. I'm not positive * however, whether it's worth switching to such locking policy because * of the performance penalty it might introduce. * * The following macros describe the simplest (should also be the fastest) * lock object on a particular platform and the init/fini/lock/unlock * operations on it. The locks defined here are not expected to be recursive * because it is assumed that they will always be called in the order: * INIT, [LOCK, UNLOCK]*, FINI. */ /* * Python's threads are serialized, so object malloc locking is disabled. */ #define SIMPLELOCK_DECL(lock) /* simple lock declaration */ #define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */ #define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */ #define SIMPLELOCK_LOCK(lock) /* acquire released lock */ #define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */ /* When you say memory, my mind reasons in terms of (pointers to) blocks */ typedef uint8_t block; /* Pool for small blocks. */ struct pool_header { union { block *_padding; uint count; } ref; /* number of allocated blocks */ block *freeblock; /* pool's free list head */ struct pool_header *nextpool; /* next pool of this size class */ struct pool_header *prevpool; /* previous pool "" */ uint arenaindex; /* index into arenas of base adr */ uint szidx; /* block size class index */ uint nextoffset; /* bytes to virgin block */ uint maxnextoffset; /* largest valid nextoffset */ }; typedef struct pool_header *poolp; /* Record keeping for arenas. */ struct arena_object { /* The address of the arena, as returned by malloc. Note that 0 * will never be returned by a successful malloc, and is used * here to mark an arena_object that doesn't correspond to an * allocated arena. */ uintptr_t address; /* Pool-aligned pointer to the next pool to be carved off. */ block* pool_address; /* The number of available pools in the arena: free pools + never- * allocated pools. */ uint nfreepools; /* The total number of pools in the arena, whether or not available. */ uint ntotalpools; /* Singly-linked list of available pools. */ struct pool_header* freepools; /* Whenever this arena_object is not associated with an allocated * arena, the nextarena member is used to link all unassociated * arena_objects in the singly-linked `unused_arena_objects` list. * The prevarena member is unused in this case. * * When this arena_object is associated with an allocated arena * with at least one available pool, both members are used in the * doubly-linked `usable_arenas` list, which is maintained in * increasing order of `nfreepools` values. * * Else this arena_object is associated with an allocated arena * all of whose pools are in use. `nextarena` and `prevarena` * are both meaningless in this case. */ struct arena_object* nextarena; struct arena_object* prevarena; }; #define POOL_OVERHEAD _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT) #define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */ /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */ #define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE)) /* Return total number of blocks in pool of size index I, as a uint. */ #define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I)) /*==========================================================================*/ /* * This malloc lock */ SIMPLELOCK_DECL(_malloc_lock) #define LOCK() SIMPLELOCK_LOCK(_malloc_lock) #define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock) #define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock) #define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock) /* * Pool table -- headed, circular, doubly-linked lists of partially used pools. This is involved. For an index i, usedpools[i+i] is the header for a list of all partially used pools holding small blocks with "size class idx" i. So usedpools[0] corresponds to blocks of size 8, usedpools[2] to blocks of size 16, and so on: index 2*i <-> blocks of size (i+1)<<ALIGNMENT_SHIFT. Pools are carved off an arena's highwater mark (an arena_object's pool_address member) as needed. Once carved off, a pool is in one of three states forever after: used == partially used, neither empty nor full At least one block in the pool is currently allocated, and at least one block in the pool is not currently allocated (note this implies a pool has room for at least two blocks). This is a pool's initial state, as a pool is created only when malloc needs space. The pool holds blocks of a fixed size, and is in the circular list headed at usedpools[i] (see above). It's linked to the other used pools of the same size class via the pool_header's nextpool and prevpool members. If all but one block is currently allocated, a malloc can cause a transition to the full state. If all but one block is not currently allocated, a free can cause a transition to the empty state. full == all the pool's blocks are currently allocated On transition to full, a pool is unlinked from its usedpools[] list. It's not linked to from anything then anymore, and its nextpool and prevpool members are meaningless until it transitions back to used. A free of a block in a full pool puts the pool back in the used state. Then it's linked in at the front of the appropriate usedpools[] list, so that the next allocation for its size class will reuse the freed block. empty == all the pool's blocks are currently available for allocation On transition to empty, a pool is unlinked from its usedpools[] list, and linked to the front of its arena_object's singly-linked freepools list, via its nextpool member. The prevpool member has no meaning in this case. Empty pools have no inherent size class: the next time a malloc finds an empty list in usedpools[], it takes the first pool off of freepools. If the size class needed happens to be the same as the size class the pool last had, some pool initialization can be skipped. Block Management Blocks within pools are again carved out as needed. pool->freeblock points to the start of a singly-linked list of free blocks within the pool. When a block is freed, it's inserted at the front of its pool's freeblock list. Note that the available blocks in a pool are *not* linked all together when a pool is initialized. Instead only "the first two" (lowest addresses) blocks are set up, returning the first such block, and setting pool->freeblock to a one-block list holding the second such block. This is consistent with that pymalloc strives at all levels (arena, pool, and block) never to touch a piece of memory until it's actually needed. So long as a pool is in the used state, we're certain there *is* a block available for allocating, and pool->freeblock is not NULL. If pool->freeblock points to the end of the free list before we've carved the entire pool into blocks, that means we simply haven't yet gotten to one of the higher-address blocks. The offset from the pool_header to the start of "the next" virgin block is stored in the pool_header nextoffset member, and the largest value of nextoffset that makes sense is stored in the maxnextoffset member when a pool is initialized. All the blocks in a pool have been passed out at least once when and only when nextoffset > maxnextoffset. Major obscurity: While the usedpools vector is declared to have poolp entries, it doesn't really. It really contains two pointers per (conceptual) poolp entry, the nextpool and prevpool members of a pool_header. The excruciating initialization code below fools C so that usedpool[i+i] "acts like" a genuine poolp, but only so long as you only reference its nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is compensating for that a pool_header's nextpool and prevpool members immediately follow a pool_header's first two members: union { block *_padding; uint count; } ref; block *freeblock; each of which consume sizeof(block *) bytes. So what usedpools[i+i] really contains is a fudged-up pointer p such that *if* C believes it's a poolp pointer, then p->nextpool and p->prevpool are both p (meaning that the headed circular list is empty). It's unclear why the usedpools setup is so convoluted. It could be to minimize the amount of cache required to hold this heavily-referenced table (which only *needs* the two interpool pointer members of a pool_header). OTOH, referencing code has to remember to "double the index" and doing so isn't free, usedpools[0] isn't a strictly legal pointer, and we're crucially relying on that C doesn't insert any padding anywhere in a pool_header at or before the prevpool member. **************************************************************************** */ #define PTA(x) ((poolp )((uint8_t *)&(usedpools[2*(x)]) - 2*sizeof(block *))) #define PT(x) PTA(x), PTA(x) static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = { PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7) #if NB_SMALL_SIZE_CLASSES > 8 , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15) #if NB_SMALL_SIZE_CLASSES > 16 , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23) #if NB_SMALL_SIZE_CLASSES > 24 , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31) #if NB_SMALL_SIZE_CLASSES > 32 , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39) #if NB_SMALL_SIZE_CLASSES > 40 , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47) #if NB_SMALL_SIZE_CLASSES > 48 , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55) #if NB_SMALL_SIZE_CLASSES > 56 , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63) #if NB_SMALL_SIZE_CLASSES > 64 #error "NB_SMALL_SIZE_CLASSES should be less than 64" #endif /* NB_SMALL_SIZE_CLASSES > 64 */ #endif /* NB_SMALL_SIZE_CLASSES > 56 */ #endif /* NB_SMALL_SIZE_CLASSES > 48 */ #endif /* NB_SMALL_SIZE_CLASSES > 40 */ #endif /* NB_SMALL_SIZE_CLASSES > 32 */ #endif /* NB_SMALL_SIZE_CLASSES > 24 */ #endif /* NB_SMALL_SIZE_CLASSES > 16 */ #endif /* NB_SMALL_SIZE_CLASSES > 8 */ }; /*========================================================================== Arena management. `arenas` is a vector of arena_objects. It contains maxarenas entries, some of which may not be currently used (== they're arena_objects that aren't currently associated with an allocated arena). Note that arenas proper are separately malloc'ed. Prior to Python 2.5, arenas were never free()'ed. Starting with Python 2.5, we do try to free() arenas, and use some mild heuristic strategies to increase the likelihood that arenas eventually can be freed. unused_arena_objects This is a singly-linked list of the arena_objects that are currently not being used (no arena is associated with them). Objects are taken off the head of the list in new_arena(), and are pushed on the head of the list in PyObject_Free() when the arena is empty. Key invariant: an arena_object is on this list if and only if its .address member is 0. usable_arenas This is a doubly-linked list of the arena_objects associated with arenas that have pools available. These pools are either waiting to be reused, or have not been used before. The list is sorted to have the most- allocated arenas first (ascending order based on the nfreepools member). This means that the next allocation will come from a heavily used arena, which gives the nearly empty arenas a chance to be returned to the system. In my unscientific tests this dramatically improved the number of arenas that could be freed. Note that an arena_object associated with an arena all of whose pools are currently in use isn't on either list. */ /* Array of objects used to track chunks of memory (arenas). */ static struct arena_object* arenas = NULL; /* Number of slots currently allocated in the `arenas` vector. */ static uint maxarenas = 0; /* The head of the singly-linked, NULL-terminated list of available * arena_objects. */ static struct arena_object* unused_arena_objects = NULL; /* The head of the doubly-linked, NULL-terminated at each end, list of * arena_objects associated with arenas that have pools available. */ static struct arena_object* usable_arenas = NULL; /* How many arena_objects do we initially allocate? * 16 = can allocate 16 arenas = 16 * ARENA_SIZE = 4MB before growing the * `arenas` vector. */ #define INITIAL_ARENA_OBJECTS 16 /* Number of arenas allocated that haven't been free()'d. */ static size_t narenas_currently_allocated = 0; /* Total number of times malloc() called to allocate an arena. */ static size_t ntimes_arena_allocated = 0; /* High water mark (max value ever seen) for narenas_currently_allocated. */ static size_t narenas_highwater = 0; static Py_ssize_t _Py_AllocatedBlocks = 0; Py_ssize_t _Py_GetAllocatedBlocks(void) { return _Py_AllocatedBlocks; } /* Allocate a new arena. If we run out of memory, return NULL. Else * allocate a new arena, and return the address of an arena_object * describing the new arena. It's expected that the caller will set * `usable_arenas` to the return value. */ static struct arena_object* new_arena(void) { struct arena_object* arenaobj; uint excess; /* number of bytes above pool alignment */ void *address; static int debug_stats = -1; if (debug_stats == -1) { char *opt = Py_GETENV("PYTHONMALLOCSTATS"); debug_stats = (opt != NULL && *opt != '\0'); } if (debug_stats) _PyObject_DebugMallocStats(stderr); if (unused_arena_objects == NULL) { uint i; uint numarenas; size_t nbytes; /* Double the number of arena objects on each allocation. * Note that it's possible for `numarenas` to overflow. */ numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS; if (numarenas <= maxarenas) return NULL; /* overflow */ #if SIZEOF_SIZE_T <= SIZEOF_INT if (numarenas > SIZE_MAX / sizeof(*arenas)) return NULL; /* overflow */ #endif nbytes = numarenas * sizeof(*arenas); arenaobj = (struct arena_object *)PyMem_RawRealloc(arenas, nbytes); if (arenaobj == NULL) return NULL; arenas = arenaobj; /* We might need to fix pointers that were copied. However, * new_arena only gets called when all the pages in the * previous arenas are full. Thus, there are *no* pointers * into the old array. Thus, we don't have to worry about * invalid pointers. Just to be sure, some asserts: */ assert(usable_arenas == NULL); assert(unused_arena_objects == NULL); /* Put the new arenas on the unused_arena_objects list. */ for (i = maxarenas; i < numarenas; ++i) { arenas[i].address = 0; /* mark as unassociated */ arenas[i].nextarena = i < numarenas - 1 ? &arenas[i+1] : NULL; } /* Update globals. */ unused_arena_objects = &arenas[maxarenas]; maxarenas = numarenas; } /* Take the next available arena object off the head of the list. */ assert(unused_arena_objects != NULL); arenaobj = unused_arena_objects; unused_arena_objects = arenaobj->nextarena; assert(arenaobj->address == 0); #if IsModeDbg() address = _PyObject_Arena.alloc(_PyObject_Arena.ctx, ARENA_SIZE); #else address = _PyObject_ArenaMmap(NULL, ARENA_SIZE); #endif if (address == NULL) { /* The allocation failed: return NULL after putting the * arenaobj back. */ arenaobj->nextarena = unused_arena_objects; unused_arena_objects = arenaobj; return NULL; } arenaobj->address = (uintptr_t)address; ++narenas_currently_allocated; ++ntimes_arena_allocated; if (narenas_currently_allocated > narenas_highwater) narenas_highwater = narenas_currently_allocated; arenaobj->freepools = NULL; /* pool_address <- first pool-aligned address in the arena nfreepools <- number of whole pools that fit after alignment */ arenaobj->pool_address = (block*)arenaobj->address; arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE; assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE); excess = (uint)(arenaobj->address & POOL_SIZE_MASK); if (excess != 0) { --arenaobj->nfreepools; arenaobj->pool_address += POOL_SIZE - excess; } arenaobj->ntotalpools = arenaobj->nfreepools; return arenaobj; } /* address_in_range(P, POOL) Return true if and only if P is an address that was allocated by pymalloc. POOL must be the pool address associated with P, i.e., POOL = POOL_ADDR(P) (the caller is asked to compute this because the macro expands POOL more than once, and for efficiency it's best for the caller to assign POOL_ADDR(P) to a variable and pass the latter to the macro; because address_in_range is called on every alloc/realloc/free, micro-efficiency is important here). Tricky: Let B be the arena base address associated with the pool, B = arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if B <= P < B + ARENA_SIZE Subtracting B throughout, this is true iff 0 <= P-B < ARENA_SIZE By using unsigned arithmetic, the "0 <=" half of the test can be skipped. Obscure: A PyMem "free memory" function can call the pymalloc free or realloc before the first arena has been allocated. `arenas` is still NULL in that case. We're relying on that maxarenas is also 0 in that case, so that (POOL)->arenaindex < maxarenas must be false, saving us from trying to index into a NULL arenas. Details: given P and POOL, the arena_object corresponding to P is AO = arenas[(POOL)->arenaindex]. Suppose obmalloc controls P. Then (barring wild stores, etc), POOL is the correct address of P's pool, AO.address is the correct base address of the pool's arena, and P must be within ARENA_SIZE of AO.address. In addition, AO.address is not 0 (no arena can start at address 0 (NULL)). Therefore address_in_range correctly reports that obmalloc controls P. Now suppose obmalloc does not control P (e.g., P was obtained via a direct call to the system malloc() or realloc()). (POOL)->arenaindex may be anything in this case -- it may even be uninitialized trash. If the trash arenaindex is >= maxarenas, the macro correctly concludes at once that obmalloc doesn't control P. Else arenaindex is < maxarena, and AO is read up. If AO corresponds to an allocated arena, obmalloc controls all the memory in slice AO.address : AO.address+ARENA_SIZE. By case assumption, P is not controlled by obmalloc, so P doesn't lie in that slice, so the macro correctly reports that P is not controlled by obmalloc. Finally, if P is not controlled by obmalloc and AO corresponds to an unused arena_object (one not currently associated with an allocated arena), AO.address is 0, and the second test in the macro reduces to: P < ARENA_SIZE If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part of the test still passes, and the third clause (AO.address != 0) is necessary to get the correct result: AO.address is 0 in this case, so the macro correctly reports that P is not controlled by obmalloc (despite that P lies in slice AO.address : AO.address + ARENA_SIZE). Note: The third (AO.address != 0) clause was added in Python 2.5. Before 2.5, arenas were never free()'ed, and an arenaindex < maxarena always corresponded to a currently-allocated arena, so the "P is not controlled by obmalloc, AO corresponds to an unused arena_object, and P < ARENA_SIZE" case was impossible. Note that the logic is excruciating, and reading up possibly uninitialized memory when P is not controlled by obmalloc (to get at (POOL)->arenaindex) creates problems for some memory debuggers. The overwhelming advantage is that this test determines whether an arbitrary address is controlled by obmalloc in a small constant time, independent of the number of arenas obmalloc controls. Since this test is needed at every entry point, it's extremely desirable that it be this fast. */ static inline bool _Py_NO_ADDRESS_SAFETY_ANALYSIS _Py_NO_SANITIZE_THREAD _Py_NO_SANITIZE_MEMORY address_in_range(void *p, poolp pool) { #ifdef WITH_THREAD // Since address_in_range may be reading from memory which was not allocated // by Python, it is important that pool->arenaindex is read only once, as // another thread may be concurrently modifying the value without holding // the GIL. The following dance forces the compiler to read pool->arenaindex // only once. uint arenaindex = *((volatile uint *)&pool->arenaindex); return arenaindex < maxarenas && (uintptr_t)p - arenas[arenaindex].address < ARENA_SIZE && arenas[arenaindex].address != 0; #else return pool->arenaindex < maxarenas && (uintptr_t)p - arenas[pool->arenaindex].address < ARENA_SIZE && arenas[pool->arenaindex].address != 0; #endif } /*==========================================================================*/ /* malloc. Note that nbytes==0 tries to return a non-NULL pointer, distinct * from all other currently live pointers. This may not be possible. */ /* * The basic blocks are ordered by decreasing execution frequency, * which minimizes the number of jumps in the most common cases, * improves branching prediction and instruction scheduling (small * block allocations typically result in a couple of instructions). * Unless the optimizer reorders everything, being too smart... */ static void * _PyObject_Alloc(int use_calloc, void *ctx, size_t nelem, size_t elsize) { size_t nbytes; block *bp; poolp pool; poolp next; uint size; _Py_AllocatedBlocks++; assert(elsize == 0 || nelem <= PY_SSIZE_T_MAX / elsize); nbytes = nelem * elsize; #ifdef WITH_VALGRIND if (UNLIKELY(running_on_valgrind == -1)) running_on_valgrind = RUNNING_ON_VALGRIND; if (UNLIKELY(running_on_valgrind)) goto redirect; #endif if (nelem == 0 || elsize == 0) goto redirect; if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) { LOCK(); /* * Most frequent paths first */ size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT; pool = usedpools[size + size]; if (pool != pool->nextpool) { /* * There is a used pool for this size class. * Pick up the head block of its free list. */ ++pool->ref.count; bp = pool->freeblock; assert(bp != NULL); if ((pool->freeblock = *(block **)bp) != NULL) { UNLOCK(); if (use_calloc) bzero(bp, nbytes); return (void *)bp; } /* * Reached the end of the free list, try to extend it. */ if (pool->nextoffset <= pool->maxnextoffset) { /* There is room for another block. */ pool->freeblock = (block*)pool + pool->nextoffset; pool->nextoffset += INDEX2SIZE(size); *(block **)(pool->freeblock) = NULL; UNLOCK(); if (use_calloc) bzero(bp, nbytes); return (void *)bp; } /* Pool is full, unlink from used pools. */ next = pool->nextpool; pool = pool->prevpool; next->prevpool = pool; pool->nextpool = next; UNLOCK(); if (use_calloc) bzero(bp, nbytes); return (void *)bp; } /* There isn't a pool of the right size class immediately * available: use a free pool. */ if (usable_arenas == NULL) { /* No arena has a free pool: allocate a new arena. */ #ifdef WITH_MEMORY_LIMITS if (narenas_currently_allocated >= MAX_ARENAS) { UNLOCK(); goto redirect; } #endif usable_arenas = new_arena(); if (usable_arenas == NULL) { UNLOCK(); goto redirect; } usable_arenas->nextarena = usable_arenas->prevarena = NULL; } assert(usable_arenas->address != 0); /* Try to get a cached free pool. */ pool = usable_arenas->freepools; if (pool != NULL) { /* Unlink from cached pools. */ usable_arenas->freepools = pool->nextpool; /* This arena already had the smallest nfreepools * value, so decreasing nfreepools doesn't change * that, and we don't need to rearrange the * usable_arenas list. However, if the arena has * become wholly allocated, we need to remove its * arena_object from usable_arenas. */ --usable_arenas->nfreepools; if (usable_arenas->nfreepools == 0) { /* Wholly allocated: remove. */ assert(usable_arenas->freepools == NULL); assert(usable_arenas->nextarena == NULL || usable_arenas->nextarena->prevarena == usable_arenas); usable_arenas = usable_arenas->nextarena; if (usable_arenas != NULL) { usable_arenas->prevarena = NULL; assert(usable_arenas->address != 0); } } else { /* nfreepools > 0: it must be that freepools * isn't NULL, or that we haven't yet carved * off all the arena's pools for the first * time. */ assert(usable_arenas->freepools != NULL || usable_arenas->pool_address <= (block*)usable_arenas->address + ARENA_SIZE - POOL_SIZE); } init_pool: /* Frontlink to used pools. */ next = usedpools[size + size]; /* == prev */ pool->nextpool = next; pool->prevpool = next; next->nextpool = pool; next->prevpool = pool; pool->ref.count = 1; if (pool->szidx == size) { /* Luckily, this pool last contained blocks * of the same size class, so its header * and free list are already initialized. */ bp = pool->freeblock; assert(bp != NULL); pool->freeblock = *(block **)bp; UNLOCK(); if (use_calloc) bzero(bp, nbytes); return (void *)bp; } /* * Initialize the pool header, set up the free list to * contain just the second block, and return the first * block. */ pool->szidx = size; size = INDEX2SIZE(size); bp = (block *)pool + POOL_OVERHEAD; pool->nextoffset = POOL_OVERHEAD + (size << 1); pool->maxnextoffset = POOL_SIZE - size; pool->freeblock = bp + size; *(block **)(pool->freeblock) = NULL; UNLOCK(); if (use_calloc) bzero(bp, nbytes); return (void *)bp; } /* Carve off a new pool. */ assert(usable_arenas->nfreepools > 0); assert(usable_arenas->freepools == NULL); pool = (poolp)usable_arenas->pool_address; assert((block*)pool <= (block*)usable_arenas->address + ARENA_SIZE - POOL_SIZE); pool->arenaindex = (uint)(usable_arenas - arenas); assert(&arenas[pool->arenaindex] == usable_arenas); pool->szidx = DUMMY_SIZE_IDX; usable_arenas->pool_address += POOL_SIZE; --usable_arenas->nfreepools; if (usable_arenas->nfreepools == 0) { assert(usable_arenas->nextarena == NULL || usable_arenas->nextarena->prevarena == usable_arenas); /* Unlink the arena: it is completely allocated. */ usable_arenas = usable_arenas->nextarena; if (usable_arenas != NULL) { usable_arenas->prevarena = NULL; assert(usable_arenas->address != 0); } } goto init_pool; } /* The small block allocator ends here. */ redirect: /* Redirect the original request to the underlying (libc) allocator. * We jump here on bigger requests, on error in the code above (as a * last chance to serve the request) or when the max memory limit * has been reached. */ { void *result; if (use_calloc) result = PyMem_RawCalloc(nelem, elsize); else result = PyMem_RawMalloc(nbytes); if (!result) _Py_AllocatedBlocks--; return result; } } static inline void * _PyObject_Malloc(void *ctx, size_t nbytes) { return _PyObject_Alloc(0, ctx, 1, nbytes); } static inline void * _PyObject_Calloc(void *ctx, size_t nelem, size_t elsize) { return _PyObject_Alloc(1, ctx, nelem, elsize); } /* free */ static void _PyObject_Free(void *ctx, void *p) { poolp pool; block *lastfree; poolp next, prev; uint size; if (p == NULL) /* free(NULL) has no effect */ return; _Py_AllocatedBlocks--; #ifdef WITH_VALGRIND if (UNLIKELY(running_on_valgrind > 0)) goto redirect; #endif pool = POOL_ADDR(p); if (address_in_range(p, pool)) { /* We allocated this address. */ LOCK(); /* Link p to the start of the pool's freeblock list. Since * the pool had at least the p block outstanding, the pool * wasn't empty (so it's already in a usedpools[] list, or * was full and is in no list -- it's not in the freeblocks * list in any case). */ assert(pool->ref.count > 0); /* else it was empty */ *(block **)p = lastfree = pool->freeblock; pool->freeblock = (block *)p; if (lastfree) { struct arena_object* ao; uint nf; /* ao->nfreepools */ /* freeblock wasn't NULL, so the pool wasn't full, * and the pool is in a usedpools[] list. */ if (--pool->ref.count != 0) { /* pool isn't empty: leave it in usedpools */ UNLOCK(); return; } /* Pool is now empty: unlink from usedpools, and * link to the front of freepools. This ensures that * previously freed pools will be allocated later * (being not referenced, they are perhaps paged out). */ next = pool->nextpool; prev = pool->prevpool; next->prevpool = prev; prev->nextpool = next; /* Link the pool to freepools. This is a singly-linked * list, and pool->prevpool isn't used there. */ ao = &arenas[pool->arenaindex]; pool->nextpool = ao->freepools; ao->freepools = pool; nf = ++ao->nfreepools; /* All the rest is arena management. We just freed * a pool, and there are 4 cases for arena mgmt: * 1. If all the pools are free, return the arena to * the system free(). * 2. If this is the only free pool in the arena, * add the arena back to the `usable_arenas` list. * 3. If the "next" arena has a smaller count of free * pools, we have to "slide this arena right" to * restore that usable_arenas is sorted in order of * nfreepools. * 4. Else there's nothing more to do. */ if (nf == ao->ntotalpools) { /* Case 1. First unlink ao from usable_arenas. */ assert(ao->prevarena == NULL || ao->prevarena->address != 0); assert(ao ->nextarena == NULL || ao->nextarena->address != 0); /* Fix the pointer in the prevarena, or the * usable_arenas pointer. */ if (ao->prevarena == NULL) { usable_arenas = ao->nextarena; assert(usable_arenas == NULL || usable_arenas->address != 0); } else { assert(ao->prevarena->nextarena == ao); ao->prevarena->nextarena = ao->nextarena; } /* Fix the pointer in the nextarena. */ if (ao->nextarena != NULL) { assert(ao->nextarena->prevarena == ao); ao->nextarena->prevarena = ao->prevarena; } /* Record that this arena_object slot is * available to be reused. */ ao->nextarena = unused_arena_objects; unused_arena_objects = ao; /* Free the entire arena. */ #if IsModeDbg() _PyObject_Arena.free(_PyObject_Arena.ctx, (void *)ao->address, ARENA_SIZE); #else _PyObject_ArenaMunmap(NULL, (void *)ao->address, ARENA_SIZE); #endif ao->address = 0; /* mark unassociated */ --narenas_currently_allocated; UNLOCK(); return; } if (nf == 1) { /* Case 2. Put ao at the head of * usable_arenas. Note that because * ao->nfreepools was 0 before, ao isn't * currently on the usable_arenas list. */ ao->nextarena = usable_arenas; ao->prevarena = NULL; if (usable_arenas) usable_arenas->prevarena = ao; usable_arenas = ao; assert(usable_arenas->address != 0); UNLOCK(); return; } /* If this arena is now out of order, we need to keep * the list sorted. The list is kept sorted so that * the "most full" arenas are used first, which allows * the nearly empty arenas to be completely freed. In * a few un-scientific tests, it seems like this * approach allowed a lot more memory to be freed. */ if (ao->nextarena == NULL || nf <= ao->nextarena->nfreepools) { /* Case 4. Nothing to do. */ UNLOCK(); return; } /* Case 3: We have to move the arena towards the end * of the list, because it has more free pools than * the arena to its right. * First unlink ao from usable_arenas. */ if (ao->prevarena != NULL) { /* ao isn't at the head of the list */ assert(ao->prevarena->nextarena == ao); ao->prevarena->nextarena = ao->nextarena; } else { /* ao is at the head of the list */ assert(usable_arenas == ao); usable_arenas = ao->nextarena; } ao->nextarena->prevarena = ao->prevarena; /* Locate the new insertion point by iterating over * the list, using our nextarena pointer. */ while (ao->nextarena != NULL && nf > ao->nextarena->nfreepools) { ao->prevarena = ao->nextarena; ao->nextarena = ao->nextarena->nextarena; } /* Insert ao at this point. */ assert(ao->nextarena == NULL || ao->prevarena == ao->nextarena->prevarena); assert(ao->prevarena->nextarena == ao->nextarena); ao->prevarena->nextarena = ao; if (ao->nextarena != NULL) ao->nextarena->prevarena = ao; /* Verify that the swaps worked. */ assert(ao->nextarena == NULL || nf <= ao->nextarena->nfreepools); assert(ao->prevarena == NULL || nf > ao->prevarena->nfreepools); assert(ao->nextarena == NULL || ao->nextarena->prevarena == ao); assert((usable_arenas == ao && ao->prevarena == NULL) || ao->prevarena->nextarena == ao); UNLOCK(); return; } /* Pool was full, so doesn't currently live in any list: * link it to the front of the appropriate usedpools[] list. * This mimics LRU pool usage for new allocations and * targets optimal filling when several pools contain * blocks of the same size class. */ --pool->ref.count; assert(pool->ref.count > 0); /* else the pool is empty */ size = pool->szidx; next = usedpools[size + size]; prev = next->prevpool; /* insert pool before next: prev <-> pool <-> next */ pool->nextpool = next; pool->prevpool = prev; next->prevpool = pool; prev->nextpool = pool; UNLOCK(); return; } #ifdef WITH_VALGRIND redirect: #endif /* We didn't allocate this address. */ PyMem_RawFree(p); } /* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0, * then as the Python docs promise, we do not treat this like free(p), and * return a non-NULL result. */ static void * _PyObject_Realloc(void *ctx, void *p, size_t nbytes) { void *bp; poolp pool; size_t size; if (p == NULL) return _PyObject_Alloc(0, ctx, 1, nbytes); #ifdef WITH_VALGRIND /* Treat running_on_valgrind == -1 the same as 0 */ if (UNLIKELY(running_on_valgrind > 0)) goto redirect; #endif pool = POOL_ADDR(p); if (address_in_range(p, pool)) { /* We're in charge of this block */ size = INDEX2SIZE(pool->szidx); if (nbytes <= size) { /* The block is staying the same or shrinking. If * it's shrinking, there's a tradeoff: it costs * cycles to copy the block to a smaller size class, * but it wastes memory not to copy it. The * compromise here is to copy on shrink only if at * least 25% of size can be shaved off. */ if (4 * nbytes > 3 * size) { /* It's the same, * or shrinking and new/old > 3/4. */ return p; } size = nbytes; } bp = _PyObject_Alloc(0, ctx, 1, nbytes); if (bp != NULL) { memcpy(bp, p, size); _PyObject_Free(ctx, p); } return bp; } #ifdef WITH_VALGRIND redirect: #endif /* We're not managing this block. If nbytes <= * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this * block. However, if we do, we need to copy the valid data from * the C-managed block to one of our blocks, and there's no portable * way to know how much of the memory space starting at p is valid. * As bug 1185883 pointed out the hard way, it's possible that the * C-managed block is "at the end" of allocated VM space, so that * a memory fault can occur if we try to copy nbytes bytes starting * at p. Instead we punt: let C continue to manage this block. */ if (nbytes) return PyMem_RawRealloc(p, nbytes); /* C doesn't define the result of realloc(p, 0) (it may or may not * return NULL then), but Python's docs promise that nbytes==0 never * returns NULL. We don't pass 0 to realloc(), to avoid that endcase * to begin with. Even then, we can't be sure that realloc() won't * return NULL. */ bp = PyMem_RawRealloc(p, 1); return bp ? bp : p; } #else /* ! WITH_PYMALLOC */ /*==========================================================================*/ /* pymalloc not enabled: Redirect the entry points to malloc. These will * only be used by extensions that are compiled with pymalloc enabled. */ Py_ssize_t _Py_GetAllocatedBlocks(void) { return 0; } #endif /* WITH_PYMALLOC */ /*==========================================================================*/ /* A x-platform debugging allocator. This doesn't manage memory directly, * it wraps a real allocator, adding extra debugging info to the memory blocks. */ /* Special bytes broadcast into debug memory blocks at appropriate times. * Strings of these are unlikely to be valid addresses, floats, ints or * 7-bit ASCII. */ #undef CLEANBYTE #undef DEADBYTE #undef FORBIDDENBYTE #define CLEANBYTE 0xCB /* clean (newly allocated) memory */ #define DEADBYTE 0xDB /* dead (newly freed) memory */ #define FORBIDDENBYTE 0xFB /* untouchable bytes at each end of a block */ static size_t serialno = 0; /* incremented on each debug {m,re}alloc */ /* serialno is always incremented via calling this routine. The point is * to supply a single place to set a breakpoint. */ static inline void bumpserialno(void) { ++serialno; } #define SST SIZEOF_SIZE_T static inline optimizespeed noasan size_t read_size_t(const void *p) { return READ64BE(p); } static inline optimizespeed noasan void write_size_t(void *p, size_t n) { WRITE64BE((char *)p, n); } #if IsModeDbg() /* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and fills them with useful stuff, here calling the underlying malloc's result p: p[0: S] Number of bytes originally asked for. This is a size_t, big-endian (easier to read in a memory dump). p[S] API ID. See PEP 445. This is a character, but seems undocumented. p[S+1: 2*S] Copies of FORBIDDENBYTE. Used to catch under- writes and reads. p[2*S: 2*S+n] The requested memory, filled with copies of CLEANBYTE. Used to catch reference to uninitialized memory. &p[2*S] is returned. Note that this is 8-byte aligned if pymalloc handled the request itself. p[2*S+n: 2*S+n+S] Copies of FORBIDDENBYTE. Used to catch over- writes and reads. p[2*S+n+S: 2*S+n+2*S] A serial number, incremented by 1 on each call to _PyMem_DebugMalloc and _PyMem_DebugRealloc. This is a big-endian size_t. If "bad memory" is detected later, the serial number gives an excellent way to set a breakpoint on the next run, to capture the instant at which this block was passed out. */ static void * _PyMem_DebugRawAlloc(int use_calloc, void *ctx, size_t nbytes) { debug_alloc_api_t *api = (debug_alloc_api_t *)ctx; uint8_t *p; /* base address of malloc'ed block */ uint8_t *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */ size_t total; /* nbytes + 4*SST */ bumpserialno(); total = nbytes + 4*SST; if (nbytes > PY_SSIZE_T_MAX - 4*SST) /* overflow: can't represent total as a Py_ssize_t */ return NULL; if (use_calloc) p = (uint8_t *)api->alloc.calloc(api->alloc.ctx, 1, total); else p = (uint8_t *)api->alloc.malloc(api->alloc.ctx, total); if (p == NULL) return NULL; /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */ write_size_t(p, nbytes); p[SST] = (uint8_t)api->api_id; memset(p + SST + 1, FORBIDDENBYTE, SST-1); if (nbytes > 0 && !use_calloc) memset(p + 2*SST, CLEANBYTE, nbytes); /* at tail, write pad (SST bytes) and serialno (SST bytes) */ tail = p + 2*SST + nbytes; memset(tail, FORBIDDENBYTE, SST); write_size_t(tail + SST, serialno); _PyMem_DebugCheckAddress(api->api_id, p+2*SST); if (IsAsan()) { __asan_poison((p + SST + 1), SST-1, kAsanHeapUnderrun); __asan_poison(tail, SST, kAsanHeapOverrun); } return p + 2*SST; } static void * _PyMem_DebugRawMalloc(void *ctx, size_t nbytes) { return _PyMem_DebugRawAlloc(0, ctx, nbytes); } static void * _PyMem_DebugRawCalloc(void *ctx, size_t nelem, size_t elsize) { size_t nbytes; assert(elsize == 0 || nelem <= PY_SSIZE_T_MAX / elsize); nbytes = nelem * elsize; return _PyMem_DebugRawAlloc(1, ctx, nbytes); } /* Heuristic checking if the memory has been freed. Rely on the debug hooks on Python memory allocators which fills the memory with DEADBYTE (0xDB) when memory is deallocated. */ int (_PyMem_IsFreed)(void *ptr, size_t size) { unsigned char *bytes = ptr; for (size_t i=0; i < size; i++) { if (bytes[i] != DEADBYTE) { return 0; } } return 1; } /* The debug free first checks the 2*SST bytes on each end for sanity (in particular, that the FORBIDDENBYTEs with the api ID are still intact). Then fills the original bytes with DEADBYTE. Then calls the underlying free. */ static void _PyMem_DebugRawFree(void *ctx, void *p) { debug_alloc_api_t *api; uint8_t *q; size_t nbytes; if (p == NULL) return; api = (debug_alloc_api_t *)ctx; q = (uint8_t *)p - 2*SST; /* address returned from malloc */ _PyMem_DebugCheckAddress(api->api_id, p); nbytes = read_size_t(q); nbytes += 4*SST; if (nbytes > 0) { if (IsAsan()) { __asan_unpoison(q, nbytes); } memset(q, DEADBYTE, nbytes); } api->alloc.free(api->alloc.ctx, q); } static noasan void * _PyMem_DebugRawRealloc(void *ctx, void *p, size_t nbytes) { _Static_assert(sizeof(size_t) == 8, ""); debug_alloc_api_t *api = (debug_alloc_api_t *)ctx; uint8_t *q = (uint8_t *)p; uint8_t *tail; size_t total; /* nbytes + 4*SST */ size_t original_nbytes; size_t w; int i; if (p == NULL) return _PyMem_DebugRawAlloc(0, ctx, nbytes); _PyMem_DebugCheckAddress(api->api_id, p); bumpserialno(); original_nbytes = read_size_t(q - 2*SST); total = nbytes + 4*SST; if (nbytes > PY_SSIZE_T_MAX - 4*SST) /* overflow: can't represent total as a Py_ssize_t */ return NULL; /* Resize and add decorations. */ q = (uint8_t *)api->alloc.realloc(api->alloc.ctx, q - 2*SST, total); if (q == NULL) return NULL; write_size_t(q, nbytes); assert(q[SST] == (uint8_t)api->api_id); for (i = 1; i < SST; ++i) assert(q[SST + i] == FORBIDDENBYTE); q += 2*SST; tail = q + nbytes; w = 0x0101010101010101ull * FORBIDDENBYTE; WRITE64LE(tail, w); if (IsAsan()) __asan_poison(tail, SST, kAsanHeapOverrun); write_size_t(tail + SST, serialno); if (nbytes > original_nbytes) { /* growing: mark new extra memory clean */ if (IsAsan()) { __asan_unpoison((q + original_nbytes), nbytes - original_nbytes); } memset(q + original_nbytes, CLEANBYTE, nbytes - original_nbytes); } return q; } static inline void _PyMem_DebugCheckGIL(void) { #ifdef WITH_THREAD if (!PyGILState_Check()) Py_FatalError("Python memory allocator called " "without holding the GIL"); #endif } static void * _PyMem_DebugMalloc(void *ctx, size_t nbytes) { _PyMem_DebugCheckGIL(); return _PyMem_DebugRawMalloc(ctx, nbytes); } static void * _PyMem_DebugCalloc(void *ctx, size_t nelem, size_t elsize) { _PyMem_DebugCheckGIL(); return _PyMem_DebugRawCalloc(ctx, nelem, elsize); } static void _PyMem_DebugFree(void *ctx, void *ptr) { _PyMem_DebugCheckGIL(); _PyMem_DebugRawFree(ctx, ptr); } static void * _PyMem_DebugRealloc(void *ctx, void *ptr, size_t nbytes) { _PyMem_DebugCheckGIL(); return _PyMem_DebugRawRealloc(ctx, ptr, nbytes); } /* Check the forbidden bytes on both ends of the memory allocated for p. * If anything is wrong, print info to stderr via _PyObject_DebugDumpAddress, * and call Py_FatalError to kill the program. * The API id, is also checked. */ static noasan void _PyMem_DebugCheckAddress(char api, const void *p) { const uint8_t *q = (const uint8_t *)p; char msgbuf[64]; char *msg; size_t nbytes; const uint8_t *tail; int i; char id; if (p == NULL) { msg = "didn't expect a NULL pointer"; goto error; } /* Check the API id */ id = (char)q[-SST]; if (id != api) { msg = msgbuf; snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api); msgbuf[sizeof(msgbuf)-1] = 0; goto error; } /* Check the stuff at the start of p first: if there's underwrite * corruption, the number-of-bytes field may be nuts, and checking * the tail could lead to a segfault then. */ for (i = SST-1; i >= 1; --i) { if (*(q-i) != FORBIDDENBYTE) { msg = "bad leading pad byte"; goto error; } } nbytes = read_size_t(q - 2*SST); tail = q + nbytes; for (i = 0; i < SST; ++i) { if (tail[i] != FORBIDDENBYTE) { msg = "bad trailing pad byte"; goto error; } } return; error: _PyObject_DebugDumpAddress(p); Py_FatalError(msg); } /* Display info to stderr about the memory block at p. */ static noasan void _PyObject_DebugDumpAddress(const void *p) { const uint8_t *q = (const uint8_t *)p; const uint8_t *tail; size_t nbytes, serial; int i; int ok; char id; fprintf(stderr, "Debug memory block at address p=%p:", p); if (p == NULL) { fprintf(stderr, "\n"); return; } id = (char)q[-SST]; fprintf(stderr, " API '%c'\n", id); nbytes = read_size_t(q - 2*SST); fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally " "requested\n", nbytes); /* In case this is nuts, check the leading pad bytes first. */ fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1); ok = 1; for (i = 1; i <= SST-1; ++i) { if (*(q-i) != FORBIDDENBYTE) { ok = 0; break; } } if (ok) fputs("FORBIDDENBYTE, as expected.\n", stderr); else { fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", FORBIDDENBYTE); for (i = SST-1; i >= 1; --i) { const uint8_t byte = *(q-i); fprintf(stderr, " at p-%d: 0x%02x", i, byte); if (byte != FORBIDDENBYTE) fputs(" *** OUCH", stderr); fputc('\n', stderr); } fputs(" Because memory is corrupted at the start, the " "count of bytes requested\n" " may be bogus, and checking the trailing pad " "bytes may segfault.\n", stderr); } tail = q + nbytes; fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail); ok = 1; for (i = 0; i < SST; ++i) { if (tail[i] != FORBIDDENBYTE) { ok = 0; break; } } if (ok) fputs("FORBIDDENBYTE, as expected.\n", stderr); else { fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n", FORBIDDENBYTE); for (i = 0; i < SST; ++i) { const uint8_t byte = tail[i]; fprintf(stderr, " at tail+%d: 0x%02x", i, byte); if (byte != FORBIDDENBYTE) fputs(" *** OUCH", stderr); fputc('\n', stderr); } } serial = read_size_t(tail + SST); fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T "u to debug malloc/realloc.\n", serial); if (nbytes > 0) { i = 0; fputs(" Data at p:", stderr); /* print up to 8 bytes at the start */ while (q < tail && i < 8) { fprintf(stderr, " %02x", *q); ++i; ++q; } /* and up to 8 at the end */ if (q < tail) { if (tail - q > 8) { fputs(" ...", stderr); q = tail - 8; } while (q < tail) { fprintf(stderr, " %02x", *q); ++q; } } fputc('\n', stderr); } fputc('\n', stderr); fflush(stderr); #if IsModeDbg() PYTHON_YOINK("_tracemalloc"); _PyMem_DumpTraceback(fileno(stderr), p); #endif } #endif static size_t printone(FILE *out, const char* msg, size_t value) { int i, k; char buf[100]; size_t origvalue = value; fputs(msg, out); for (i = (int)strlen(msg); i < 35; ++i) fputc(' ', out); fputc('=', out); /* Write the value with commas. */ i = 22; buf[i--] = '\0'; buf[i--] = '\n'; k = 3; do { size_t nextvalue = value / 10; unsigned int digit = (unsigned int)(value - nextvalue * 10); value = nextvalue; buf[i--] = (char)(digit + '0'); --k; if (k == 0 && value && i >= 0) { k = 3; buf[i--] = ','; } } while (value && i >= 0); while (i >= 0) buf[i--] = ' '; fputs(buf, out); return origvalue; } void _PyDebugAllocatorStats(FILE *out, const char *block_name, int num_blocks, size_t sizeof_block) { char buf1[128]; char buf2[128]; PyOS_snprintf(buf1, sizeof(buf1), "%d %ss * %" PY_FORMAT_SIZE_T "d bytes each", num_blocks, block_name, sizeof_block); PyOS_snprintf(buf2, sizeof(buf2), "%48s ", buf1); (void)printone(out, buf2, num_blocks * sizeof_block); } #ifdef WITH_PYMALLOC #ifdef Py_DEBUG /* Is target in the list? The list is traversed via the nextpool pointers. * The list may be NULL-terminated, or circular. Return 1 if target is in * list, else 0. */ static int pool_is_in_list(const poolp target, poolp list) { poolp origlist = list; assert(target != NULL); if (list == NULL) return 0; do { if (target == list) return 1; list = list->nextpool; } while (list != NULL && list != origlist); return 0; } #endif /* Print summary info to "out" about the state of pymalloc's structures. * In Py_DEBUG mode, also perform some expensive internal consistency * checks. */ void _PyObject_DebugMallocStats(FILE *out) { uint i; const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT; /* # of pools, allocated blocks, and free blocks per class index */ size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT]; /* total # of allocated bytes in used and full pools */ size_t allocated_bytes = 0; /* total # of available bytes in used pools */ size_t available_bytes = 0; /* # of free pools + pools not yet carved out of current arena */ uint numfreepools = 0; /* # of bytes for arena alignment padding */ size_t arena_alignment = 0; /* # of bytes in used and full pools used for pool_headers */ size_t pool_header_bytes = 0; /* # of bytes in used and full pools wasted due to quantization, * i.e. the necessarily leftover space at the ends of used and * full pools. */ size_t quantization = 0; /* # of arenas actually allocated. */ size_t narenas = 0; /* running total -- should equal narenas * ARENA_SIZE */ size_t total; char buf[128]; fprintf(out, "Small block threshold = %d, in %u size classes.\n", SMALL_REQUEST_THRESHOLD, numclasses); for (i = 0; i < numclasses; ++i) numpools[i] = numblocks[i] = numfreeblocks[i] = 0; /* Because full pools aren't linked to from anything, it's easiest * to march over all the arenas. If we're lucky, most of the memory * will be living in full pools -- would be a shame to miss them. */ for (i = 0; i < maxarenas; ++i) { uint j; uintptr_t base = arenas[i].address; /* Skip arenas which are not allocated. */ if (arenas[i].address == (uintptr_t)NULL) continue; narenas += 1; numfreepools += arenas[i].nfreepools; /* round up to pool alignment */ if (base & (uintptr_t)POOL_SIZE_MASK) { arena_alignment += POOL_SIZE; base &= ~(uintptr_t)POOL_SIZE_MASK; base += POOL_SIZE; } /* visit every pool in the arena */ assert(base <= (uintptr_t) arenas[i].pool_address); for (j = 0; base < (uintptr_t) arenas[i].pool_address; ++j, base += POOL_SIZE) { poolp p = (poolp)base; const uint sz = p->szidx; uint freeblocks; if (p->ref.count == 0) { /* currently unused */ #ifdef Py_DEBUG assert(pool_is_in_list(p, arenas[i].freepools)); #endif continue; } ++numpools[sz]; numblocks[sz] += p->ref.count; freeblocks = NUMBLOCKS(sz) - p->ref.count; numfreeblocks[sz] += freeblocks; #ifdef Py_DEBUG if (freeblocks > 0) assert(pool_is_in_list(p, usedpools[sz + sz])); #endif } } assert(narenas == narenas_currently_allocated); fputc('\n', out); fputs("class size num pools blocks in use avail blocks\n" "----- ---- --------- ------------- ------------\n", out); for (i = 0; i < numclasses; ++i) { size_t p = numpools[i]; size_t b = numblocks[i]; size_t f = numfreeblocks[i]; uint size = INDEX2SIZE(i); if (p == 0) { assert(b == 0 && f == 0); continue; } fprintf(out, "%5u %6u " "%11" PY_FORMAT_SIZE_T "u " "%15" PY_FORMAT_SIZE_T "u " "%13" PY_FORMAT_SIZE_T "u\n", i, size, p, b, f); allocated_bytes += b * size; available_bytes += f * size; pool_header_bytes += p * POOL_OVERHEAD; quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size); } fputc('\n', out); #if IsModeDbg() if (_PyMem_DebugEnabled()) (void)printone(out, "# times object malloc called", serialno); #endif (void)printone(out, "# arenas allocated total", ntimes_arena_allocated); (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas); (void)printone(out, "# arenas highwater mark", narenas_highwater); (void)printone(out, "# arenas allocated current", narenas); PyOS_snprintf(buf, sizeof(buf), "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena", narenas, ARENA_SIZE); (void)printone(out, buf, narenas * ARENA_SIZE); fputc('\n', out); total = printone(out, "# bytes in allocated blocks", allocated_bytes); total += printone(out, "# bytes in available blocks", available_bytes); PyOS_snprintf(buf, sizeof(buf), "%u unused pools * %d bytes", numfreepools, POOL_SIZE); total += printone(out, buf, (size_t)numfreepools * POOL_SIZE); total += printone(out, "# bytes lost to pool headers", pool_header_bytes); total += printone(out, "# bytes lost to quantization", quantization); total += printone(out, "# bytes lost to arena alignment", arena_alignment); (void)printone(out, "Total", total); } #endif /* #ifdef WITH_PYMALLOC */
86,008
2,523
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/longobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/intrin/popcnt.h" #include "libc/fmt/conv.h" #include "libc/limits.h" #include "libc/log/check.h" #include "libc/math.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longintrepr.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymath.h" #include "third_party/python/Include/structseq.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ /* Long (arbitrary precision) integer object implementation */ /* XXX The functional organization of this file is terrible */ #ifndef NSMALLPOSINTS #define NSMALLPOSINTS 257L #endif #ifndef NSMALLNEGINTS #define NSMALLNEGINTS 5L #endif /* convert a PyLong of size 1, 0 or -1 to an sdigit */ #define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \ Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \ (Py_SIZE(x) == 0 ? (sdigit)0 : \ (sdigit)(x)->ob_digit[0])) #if NSMALLNEGINTS + NSMALLPOSINTS > 0 /* Small integers are preallocated in this array so that they can be shared. The integers that are preallocated are those in the range -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). */ static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS]; #ifdef COUNT_ALLOCS Py_ssize_t quick_int_allocs, quick_neg_int_allocs; #endif static inline PyObject * get_small_int(sdigit ival) { PyObject *v; assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS); v = (PyObject *)&small_ints[ival + NSMALLNEGINTS]; Py_INCREF(v); #ifdef COUNT_ALLOCS if (ival >= 0) quick_int_allocs++; else quick_neg_int_allocs++; #endif return v; } #define CHECK_SMALL_INT(ival) \ do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \ return get_small_int((sdigit)ival); \ } while(0) static PyLongObject * maybe_small_long(PyLongObject *v) { if (v && Py_ABS(Py_SIZE(v)) <= 1) { sdigit ival = MEDIUM_VALUE(v); if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { Py_DECREF(v); return (PyLongObject *)get_small_int(ival); } } return v; } #else #define CHECK_SMALL_INT(ival) #define maybe_small_long(val) (val) #endif /* If a freshly-allocated int is already shared, it must be a small integer, so negating it must go to PyLong_FromLong */ Py_LOCAL_INLINE(void) _PyLong_Negate(PyLongObject **x_p) { PyLongObject *x; x = (PyLongObject *)*x_p; if (Py_REFCNT(x) == 1) { Py_SIZE(x) = -Py_SIZE(x); return; } *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x)); Py_DECREF(x); } /* For int multiplication, use the O(N**2) school algorithm unless * both operands contain more than KARATSUBA_CUTOFF digits (this * being an internal Python int digit, in base BASE). */ #define KARATSUBA_CUTOFF 70 #define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF) /* For exponentiation, use the binary left-to-right algorithm * unless the exponent contains more than FIVEARY_CUTOFF digits. * In that case, do 5 bits at a time. The potential drawback is that * a table of 2**5 intermediate results is computed. */ #define FIVEARY_CUTOFF 8 #define SIGCHECK(PyTryBlock) \ do { \ if (PyErr_CheckSignals()) PyTryBlock \ } while(0) /* Normalize (remove leading zeros from) an int object. Doesn't attempt to free the storage--in most cases, due to the nature of the algorithms used, this could save at most be one word anyway. */ static PyLongObject * long_normalize(PyLongObject *v) { Py_ssize_t j = Py_ABS(Py_SIZE(v)); Py_ssize_t i = j; while (i > 0 && v->ob_digit[i-1] == 0) --i; if (i != j) Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i; return v; } /* _PyLong_FromNbInt: Convert the given object to a PyLongObject using the nb_int slot, if available. Raise TypeError if either the nb_int slot is not available or the result of the call to nb_int returns something not of type int. */ PyLongObject * _PyLong_FromNbInt(PyObject *integral) { PyNumberMethods *nb; PyObject *result; /* Fast path for the case that we already have an int. */ if (PyLong_CheckExact(integral)) { Py_INCREF(integral); return (PyLongObject *)integral; } nb = Py_TYPE(integral)->tp_as_number; if (nb == NULL || nb->nb_int == NULL) { PyErr_Format(PyExc_TypeError, "an integer is required (got type %.200s)", Py_TYPE(integral)->tp_name); return NULL; } /* Convert using the nb_int slot, which should return something of exact type int. */ result = nb->nb_int(integral); if (!result || PyLong_CheckExact(result)) return (PyLongObject *)result; if (!PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, "__int__ returned non-int (type %.200s)", result->ob_type->tp_name); Py_DECREF(result); return NULL; } /* Issue #17576: warn if 'result' not of exact type int. */ if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__int__ returned non-int (type %.200s). " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", result->ob_type->tp_name)) { Py_DECREF(result); return NULL; } return (PyLongObject *)result; } /* Allocate a new int object with size digits. Return NULL and set exception if we run out of memory. */ #define MAX_LONG_DIGITS \ ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit)) PyLongObject * _PyLong_New(Py_ssize_t size) { PyLongObject *result; /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) + sizeof(digit)*size. Previous incarnations of this code used sizeof(PyVarObject) instead of the offsetof, but this risks being incorrect in the presence of padding between the PyVarObject header and the digits. */ if (size > (Py_ssize_t)MAX_LONG_DIGITS) { PyErr_SetString(PyExc_OverflowError, "too many digits in integer"); return NULL; } result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) + size*sizeof(digit)); if (!result) { PyErr_NoMemory(); return NULL; } return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size); } PyObject * _PyLong_Copy(PyLongObject *src) { PyLongObject *result; Py_ssize_t i; assert(src != NULL); i = Py_SIZE(src); if (i < 0) i = -(i); if (i < 2) { sdigit ival = MEDIUM_VALUE(src); CHECK_SMALL_INT(ival); } result = _PyLong_New(i); if (result != NULL) { Py_SIZE(result) = Py_SIZE(src); while (--i >= 0) result->ob_digit[i] = src->ob_digit[i]; } return (PyObject *)result; } /* Create a new int object from a C long int */ PyObject * PyLong_FromLong(long ival) { PyLongObject *v; unsigned long abs_ival; unsigned long t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; int sign; CHECK_SMALL_INT(ival); if (ival < 0) { /* negate: can't write this as abs_ival = -ival since that invokes undefined behaviour when ival is LONG_MIN */ abs_ival = 0U-(unsigned long)ival; sign = -1; } else { abs_ival = (unsigned long)ival; sign = ival == 0 ? 0 : 1; } /* Fast path for single-digit ints */ if (!(abs_ival >> PyLong_SHIFT)) { v = _PyLong_New(1); if (v) { Py_SIZE(v) = sign; v->ob_digit[0] = Py_SAFE_DOWNCAST( abs_ival, unsigned long, digit); } return (PyObject*)v; } #if PyLong_SHIFT==15 /* 2 digits */ if (!(abs_ival >> 2*PyLong_SHIFT)) { v = _PyLong_New(2); if (v) { Py_SIZE(v) = 2*sign; v->ob_digit[0] = Py_SAFE_DOWNCAST( abs_ival & PyLong_MASK, unsigned long, digit); v->ob_digit[1] = Py_SAFE_DOWNCAST( abs_ival >> PyLong_SHIFT, unsigned long, digit); } return (PyObject*)v; } #endif /* Larger numbers: loop to determine number of digits */ t = abs_ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; } v = _PyLong_New(ndigits); if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = ndigits*sign; t = abs_ival; while (t) { *p++ = Py_SAFE_DOWNCAST( t & PyLong_MASK, unsigned long, digit); t >>= PyLong_SHIFT; } } return (PyObject *)v; } /* Create a new int object from a C unsigned long int */ PyObject * PyLong_FromUnsignedLong(unsigned long ival) { PyLongObject *v; unsigned long t; int ndigits = 0; if (ival < PyLong_BASE) return PyLong_FromLong(ival); /* Count the number of Python digits. */ t = (unsigned long)ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; } v = _PyLong_New(ndigits); if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = ndigits; while (ival) { *p++ = (digit)(ival & PyLong_MASK); ival >>= PyLong_SHIFT; } } return (PyObject *)v; } /* Create a new int object from a C double */ PyObject * PyLong_FromDouble(double dval) { PyLongObject *v; double frac; int i, ndig, expo, neg; neg = 0; if (Py_IS_INFINITY(dval)) { PyErr_SetString(PyExc_OverflowError, "cannot convert float infinity to integer"); return NULL; } if (Py_IS_NAN(dval)) { PyErr_SetString(PyExc_ValueError, "cannot convert float NaN to integer"); return NULL; } if (dval < 0.0) { neg = 1; dval = -dval; } frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */ if (expo <= 0) return PyLong_FromLong(0L); ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */ v = _PyLong_New(ndig); if (v == NULL) return NULL; frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1); for (i = ndig; --i >= 0; ) { digit bits = (digit)frac; v->ob_digit[i] = bits; frac = frac - (double)bits; frac = ldexp(frac, PyLong_SHIFT); } if (neg) Py_SIZE(v) = -(Py_SIZE(v)); return (PyObject *)v; } /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define * anything about what happens when a signed integer operation overflows, * and some compilers think they're doing you a favor by being "clever" * then. The bit pattern for the largest positive signed long is * (unsigned long)LONG_MAX, and for the smallest negative signed long * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN. * However, some other compilers warn about applying unary minus to an * unsigned operand. Hence the weird "0-". */ #define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) #define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN) /* Get a C long int from an int object or any object that has an __int__ method. On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of the result. Otherwise *overflow is 0. For other errors (e.g., TypeError), return -1 and set an error condition. In this case *overflow will be 0. */ long PyLong_AsLongAndOverflow(PyObject *vv, int *overflow) { /* This version by Tim Peters */ PyLongObject *v; unsigned long x, prev; long res; Py_ssize_t i; int sign; int do_decref = 0; /* if nb_int was called */ *overflow = 0; if (vv == NULL) { PyErr_BadInternalCall(); return -1; } if (PyLong_Check(vv)) { v = (PyLongObject *)vv; } else { v = _PyLong_FromNbInt(vv); if (v == NULL) return -1; do_decref = 1; } res = -1; i = Py_SIZE(v); switch (i) { case -1: res = -(sdigit)v->ob_digit[0]; break; case 0: res = 0; break; case 1: res = v->ob_digit[0]; break; default: sign = 1; x = 0; if (i < 0) { sign = -1; i = -(i); } while (--i >= 0) { prev = x; x = (x << PyLong_SHIFT) | v->ob_digit[i]; if ((x >> PyLong_SHIFT) != prev) { *overflow = sign; goto exit; } } /* Haven't lost any bits, but casting to long requires extra * care (see comment above). */ if (x <= (unsigned long)LONG_MAX) { res = (long)x * sign; } else if (sign < 0 && x == PY_ABS_LONG_MIN) { res = LONG_MIN; } else { *overflow = sign; /* res is already set to -1 */ } } exit: if (do_decref) { Py_DECREF(v); } return res; } /* Get a C long int from an int object or any object that has an __int__ method. Return -1 and set an error if overflow occurs. */ long PyLong_AsLong(PyObject *obj) { int overflow; long result = PyLong_AsLongAndOverflow(obj, &overflow); if (overflow) { /* XXX: could be cute and give a different message for overflow == -1 */ PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C long"); } return result; } /* Get a C int from an int object or any object that has an __int__ method. Return -1 and set an error if overflow occurs. */ int _PyLong_AsInt(PyObject *obj) { int overflow; long result = PyLong_AsLongAndOverflow(obj, &overflow); if (overflow || result > INT_MAX || result < INT_MIN) { /* XXX: could be cute and give a different message for overflow == -1 */ PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int"); return -1; } return (int)result; } /* Get a Py_ssize_t from an int object. Returns -1 and sets an error condition if overflow occurs. */ Py_ssize_t PyLong_AsSsize_t(PyObject *vv) { PyLongObject *v; size_t x, prev; Py_ssize_t i; int sign; if (vv == NULL) { PyErr_BadInternalCall(); return -1; } if (!PyLong_Check(vv)) { PyErr_SetString(PyExc_TypeError, "an integer is required"); return -1; } v = (PyLongObject *)vv; i = Py_SIZE(v); switch (i) { case -1: return -(sdigit)v->ob_digit[0]; case 0: return 0; case 1: return v->ob_digit[0]; } sign = 1; x = 0; if (i < 0) { sign = -1; i = -(i); } while (--i >= 0) { prev = x; x = (x << PyLong_SHIFT) | v->ob_digit[i]; if ((x >> PyLong_SHIFT) != prev) goto overflow; } /* Haven't lost any bits, but casting to a signed type requires * extra care (see comment above). */ if (x <= (size_t)PY_SSIZE_T_MAX) { return (Py_ssize_t)x * sign; } else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) { return PY_SSIZE_T_MIN; } /* else overflow */ overflow: PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C ssize_t"); return -1; } /* Get a C unsigned long int from an int object. Returns -1 and sets an error condition if overflow occurs. */ unsigned long PyLong_AsUnsignedLong(PyObject *vv) { PyLongObject *v; unsigned long x, prev; Py_ssize_t i; if (vv == NULL) { PyErr_BadInternalCall(); return (unsigned long)-1; } if (!PyLong_Check(vv)) { PyErr_SetString(PyExc_TypeError, "an integer is required"); return (unsigned long)-1; } v = (PyLongObject *)vv; i = Py_SIZE(v); x = 0; if (i < 0) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to unsigned int"); return (unsigned long) -1; } switch (i) { case 0: return 0; case 1: return v->ob_digit[0]; } while (--i >= 0) { prev = x; x = (x << PyLong_SHIFT) | v->ob_digit[i]; if ((x >> PyLong_SHIFT) != prev) { PyErr_SetString(PyExc_OverflowError, "Python int too large to convert " "to C unsigned long"); return (unsigned long) -1; } } return x; } /* Get a C size_t from an int object. Returns (size_t)-1 and sets an error condition if overflow occurs. */ size_t PyLong_AsSize_t(PyObject *vv) { PyLongObject *v; size_t x, prev; Py_ssize_t i; if (vv == NULL) { PyErr_BadInternalCall(); return (size_t) -1; } if (!PyLong_Check(vv)) { PyErr_SetString(PyExc_TypeError, "an integer is required"); return (size_t)-1; } v = (PyLongObject *)vv; i = Py_SIZE(v); x = 0; if (i < 0) { PyErr_SetString(PyExc_OverflowError, "can't convert negative value to size_t"); return (size_t) -1; } switch (i) { case 0: return 0; case 1: return v->ob_digit[0]; } while (--i >= 0) { prev = x; x = (x << PyLong_SHIFT) | v->ob_digit[i]; if ((x >> PyLong_SHIFT) != prev) { PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C size_t"); return (size_t) -1; } } return x; } /* Get a C unsigned long int from an int object, ignoring the high bits. Returns -1 and sets an error condition if an error occurs. */ static unsigned long _PyLong_AsUnsignedLongMask(PyObject *vv) { PyLongObject *v; unsigned long x; Py_ssize_t i; int sign; if (vv == NULL || !PyLong_Check(vv)) { PyErr_BadInternalCall(); return (unsigned long) -1; } v = (PyLongObject *)vv; i = Py_SIZE(v); switch (i) { case 0: return 0; case 1: return v->ob_digit[0]; } sign = 1; x = 0; if (i < 0) { sign = -1; i = -i; } while (--i >= 0) { x = (x << PyLong_SHIFT) | v->ob_digit[i]; } return x * sign; } unsigned long PyLong_AsUnsignedLongMask(PyObject *op) { PyLongObject *lo; unsigned long val; if (op == NULL) { PyErr_BadInternalCall(); return (unsigned long)-1; } if (PyLong_Check(op)) { return _PyLong_AsUnsignedLongMask(op); } lo = _PyLong_FromNbInt(op); if (lo == NULL) return (unsigned long)-1; val = _PyLong_AsUnsignedLongMask((PyObject *)lo); Py_DECREF(lo); return val; } int _PyLong_Sign(PyObject *vv) { PyLongObject *v = (PyLongObject *)vv; assert(v != NULL); assert(PyLong_Check(v)); return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1); } /* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d < 2**k if d is nonzero, else 0. */ static inline int bits_in_digit(digit d) { #if defined(__GNUC__) && !defined(__STRICT_ANSI__) /* [jart] faster bit scanning */ if (d) { _Static_assert(sizeof(digit) <= sizeof(unsigned), ""); return (__builtin_clz(d) ^ (sizeof(unsigned) * CHAR_BIT - 1)) + 1; } else { return 0; } #else static const unsigned char BitLengthTable[32] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; int d_bits = 0; while (d >= 32) { d_bits += 6; d >>= 6; } d_bits += (int)BitLengthTable[d]; return d_bits; #endif } size_t _PyLong_NumBits(PyObject *vv) { PyLongObject *v = (PyLongObject *)vv; size_t result = 0; Py_ssize_t ndigits; assert(v != NULL); assert(PyLong_Check(v)); ndigits = Py_ABS(Py_SIZE(v)); assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); if (ndigits > 0) { if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT) goto Overflow; /* [jart] faster bit scanning */ result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT; result += bits_in_digit(v->ob_digit[ndigits - 1]); } return result; Overflow: PyErr_SetString(PyExc_OverflowError, "int has too many bits " "to express in a platform size_t"); return (size_t)-1; } PyObject * _PyLong_FromByteArray(const unsigned char* bytes, size_t n, int little_endian, int is_signed) { const unsigned char* pstartbyte; /* LSB of bytes */ int incr; /* direction to move pstartbyte */ const unsigned char* pendbyte; /* MSB of bytes */ size_t numsignificantbytes; /* number of bytes that matter */ Py_ssize_t ndigits; /* number of Python int digits */ PyLongObject* v; /* result */ Py_ssize_t idigit = 0; /* next free index in v->ob_digit */ if (n == 0) return PyLong_FromLong(0L); if (little_endian) { pstartbyte = bytes; pendbyte = bytes + n - 1; incr = 1; } else { pstartbyte = bytes + n - 1; pendbyte = bytes; incr = -1; } if (is_signed) is_signed = *pendbyte >= 0x80; /* Compute numsignificantbytes. This consists of finding the most significant byte. Leading 0 bytes are insignificant if the number is positive, and leading 0xff bytes if negative. */ { size_t i; const unsigned char* p = pendbyte; const int pincr = -incr; /* search MSB to LSB */ const unsigned char insignificant = is_signed ? 0xff : 0x00; for (i = 0; i < n; ++i, p += pincr) { if (*p != insignificant) break; } numsignificantbytes = n - i; /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so actually has 2 significant bytes. OTOH, 0xff0001 == -0x00ffff, so we wouldn't *need* to bump it there; but we do for 0xffff = -0x0001. To be safe without bothering to check every case, bump it regardless. */ if (is_signed && numsignificantbytes < n) ++numsignificantbytes; } /* How many Python int digits do we need? We have 8*numsignificantbytes bits, and each Python int digit has PyLong_SHIFT bits, so it's the ceiling of the quotient. */ /* catch overflow before it happens */ if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) { PyErr_SetString(PyExc_OverflowError, "byte array too long to convert to int"); return NULL; } ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT; v = _PyLong_New(ndigits); if (v == NULL) return NULL; /* Copy the bits over. The tricky parts are computing 2's-comp on the fly for signed numbers, and dealing with the mismatch between 8-bit bytes and (probably) 15-bit Python digits.*/ { size_t i; twodigits carry = 1; /* for 2's-comp calculation */ twodigits accum = 0; /* sliding register */ unsigned int accumbits = 0; /* number of bits in accum */ const unsigned char* p = pstartbyte; for (i = 0; i < numsignificantbytes; ++i, p += incr) { twodigits thisbyte = *p; /* Compute correction for 2's comp, if needed. */ if (is_signed) { thisbyte = (0xff ^ thisbyte) + carry; carry = thisbyte >> 8; thisbyte &= 0xff; } /* Because we're going LSB to MSB, thisbyte is more significant than what's already in accum, so needs to be prepended to accum. */ accum |= (twodigits)thisbyte << accumbits; accumbits += 8; if (accumbits >= PyLong_SHIFT) { /* There's enough to fill a Python digit. */ assert(idigit < ndigits); v->ob_digit[idigit] = (digit)(accum & PyLong_MASK); ++idigit; accum >>= PyLong_SHIFT; accumbits -= PyLong_SHIFT; assert(accumbits < PyLong_SHIFT); } } assert(accumbits < PyLong_SHIFT); if (accumbits) { assert(idigit < ndigits); v->ob_digit[idigit] = (digit)accum; ++idigit; } } Py_SIZE(v) = is_signed ? -idigit : idigit; return (PyObject *)long_normalize(v); } int _PyLong_AsByteArray(PyLongObject* v, unsigned char* bytes, size_t n, int little_endian, int is_signed) { Py_ssize_t i; /* index into v->ob_digit */ Py_ssize_t ndigits; /* |v->ob_size| */ twodigits accum; /* sliding register */ unsigned int accumbits; /* # bits in accum */ int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */ digit carry; /* for computing 2's-comp */ size_t j; /* # bytes filled */ unsigned char* p; /* pointer to next byte in bytes */ int pincr; /* direction to move p */ assert(v != NULL && PyLong_Check(v)); if (Py_SIZE(v) < 0) { ndigits = -(Py_SIZE(v)); if (!is_signed) { PyErr_SetString(PyExc_OverflowError, "can't convert negative int to unsigned"); return -1; } do_twos_comp = 1; } else { ndigits = Py_SIZE(v); do_twos_comp = 0; } if (little_endian) { p = bytes; pincr = 1; } else { p = bytes + n - 1; pincr = -1; } /* Copy over all the Python digits. It's crucial that every Python digit except for the MSD contribute exactly PyLong_SHIFT bits to the total, so first assert that the int is normalized. */ assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0); j = 0; accum = 0; accumbits = 0; carry = do_twos_comp ? 1 : 0; for (i = 0; i < ndigits; ++i) { digit thisdigit = v->ob_digit[i]; if (do_twos_comp) { thisdigit = (thisdigit ^ PyLong_MASK) + carry; carry = thisdigit >> PyLong_SHIFT; thisdigit &= PyLong_MASK; } /* Because we're going LSB to MSB, thisdigit is more significant than what's already in accum, so needs to be prepended to accum. */ accum |= (twodigits)thisdigit << accumbits; /* The most-significant digit may be (probably is) at least partly empty. */ if (i == ndigits - 1) { /* Count # of sign bits -- they needn't be stored, * although for signed conversion we need later to * make sure at least one sign bit gets stored. */ digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit; while (s != 0) { s >>= 1; accumbits++; } } else accumbits += PyLong_SHIFT; /* Store as many bytes as possible. */ while (accumbits >= 8) { if (j >= n) goto Overflow; ++j; *p = (unsigned char)(accum & 0xff); p += pincr; accumbits -= 8; accum >>= 8; } } /* Store the straggler (if any). */ assert(accumbits < 8); assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */ if (accumbits > 0) { if (j >= n) goto Overflow; ++j; if (do_twos_comp) { /* Fill leading bits of the byte with sign bits (appropriately pretending that the int had an infinite supply of sign bits). */ accum |= (~(twodigits)0) << accumbits; } *p = (unsigned char)(accum & 0xff); p += pincr; } else if (j == n && n > 0 && is_signed) { /* The main loop filled the byte array exactly, so the code just above didn't get to ensure there's a sign bit, and the loop below wouldn't add one either. Make sure a sign bit exists. */ unsigned char msb = *(p - pincr); int sign_bit_set = msb >= 0x80; assert(accumbits == 0); if (sign_bit_set == do_twos_comp) return 0; else goto Overflow; } /* Fill remaining bytes with copies of the sign bit. */ { unsigned char signbyte = do_twos_comp ? 0xffU : 0U; for ( ; j < n; ++j, p += pincr) *p = signbyte; } return 0; Overflow: PyErr_SetString(PyExc_OverflowError, "int too big to convert"); return -1; } /* Create a new int object from a C pointer */ PyObject * PyLong_FromVoidPtr(void *p) { #if SIZEOF_VOID_P <= SIZEOF_LONG return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p); #else #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)" #endif return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p); #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ } /* Get a C pointer from an int object. */ void * PyLong_AsVoidPtr(PyObject *vv) { #if SIZEOF_VOID_P <= SIZEOF_LONG long x; if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) x = PyLong_AsLong(vv); else x = PyLong_AsUnsignedLong(vv); #else #if SIZEOF_LONG_LONG < SIZEOF_VOID_P # error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)" #endif long long x; if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0) x = PyLong_AsLongLong(vv); else x = PyLong_AsUnsignedLongLong(vv); #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */ if (x == -1 && PyErr_Occurred()) return NULL; return (void *)x; } /* Initial long long support by Chris Herborth ([email protected]), later * rewritten to use the newer PyLong_{As,From}ByteArray API. */ #define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN) /* Create a new int object from a C long long int. */ PyObject * PyLong_FromLongLong(long long ival) { PyLongObject *v; unsigned long long abs_ival; unsigned long long t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; int negative = 0; CHECK_SMALL_INT(ival); if (ival < 0) { /* avoid signed overflow on negation; see comments in PyLong_FromLong above. */ abs_ival = (unsigned long long)(-1-ival) + 1; negative = 1; } else { abs_ival = (unsigned long long)ival; } /* Count the number of Python digits. We used to pick 5 ("big enough for anything"), but that's a waste of time and space given that 5*15 = 75 bits are rarely needed. */ t = abs_ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; } v = _PyLong_New(ndigits); if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = negative ? -ndigits : ndigits; t = abs_ival; while (t) { *p++ = (digit)(t & PyLong_MASK); t >>= PyLong_SHIFT; } } return (PyObject *)v; } /* Create a new int object from a C unsigned long long int. */ PyObject * PyLong_FromUnsignedLongLong(unsigned long long ival) { PyLongObject *v; unsigned long long t; int ndigits = 0; if (ival < PyLong_BASE) return PyLong_FromLong((long)ival); /* Count the number of Python digits. */ t = (unsigned long long)ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; } v = _PyLong_New(ndigits); if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = ndigits; while (ival) { *p++ = (digit)(ival & PyLong_MASK); ival >>= PyLong_SHIFT; } } return (PyObject *)v; } /* Create a new int object from a C Py_ssize_t. */ PyObject * PyLong_FromSsize_t(Py_ssize_t ival) { PyLongObject *v; size_t abs_ival; size_t t; /* unsigned so >> doesn't propagate sign bit */ int ndigits = 0; int negative = 0; CHECK_SMALL_INT(ival); if (ival < 0) { /* avoid signed overflow when ival = SIZE_T_MIN */ abs_ival = (size_t)(-1-ival)+1; negative = 1; } else { abs_ival = (size_t)ival; } /* Count the number of Python digits. */ t = abs_ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; } v = _PyLong_New(ndigits); if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = negative ? -ndigits : ndigits; t = abs_ival; while (t) { *p++ = (digit)(t & PyLong_MASK); t >>= PyLong_SHIFT; } } return (PyObject *)v; } /* Create a new int object from a C size_t. */ PyObject * PyLong_FromSize_t(size_t ival) { PyLongObject *v; size_t t; int ndigits = 0; if (ival < PyLong_BASE) return PyLong_FromLong((long)ival); /* Count the number of Python digits. */ t = ival; while (t) { ++ndigits; t >>= PyLong_SHIFT; } v = _PyLong_New(ndigits); if (v != NULL) { digit *p = v->ob_digit; Py_SIZE(v) = ndigits; while (ival) { *p++ = (digit)(ival & PyLong_MASK); ival >>= PyLong_SHIFT; } } return (PyObject *)v; } /* Get a C long long int from an int object or any object that has an __int__ method. Return -1 and set an error if overflow occurs. */ long long PyLong_AsLongLong(PyObject *vv) { PyLongObject *v; long long bytes; int res; int do_decref = 0; /* if nb_int was called */ if (vv == NULL) { PyErr_BadInternalCall(); return -1; } if (PyLong_Check(vv)) { v = (PyLongObject *)vv; } else { v = _PyLong_FromNbInt(vv); if (v == NULL) return -1; do_decref = 1; } res = 0; switch(Py_SIZE(v)) { case -1: bytes = -(sdigit)v->ob_digit[0]; break; case 0: bytes = 0; break; case 1: bytes = v->ob_digit[0]; break; default: res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes, SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1); } if (do_decref) { Py_DECREF(v); } /* Plan 9 can't handle long long in ? : expressions */ if (res < 0) return (long long)-1; else return bytes; } /* Get a C unsigned long long int from an int object. Return -1 and set an error if overflow occurs. */ unsigned long long PyLong_AsUnsignedLongLong(PyObject *vv) { PyLongObject *v; unsigned long long bytes; int res; if (vv == NULL) { PyErr_BadInternalCall(); return (unsigned long long)-1; } if (!PyLong_Check(vv)) { PyErr_SetString(PyExc_TypeError, "an integer is required"); return (unsigned long long)-1; } v = (PyLongObject*)vv; switch(Py_SIZE(v)) { case 0: return 0; case 1: return v->ob_digit[0]; } res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes, SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0); /* Plan 9 can't handle long long in ? : expressions */ if (res < 0) return (unsigned long long)res; else return bytes; } /* Get a C unsigned long int from an int object, ignoring the high bits. Returns -1 and sets an error condition if an error occurs. */ static unsigned long long _PyLong_AsUnsignedLongLongMask(PyObject *vv) { PyLongObject *v; unsigned long long x; Py_ssize_t i; int sign; if (vv == NULL || !PyLong_Check(vv)) { PyErr_BadInternalCall(); return (unsigned long) -1; } v = (PyLongObject *)vv; switch(Py_SIZE(v)) { case 0: return 0; case 1: return v->ob_digit[0]; } i = Py_SIZE(v); sign = 1; x = 0; if (i < 0) { sign = -1; i = -i; } while (--i >= 0) { x = (x << PyLong_SHIFT) | v->ob_digit[i]; } return x * sign; } unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *op) { PyLongObject *lo; unsigned long long val; if (op == NULL) { PyErr_BadInternalCall(); return (unsigned long)-1; } if (PyLong_Check(op)) { return _PyLong_AsUnsignedLongLongMask(op); } lo = _PyLong_FromNbInt(op); if (lo == NULL) return (unsigned long long)-1; val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo); Py_DECREF(lo); return val; } /* Get a C long long int from an int object or any object that has an __int__ method. On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of the result. Otherwise *overflow is 0. For other errors (e.g., TypeError), return -1 and set an error condition. In this case *overflow will be 0. */ long long PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow) { /* This version by Tim Peters */ PyLongObject *v; unsigned long long x, prev; long long res; Py_ssize_t i; int sign; int do_decref = 0; /* if nb_int was called */ *overflow = 0; if (vv == NULL) { PyErr_BadInternalCall(); return -1; } if (PyLong_Check(vv)) { v = (PyLongObject *)vv; } else { v = _PyLong_FromNbInt(vv); if (v == NULL) return -1; do_decref = 1; } res = -1; i = Py_SIZE(v); switch (i) { case -1: res = -(sdigit)v->ob_digit[0]; break; case 0: res = 0; break; case 1: res = v->ob_digit[0]; break; default: sign = 1; x = 0; if (i < 0) { sign = -1; i = -(i); } while (--i >= 0) { prev = x; x = (x << PyLong_SHIFT) + v->ob_digit[i]; if ((x >> PyLong_SHIFT) != prev) { *overflow = sign; goto exit; } } /* Haven't lost any bits, but casting to long requires extra * care (see comment above). */ if (x <= (unsigned long long)PY_LLONG_MAX) { res = (long long)x * sign; } else if (sign < 0 && x == PY_ABS_LLONG_MIN) { res = PY_LLONG_MIN; } else { *overflow = sign; /* res is already set to -1 */ } } exit: if (do_decref) { Py_DECREF(v); } return res; } #define CHECK_BINOP(v,w) \ do { \ if (!PyLong_Check(v) || !PyLong_Check(w)) \ Py_RETURN_NOTIMPLEMENTED; \ } while(0) /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] * is modified in place, by adding y to it. Carries are propagated as far as * x[m-1], and the remaining carry (0 or 1) is returned. */ static digit v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) { Py_ssize_t i; digit carry = 0; assert(m >= n); for (i = 0; i < n; ++i) { carry += x[i] + y[i]; x[i] = carry & PyLong_MASK; carry >>= PyLong_SHIFT; assert((carry & 1) == carry); } for (; carry && i < m; ++i) { carry += x[i]; x[i] = carry & PyLong_MASK; carry >>= PyLong_SHIFT; assert((carry & 1) == carry); } return carry; } /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n] * is modified in place, by subtracting y from it. Borrows are propagated as * far as x[m-1], and the remaining borrow (0 or 1) is returned. */ static digit v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n) { Py_ssize_t i; digit borrow = 0; assert(m >= n); for (i = 0; i < n; ++i) { borrow = x[i] - y[i] - borrow; x[i] = borrow & PyLong_MASK; borrow >>= PyLong_SHIFT; borrow &= 1; /* keep only 1 sign bit */ } for (; borrow && i < m; ++i) { borrow = x[i] - borrow; x[i] = borrow & PyLong_MASK; borrow >>= PyLong_SHIFT; borrow &= 1; } return borrow; } /* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put * result in z[0:m], and return the d bits shifted out of the top. */ static digit v_lshift(digit *z, digit *a, Py_ssize_t m, int d) { Py_ssize_t i; digit carry = 0; assert(0 <= d && d < PyLong_SHIFT); for (i=0; i < m; i++) { twodigits acc = (twodigits)a[i] << d | carry; z[i] = (digit)acc & PyLong_MASK; carry = (digit)(acc >> PyLong_SHIFT); } return carry; } /* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put * result in z[0:m], and return the d bits shifted out of the bottom. */ static digit v_rshift(digit *z, digit *a, Py_ssize_t m, int d) { Py_ssize_t i; digit carry = 0; digit mask = ((digit)1 << d) - 1U; assert(0 <= d && d < PyLong_SHIFT); for (i=m; i-- > 0;) { twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i]; carry = (digit)acc & mask; z[i] = (digit)(acc >> d); } return carry; } /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient in pout, and returning the remainder. pin and pout point at the LSD. It's OK for pin == pout on entry, which saves oodles of mallocs/frees in _PyLong_Format, but that should be done with great care since ints are immutable. */ static digit inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n) { twodigits rem = 0; assert(n > 0 && n <= PyLong_MASK); pin += size; pout += size; while (--size >= 0) { digit hi; rem = (rem << PyLong_SHIFT) | *--pin; *--pout = hi = (digit)(rem / n); rem -= (twodigits)hi * n; } return (digit)rem; } /* Divide an integer by a digit, returning both the quotient (as function result) and the remainder (through *prem). The sign of a is ignored; n should not be zero. */ static PyLongObject * divrem1(PyLongObject *a, digit n, digit *prem) { const Py_ssize_t size = Py_ABS(Py_SIZE(a)); PyLongObject *z; assert(n > 0 && n <= PyLong_MASK); z = _PyLong_New(size); if (z == NULL) return NULL; *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n); return long_normalize(z); } /* Convert an integer to a base 10 string. Returns a new non-shared string. (Return value is non-shared so that callers can modify the returned value if necessary.) */ static int long_to_decimal_string_internal(PyObject *aa, PyObject **p_output, _PyUnicodeWriter *writer, _PyBytesWriter *bytes_writer, char **bytes_str) { PyLongObject *scratch, *a; PyObject *str = NULL; Py_ssize_t size, strlen, size_a, i, j; digit *pout, *pin, rem, tenpow; int negative; int d; enum PyUnicode_Kind kind = 0; a = (PyLongObject *)aa; if (a == NULL || !PyLong_Check(a)) { PyErr_BadInternalCall(); return -1; } size_a = Py_ABS(Py_SIZE(a)); negative = Py_SIZE(a) < 0; /* quick and dirty upper bound for the number of digits required to express a in base _PyLong_DECIMAL_BASE: #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE)) But log2(a) < size_a * PyLong_SHIFT, and log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT > 3.3 * _PyLong_DECIMAL_SHIFT size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) = size_a + size_a / d < size_a + size_a / floor(d), where d = (3.3 * _PyLong_DECIMAL_SHIFT) / (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT) */ d = (33 * _PyLong_DECIMAL_SHIFT) / (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT); assert(size_a < PY_SSIZE_T_MAX/2); size = 1 + size_a + size_a / d; scratch = _PyLong_New(size); if (scratch == NULL) return -1; /* convert array of base _PyLong_BASE digits in pin to an array of base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP, Volume 2 (3rd edn), section 4.4, Method 1b). */ pin = a->ob_digit; pout = scratch->ob_digit; size = 0; for (i = size_a; --i >= 0; ) { digit hi = pin[i]; for (j = 0; j < size; j++) { twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi; hi = (digit)(z / _PyLong_DECIMAL_BASE); pout[j] = (digit)(z - (twodigits)hi * _PyLong_DECIMAL_BASE); } while (hi) { pout[size++] = hi % _PyLong_DECIMAL_BASE; hi /= _PyLong_DECIMAL_BASE; } /* check for keyboard interrupt */ SIGCHECK({ Py_DECREF(scratch); return -1; }); } /* pout should have at least one digit, so that the case when a = 0 works correctly */ if (size == 0) pout[size++] = 0; /* calculate exact length of output string, and allocate */ strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT; tenpow = 10; rem = pout[size-1]; while (rem >= tenpow) { tenpow *= 10; strlen++; } if (writer) { if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) { Py_DECREF(scratch); return -1; } kind = writer->kind; } else if (bytes_writer) { *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen); if (*bytes_str == NULL) { Py_DECREF(scratch); return -1; } } else { str = PyUnicode_New(strlen, '9'); if (str == NULL) { Py_DECREF(scratch); return -1; } kind = PyUnicode_KIND(str); } #define WRITE_DIGITS(p) \ do { \ /* pout[0] through pout[size-2] contribute exactly \ _PyLong_DECIMAL_SHIFT digits each */ \ for (i=0; i < size - 1; i++) { \ rem = pout[i]; \ for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \ *--p = '0' + rem % 10; \ rem /= 10; \ } \ } \ /* pout[size-1]: always produce at least one decimal digit */ \ rem = pout[i]; \ do { \ *--p = '0' + rem % 10; \ rem /= 10; \ } while (rem != 0); \ \ /* and sign */ \ if (negative) \ *--p = '-'; \ } while (0) #define WRITE_UNICODE_DIGITS(TYPE) \ do { \ if (writer) \ p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \ else \ p = (TYPE*)PyUnicode_DATA(str) + strlen; \ \ WRITE_DIGITS(p); \ \ /* check we've counted correctly */ \ if (writer) \ assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \ else \ assert(p == (TYPE*)PyUnicode_DATA(str)); \ } while (0) /* fill the string right-to-left */ if (bytes_writer) { char *p = *bytes_str + strlen; WRITE_DIGITS(p); assert(p == *bytes_str); } else if (kind == PyUnicode_1BYTE_KIND) { Py_UCS1 *p; WRITE_UNICODE_DIGITS(Py_UCS1); } else if (kind == PyUnicode_2BYTE_KIND) { Py_UCS2 *p; WRITE_UNICODE_DIGITS(Py_UCS2); } else { Py_UCS4 *p; assert (kind == PyUnicode_4BYTE_KIND); WRITE_UNICODE_DIGITS(Py_UCS4); } #undef WRITE_DIGITS #undef WRITE_UNICODE_DIGITS Py_DECREF(scratch); if (writer) { writer->pos += strlen; } else if (bytes_writer) { (*bytes_str) += strlen; } else { assert(_PyUnicode_CheckConsistency(str, 1)); *p_output = (PyObject *)str; } return 0; } static PyObject * long_to_decimal_string(PyObject *aa) { PyObject *v; if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1) return NULL; return v; } /* Convert an int object to a string, using a given conversion base, which should be one of 2, 8 or 16. Return a string object. If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x' if alternate is nonzero. */ static int long_format_binary(PyObject *aa, int base, int alternate, PyObject **p_output, _PyUnicodeWriter *writer, _PyBytesWriter *bytes_writer, char **bytes_str) { PyLongObject *a = (PyLongObject *)aa; PyObject *v = NULL; Py_ssize_t sz; Py_ssize_t size_a; enum PyUnicode_Kind kind = 0; int negative; int bits; assert(base == 2 || base == 8 || base == 16); if (a == NULL || !PyLong_Check(a)) { PyErr_BadInternalCall(); return -1; } size_a = Py_ABS(Py_SIZE(a)); negative = Py_SIZE(a) < 0; /* Compute a rough upper bound for the length of the string */ switch (base) { case 16: bits = 4; break; case 8: bits = 3; break; case 2: bits = 1; break; default: assert(0); /* shouldn't ever get here */ bits = 0; /* to silence gcc warning */ } /* Compute exact length 'sz' of output string. */ if (size_a == 0) { sz = 1; } else { Py_ssize_t size_a_in_bits; /* Ensure overflow doesn't occur during computation of sz. */ if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) { PyErr_SetString(PyExc_OverflowError, "int too large to format"); return -1; } size_a_in_bits = (size_a - 1) * PyLong_SHIFT + bits_in_digit(a->ob_digit[size_a - 1]); /* Allow 1 character for a '-' sign. */ sz = negative + (size_a_in_bits + (bits - 1)) / bits; } if (alternate) { /* 2 characters for prefix */ sz += 2; } if (writer) { if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1) return -1; kind = writer->kind; } else if (bytes_writer) { *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz); if (*bytes_str == NULL) return -1; } else { v = PyUnicode_New(sz, 'x'); if (v == NULL) return -1; kind = PyUnicode_KIND(v); } #define WRITE_DIGITS(p) \ do { \ if (size_a == 0) { \ *--p = '0'; \ } \ else { \ /* JRH: special case for power-of-2 bases */ \ twodigits accum = 0; \ int accumbits = 0; /* # of bits in accum */ \ Py_ssize_t i; \ for (i = 0; i < size_a; ++i) { \ accum |= (twodigits)a->ob_digit[i] << accumbits; \ accumbits += PyLong_SHIFT; \ assert(accumbits >= bits); \ do { \ char cdigit; \ cdigit = (char)(accum & (base - 1)); \ cdigit += (cdigit < 10) ? '0' : 'a'-10; \ *--p = cdigit; \ accumbits -= bits; \ accum >>= bits; \ } while (i < size_a-1 ? accumbits >= bits : accum > 0); \ } \ } \ \ if (alternate) { \ if (base == 16) \ *--p = 'x'; \ else if (base == 8) \ *--p = 'o'; \ else /* (base == 2) */ \ *--p = 'b'; \ *--p = '0'; \ } \ if (negative) \ *--p = '-'; \ } while (0) #define WRITE_UNICODE_DIGITS(TYPE) \ do { \ if (writer) \ p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \ else \ p = (TYPE*)PyUnicode_DATA(v) + sz; \ \ WRITE_DIGITS(p); \ \ if (writer) \ assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \ else \ assert(p == (TYPE*)PyUnicode_DATA(v)); \ } while (0) if (bytes_writer) { char *p = *bytes_str + sz; WRITE_DIGITS(p); assert(p == *bytes_str); } else if (kind == PyUnicode_1BYTE_KIND) { Py_UCS1 *p; WRITE_UNICODE_DIGITS(Py_UCS1); } else if (kind == PyUnicode_2BYTE_KIND) { Py_UCS2 *p; WRITE_UNICODE_DIGITS(Py_UCS2); } else { Py_UCS4 *p; assert (kind == PyUnicode_4BYTE_KIND); WRITE_UNICODE_DIGITS(Py_UCS4); } #undef WRITE_DIGITS #undef WRITE_UNICODE_DIGITS if (writer) { writer->pos += sz; } else if (bytes_writer) { (*bytes_str) += sz; } else { assert(_PyUnicode_CheckConsistency(v, 1)); *p_output = v; } return 0; } PyObject * _PyLong_Format(PyObject *obj, int base) { PyObject *str; int err; if (base == 10) err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL); else err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL); if (err == -1) return NULL; return str; } int _PyLong_FormatWriter(_PyUnicodeWriter *writer, PyObject *obj, int base, int alternate) { if (base == 10) return long_to_decimal_string_internal(obj, NULL, writer, NULL, NULL); else return long_format_binary(obj, base, alternate, NULL, writer, NULL, NULL); } char* _PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str, PyObject *obj, int base, int alternate) { char *str2; int res; str2 = str; if (base == 10) res = long_to_decimal_string_internal(obj, NULL, NULL, writer, &str2); else res = long_format_binary(obj, base, alternate, NULL, NULL, writer, &str2); if (res < 0) return NULL; assert(str2 != NULL); return str2; } /* Table of digit values for 8-bit string -> integer conversion. * '0' maps to 0, ..., '9' maps to 9. * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35. * All other indices map to 37. * Note that when converting a base B string, a char c is a legitimate * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B. */ const unsigned char _PyLong_DigitValue[256] = { 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37, 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, }; /* *str points to the first digit in a string of base `base` digits. base * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first * non-digit (which may be *str!). A normalized int is returned. * The point to this routine is that it takes time linear in the number of * string characters. * * Return values: * -1 on syntax error (exception needs to be set, *res is untouched) * 0 else (exception may be set, in that case *res is set to NULL) */ static int long_from_binary_base(const char **str, int base, PyLongObject **res) { const char *p = *str; const char *start = p; char prev = 0; Py_ssize_t digits = 0; int bits_per_char; Py_ssize_t n; PyLongObject *z; twodigits accum; int bits_in_accum; digit *pdigit; assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0); n = base; for (bits_per_char = -1; n; ++bits_per_char) { n >>= 1; } /* count digits and set p to end-of-string */ while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') { if (*p == '_') { if (prev == '_') { *str = p - 1; return -1; } } else { ++digits; } prev = *p; ++p; } if (prev == '_') { /* Trailing underscore not allowed. */ *str = p - 1; return -1; } *str = p; /* n <- the number of Python digits needed, = ceiling((digits * bits_per_char) / PyLong_SHIFT). */ if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) { PyErr_SetString(PyExc_ValueError, "int string too large to convert"); *res = NULL; return 0; } n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT; z = _PyLong_New(n); if (z == NULL) { *res = NULL; return 0; } /* Read string from right, and fill in int from left; i.e., * from least to most significant in both. */ accum = 0; bits_in_accum = 0; pdigit = z->ob_digit; while (--p >= start) { int k; if (*p == '_') { continue; } k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)]; assert(k >= 0 && k < base); accum |= (twodigits)k << bits_in_accum; bits_in_accum += bits_per_char; if (bits_in_accum >= PyLong_SHIFT) { *pdigit++ = (digit)(accum & PyLong_MASK); assert(pdigit - z->ob_digit <= n); accum >>= PyLong_SHIFT; bits_in_accum -= PyLong_SHIFT; assert(bits_in_accum < PyLong_SHIFT); } } if (bits_in_accum) { assert(bits_in_accum <= PyLong_SHIFT); *pdigit++ = (digit)accum; assert(pdigit - z->ob_digit <= n); } while (pdigit - z->ob_digit < n) *pdigit++ = 0; *res = long_normalize(z); return 0; } /* Parses an int from a bytestring. Leading and trailing whitespace will be * ignored. * * If successful, a PyLong object will be returned and 'pend' will be pointing * to the first unused byte unless it's NULL. * * If unsuccessful, NULL will be returned. */ PyObject * PyLong_FromString(const char *str, char **pend, int base) { int sign = 1, error_if_nonzero = 0; const char *start, *orig_str = str; PyLongObject *z = NULL; PyObject *strobj; Py_ssize_t slen; if ((base != 0 && base < 2) || base > 36) { PyErr_SetString(PyExc_ValueError, "int() arg 2 must be >= 2 and <= 36"); return NULL; } while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) { str++; } if (*str == '+') { ++str; } else if (*str == '-') { ++str; sign = -1; } if (base == 0) { if (str[0] != '0') { base = 10; } else if (str[1] == 'x' || str[1] == 'X') { base = 16; } else if (str[1] == 'o' || str[1] == 'O') { base = 8; } else if (str[1] == 'b' || str[1] == 'B') { base = 2; } else { /* "old" (C-style) octal literal, now invalid. it might still be zero though */ error_if_nonzero = 1; base = 10; } } if (str[0] == '0' && ((base == 16 && (str[1] == 'x' || str[1] == 'X')) || (base == 8 && (str[1] == 'o' || str[1] == 'O')) || (base == 2 && (str[1] == 'b' || str[1] == 'B')))) { str += 2; /* One underscore allowed here. */ if (*str == '_') { ++str; } } if (str[0] == '_') { /* May not start with underscores. */ goto onError; } start = str; if ((base & (base - 1)) == 0) { int res = long_from_binary_base(&str, base, &z); if (res < 0) { /* Syntax error. */ goto onError; } } else { /*** Binary bases can be converted in time linear in the number of digits, because Python's representation base is binary. Other bases (including decimal!) use the simple quadratic-time algorithm below, complicated by some speed tricks. First some math: the largest integer that can be expressed in N base-B digits is B**N-1. Consequently, if we have an N-digit input in base B, the worst- case number of Python digits needed to hold it is the smallest integer n s.t. BASE**n-1 >= B**N-1 [or, adding 1 to both sides] BASE**n >= B**N [taking logs to base BASE] n >= log(B**N)/log(BASE) = N * log(B)/log(BASE) The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute this quickly. A Python int with that much space is reserved near the start, and the result is computed into it. The input string is actually treated as being in base base**i (i.e., i digits are processed at a time), where two more static arrays hold: convwidth_base[base] = the largest integer i such that base**i <= BASE convmultmax_base[base] = base ** convwidth_base[base] The first of these is the largest i such that i consecutive input digits must fit in a single Python digit. The second is effectively the input base we're really using. Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base convmultmax_base[base], the result is "simply" (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1 where B = convmultmax_base[base]. Error analysis: as above, the number of Python digits `n` needed is worst- case n >= N * log(B)/log(BASE) where `N` is the number of input digits in base `B`. This is computed via size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1; below. Two numeric concerns are how much space this can waste, and whether the computed result can be too small. To be concrete, assume BASE = 2**15, which is the default (and it's unlikely anyone changes that). Waste isn't a problem: provided the first input digit isn't 0, the difference between the worst-case input with N digits and the smallest input with N digits is about a factor of B, but B is small compared to BASE so at most one allocated Python digit can remain unused on that count. If N*log(B)/log(BASE) is mathematically an exact integer, then truncating that and adding 1 returns a result 1 larger than necessary. However, that can't happen: whenever B is a power of 2, long_from_binary_base() is called instead, and it's impossible for B**i to be an integer power of 2**15 when B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be an exact integer when B is not a power of 2, since B**i has a prime factor other than 2 in that case, but (2**15)**j's only prime factor is 2). The computed result can be too small if the true value of N*log(B)/log(BASE) is a little bit larger than an exact integer, but due to roundoff errors (in computing log(B), log(BASE), their quotient, and/or multiplying that by N) yields a numeric result a little less than that integer. Unfortunately, "how close can a transcendental function get to an integer over some range?" questions are generally theoretically intractable. Computer analysis via continued fractions is practical: expand log(B)/log(BASE) via continued fractions, giving a sequence i/j of "the best" rational approximations. Then j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that we can get very close to being in trouble, but very rarely. For example, 76573 is a denominator in one of the continued-fraction approximations to log(10)/log(2**15), and indeed: >>> log(10)/log(2**15)*76573 16958.000000654003 is very close to an integer. If we were working with IEEE single-precision, rounding errors could kill us. Finding worst cases in IEEE double-precision requires better-than-double-precision log() functions, and Tim didn't bother. Instead the code checks to see whether the allocated space is enough as each new Python digit is added, and copies the whole thing to a larger int if not. This should happen extremely rarely, and in fact I don't have a test case that triggers it(!). Instead the code was tested by artificially allocating just 1 digit at the start, so that the copying code was exercised for every digit beyond the first. ***/ twodigits c; /* current input character */ double fsize_z; Py_ssize_t size_z; Py_ssize_t digits = 0; int i; int convwidth; twodigits convmultmax, convmult; digit *pz, *pzstop; const char *scan, *lastdigit; char prev = 0; static double log_base_BASE[37] = {0.0e0,}; static int convwidth_base[37] = {0,}; static twodigits convmultmax_base[37] = {0,}; if (log_base_BASE[base] == 0.0) { twodigits convmax = base; int i = 1; log_base_BASE[base] = (log((double)base) / log((double)PyLong_BASE)); for (;;) { twodigits next = convmax * base; if (next > PyLong_BASE) { break; } convmax = next; ++i; } convmultmax_base[base] = convmax; assert(i > 0); convwidth_base[base] = i; } /* Find length of the string of numeric characters. */ scan = str; lastdigit = str; while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') { if (*scan == '_') { if (prev == '_') { /* Only one underscore allowed. */ str = lastdigit + 1; goto onError; } } else { ++digits; lastdigit = scan; } prev = *scan; ++scan; } if (prev == '_') { /* Trailing underscore not allowed. */ /* Set error pointer to first underscore. */ str = lastdigit + 1; goto onError; } /* Create an int object that can contain the largest possible * integer with this base and length. Note that there's no * need to initialize z->ob_digit -- no slot is read up before * being stored into. */ fsize_z = digits * log_base_BASE[base] + 1; if (fsize_z > (double)(MAX_LONG_DIGITS/2)) { /* The same exception as in _PyLong_New(). */ PyErr_SetString(PyExc_OverflowError, "too many digits in integer"); return NULL; } size_z = (Py_ssize_t)fsize_z; /* Uncomment next line to test exceedingly rare copy code */ /* size_z = 1; */ assert(size_z > 0); z = _PyLong_New(size_z); if (z == NULL) { return NULL; } Py_SIZE(z) = 0; /* `convwidth` consecutive input digits are treated as a single * digit in base `convmultmax`. */ convwidth = convwidth_base[base]; convmultmax = convmultmax_base[base]; /* Work ;-) */ while (str < scan) { if (*str == '_') { str++; continue; } /* grab up to convwidth digits from the input string */ c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)]; for (i = 1; i < convwidth && str != scan; ++str) { if (*str == '_') { continue; } i++; c = (twodigits)(c * base + (int)_PyLong_DigitValue[Py_CHARMASK(*str)]); assert(c < PyLong_BASE); } convmult = convmultmax; /* Calculate the shift only if we couldn't get * convwidth digits. */ if (i != convwidth) { convmult = base; for ( ; i > 1; --i) { convmult *= base; } } /* Multiply z by convmult, and add c. */ pz = z->ob_digit; pzstop = pz + Py_SIZE(z); for (; pz < pzstop; ++pz) { c += (twodigits)*pz * convmult; *pz = (digit)(c & PyLong_MASK); c >>= PyLong_SHIFT; } /* carry off the current end? */ if (c) { assert(c < PyLong_BASE); if (Py_SIZE(z) < size_z) { *pz = (digit)c; ++Py_SIZE(z); } else { PyLongObject *tmp; /* Extremely rare. Get more space. */ assert(Py_SIZE(z) == size_z); tmp = _PyLong_New(size_z + 1); if (tmp == NULL) { Py_DECREF(z); return NULL; } memcpy(tmp->ob_digit, z->ob_digit, sizeof(digit) * size_z); Py_DECREF(z); z = tmp; z->ob_digit[size_z] = (digit)c; ++size_z; } } } } if (z == NULL) { return NULL; } if (error_if_nonzero) { /* reset the base to 0, else the exception message doesn't make too much sense */ base = 0; if (Py_SIZE(z) != 0) { goto onError; } /* there might still be other problems, therefore base remains zero here for the same reason */ } if (str == start) { goto onError; } if (sign < 0) { Py_SIZE(z) = -(Py_SIZE(z)); } while (*str && Py_ISSPACE(Py_CHARMASK(*str))) { str++; } if (*str != '\0') { goto onError; } long_normalize(z); z = maybe_small_long(z); if (z == NULL) { return NULL; } if (pend != NULL) { *pend = (char *)str; } return (PyObject *) z; onError: if (pend != NULL) { *pend = (char *)str; } Py_XDECREF(z); slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200; strobj = PyUnicode_FromStringAndSize(orig_str, slen); if (strobj == NULL) { return NULL; } PyErr_Format(PyExc_ValueError, "invalid literal for int() with base %d: %.200R", base, strobj); Py_DECREF(strobj); return NULL; } /* Since PyLong_FromString doesn't have a length parameter, * check here for possible NULs in the string. * * Reports an invalid literal as a bytes object. */ PyObject * _PyLong_FromBytes(const char *s, Py_ssize_t len, int base) { PyObject *result, *strobj; char *end = NULL; result = PyLong_FromString(s, &end, base); if (end == NULL || (result != NULL && end == s + len)) return result; Py_XDECREF(result); strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200)); if (strobj != NULL) { PyErr_Format(PyExc_ValueError, "invalid literal for int() with base %d: %.200R", base, strobj); Py_DECREF(strobj); } return NULL; } PyObject * PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base) { PyObject *v, *unicode = PyUnicode_FromUnicode(u, length); if (unicode == NULL) return NULL; v = PyLong_FromUnicodeObject(unicode, base); Py_DECREF(unicode); return v; } PyObject * PyLong_FromUnicodeObject(PyObject *u, int base) { PyObject *result, *asciidig; char *buffer, *end = NULL; Py_ssize_t buflen; asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u); if (asciidig == NULL) return NULL; buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen); if (buffer == NULL) { Py_DECREF(asciidig); if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) return NULL; } else { result = PyLong_FromString(buffer, &end, base); if (end == NULL || (result != NULL && end == buffer + buflen)) { Py_DECREF(asciidig); return result; } Py_DECREF(asciidig); Py_XDECREF(result); } PyErr_Format(PyExc_ValueError, "invalid literal for int() with base %d: %.200R", base, u); return NULL; } /* forward */ static PyLongObject *x_divrem (PyLongObject *, PyLongObject *, PyLongObject **); static PyObject *long_long(PyObject *v); /* Int division with remainder, top-level routine */ static int long_divrem(PyLongObject *a, PyLongObject *b, PyLongObject **pdiv, PyLongObject **prem) { Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b)); PyLongObject *z; if (size_b == 0) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); return -1; } if (size_a < size_b || (size_a == size_b && a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) { /* |a| < |b|. */ *pdiv = (PyLongObject*)PyLong_FromLong(0); if (*pdiv == NULL) return -1; *prem = (PyLongObject *)long_long((PyObject *)a); if (*prem == NULL) { Py_CLEAR(*pdiv); return -1; } return 0; } if (size_b == 1) { digit rem = 0; z = divrem1(a, b->ob_digit[0], &rem); if (z == NULL) return -1; *prem = (PyLongObject *) PyLong_FromLong((long)rem); if (*prem == NULL) { Py_DECREF(z); return -1; } } else { z = x_divrem(a, b, prem); if (z == NULL) return -1; } /* Set the signs. The quotient z has the sign of a*b; the remainder r has the sign of a, so a = b*z + r. */ if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) { _PyLong_Negate(&z); if (z == NULL) { Py_CLEAR(*prem); return -1; } } if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) { _PyLong_Negate(prem); if (*prem == NULL) { Py_DECREF(z); Py_CLEAR(*prem); return -1; } } *pdiv = maybe_small_long(z); return 0; } /* Unsigned int division with remainder -- the algorithm. The arguments v1 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */ static PyLongObject * x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem) { PyLongObject *v, *w, *a; Py_ssize_t i, k, size_v, size_w; int d; digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak; twodigits vv; sdigit zhi; stwodigits z; /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd edn.), section 4.3.1, Algorithm D], except that we don't explicitly handle the special case when the initial estimate q for a quotient digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and that won't overflow a digit. */ /* allocate space; w will also be used to hold the final remainder */ size_v = Py_ABS(Py_SIZE(v1)); size_w = Py_ABS(Py_SIZE(w1)); assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */ v = _PyLong_New(size_v+1); if (v == NULL) { *prem = NULL; return NULL; } w = _PyLong_New(size_w); if (w == NULL) { Py_DECREF(v); *prem = NULL; return NULL; } /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2. shift v1 left by the same amount. Results go into w and v. */ d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]); carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d); assert(carry == 0); carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d); if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) { v->ob_digit[size_v] = carry; size_v++; } /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has at most (and usually exactly) k = size_v - size_w digits. */ k = size_v - size_w; assert(k >= 0); a = _PyLong_New(k); if (a == NULL) { Py_DECREF(w); Py_DECREF(v); *prem = NULL; return NULL; } v0 = v->ob_digit; w0 = w->ob_digit; wm1 = w0[size_w-1]; wm2 = w0[size_w-2]; for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) { /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving single-digit quotient q, remainder in vk[0:size_w]. */ SIGCHECK({ Py_DECREF(a); Py_DECREF(w); Py_DECREF(v); *prem = NULL; return NULL; }); /* estimate quotient digit q; may overestimate by 1 (rare) */ vtop = vk[size_w]; assert(vtop <= wm1); vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1]; q = (digit)(vv / wm1); r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */ while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT) | vk[size_w-2])) { --q; r += wm1; if (r >= PyLong_BASE) break; } assert(q <= PyLong_BASE); /* subtract q*w0[0:size_w] from vk[0:size_w+1] */ zhi = 0; for (i = 0; i < size_w; ++i) { /* invariants: -PyLong_BASE <= -q <= zhi <= 0; -PyLong_BASE * q <= z < PyLong_BASE */ z = (sdigit)vk[i] + zhi - (stwodigits)q * (stwodigits)w0[i]; vk[i] = (digit)z & PyLong_MASK; zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits, z, PyLong_SHIFT); } /* add w back if q was too large (this branch taken rarely) */ assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0); if ((sdigit)vtop + zhi < 0) { carry = 0; for (i = 0; i < size_w; ++i) { carry += vk[i] + w0[i]; vk[i] = carry & PyLong_MASK; carry >>= PyLong_SHIFT; } --q; } /* store quotient digit */ assert(q < PyLong_BASE); *--ak = q; } /* unshift remainder; we reuse w to store the result */ carry = v_rshift(w0, v0, size_w, d); assert(carry==0); Py_DECREF(v); *prem = long_normalize(w); return long_normalize(a); } /* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <= abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is rounded to DBL_MANT_DIG significant bits using round-half-to-even. If a == 0, return 0.0 and set *e = 0. If the resulting exponent e is larger than PY_SSIZE_T_MAX, raise OverflowError and return -1.0. */ /* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */ #if DBL_MANT_DIG == 53 #define EXP2_DBL_MANT_DIG 9007199254740992.0 #else #define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG)) #endif double _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e) { Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size; /* See below for why x_digits is always large enough. */ digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT]; double dx; /* Correction term for round-half-to-even rounding. For a digit x, "x + half_even_correction[x & 7]" gives x rounded to the nearest multiple of 4, rounding ties to a multiple of 8. */ static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1}; a_size = Py_ABS(Py_SIZE(a)); if (a_size == 0) { /* Special case for 0: significand 0.0, exponent 0. */ *e = 0; return 0.0; } a_bits = bits_in_digit(a->ob_digit[a_size-1]); /* The following is an overflow-free version of the check "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */ if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 && (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 || a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1)) goto overflow; a_bits = (a_size - 1) * PyLong_SHIFT + a_bits; /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size] (shifting left if a_bits <= DBL_MANT_DIG + 2). Number of digits needed for result: write // for floor division. Then if shifting left, we end up using 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT digits. If shifting right, we use a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with the inequalities m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT m // PyLong_SHIFT - n // PyLong_SHIFT <= 1 + (m - n - 1) // PyLong_SHIFT, valid for any integers m and n, we find that x_size satisfies x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT in both cases. */ if (a_bits <= DBL_MANT_DIG + 2) { shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT; shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT; x_size = 0; while (x_size < shift_digits) x_digits[x_size++] = 0; rem = v_lshift(x_digits + x_size, a->ob_digit, a_size, (int)shift_bits); x_size += a_size; x_digits[x_size++] = rem; } else { shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT; shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT; rem = v_rshift(x_digits, a->ob_digit + shift_digits, a_size - shift_digits, (int)shift_bits); x_size = a_size - shift_digits; /* For correct rounding below, we need the least significant bit of x to be 'sticky' for this shift: if any of the bits shifted out was nonzero, we set the least significant bit of x. */ if (rem) x_digits[0] |= 1; else while (shift_digits > 0) if (a->ob_digit[--shift_digits]) { x_digits[0] |= 1; break; } } assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits)); /* Round, and convert to double. */ x_digits[0] += half_even_correction[x_digits[0] & 7]; dx = x_digits[--x_size]; while (x_size > 0) dx = dx * PyLong_BASE + x_digits[--x_size]; /* Rescale; make correction if result is 1.0. */ dx /= 4.0 * EXP2_DBL_MANT_DIG; if (dx == 1.0) { if (a_bits == PY_SSIZE_T_MAX) goto overflow; dx = 0.5; a_bits += 1; } *e = a_bits; return Py_SIZE(a) < 0 ? -dx : dx; overflow: /* exponent > PY_SSIZE_T_MAX */ PyErr_SetString(PyExc_OverflowError, "huge integer: number of bits overflows a Py_ssize_t"); *e = 0; return -1.0; } /* Get a C double from an int object. Rounds to the nearest double, using the round-half-to-even rule in the case of a tie. */ double PyLong_AsDouble(PyObject *v) { Py_ssize_t exponent; double x; if (v == NULL) { PyErr_BadInternalCall(); return -1.0; } if (!PyLong_Check(v)) { PyErr_SetString(PyExc_TypeError, "an integer is required"); return -1.0; } if (Py_ABS(Py_SIZE(v)) <= 1) { /* Fast path; single digit long (31 bits) will cast safely to double. This improves performance of FP/long operations by 20%. */ return (double)MEDIUM_VALUE((PyLongObject *)v); } x = _PyLong_Frexp((PyLongObject *)v, &exponent); if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) { PyErr_SetString(PyExc_OverflowError, "int too large to convert to float"); return -1.0; } return ldexp(x, (int)exponent); } /* Methods */ static void long_dealloc(PyObject *v) { Py_TYPE(v)->tp_free(v); } static int long_compare(PyLongObject *a, PyLongObject *b) { if (Py_SIZE(a) != Py_SIZE(b)) { Py_ssize_t sign; sign = Py_SIZE(a) - Py_SIZE(b); return sign < 0 ? -1 : sign > 0 ? 1 : 0; } else { int sign; Py_ssize_t i = Py_ABS(Py_SIZE(a)); while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) ; if (i < 0) sign = 0; else { sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i]; if (Py_SIZE(a) < 0) sign = -sign; } return sign < 0 ? -1 : sign > 0 ? 1 : 0; } } #define TEST_COND(cond) \ ((cond) ? Py_True : Py_False) static PyObject * long_richcompare(PyObject *self, PyObject *other, int op) { int result; PyObject *v; CHECK_BINOP(self, other); if (self == other) { result = 0; } else { result = long_compare((PyLongObject*)self, (PyLongObject*)other); } /* Convert the return value to a Boolean */ switch (op) { case Py_EQ: v = TEST_COND(result == 0); break; case Py_NE: v = TEST_COND(result != 0); break; case Py_LE: v = TEST_COND(result <= 0); break; case Py_GE: v = TEST_COND(result >= 0); break; case Py_LT: v = TEST_COND(result == -1); break; case Py_GT: v = TEST_COND(result == 1); break; default: PyErr_BadArgument(); return NULL; } Py_INCREF(v); return v; } static Py_hash_t long_hash(PyLongObject *v) { Py_uhash_t x; Py_ssize_t i; int sign; i = Py_SIZE(v); switch(i) { case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0]; case 0: return 0; case 1: return v->ob_digit[0]; } sign = 1; x = 0; if (i < 0) { sign = -1; i = -(i); } while (--i >= 0) { /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo _PyHASH_MODULUS. The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS amounts to a rotation of the bits of x. To see this, write x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top PyLong_SHIFT bits of x (those that are shifted out of the original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) & _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT bits of x, shifted up. Then since 2**_PyHASH_BITS is congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is congruent to y modulo _PyHASH_MODULUS. So x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS). The right-hand side is just the result of rotating the _PyHASH_BITS bits of x left by PyLong_SHIFT places; since not all _PyHASH_BITS bits of x are 1s, the same is true after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is the reduction of x*2**PyLong_SHIFT modulo _PyHASH_MODULUS. */ x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) | (x >> (_PyHASH_BITS - PyLong_SHIFT)); x += v->ob_digit[i]; if (x >= _PyHASH_MODULUS) x -= _PyHASH_MODULUS; } x = x * sign; if (x == (Py_uhash_t)-1) x = (Py_uhash_t)-2; return (Py_hash_t)x; } /* Add the absolute values of two integers. */ static PyLongObject * x_add(PyLongObject *a, PyLongObject *b) { Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b)); PyLongObject *z; Py_ssize_t i; digit carry = 0; /* Ensure a is the larger of the two: */ if (size_a < size_b) { { PyLongObject *temp = a; a = b; b = temp; } { Py_ssize_t size_temp = size_a; size_a = size_b; size_b = size_temp; } } z = _PyLong_New(size_a+1); if (z == NULL) return NULL; for (i = 0; i < size_b; ++i) { carry += a->ob_digit[i] + b->ob_digit[i]; z->ob_digit[i] = carry & PyLong_MASK; carry >>= PyLong_SHIFT; } for (; i < size_a; ++i) { carry += a->ob_digit[i]; z->ob_digit[i] = carry & PyLong_MASK; carry >>= PyLong_SHIFT; } z->ob_digit[i] = carry; return long_normalize(z); } /* Subtract the absolute values of two integers. */ static PyLongObject * x_sub(PyLongObject *a, PyLongObject *b) { Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b)); PyLongObject *z; Py_ssize_t i; int sign = 1; digit borrow = 0; /* Ensure a is the larger of the two: */ if (size_a < size_b) { sign = -1; { PyLongObject *temp = a; a = b; b = temp; } { Py_ssize_t size_temp = size_a; size_a = size_b; size_b = size_temp; } } else if (size_a == size_b) { /* Find highest digit where a and b differ: */ i = size_a; while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i]) ; if (i < 0) return (PyLongObject *)PyLong_FromLong(0); if (a->ob_digit[i] < b->ob_digit[i]) { sign = -1; { PyLongObject *temp = a; a = b; b = temp; } } size_a = size_b = i+1; } z = _PyLong_New(size_a); if (z == NULL) return NULL; for (i = 0; i < size_b; ++i) { /* The following assumes unsigned arithmetic works module 2**N for some N>PyLong_SHIFT. */ borrow = a->ob_digit[i] - b->ob_digit[i] - borrow; z->ob_digit[i] = borrow & PyLong_MASK; borrow >>= PyLong_SHIFT; borrow &= 1; /* Keep only one sign bit */ } for (; i < size_a; ++i) { borrow = a->ob_digit[i] - borrow; z->ob_digit[i] = borrow & PyLong_MASK; borrow >>= PyLong_SHIFT; borrow &= 1; /* Keep only one sign bit */ } assert(borrow == 0); if (sign < 0) { Py_SIZE(z) = -Py_SIZE(z); } return long_normalize(z); } static PyObject * long_add(PyLongObject *a, PyLongObject *b) { PyLongObject *z; CHECK_BINOP(a, b); if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) { PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b)); return result; } if (Py_SIZE(a) < 0) { if (Py_SIZE(b) < 0) { z = x_add(a, b); if (z != NULL) { /* x_add received at least one multiple-digit int, and thus z must be a multiple-digit int. That also means z is not an element of small_ints, so negating it in-place is safe. */ assert(Py_REFCNT(z) == 1); Py_SIZE(z) = -(Py_SIZE(z)); } } else z = x_sub(b, a); } else { if (Py_SIZE(b) < 0) z = x_sub(a, b); else z = x_add(a, b); } return (PyObject *)z; } static PyObject * long_sub(PyLongObject *a, PyLongObject *b) { PyLongObject *z; CHECK_BINOP(a, b); if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) { PyObject* r; r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); return r; } if (Py_SIZE(a) < 0) { if (Py_SIZE(b) < 0) z = x_sub(a, b); else z = x_add(a, b); if (z != NULL) { assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1); Py_SIZE(z) = -(Py_SIZE(z)); } } else { if (Py_SIZE(b) < 0) z = x_add(a, b); else z = x_sub(a, b); } return (PyObject *)z; } /* Grade school multiplication, ignoring the signs. * Returns the absolute value of the product, or NULL if error. */ static PyLongObject * x_mul(PyLongObject *a, PyLongObject *b) { PyLongObject *z; Py_ssize_t size_a = Py_ABS(Py_SIZE(a)); Py_ssize_t size_b = Py_ABS(Py_SIZE(b)); Py_ssize_t i; z = _PyLong_New(size_a + size_b); if (z == NULL) return NULL; bzero(z->ob_digit, Py_SIZE(z) * sizeof(digit)); if (a == b) { /* Efficient squaring per HAC, Algorithm 14.16: * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf * Gives slightly less than a 2x speedup when a == b, * via exploiting that each entry in the multiplication * pyramid appears twice (except for the size_a squares). */ for (i = 0; i < size_a; ++i) { twodigits carry; twodigits f = a->ob_digit[i]; digit *pz = z->ob_digit + (i << 1); digit *pa = a->ob_digit + i + 1; digit *paend = a->ob_digit + size_a; SIGCHECK({ Py_DECREF(z); return NULL; }); carry = *pz + f * f; *pz++ = (digit)(carry & PyLong_MASK); carry >>= PyLong_SHIFT; assert(carry <= PyLong_MASK); /* Now f is added in twice in each column of the * pyramid it appears. Same as adding f<<1 once. */ f <<= 1; while (pa < paend) { carry += *pz + *pa++ * f; *pz++ = (digit)(carry & PyLong_MASK); carry >>= PyLong_SHIFT; assert(carry <= (PyLong_MASK << 1)); } if (carry) { carry += *pz; *pz++ = (digit)(carry & PyLong_MASK); carry >>= PyLong_SHIFT; } if (carry) *pz += (digit)(carry & PyLong_MASK); assert((carry >> PyLong_SHIFT) == 0); } } else { /* a is not the same as b -- gradeschool int mult */ for (i = 0; i < size_a; ++i) { twodigits carry = 0; twodigits f = a->ob_digit[i]; digit *pz = z->ob_digit + i; digit *pb = b->ob_digit; digit *pbend = b->ob_digit + size_b; SIGCHECK({ Py_DECREF(z); return NULL; }); while (pb < pbend) { carry += *pz + *pb++ * f; *pz++ = (digit)(carry & PyLong_MASK); carry >>= PyLong_SHIFT; assert(carry <= PyLong_MASK); } if (carry) *pz += (digit)(carry & PyLong_MASK); assert((carry >> PyLong_SHIFT) == 0); } } return long_normalize(z); } /* A helper for Karatsuba multiplication (k_mul). Takes an int "n" and an integer "size" representing the place to split, and sets low and high such that abs(n) == (high << size) + low, viewing the shift as being by digits. The sign bit is ignored, and the return values are >= 0. Returns 0 on success, -1 on failure. */ static int kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low) { PyLongObject *hi, *lo; Py_ssize_t size_lo, size_hi; const Py_ssize_t size_n = Py_ABS(Py_SIZE(n)); size_lo = Py_MIN(size_n, size); size_hi = size_n - size_lo; if ((hi = _PyLong_New(size_hi)) == NULL) return -1; if ((lo = _PyLong_New(size_lo)) == NULL) { Py_DECREF(hi); return -1; } memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit)); memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit)); *high = long_normalize(hi); *low = long_normalize(lo); return 0; } static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b); /* Karatsuba multiplication. Ignores the input signs, and returns the * absolute value of the product (or NULL if error). * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295). */ static PyLongObject * k_mul(PyLongObject *a, PyLongObject *b) { Py_ssize_t asize = Py_ABS(Py_SIZE(a)); Py_ssize_t bsize = Py_ABS(Py_SIZE(b)); PyLongObject *ah = NULL; PyLongObject *al = NULL; PyLongObject *bh = NULL; PyLongObject *bl = NULL; PyLongObject *ret = NULL; PyLongObject *t1, *t2, *t3; Py_ssize_t shift; /* the number of digits we split off */ Py_ssize_t i; /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl * Then the original product is * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl * By picking X to be a power of 2, "*X" is just shifting, and it's * been reduced to 3 multiplies on numbers half the size. */ /* We want to split based on the larger number; fiddle so that b * is largest. */ if (asize > bsize) { t1 = a; a = b; b = t1; i = asize; asize = bsize; bsize = i; } /* Use gradeschool math when either number is too small. */ i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF; if (asize <= i) { if (asize == 0) return (PyLongObject *)PyLong_FromLong(0); else return x_mul(a, b); } /* If a is small compared to b, splitting on b gives a degenerate * case with ah==0, and Karatsuba may be (even much) less efficient * than "grade school" then. However, we can still win, by viewing * b as a string of "big digits", each of width a->ob_size. That * leads to a sequence of balanced calls to k_mul. */ if (2 * asize <= bsize) return k_lopsided_mul(a, b); /* Split a & b into hi & lo pieces. */ shift = bsize >> 1; if (kmul_split(a, shift, &ah, &al) < 0) goto fail; assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */ if (a == b) { bh = ah; bl = al; Py_INCREF(bh); Py_INCREF(bl); } else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail; /* The plan: * 1. Allocate result space (asize + bsize digits: that's always * enough). * 2. Compute ah*bh, and copy into result at 2*shift. * 3. Compute al*bl, and copy into result at 0. Note that this * can't overlap with #2. * 4. Subtract al*bl from the result, starting at shift. This may * underflow (borrow out of the high digit), but we don't care: * we're effectively doing unsigned arithmetic mod * BASE**(sizea + sizeb), and so long as the *final* result fits, * borrows and carries out of the high digit can be ignored. * 5. Subtract ah*bh from the result, starting at shift. * 6. Compute (ah+al)*(bh+bl), and add it into the result starting * at shift. */ /* 1. Allocate result space. */ ret = _PyLong_New(asize + bsize); if (ret == NULL) goto fail; #ifdef Py_DEBUG /* Fill with trash, to catch reference to uninitialized digits. */ memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit)); #endif /* 2. t1 <- ah*bh, and copy into high digits of result. */ if ((t1 = k_mul(ah, bh)) == NULL) goto fail; assert(Py_SIZE(t1) >= 0); assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret)); memcpy(ret->ob_digit + 2*shift, t1->ob_digit, Py_SIZE(t1) * sizeof(digit)); /* Zero-out the digits higher than the ah*bh copy. */ i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1); if (i) bzero(ret->ob_digit + 2*shift + Py_SIZE(t1), i * sizeof(digit)); /* 3. t2 <- al*bl, and copy into the low digits. */ if ((t2 = k_mul(al, bl)) == NULL) { Py_DECREF(t1); goto fail; } assert(Py_SIZE(t2) >= 0); assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */ memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit)); /* Zero out remaining digits. */ i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */ if (i) bzero(ret->ob_digit + Py_SIZE(t2), i * sizeof(digit)); /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first * because it's fresher in cache. */ i = Py_SIZE(ret) - shift; /* # digits after shift */ (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2)); Py_DECREF(t2); (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1)); Py_DECREF(t1); /* 6. t3 <- (ah+al)(bh+bl), and add into result. */ if ((t1 = x_add(ah, al)) == NULL) goto fail; Py_DECREF(ah); Py_DECREF(al); ah = al = NULL; if (a == b) { t2 = t1; Py_INCREF(t2); } else if ((t2 = x_add(bh, bl)) == NULL) { Py_DECREF(t1); goto fail; } Py_DECREF(bh); Py_DECREF(bl); bh = bl = NULL; t3 = k_mul(t1, t2); Py_DECREF(t1); Py_DECREF(t2); if (t3 == NULL) goto fail; assert(Py_SIZE(t3) >= 0); /* Add t3. It's not obvious why we can't run out of room here. * See the (*) comment after this function. */ (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3)); Py_DECREF(t3); return long_normalize(ret); fail: Py_XDECREF(ret); Py_XDECREF(ah); Py_XDECREF(al); Py_XDECREF(bh); Py_XDECREF(bl); return NULL; } /* (*) Why adding t3 can't "run out of room" above. Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts to start with: 1. For any integer i, i = c(i/2) + f(i/2). In particular, bsize = c(bsize/2) + f(bsize/2). 2. shift = f(bsize/2) 3. asize <= bsize 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this routine, so asize > bsize/2 >= f(bsize/2) in this routine. We allocated asize + bsize result digits, and add t3 into them at an offset of shift. This leaves asize+bsize-shift allocated digit positions for t3 to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) = asize + c(bsize/2) available digit positions. bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has at most c(bsize/2) digits + 1 bit. If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2) digits, and al has at most f(bsize/2) digits in any case. So ah+al has at most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit. The product (ah+al)*(bh+bl) therefore has at most c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits and we have asize + c(bsize/2) available digit positions. We need to show this is always enough. An instance of c(bsize/2) cancels out in both, so the question reduces to whether asize digits is enough to hold (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize, then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4, asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1 digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If asize == bsize, then we're asking whether bsize digits is enough to hold c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits is enough to hold 2 bits. This is so if bsize >= 2, which holds because bsize >= KARATSUBA_CUTOFF >= 2. Note that since there's always enough room for (ah+al)*(bh+bl), and that's clearly >= each of ah*bh and al*bl, there's always enough room to subtract ah*bh and al*bl too. */ /* b has at least twice the digits of a, and a is big enough that Karatsuba * would pay off *if* the inputs had balanced sizes. View b as a sequence * of slices, each with a->ob_size digits, and multiply the slices by a, * one at a time. This gives k_mul balanced inputs to work with, and is * also cache-friendly (we compute one double-width slice of the result * at a time, then move on, never backtracking except for the helpful * single-width slice overlap between successive partial sums). */ static PyLongObject * k_lopsided_mul(PyLongObject *a, PyLongObject *b) { const Py_ssize_t asize = Py_ABS(Py_SIZE(a)); Py_ssize_t bsize = Py_ABS(Py_SIZE(b)); Py_ssize_t nbdone; /* # of b digits already multiplied */ PyLongObject *ret; PyLongObject *bslice = NULL; assert(asize > KARATSUBA_CUTOFF); assert(2 * asize <= bsize); /* Allocate result space, and zero it out. */ ret = _PyLong_New(asize + bsize); if (ret == NULL) return NULL; bzero(ret->ob_digit, Py_SIZE(ret) * sizeof(digit)); /* Successive slices of b are copied into bslice. */ bslice = _PyLong_New(asize); if (bslice == NULL) goto fail; nbdone = 0; while (bsize > 0) { PyLongObject *product; const Py_ssize_t nbtouse = Py_MIN(bsize, asize); /* Multiply the next slice of b by a. */ memcpy(bslice->ob_digit, b->ob_digit + nbdone, nbtouse * sizeof(digit)); Py_SIZE(bslice) = nbtouse; product = k_mul(a, bslice); if (product == NULL) goto fail; /* Add into result. */ (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone, product->ob_digit, Py_SIZE(product)); Py_DECREF(product); bsize -= nbtouse; nbdone += nbtouse; } Py_DECREF(bslice); return long_normalize(ret); fail: Py_DECREF(ret); Py_XDECREF(bslice); return NULL; } static PyObject * long_mul(PyLongObject *a, PyLongObject *b) { PyLongObject *z; CHECK_BINOP(a, b); /* fast path for single-digit multiplication */ if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) { stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b); return PyLong_FromLongLong((long long)v); } z = k_mul(a, b); /* Negate if exactly one of the inputs is negative. */ if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) { _PyLong_Negate(&z); if (z == NULL) return NULL; } return (PyObject *)z; } /* Fast modulo division for single-digit longs. */ static PyObject * fast_mod(PyLongObject *a, PyLongObject *b) { sdigit left = a->ob_digit[0]; sdigit right = b->ob_digit[0]; sdigit mod; assert(Py_ABS(Py_SIZE(a)) == 1); assert(Py_ABS(Py_SIZE(b)) == 1); if (Py_SIZE(a) == Py_SIZE(b)) { /* 'a' and 'b' have the same sign. */ mod = left % right; } else { /* Either 'a' or 'b' is negative. */ mod = right - 1 - (left - 1) % right; } return PyLong_FromLong(mod * (sdigit)Py_SIZE(b)); } /* Fast floor division for single-digit longs. */ static PyObject * fast_floor_div(PyLongObject *a, PyLongObject *b) { sdigit left = a->ob_digit[0]; sdigit right = b->ob_digit[0]; sdigit div; assert(Py_ABS(Py_SIZE(a)) == 1); assert(Py_ABS(Py_SIZE(b)) == 1); if (Py_SIZE(a) == Py_SIZE(b)) { /* 'a' and 'b' have the same sign. */ div = left / right; } else { /* Either 'a' or 'b' is negative. */ div = -1 - (left - 1) / right; } return PyLong_FromLong(div); } /* The / and % operators are now defined in terms of divmod(). The expression a mod b has the value a - b*floor(a/b). The long_divrem function gives the remainder after division of |a| by |b|, with the sign of a. This is also expressed as a - b*trunc(a/b), if trunc truncates towards zero. Some examples: a b a rem b a mod b 13 10 3 3 -13 10 -3 7 13 -10 3 -7 -13 -10 -3 -3 So, to get from rem to mod, we have to add b if a and b have different signs. We then subtract one from the 'div' part of the outcome to keep the invariant intact. */ /* Compute * *pdiv, *pmod = divmod(v, w) * NULL can be passed for pdiv or pmod, in which case that part of * the result is simply thrown away. The caller owns a reference to * each of these it requests (does not pass NULL for). */ static int l_divmod(PyLongObject *v, PyLongObject *w, PyLongObject **pdiv, PyLongObject **pmod) { PyLongObject *div, *mod; if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) { /* Fast path for single-digit longs */ div = NULL; if (pdiv != NULL) { div = (PyLongObject *)fast_floor_div(v, w); if (div == NULL) { return -1; } } if (pmod != NULL) { mod = (PyLongObject *)fast_mod(v, w); if (mod == NULL) { Py_XDECREF(div); return -1; } *pmod = mod; } if (pdiv != NULL) { /* We only want to set `*pdiv` when `*pmod` is set successfully. */ *pdiv = div; } return 0; } if (long_divrem(v, w, &div, &mod) < 0) return -1; if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) || (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) { PyLongObject *temp; PyLongObject *one; temp = (PyLongObject *) long_add(mod, w); Py_DECREF(mod); mod = temp; if (mod == NULL) { Py_DECREF(div); return -1; } one = (PyLongObject *) PyLong_FromLong(1L); if (one == NULL || (temp = (PyLongObject *) long_sub(div, one)) == NULL) { Py_DECREF(mod); Py_DECREF(div); Py_XDECREF(one); return -1; } Py_DECREF(one); Py_DECREF(div); div = temp; } if (pdiv != NULL) *pdiv = div; else Py_DECREF(div); if (pmod != NULL) *pmod = mod; else Py_DECREF(mod); return 0; } static PyObject * long_div(PyObject *a, PyObject *b) { PyLongObject *div; CHECK_BINOP(a, b); if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) { return fast_floor_div((PyLongObject*)a, (PyLongObject*)b); } if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0) div = NULL; return (PyObject *)div; } /* PyLong/PyLong -> float, with correctly rounded result. */ #define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT) #define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT) static PyObject * long_true_divide(PyObject *v, PyObject *w) { PyLongObject *a, *b, *x; Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits; digit mask, low; int inexact, negate, a_is_small, b_is_small; double dx, result; CHECK_BINOP(v, w); a = (PyLongObject *)v; b = (PyLongObject *)w; /* Method in a nutshell: 0. reduce to case a, b > 0; filter out obvious underflow/overflow 1. choose a suitable integer 'shift' 2. use integer arithmetic to compute x = floor(2**-shift*a/b) 3. adjust x for correct rounding 4. convert x to a double dx with the same value 5. return ldexp(dx, shift). In more detail: 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b returns either 0.0 or -0.0, depending on the sign of b. For a and b both nonzero, ignore signs of a and b, and add the sign back in at the end. Now write a_bits and b_bits for the bit lengths of a and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise for b). Then 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1). So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP - DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of the way, we can assume that DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP. 1. The integer 'shift' is chosen so that x has the right number of bits for a double, plus two or three extra bits that will be used in the rounding decisions. Writing a_bits and b_bits for the number of significant bits in a and b respectively, a straightforward formula for shift is: shift = a_bits - b_bits - DBL_MANT_DIG - 2 This is fine in the usual case, but if a/b is smaller than the smallest normal float then it can lead to double rounding on an IEEE 754 platform, giving incorrectly rounded results. So we adjust the formula slightly. The actual formula used is: shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2 2. The quantity x is computed by first shifting a (left -shift bits if shift <= 0, right shift bits if shift > 0) and then dividing by b. For both the shift and the division, we keep track of whether the result is inexact, in a flag 'inexact'; this information is needed at the rounding stage. With the choice of shift above, together with our assumption that a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows that x >= 1. 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace this with an exactly representable float of the form round(x/2**extra_bits) * 2**(extra_bits+shift). For float representability, we need x/2**extra_bits < 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP - DBL_MANT_DIG. This translates to the condition: extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG To round, we just modify the bottom digit of x in-place; this can end up giving a digit with value > PyLONG_MASK, but that's not a problem since digits can hold values up to 2*PyLONG_MASK+1. With the original choices for shift above, extra_bits will always be 2 or 3. Then rounding under the round-half-to-even rule, we round up iff the most significant of the extra bits is 1, and either: (a) the computation of x in step 2 had an inexact result, or (b) at least one other of the extra bits is 1, or (c) the least significant bit of x (above those to be rounded) is 1. 4. Conversion to a double is straightforward; all floating-point operations involved in the conversion are exact, so there's no danger of rounding errors. 5. Use ldexp(x, shift) to compute x*2**shift, the final result. The result will always be exactly representable as a double, except in the case that it overflows. To avoid dependence on the exact behaviour of ldexp on overflow, we check for overflow before applying ldexp. The result of ldexp is adjusted for sign before returning. */ /* Reduce to case where a and b are both positive. */ a_size = Py_ABS(Py_SIZE(a)); b_size = Py_ABS(Py_SIZE(b)); negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0); if (b_size == 0) { PyErr_SetString(PyExc_ZeroDivisionError, "division by zero"); goto error; } if (a_size == 0) goto underflow_or_zero; /* Fast path for a and b small (exactly representable in a double). Relies on floating-point division being correctly rounded; results may be subject to double rounding on x86 machines that operate with the x87 FPU set to 64-bit precision. */ a_is_small = a_size <= MANT_DIG_DIGITS || (a_size == MANT_DIG_DIGITS+1 && a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); b_is_small = b_size <= MANT_DIG_DIGITS || (b_size == MANT_DIG_DIGITS+1 && b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0); if (a_is_small && b_is_small) { double da, db; da = a->ob_digit[--a_size]; while (a_size > 0) da = da * PyLong_BASE + a->ob_digit[--a_size]; db = b->ob_digit[--b_size]; while (b_size > 0) db = db * PyLong_BASE + b->ob_digit[--b_size]; result = da / db; goto success; } /* Catch obvious cases of underflow and overflow */ diff = a_size - b_size; if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1) /* Extreme overflow */ goto overflow; else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT) /* Extreme underflow */ goto underflow_or_zero; /* Next line is now safe from overflowing a Py_ssize_t */ diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) - bits_in_digit(b->ob_digit[b_size - 1]); /* Now diff = a_bits - b_bits. */ if (diff > DBL_MAX_EXP) goto overflow; else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1) goto underflow_or_zero; /* Choose value for shift; see comments for step 1 above. */ shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2; inexact = 0; /* x = abs(a * 2**-shift) */ if (shift <= 0) { Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT; digit rem; /* x = a << -shift */ if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) { /* In practice, it's probably impossible to end up here. Both a and b would have to be enormous, using close to SIZE_T_MAX bytes of memory each. */ PyErr_SetString(PyExc_OverflowError, "intermediate overflow during division"); goto error; } x = _PyLong_New(a_size + shift_digits + 1); if (x == NULL) goto error; for (i = 0; i < shift_digits; i++) x->ob_digit[i] = 0; rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit, a_size, -shift % PyLong_SHIFT); x->ob_digit[a_size + shift_digits] = rem; } else { Py_ssize_t shift_digits = shift / PyLong_SHIFT; digit rem; /* x = a >> shift */ assert(a_size >= shift_digits); x = _PyLong_New(a_size - shift_digits); if (x == NULL) goto error; rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits, a_size - shift_digits, shift % PyLong_SHIFT); /* set inexact if any of the bits shifted out is nonzero */ if (rem) inexact = 1; while (!inexact && shift_digits > 0) if (a->ob_digit[--shift_digits]) inexact = 1; } long_normalize(x); x_size = Py_SIZE(x); /* x //= b. If the remainder is nonzero, set inexact. We own the only reference to x, so it's safe to modify it in-place. */ if (b_size == 1) { digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size, b->ob_digit[0]); long_normalize(x); if (rem) inexact = 1; } else { PyLongObject *div, *rem; div = x_divrem(x, b, &rem); Py_DECREF(x); x = div; if (x == NULL) goto error; if (Py_SIZE(rem)) inexact = 1; Py_DECREF(rem); } x_size = Py_ABS(Py_SIZE(x)); assert(x_size > 0); /* result of division is never zero */ x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]); /* The number of extra bits that have to be rounded away. */ extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG; assert(extra_bits == 2 || extra_bits == 3); /* Round by directly modifying the low digit of x. */ mask = (digit)1 << (extra_bits - 1); low = x->ob_digit[0] | inexact; if ((low & mask) && (low & (3U*mask-1U))) low += mask; x->ob_digit[0] = low & ~(2U*mask-1U); /* Convert x to a double dx; the conversion is exact. */ dx = x->ob_digit[--x_size]; while (x_size > 0) dx = dx * PyLong_BASE + x->ob_digit[--x_size]; Py_DECREF(x); /* Check whether ldexp result will overflow a double. */ if (shift + x_bits >= DBL_MAX_EXP && (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits))) goto overflow; result = ldexp(dx, (int)shift); success: return PyFloat_FromDouble(negate ? -result : result); underflow_or_zero: return PyFloat_FromDouble(negate ? -0.0 : 0.0); overflow: PyErr_SetString(PyExc_OverflowError, "integer division result too large for a float"); error: return NULL; } static PyObject * long_mod(PyObject *a, PyObject *b) { PyLongObject *mod; CHECK_BINOP(a, b); if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) { return fast_mod((PyLongObject*)a, (PyLongObject*)b); } if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0) mod = NULL; return (PyObject *)mod; } static PyObject * long_divmod(PyObject *a, PyObject *b) { PyLongObject *div, *mod; PyObject *z; CHECK_BINOP(a, b); if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) { return NULL; } z = PyTuple_New(2); if (z != NULL) { PyTuple_SetItem(z, 0, (PyObject *) div); PyTuple_SetItem(z, 1, (PyObject *) mod); } else { Py_DECREF(div); Py_DECREF(mod); } return z; } /* pow(v, w, x) */ static PyObject * long_pow(PyObject *v, PyObject *w, PyObject *x) { PyLongObject *a, *b, *c; /* a,b,c = v,w,x */ int negativeOutput = 0; /* if x<0 return negative output */ PyLongObject *z = NULL; /* accumulated result */ Py_ssize_t i, j, k; /* counters */ PyLongObject *temp = NULL; /* 5-ary values. If the exponent is large enough, table is * precomputed so that table[i] == a**i % c for i in range(32). */ PyLongObject *table[32] = {0}; /* a, b, c = v, w, x */ CHECK_BINOP(v, w); a = (PyLongObject*)v; Py_INCREF(a); b = (PyLongObject*)w; Py_INCREF(b); if (PyLong_Check(x)) { c = (PyLongObject *)x; Py_INCREF(x); } else if (x == Py_None) c = NULL; else { Py_DECREF(a); Py_DECREF(b); Py_RETURN_NOTIMPLEMENTED; } if (Py_SIZE(b) < 0) { /* if exponent is negative */ if (c) { PyErr_SetString(PyExc_ValueError, "pow() 2nd argument " "cannot be negative when 3rd argument specified"); goto Error; } else { /* else return a float. This works because we know that this calls float_pow() which converts its arguments to double. */ Py_DECREF(a); Py_DECREF(b); return PyFloat_Type.tp_as_number->nb_power(v, w, x); } } if (c) { /* if modulus == 0: raise ValueError() */ if (Py_SIZE(c) == 0) { PyErr_SetString(PyExc_ValueError, "pow() 3rd argument cannot be 0"); goto Error; } /* if modulus < 0: negativeOutput = True modulus = -modulus */ if (Py_SIZE(c) < 0) { negativeOutput = 1; temp = (PyLongObject *)_PyLong_Copy(c); if (temp == NULL) goto Error; Py_DECREF(c); c = temp; temp = NULL; _PyLong_Negate(&c); if (c == NULL) goto Error; } /* if modulus == 1: return 0 */ if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) { z = (PyLongObject *)PyLong_FromLong(0L); goto Done; } /* Reduce base by modulus in some cases: 1. If base < 0. Forcing the base non-negative makes things easier. 2. If base is obviously larger than the modulus. The "small exponent" case later can multiply directly by base repeatedly, while the "large exponent" case multiplies directly by base 31 times. It can be unboundedly faster to multiply by base % modulus instead. We could _always_ do this reduction, but l_divmod() isn't cheap, so we only do it when it buys something. */ if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) { if (l_divmod(a, c, NULL, &temp) < 0) goto Error; Py_DECREF(a); a = temp; temp = NULL; } } /* At this point a, b, and c are guaranteed non-negative UNLESS c is NULL, in which case a may be negative. */ z = (PyLongObject *)PyLong_FromLong(1L); if (z == NULL) goto Error; /* Perform a modular reduction, X = X % c, but leave X alone if c * is NULL. */ #define REDUCE(X) \ do { \ if (c != NULL) { \ if (l_divmod(X, c, NULL, &temp) < 0) \ goto Error; \ Py_XDECREF(X); \ X = temp; \ temp = NULL; \ } \ } while(0) /* Multiply two values, then reduce the result: result = X*Y % c. If c is NULL, skip the mod. */ #define MULT(X, Y, result) \ do { \ temp = (PyLongObject *)long_mul(X, Y); \ if (temp == NULL) \ goto Error; \ Py_XDECREF(result); \ result = temp; \ temp = NULL; \ REDUCE(result); \ } while(0) if (Py_SIZE(b) <= FIVEARY_CUTOFF) { /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ for (i = Py_SIZE(b) - 1; i >= 0; --i) { digit bi = b->ob_digit[i]; for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) { MULT(z, z, z); if (bi & j) MULT(z, a, z); } } } else { /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ Py_INCREF(z); /* still holds 1L */ table[0] = z; for (i = 1; i < 32; ++i) MULT(table[i-1], a, table[i]); for (i = Py_SIZE(b) - 1; i >= 0; --i) { const digit bi = b->ob_digit[i]; for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) { const int index = (bi >> j) & 0x1f; for (k = 0; k < 5; ++k) MULT(z, z, z); if (index) MULT(z, table[index], z); } } } if (negativeOutput && (Py_SIZE(z) != 0)) { temp = (PyLongObject *)long_sub(z, c); if (temp == NULL) goto Error; Py_DECREF(z); z = temp; temp = NULL; } goto Done; Error: Py_CLEAR(z); /* fall through */ Done: if (Py_SIZE(b) > FIVEARY_CUTOFF) { for (i = 0; i < 32; ++i) Py_XDECREF(table[i]); } Py_DECREF(a); Py_DECREF(b); Py_XDECREF(c); Py_XDECREF(temp); return (PyObject *)z; } static PyObject * long_invert(PyLongObject *v) { /* Implement ~x as -(x+1) */ PyLongObject *x; PyLongObject *w; if (Py_ABS(Py_SIZE(v)) <=1) return PyLong_FromLong(-(MEDIUM_VALUE(v)+1)); w = (PyLongObject *)PyLong_FromLong(1L); if (w == NULL) return NULL; x = (PyLongObject *) long_add(v, w); Py_DECREF(w); if (x == NULL) return NULL; _PyLong_Negate(&x); /* No need for maybe_small_long here, since any small longs will have been caught in the Py_SIZE <= 1 fast path. */ return (PyObject *)x; } static PyObject * long_neg(PyLongObject *v) { PyLongObject *z; if (Py_ABS(Py_SIZE(v)) <= 1) return PyLong_FromLong(-MEDIUM_VALUE(v)); z = (PyLongObject *)_PyLong_Copy(v); if (z != NULL) Py_SIZE(z) = -(Py_SIZE(v)); return (PyObject *)z; } static PyObject * long_abs(PyLongObject *v) { if (Py_SIZE(v) < 0) return long_neg(v); else return long_long((PyObject *)v); } static int long_bool(PyLongObject *v) { return Py_SIZE(v) != 0; } static PyObject * long_rshift(PyLongObject *a, PyLongObject *b) { PyLongObject *z = NULL; Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j; digit lomask, himask; CHECK_BINOP(a, b); if (Py_SIZE(a) < 0) { /* Right shifting negative numbers is harder */ PyLongObject *a1, *a2; a1 = (PyLongObject *) long_invert(a); if (a1 == NULL) goto rshift_error; a2 = (PyLongObject *) long_rshift(a1, b); Py_DECREF(a1); if (a2 == NULL) goto rshift_error; z = (PyLongObject *) long_invert(a2); Py_DECREF(a2); } else { shiftby = PyLong_AsSsize_t((PyObject *)b); if (shiftby == -1L && PyErr_Occurred()) goto rshift_error; if (shiftby < 0) { PyErr_SetString(PyExc_ValueError, "negative shift count"); goto rshift_error; } wordshift = shiftby / PyLong_SHIFT; newsize = Py_ABS(Py_SIZE(a)) - wordshift; if (newsize <= 0) return PyLong_FromLong(0); loshift = shiftby % PyLong_SHIFT; hishift = PyLong_SHIFT - loshift; lomask = ((digit)1 << hishift) - 1; himask = PyLong_MASK ^ lomask; z = _PyLong_New(newsize); if (z == NULL) goto rshift_error; if (Py_SIZE(a) < 0) Py_SIZE(z) = -(Py_SIZE(z)); for (i = 0, j = wordshift; i < newsize; i++, j++) { z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask; if (i+1 < newsize) z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask; } z = long_normalize(z); } rshift_error: return (PyObject *) maybe_small_long(z); } static PyObject * long_lshift(PyObject *v, PyObject *w) { /* This version due to Tim Peters */ PyLongObject *a = (PyLongObject*)v; PyLongObject *b = (PyLongObject*)w; PyLongObject *z = NULL; Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j; twodigits accum; CHECK_BINOP(a, b); shiftby = PyLong_AsSsize_t((PyObject *)b); if (shiftby == -1L && PyErr_Occurred()) return NULL; if (shiftby < 0) { PyErr_SetString(PyExc_ValueError, "negative shift count"); return NULL; } if (Py_SIZE(a) == 0) { return PyLong_FromLong(0); } /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */ wordshift = shiftby / PyLong_SHIFT; remshift = shiftby - wordshift * PyLong_SHIFT; oldsize = Py_ABS(Py_SIZE(a)); newsize = oldsize + wordshift; if (remshift) ++newsize; z = _PyLong_New(newsize); if (z == NULL) return NULL; if (Py_SIZE(a) < 0) { assert(Py_REFCNT(z) == 1); Py_SIZE(z) = -Py_SIZE(z); } for (i = 0; i < wordshift; i++) z->ob_digit[i] = 0; accum = 0; for (i = wordshift, j = 0; j < oldsize; i++, j++) { accum |= (twodigits)a->ob_digit[j] << remshift; z->ob_digit[i] = (digit)(accum & PyLong_MASK); accum >>= PyLong_SHIFT; } if (remshift) z->ob_digit[newsize-1] = (digit)accum; else assert(!accum); z = long_normalize(z); return (PyObject *) maybe_small_long(z); } /* Compute two's complement of digit vector a[0:m], writing result to z[0:m]. The digit vector a need not be normalized, but should not be entirely zero. a and z may point to the same digit vector. */ static void v_complement(digit *z, digit *a, Py_ssize_t m) { Py_ssize_t i; digit carry = 1; for (i = 0; i < m; ++i) { carry += a[i] ^ PyLong_MASK; z[i] = carry & PyLong_MASK; carry >>= PyLong_SHIFT; } assert(carry == 0); } /* Bitwise and/xor/or operations */ static PyObject * long_bitwise(PyLongObject *a, char op, /* '&', '|', '^' */ PyLongObject *b) { int nega, negb, negz; Py_ssize_t size_a, size_b, size_z, i; PyLongObject *z; /* Bitwise operations for negative numbers operate as though on a two's complement representation. So convert arguments from sign-magnitude to two's complement, and convert the result back to sign-magnitude at the end. */ /* If a is negative, replace it by its two's complement. */ size_a = Py_ABS(Py_SIZE(a)); nega = Py_SIZE(a) < 0; if (nega) { z = _PyLong_New(size_a); if (z == NULL) return NULL; v_complement(z->ob_digit, a->ob_digit, size_a); a = z; } else /* Keep reference count consistent. */ Py_INCREF(a); /* Same for b. */ size_b = Py_ABS(Py_SIZE(b)); negb = Py_SIZE(b) < 0; if (negb) { z = _PyLong_New(size_b); if (z == NULL) { Py_DECREF(a); return NULL; } v_complement(z->ob_digit, b->ob_digit, size_b); b = z; } else Py_INCREF(b); /* Swap a and b if necessary to ensure size_a >= size_b. */ if (size_a < size_b) { z = a; a = b; b = z; size_z = size_a; size_a = size_b; size_b = size_z; negz = nega; nega = negb; negb = negz; } /* JRH: The original logic here was to allocate the result value (z) as the longer of the two operands. However, there are some cases where the result is guaranteed to be shorter than that: AND of two positives, OR of two negatives: use the shorter number. AND with mixed signs: use the positive number. OR with mixed signs: use the negative number. */ switch (op) { case '^': negz = nega ^ negb; size_z = size_a; break; case '&': negz = nega & negb; size_z = negb ? size_a : size_b; break; case '|': negz = nega | negb; size_z = negb ? size_b : size_a; break; default: PyErr_BadArgument(); return NULL; } /* We allow an extra digit if z is negative, to make sure that the final two's complement of z doesn't overflow. */ z = _PyLong_New(size_z + negz); if (z == NULL) { Py_DECREF(a); Py_DECREF(b); return NULL; } /* Compute digits for overlap of a and b. */ switch(op) { case '&': for (i = 0; i < size_b; ++i) z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i]; break; case '|': for (i = 0; i < size_b; ++i) z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i]; break; case '^': for (i = 0; i < size_b; ++i) z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i]; break; default: PyErr_BadArgument(); return NULL; } /* Copy any remaining digits of a, inverting if necessary. */ if (op == '^' && negb) for (; i < size_z; ++i) z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK; else if (i < size_z) memcpy(&z->ob_digit[i], &a->ob_digit[i], (size_z-i)*sizeof(digit)); /* Complement result if negative. */ if (negz) { Py_SIZE(z) = -(Py_SIZE(z)); z->ob_digit[size_z] = PyLong_MASK; v_complement(z->ob_digit, z->ob_digit, size_z+1); } Py_DECREF(a); Py_DECREF(b); return (PyObject *)maybe_small_long(long_normalize(z)); } static PyObject * long_and(PyObject *a, PyObject *b) { PyObject *c; CHECK_BINOP(a, b); c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b); return c; } static PyObject * long_xor(PyObject *a, PyObject *b) { PyObject *c; CHECK_BINOP(a, b); c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b); return c; } static PyObject * long_or(PyObject *a, PyObject *b) { PyObject *c; CHECK_BINOP(a, b); c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b); return c; } static PyObject * long_long(PyObject *v) { if (PyLong_CheckExact(v)) Py_INCREF(v); else v = _PyLong_Copy((PyLongObject *)v); return v; } PyObject * _PyLong_GCD(PyObject *aarg, PyObject *barg) { PyLongObject *a, *b, *c = NULL, *d = NULL, *r; stwodigits x, y, q, s, t, c_carry, d_carry; stwodigits A, B, C, D, T; int nbits, k; Py_ssize_t size_a, size_b, alloc_a, alloc_b; digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end; a = (PyLongObject *)aarg; b = (PyLongObject *)barg; size_a = Py_SIZE(a); size_b = Py_SIZE(b); if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) { Py_INCREF(a); Py_INCREF(b); goto simple; } /* Initial reduction: make sure that 0 <= b <= a. */ a = (PyLongObject *)long_abs(a); if (a == NULL) return NULL; b = (PyLongObject *)long_abs(b); if (b == NULL) { Py_DECREF(a); return NULL; } if (long_compare(a, b) < 0) { r = a; a = b; b = r; } /* We now own references to a and b */ alloc_a = Py_SIZE(a); alloc_b = Py_SIZE(b); /* reduce until a fits into 2 digits */ while ((size_a = Py_SIZE(a)) > 2) { nbits = bits_in_digit(a->ob_digit[size_a-1]); /* extract top 2*PyLong_SHIFT bits of a into x, along with corresponding bits of b into y */ size_b = Py_SIZE(b); assert(size_b <= size_a); if (size_b == 0) { if (size_a < alloc_a) { r = (PyLongObject *)_PyLong_Copy(a); Py_DECREF(a); } else r = a; Py_DECREF(b); Py_XDECREF(c); Py_XDECREF(d); return (PyObject *)r; } x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) | ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) | (a->ob_digit[size_a-3] >> nbits)); y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) | (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) | (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0)); /* inner loop of Lehmer's algorithm; A, B, C, D never grow larger than PyLong_MASK during the algorithm. */ A = 1; B = 0; C = 0; D = 1; for (k=0;; k++) { if (y-C == 0) break; q = (x+(A-1))/(y-C); s = B+q*D; t = x-q*y; if (s > t) break; x = y; y = t; t = A+q*C; A = D; B = C; C = s; D = t; } if (k == 0) { /* no progress; do a Euclidean step */ if (l_divmod(a, b, NULL, &r) < 0) goto error; Py_DECREF(a); a = b; b = r; alloc_a = alloc_b; alloc_b = Py_SIZE(b); continue; } /* a, b = A*b-B*a, D*a-C*b if k is odd a, b = A*a-B*b, D*b-C*a if k is even */ if (k&1) { T = -A; A = -B; B = T; T = -C; C = -D; D = T; } if (c != NULL) Py_SIZE(c) = size_a; else if (Py_REFCNT(a) == 1) { Py_INCREF(a); c = a; } else { alloc_a = size_a; c = _PyLong_New(size_a); if (c == NULL) goto error; } if (d != NULL) Py_SIZE(d) = size_a; else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) { Py_INCREF(b); d = b; Py_SIZE(d) = size_a; } else { alloc_b = size_a; d = _PyLong_New(size_a); if (d == NULL) goto error; } a_end = a->ob_digit + size_a; b_end = b->ob_digit + size_b; /* compute new a and new b in parallel */ a_digit = a->ob_digit; b_digit = b->ob_digit; c_digit = c->ob_digit; d_digit = d->ob_digit; c_carry = 0; d_carry = 0; while (b_digit < b_end) { c_carry += (A * *a_digit) - (B * *b_digit); d_carry += (D * *b_digit++) - (C * *a_digit++); *c_digit++ = (digit)(c_carry & PyLong_MASK); *d_digit++ = (digit)(d_carry & PyLong_MASK); c_carry >>= PyLong_SHIFT; d_carry >>= PyLong_SHIFT; } while (a_digit < a_end) { c_carry += A * *a_digit; d_carry -= C * *a_digit++; *c_digit++ = (digit)(c_carry & PyLong_MASK); *d_digit++ = (digit)(d_carry & PyLong_MASK); c_carry >>= PyLong_SHIFT; d_carry >>= PyLong_SHIFT; } assert(c_carry == 0); assert(d_carry == 0); Py_INCREF(c); Py_INCREF(d); Py_DECREF(a); Py_DECREF(b); a = long_normalize(c); b = long_normalize(d); } Py_XDECREF(c); Py_XDECREF(d); simple: assert(Py_REFCNT(a) > 0); assert(Py_REFCNT(b) > 0); /* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid undefined behaviour when LONG_MAX type is smaller than 60 bits */ #if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT /* a fits into a long, so b must too */ x = PyLong_AsLong((PyObject *)a); y = PyLong_AsLong((PyObject *)b); #elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT x = PyLong_AsLongLong((PyObject *)a); y = PyLong_AsLongLong((PyObject *)b); #else # error "_PyLong_GCD" #endif x = Py_ABS(x); y = Py_ABS(y); Py_DECREF(a); Py_DECREF(b); /* usual Euclidean algorithm for longs */ while (y != 0) { t = y; y = x % y; x = t; } #if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT return PyLong_FromLong(x); #elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT return PyLong_FromLongLong(x); #else # error "_PyLong_GCD" #endif error: Py_DECREF(a); Py_DECREF(b); Py_XDECREF(c); Py_XDECREF(d); return NULL; } static PyObject * long_float(PyObject *v) { double result; result = PyLong_AsDouble(v); if (result == -1.0 && PyErr_Occurred()) return NULL; return PyFloat_FromDouble(result); } static PyObject * long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject * long_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *obase = NULL, *x = NULL; Py_ssize_t base; static char *kwlist[] = {"x", "base", 0}; if (type != &PyLong_Type) return long_subtype_new(type, args, kwds); /* Wimp out */ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist, &x, &obase)) return NULL; if (x == NULL) { if (obase != NULL) { PyErr_SetString(PyExc_TypeError, "int() missing string argument"); return NULL; } return PyLong_FromLong(0L); } if (obase == NULL) return PyNumber_Long(x); base = PyNumber_AsSsize_t(obase, NULL); if (base == -1 && PyErr_Occurred()) return NULL; if ((base != 0 && base < 2) || base > 36) { PyErr_SetString(PyExc_ValueError, "int() base must be >= 2 and <= 36, or 0"); return NULL; } if (PyUnicode_Check(x)) return PyLong_FromUnicodeObject(x, (int)base); else if (PyByteArray_Check(x) || PyBytes_Check(x)) { char *string; if (PyByteArray_Check(x)) string = PyByteArray_AS_STRING(x); else string = PyBytes_AS_STRING(x); return _PyLong_FromBytes(string, Py_SIZE(x), (int)base); } else { PyErr_SetString(PyExc_TypeError, "int() can't convert non-string with explicit base"); return NULL; } } /* Wimpy, slow approach to tp_new calls for subtypes of int: first create a regular int from whatever arguments we got, then allocate a subtype instance and initialize it from the regular int. The regular int is then thrown away. */ static PyObject * long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyLongObject *tmp, *newobj; Py_ssize_t i, n; assert(PyType_IsSubtype(type, &PyLong_Type)); tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds); if (tmp == NULL) return NULL; assert(PyLong_Check(tmp)); n = Py_SIZE(tmp); if (n < 0) n = -n; newobj = (PyLongObject *)type->tp_alloc(type, n); if (newobj == NULL) { Py_DECREF(tmp); return NULL; } assert(PyLong_Check(newobj)); Py_SIZE(newobj) = Py_SIZE(tmp); for (i = 0; i < n; i++) newobj->ob_digit[i] = tmp->ob_digit[i]; Py_DECREF(tmp); return (PyObject *)newobj; } static PyObject * long_getnewargs(PyLongObject *v) { return Py_BuildValue("(N)", _PyLong_Copy(v)); } static PyObject * long_get0(PyLongObject *v, void *context) { return PyLong_FromLong(0L); } static PyObject * long_get1(PyLongObject *v, void *context) { return PyLong_FromLong(1L); } static PyObject * long__format__(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *format_spec; _PyUnicodeWriter writer; int ret; if (!_PyArg_ParseStack(args, nargs, "U:__format__", &format_spec)) return NULL; _PyUnicodeWriter_Init(&writer); ret = _PyLong_FormatAdvancedWriter( &writer, self, format_spec, 0, PyUnicode_GET_LENGTH(format_spec)); if (ret == -1) { _PyUnicodeWriter_Dealloc(&writer); return NULL; } return _PyUnicodeWriter_Finish(&writer); } /* Return a pair (q, r) such that a = b * q + r, and abs(r) <= abs(b)/2, with equality possible only if q is even. In other words, q == a / b, rounded to the nearest integer using round-half-to-even. */ PyObject * _PyLong_DivmodNear(PyObject *a, PyObject *b) { PyLongObject *quo = NULL, *rem = NULL; PyObject *one = NULL, *twice_rem, *result, *temp; int cmp, quo_is_odd, quo_is_neg; /* Equivalent Python code: def divmod_near(a, b): q, r = divmod(a, b) # round up if either r / b > 0.5, or r / b == 0.5 and q is odd. # The expression r / b > 0.5 is equivalent to 2 * r > b if b is # positive, 2 * r < b if b negative. greater_than_half = 2*r > b if b > 0 else 2*r < b exactly_half = 2*r == b if greater_than_half or exactly_half and q % 2 == 1: q += 1 r -= b return q, r */ if (!PyLong_Check(a) || !PyLong_Check(b)) { PyErr_SetString(PyExc_TypeError, "non-integer arguments in division"); return NULL; } /* Do a and b have different signs? If so, quotient is negative. */ quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0); one = PyLong_FromLong(1L); if (one == NULL) return NULL; if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0) goto error; /* compare twice the remainder with the divisor, to see if we need to adjust the quotient and remainder */ twice_rem = long_lshift((PyObject *)rem, one); if (twice_rem == NULL) goto error; if (quo_is_neg) { temp = long_neg((PyLongObject*)twice_rem); Py_DECREF(twice_rem); twice_rem = temp; if (twice_rem == NULL) goto error; } cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b); Py_DECREF(twice_rem); quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0); if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) { /* fix up quotient */ if (quo_is_neg) temp = long_sub(quo, (PyLongObject *)one); else temp = long_add(quo, (PyLongObject *)one); Py_DECREF(quo); quo = (PyLongObject *)temp; if (quo == NULL) goto error; /* and remainder */ if (quo_is_neg) temp = long_add(rem, (PyLongObject *)b); else temp = long_sub(rem, (PyLongObject *)b); Py_DECREF(rem); rem = (PyLongObject *)temp; if (rem == NULL) goto error; } result = PyTuple_New(2); if (result == NULL) goto error; /* PyTuple_SET_ITEM steals references */ PyTuple_SET_ITEM(result, 0, (PyObject *)quo); PyTuple_SET_ITEM(result, 1, (PyObject *)rem); Py_DECREF(one); return result; error: Py_XDECREF(quo); Py_XDECREF(rem); Py_XDECREF(one); return NULL; } static PyObject * long_round(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *o_ndigits=NULL, *temp, *result, *ndigits; /* To round an integer m to the nearest 10**n (n positive), we make use of * the divmod_near operation, defined by: * * divmod_near(a, b) = (q, r) * * where q is the nearest integer to the quotient a / b (the * nearest even integer in the case of a tie) and r == a - q * b. * Hence q * b = a - r is the nearest multiple of b to a, * preferring even multiples in the case of a tie. * * So the nearest multiple of 10**n to m is: * * m - divmod_near(m, 10**n)[1]. */ if (!_PyArg_ParseStack(args, nargs, "|O", &o_ndigits)) return NULL; if (o_ndigits == NULL) return long_long(self); ndigits = PyNumber_Index(o_ndigits); if (ndigits == NULL) return NULL; /* if ndigits >= 0 then no rounding is necessary; return self unchanged */ if (Py_SIZE(ndigits) >= 0) { Py_DECREF(ndigits); return long_long(self); } /* result = self - divmod_near(self, 10 ** -ndigits)[1] */ temp = long_neg((PyLongObject*)ndigits); Py_DECREF(ndigits); ndigits = temp; if (ndigits == NULL) return NULL; result = PyLong_FromLong(10L); if (result == NULL) { Py_DECREF(ndigits); return NULL; } temp = long_pow(result, ndigits, Py_None); Py_DECREF(ndigits); Py_DECREF(result); result = temp; if (result == NULL) return NULL; temp = _PyLong_DivmodNear(self, result); Py_DECREF(result); result = temp; if (result == NULL) return NULL; temp = long_sub((PyLongObject *)self, (PyLongObject *)PyTuple_GET_ITEM(result, 1)); Py_DECREF(result); result = temp; return result; } static PyObject * long_sizeof(PyLongObject *v) { Py_ssize_t res; res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(v))*sizeof(digit); return PyLong_FromSsize_t(res); } static PyObject * long_bit_length(PyLongObject *v) { PyLongObject *result, *x, *y; Py_ssize_t ndigits, msd_bits; assert(v != NULL); assert(PyLong_Check(v)); ndigits = Py_ABS(Py_SIZE(v)); if (ndigits == 0) return PyLong_FromLong(0); /* [jart] faster bit scanning */ msd_bits = bits_in_digit(v->ob_digit[ndigits-1]); if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT) return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits); /* expression above may overflow; use Python integers instead */ result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1); if (result == NULL) return NULL; x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT); if (x == NULL) goto error; y = (PyLongObject *)long_mul(result, x); Py_DECREF(x); if (y == NULL) goto error; Py_DECREF(result); result = y; x = (PyLongObject *)PyLong_FromLong((long)msd_bits); if (x == NULL) goto error; y = (PyLongObject *)long_add(result, x); Py_DECREF(x); if (y == NULL) goto error; Py_DECREF(result); result = y; return (PyObject *)result; error: Py_DECREF(result); return NULL; } PyDoc_STRVAR(long_bit_length_doc, "int.bit_length() -> int\n\ \n\ Number of bits necessary to represent self in binary.\n\ >>> bin(37)\n\ '0b100101'\n\ >>> (37).bit_length()\n\ 6"); /* [jart] the nsa instruction */ static PyObject * long_bit_count(PyLongObject *v) { Py_ssize_t digs; assert(v != NULL); assert(PyLong_Check(v)); digs = Py_ABS(Py_SIZE(v)); if (digs > PY_SSIZE_T_MAX/PyLong_SHIFT) goto Overflow; return PyLong_FromSize_t(_countbits(v->ob_digit, digs * sizeof(digit))); Overflow: PyErr_SetString(PyExc_OverflowError, "size_t too small"); return NULL; } PyDoc_STRVAR(long_bit_count_doc, "int.bit_count() -> int\n\ \n\ Population count of integer.\n\ >>> bin(37)\n\ '0b100101'\n\ >>> (37).bit_count()\n\ 3"); #if 0 static PyObject * long_is_finite(PyObject *v) { Py_RETURN_TRUE; } #endif static PyObject * long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds) { PyObject *byteorder_str; PyObject *is_signed_obj = NULL; Py_ssize_t length; int little_endian; int is_signed; PyObject *bytes; static char *kwlist[] = {"length", "byteorder", "signed", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist, &length, &byteorder_str, &is_signed_obj)) return NULL; if (args != NULL && Py_SIZE(args) > 2) { PyErr_SetString(PyExc_TypeError, "'signed' is a keyword-only argument"); return NULL; } if (_PyUnicode_EqualToASCIIString(byteorder_str, "little")) little_endian = 1; else if (_PyUnicode_EqualToASCIIString(byteorder_str, "big")) little_endian = 0; else { PyErr_SetString(PyExc_ValueError, "byteorder must be either 'little' or 'big'"); return NULL; } if (is_signed_obj != NULL) { int cmp = PyObject_IsTrue(is_signed_obj); if (cmp < 0) return NULL; is_signed = cmp ? 1 : 0; } else { /* If the signed argument was omitted, use False as the default. */ is_signed = 0; } if (length < 0) { PyErr_SetString(PyExc_ValueError, "length argument must be non-negative"); return NULL; } bytes = PyBytes_FromStringAndSize(NULL, length); if (bytes == NULL) return NULL; if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes), length, little_endian, is_signed) < 0) { Py_DECREF(bytes); return NULL; } return bytes; } PyDoc_STRVAR(long_to_bytes_doc, "int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\ \n\ Return an array of bytes representing an integer.\n\ \n\ The integer is represented using length bytes. An OverflowError is\n\ raised if the integer is not representable with the given number of\n\ bytes.\n\ \n\ The byteorder argument determines the byte order used to represent the\n\ integer. If byteorder is 'big', the most significant byte is at the\n\ beginning of the byte array. If byteorder is 'little', the most\n\ significant byte is at the end of the byte array. To request the native\n\ byte order of the host system, use `sys.byteorder' as the byte order value.\n\ \n\ The signed keyword-only argument determines whether two's complement is\n\ used to represent the integer. If signed is False and a negative integer\n\ is given, an OverflowError is raised."); static PyObject * long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *byteorder_str; PyObject *is_signed_obj = NULL; int little_endian; int is_signed; PyObject *obj; PyObject *bytes; PyObject *long_obj; static char *kwlist[] = {"bytes", "byteorder", "signed", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist, &obj, &byteorder_str, &is_signed_obj)) return NULL; if (args != NULL && Py_SIZE(args) > 2) { PyErr_SetString(PyExc_TypeError, "'signed' is a keyword-only argument"); return NULL; } if (_PyUnicode_EqualToASCIIString(byteorder_str, "little")) little_endian = 1; else if (_PyUnicode_EqualToASCIIString(byteorder_str, "big")) little_endian = 0; else { PyErr_SetString(PyExc_ValueError, "byteorder must be either 'little' or 'big'"); return NULL; } if (is_signed_obj != NULL) { int cmp = PyObject_IsTrue(is_signed_obj); if (cmp < 0) return NULL; is_signed = cmp ? 1 : 0; } else { /* If the signed argument was omitted, use False as the default. */ is_signed = 0; } bytes = PyObject_Bytes(obj); if (bytes == NULL) return NULL; long_obj = _PyLong_FromByteArray( (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes), little_endian, is_signed); Py_DECREF(bytes); if (long_obj != NULL && type != &PyLong_Type) { Py_SETREF(long_obj, PyObject_CallFunctionObjArgs((PyObject *)type, long_obj, NULL)); } return long_obj; } PyDoc_STRVAR(long_from_bytes_doc, "int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\ \n\ Return the integer represented by the given array of bytes.\n\ \n\ The bytes argument must be a bytes-like object (e.g. bytes or bytearray).\n\ \n\ The byteorder argument determines the byte order used to represent the\n\ integer. If byteorder is 'big', the most significant byte is at the\n\ beginning of the byte array. If byteorder is 'little', the most\n\ significant byte is at the end of the byte array. To request the native\n\ byte order of the host system, use `sys.byteorder' as the byte order value.\n\ \n\ The signed keyword-only argument indicates whether two's complement is\n\ used to represent the integer."); static PyMethodDef long_methods[] = { {"conjugate", (PyCFunction)long_long, METH_NOARGS, "Returns self, the complex conjugate of any int."}, {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS, long_bit_length_doc}, {"bit_count", (PyCFunction)long_bit_count, METH_NOARGS, long_bit_count_doc}, #if 0 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS, "Returns always True."}, #endif {"to_bytes", (PyCFunction)long_to_bytes, METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc}, {"from_bytes", (PyCFunction)long_from_bytes, METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc}, {"__trunc__", (PyCFunction)long_long, METH_NOARGS, "Truncating an Integral returns itself."}, {"__floor__", (PyCFunction)long_long, METH_NOARGS, "Flooring an Integral returns itself."}, {"__ceil__", (PyCFunction)long_long, METH_NOARGS, "Ceiling of an Integral returns itself."}, {"__round__", (PyCFunction)long_round, METH_FASTCALL, "Rounding an Integral returns itself.\n" "Rounding with an ndigits argument also returns an integer."}, {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS}, {"__format__", (PyCFunction)long__format__, METH_FASTCALL}, {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS, "Returns size in memory, in bytes"}, {NULL, NULL} /* sentinel */ }; static PyGetSetDef long_getset[] = { {"real", (getter)long_long, (setter)NULL, "the real part of a complex number", NULL}, {"imag", (getter)long_get0, (setter)NULL, "the imaginary part of a complex number", NULL}, {"numerator", (getter)long_long, (setter)NULL, "the numerator of a rational number in lowest terms", NULL}, {"denominator", (getter)long_get1, (setter)NULL, "the denominator of a rational number in lowest terms", NULL}, {NULL} /* Sentinel */ }; PyDoc_STRVAR(long_doc, "int(x=0) -> integer\n\ int(x, base=10) -> integer\n\ \n\ Convert a number or string to an integer, or return 0 if no arguments\n\ are given. If x is a number, return x.__int__(). For floating point\n\ numbers, this truncates towards zero.\n\ \n\ If x is not a number or if base is given, then x must be a string,\n\ bytes, or bytearray instance representing an integer literal in the\n\ given base. The literal can be preceded by '+' or '-' and be surrounded\n\ by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\ Base 0 means to interpret the base from the string as an integer literal.\n\ >>> int('0b100', base=0)\n\ 4"); static PyNumberMethods long_as_number = { (binaryfunc)long_add, /*nb_add*/ (binaryfunc)long_sub, /*nb_subtract*/ (binaryfunc)long_mul, /*nb_multiply*/ long_mod, /*nb_remainder*/ long_divmod, /*nb_divmod*/ long_pow, /*nb_power*/ (unaryfunc)long_neg, /*nb_negative*/ (unaryfunc)long_long, /*tp_positive*/ (unaryfunc)long_abs, /*tp_absolute*/ (inquiry)long_bool, /*tp_bool*/ (unaryfunc)long_invert, /*nb_invert*/ long_lshift, /*nb_lshift*/ (binaryfunc)long_rshift, /*nb_rshift*/ long_and, /*nb_and*/ long_xor, /*nb_xor*/ long_or, /*nb_or*/ long_long, /*nb_int*/ 0, /*nb_reserved*/ long_float, /*nb_float*/ 0, /* nb_inplace_add */ 0, /* nb_inplace_subtract */ 0, /* nb_inplace_multiply */ 0, /* nb_inplace_remainder */ 0, /* nb_inplace_power */ 0, /* nb_inplace_lshift */ 0, /* nb_inplace_rshift */ 0, /* nb_inplace_and */ 0, /* nb_inplace_xor */ 0, /* nb_inplace_or */ long_div, /* nb_floor_divide */ long_true_divide, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ long_long, /* nb_index */ }; PyTypeObject PyLong_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "int", /* tp_name */ offsetof(PyLongObject, ob_digit), /* tp_basicsize */ sizeof(digit), /* tp_itemsize */ long_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ long_to_decimal_string, /* tp_repr */ &long_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)long_hash, /* tp_hash */ 0, /* tp_call */ long_to_decimal_string, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */ long_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ long_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ long_methods, /* tp_methods */ 0, /* tp_members */ long_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ long_new, /* tp_new */ PyObject_Del, /* tp_free */ }; static PyTypeObject Int_InfoType; PyDoc_STRVAR(int_info__doc__, "sys.int_info\n\ \n\ A struct sequence that holds information about Python's\n\ internal representation of integers. The attributes are read only."); static PyStructSequence_Field int_info_fields[] = { {"bits_per_digit", PyDoc_STR("size of a digit in bits")}, {"sizeof_digit", PyDoc_STR("size in bytes of the C type used to represent a digit")}, {NULL, NULL} }; static PyStructSequence_Desc int_info_desc = { "sys.int_info", /* name */ int_info__doc__, /* doc */ int_info_fields, /* fields */ 2 /* number of fields */ }; PyObject * PyLong_GetInfo(void) { PyObject* int_info; int field = 0; int_info = PyStructSequence_New(&Int_InfoType); if (int_info == NULL) return NULL; PyStructSequence_SET_ITEM(int_info, field++, PyLong_FromLong(PyLong_SHIFT)); PyStructSequence_SET_ITEM(int_info, field++, PyLong_FromLong(sizeof(digit))); if (PyErr_Occurred()) { Py_CLEAR(int_info); return NULL; } return int_info; } int _PyLong_Init(void) { #if NSMALLNEGINTS + NSMALLPOSINTS > 0 int ival, size; PyLongObject *v = small_ints; for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) { size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1); if (Py_TYPE(v) == &PyLong_Type) { /* The element is already initialized, most likely * the Python interpreter was initialized before. */ Py_ssize_t refcnt; PyObject* op = (PyObject*)v; refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op); _Py_NewReference(op); /* _Py_NewReference sets the ref count to 1 but * the ref count might be larger. Set the refcnt * to the original refcnt + 1 */ Py_REFCNT(op) = refcnt + 1; assert(Py_SIZE(op) == size); assert(v->ob_digit[0] == (digit)abs(ival)); } else { (void)PyObject_INIT(v, &PyLong_Type); } Py_SIZE(v) = size; v->ob_digit[0] = (digit)abs(ival); } #endif /* initialize int_info */ if (Int_InfoType.tp_name == NULL) { if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0) return 0; } return 1; } void PyLong_Fini(void) { /* Integers are currently statically allocated. Py_DECREF is not needed, but Python must forget about the reference or multiple reinitializations will fail. */ #if NSMALLNEGINTS + NSMALLPOSINTS > 0 int i; PyLongObject *v = small_ints; for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) { _Py_DEC_REFTOTAL; _Py_ForgetReference((PyObject*)v); } #endif }
174,010
5,590
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/setobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ /* set object implementation Written and maintained by Raymond D. Hettinger <[email protected]> Derived from Lib/sets.py and Objects/dictobject.c. The basic lookup function used by all operations. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4. The initial probe index is computed as hash mod the table size. Subsequent probe indices are computed as explained in Objects/dictobject.c. To improve cache locality, each probe inspects a series of consecutive nearby entries before moving on to probes elsewhere in memory. This leaves us with a hybrid of linear probing and open addressing. The linear probing reduces the cost of hash collisions because consecutive memory accesses tend to be much cheaper than scattered probes. After LINEAR_PROBES steps, we then use open addressing with the upper bits from the hash value. This helps break-up long chains of collisions. All arithmetic on hash should ignore overflow. Unlike the dictionary implementation, the lookkey function can return NULL if the rich comparison returns an error. */ /* Object used as dummy key to fill deleted entries */ static PyObject _dummy_struct; #define dummy (&_dummy_struct) /* ======================================================================== */ /* ======= Begin logic for probing the hash table ========================= */ /* Set this to zero to turn-off linear probing */ #ifndef LINEAR_PROBES #define LINEAR_PROBES 9 #endif /* This must be >= 1 */ #define PERTURB_SHIFT 5 static setentry * set_lookkey(PySetObject *so, PyObject *key, Py_hash_t hash) { setentry *table; setentry *entry; size_t perturb; size_t mask = so->mask; size_t i = (size_t)hash & mask; /* Unsigned for defined overflow behavior */ size_t j; int cmp; entry = &so->table[i]; if (entry->key == NULL) return entry; perturb = hash; while (1) { if (entry->hash == hash) { PyObject *startkey = entry->key; /* startkey cannot be a dummy because the dummy hash field is -1 */ assert(startkey != dummy); if (startkey == key) return entry; if (PyUnicode_CheckExact(startkey) && PyUnicode_CheckExact(key) && _PyUnicode_EQ(startkey, key)) return entry; table = so->table; Py_INCREF(startkey); cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); Py_DECREF(startkey); if (cmp < 0) /* unlikely */ return NULL; if (table != so->table || entry->key != startkey) /* unlikely */ return set_lookkey(so, key, hash); if (cmp > 0) /* likely */ return entry; mask = so->mask; /* help avoid a register spill */ } if (i + LINEAR_PROBES <= mask) { for (j = 0 ; j < LINEAR_PROBES ; j++) { entry++; if (entry->hash == 0 && entry->key == NULL) return entry; if (entry->hash == hash) { PyObject *startkey = entry->key; assert(startkey != dummy); if (startkey == key) return entry; if (PyUnicode_CheckExact(startkey) && PyUnicode_CheckExact(key) && _PyUnicode_EQ(startkey, key)) return entry; table = so->table; Py_INCREF(startkey); cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); Py_DECREF(startkey); if (cmp < 0) return NULL; if (table != so->table || entry->key != startkey) return set_lookkey(so, key, hash); if (cmp > 0) return entry; mask = so->mask; } } } perturb >>= PERTURB_SHIFT; i = (i * 5 + 1 + perturb) & mask; entry = &so->table[i]; if (entry->key == NULL) return entry; } } static int set_table_resize(PySetObject *, Py_ssize_t); static int set_add_entry(PySetObject *so, PyObject *key, Py_hash_t hash) { setentry *table; setentry *freeslot; setentry *entry; size_t perturb; size_t mask; size_t i; /* Unsigned for defined overflow behavior */ size_t j; int cmp; /* Pre-increment is necessary to prevent arbitrary code in the rich comparison from deallocating the key just before the insertion. */ Py_INCREF(key); restart: mask = so->mask; i = (size_t)hash & mask; entry = &so->table[i]; if (entry->key == NULL) goto found_unused; freeslot = NULL; perturb = hash; while (1) { if (entry->hash == hash) { PyObject *startkey = entry->key; /* startkey cannot be a dummy because the dummy hash field is -1 */ assert(startkey != dummy); if (startkey == key) goto found_active; if (PyUnicode_CheckExact(startkey) && PyUnicode_CheckExact(key) && _PyUnicode_EQ(startkey, key)) goto found_active; table = so->table; Py_INCREF(startkey); cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); Py_DECREF(startkey); if (cmp > 0) /* likely */ goto found_active; if (cmp < 0) goto comparison_error; /* Continuing the search from the current entry only makes sense if the table and entry are unchanged; otherwise, we have to restart from the beginning */ if (table != so->table || entry->key != startkey) goto restart; mask = so->mask; /* help avoid a register spill */ } else if (entry->hash == -1 && freeslot == NULL) freeslot = entry; if (i + LINEAR_PROBES <= mask) { for (j = 0 ; j < LINEAR_PROBES ; j++) { entry++; if (entry->hash == 0 && entry->key == NULL) goto found_unused_or_dummy; if (entry->hash == hash) { PyObject *startkey = entry->key; assert(startkey != dummy); if (startkey == key) goto found_active; if (PyUnicode_CheckExact(startkey) && PyUnicode_CheckExact(key) && _PyUnicode_EQ(startkey, key)) goto found_active; table = so->table; Py_INCREF(startkey); cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); Py_DECREF(startkey); if (cmp > 0) goto found_active; if (cmp < 0) goto comparison_error; if (table != so->table || entry->key != startkey) goto restart; mask = so->mask; } else if (entry->hash == -1 && freeslot == NULL) freeslot = entry; } } perturb >>= PERTURB_SHIFT; i = (i * 5 + 1 + perturb) & mask; entry = &so->table[i]; if (entry->key == NULL) goto found_unused_or_dummy; } found_unused_or_dummy: if (freeslot == NULL) goto found_unused; so->used++; freeslot->key = key; freeslot->hash = hash; return 0; found_unused: so->fill++; so->used++; entry->key = key; entry->hash = hash; if ((size_t)so->fill*3 < mask*2) return 0; return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); found_active: Py_DECREF(key); return 0; comparison_error: Py_DECREF(key); return -1; } /* Internal routine used by set_table_resize() to insert an item which is known to be absent from the set. This routine also assumes that the set contains no deleted entries. Besides the performance benefit, there is also safety benefit since using set_add_entry() risks making a callback in the middle of a set_table_resize(), see issue 1456209. The caller is responsible for updating the key's reference count and the setobject's fill and used fields. */ static void set_insert_clean(setentry *table, size_t mask, PyObject *key, Py_hash_t hash) { setentry *entry; size_t perturb = hash; size_t i = (size_t)hash & mask; size_t j; while (1) { entry = &table[i]; if (entry->key == NULL) goto found_null; if (i + LINEAR_PROBES <= mask) { for (j = 0; j < LINEAR_PROBES; j++) { entry++; if (entry->key == NULL) goto found_null; } } perturb >>= PERTURB_SHIFT; i = (i * 5 + 1 + perturb) & mask; } found_null: entry->key = key; entry->hash = hash; } /* ======== End logic for probing the hash table ========================== */ /* ======================================================================== */ /* Restructure the table by allocating a new table and reinserting all keys again. When entries have been deleted, the new table may actually be smaller than the old one. */ static int set_table_resize(PySetObject *so, Py_ssize_t minused) { setentry *oldtable, *newtable, *entry; Py_ssize_t oldfill = so->fill; Py_ssize_t oldused = so->used; Py_ssize_t oldmask = so->mask; size_t newmask; int is_oldtable_malloced; setentry small_copy[PySet_MINSIZE]; assert(minused >= 0); /* Find the smallest table size > minused. */ /* XXX speed-up with intrinsics */ size_t newsize = PySet_MINSIZE; while (newsize <= (size_t)minused) { newsize <<= 1; // The largest possible value is PY_SSIZE_T_MAX + 1. } /* Get space for a new table. */ oldtable = so->table; assert(oldtable != NULL); is_oldtable_malloced = oldtable != so->smalltable; if (newsize == PySet_MINSIZE) { /* A large table is shrinking, or we can't get any smaller. */ newtable = so->smalltable; if (newtable == oldtable) { if (so->fill == so->used) { /* No dummies, so no point doing anything. */ return 0; } /* We're not going to resize it, but rebuild the table anyway to purge old dummy entries. Subtle: This is *necessary* if fill==size, as set_lookkey needs at least one virgin slot to terminate failing searches. If fill < size, it's merely desirable, as dummies slow searches. */ assert(so->fill > so->used); memcpy(small_copy, oldtable, sizeof(small_copy)); oldtable = small_copy; } } else { newtable = PyMem_NEW(setentry, newsize); if (newtable == NULL) { PyErr_NoMemory(); return -1; } } /* Make the set empty, using the new table. */ assert(newtable != oldtable); bzero(newtable, sizeof(setentry) * newsize); so->fill = oldused; so->used = oldused; so->mask = newsize - 1; so->table = newtable; /* Copy the data over; this is refcount-neutral for active entries; dummy entries aren't copied over, of course */ newmask = (size_t)so->mask; if (oldfill == oldused) { for (entry = oldtable; entry <= oldtable + oldmask; entry++) { if (entry->key != NULL) { set_insert_clean(newtable, newmask, entry->key, entry->hash); } } } else { for (entry = oldtable; entry <= oldtable + oldmask; entry++) { if (entry->key != NULL && entry->key != dummy) { set_insert_clean(newtable, newmask, entry->key, entry->hash); } } } if (is_oldtable_malloced) PyMem_DEL(oldtable); return 0; } static int set_contains_entry(PySetObject *so, PyObject *key, Py_hash_t hash) { setentry *entry; entry = set_lookkey(so, key, hash); if (entry != NULL) return entry->key != NULL; return -1; } #define DISCARD_NOTFOUND 0 #define DISCARD_FOUND 1 static int set_discard_entry(PySetObject *so, PyObject *key, Py_hash_t hash) { setentry *entry; PyObject *old_key; entry = set_lookkey(so, key, hash); if (entry == NULL) return -1; if (entry->key == NULL) return DISCARD_NOTFOUND; old_key = entry->key; entry->key = dummy; entry->hash = -1; so->used--; Py_DECREF(old_key); return DISCARD_FOUND; } static int set_add_key(PySetObject *so, PyObject *key) { Py_hash_t hash; if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; } return set_add_entry(so, key, hash); } static int set_contains_key(PySetObject *so, PyObject *key) { Py_hash_t hash; if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; } return set_contains_entry(so, key, hash); } static int set_discard_key(PySetObject *so, PyObject *key) { Py_hash_t hash; if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; } return set_discard_entry(so, key, hash); } static void set_empty_to_minsize(PySetObject *so) { bzero(so->smalltable, sizeof(so->smalltable)); so->fill = 0; so->used = 0; so->mask = PySet_MINSIZE - 1; so->table = so->smalltable; so->hash = -1; } static int set_clear_internal(PySetObject *so) { setentry *entry; setentry *table = so->table; Py_ssize_t fill = so->fill; Py_ssize_t used = so->used; int table_is_malloced = table != so->smalltable; setentry small_copy[PySet_MINSIZE]; assert (PyAnySet_Check(so)); assert(table != NULL); /* This is delicate. During the process of clearing the set, * decrefs can cause the set to mutate. To avoid fatal confusion * (voice of experience), we have to make the set empty before * clearing the slots, and never refer to anything via so->ref while * clearing. */ if (table_is_malloced) set_empty_to_minsize(so); else if (fill > 0) { /* It's a small table with something that needs to be cleared. * Afraid the only safe way is to copy the set entries into * another small table first. */ memcpy(small_copy, table, sizeof(small_copy)); table = small_copy; set_empty_to_minsize(so); } /* else it's a small table that's already empty */ /* Now we can finally clear things. If C had refcounts, we could * assert that the refcount on table is 1 now, i.e. that this function * has unique access to it, so decref side-effects can't alter it. */ for (entry = table; used > 0; entry++) { if (entry->key && entry->key != dummy) { used--; Py_DECREF(entry->key); } } if (table_is_malloced) PyMem_DEL(table); return 0; } /* * Iterate over a set table. Use like so: * * Py_ssize_t pos; * setentry *entry; * pos = 0; # important! pos should not otherwise be changed by you * while (set_next(yourset, &pos, &entry)) { * Refer to borrowed reference in entry->key. * } * * CAUTION: In general, it isn't safe to use set_next in a loop that * mutates the table. */ static int set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr) { Py_ssize_t i; Py_ssize_t mask; setentry *entry; assert (PyAnySet_Check(so)); i = *pos_ptr; assert(i >= 0); mask = so->mask; entry = &so->table[i]; while (i <= mask && (entry->key == NULL || entry->key == dummy)) { i++; entry++; } *pos_ptr = i+1; if (i > mask) return 0; assert(entry != NULL); *entry_ptr = entry; return 1; } static void set_dealloc(PySetObject *so) { setentry *entry; Py_ssize_t used = so->used; /* bpo-31095: UnTrack is needed before calling any callbacks */ PyObject_GC_UnTrack(so); Py_TRASHCAN_SAFE_BEGIN(so) if (so->weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *) so); for (entry = so->table; used > 0; entry++) { if (entry->key && entry->key != dummy) { used--; Py_DECREF(entry->key); } } if (so->table != so->smalltable) PyMem_DEL(so->table); Py_TYPE(so)->tp_free(so); Py_TRASHCAN_SAFE_END(so) } static PyObject * set_repr(PySetObject *so) { PyObject *result=NULL, *keys, *listrepr, *tmp; int status = Py_ReprEnter((PyObject*)so); if (status != 0) { if (status < 0) return NULL; return PyUnicode_FromFormat("%s(...)", Py_TYPE(so)->tp_name); } /* shortcut for the empty set */ if (!so->used) { Py_ReprLeave((PyObject*)so); return PyUnicode_FromFormat("%s()", Py_TYPE(so)->tp_name); } keys = PySequence_List((PyObject *)so); if (keys == NULL) goto done; /* repr(keys)[1:-1] */ listrepr = PyObject_Repr(keys); Py_DECREF(keys); if (listrepr == NULL) goto done; tmp = PyUnicode_Substring(listrepr, 1, PyUnicode_GET_LENGTH(listrepr)-1); Py_DECREF(listrepr); if (tmp == NULL) goto done; listrepr = tmp; if (Py_TYPE(so) != &PySet_Type) result = PyUnicode_FromFormat("%s({%U})", Py_TYPE(so)->tp_name, listrepr); else result = PyUnicode_FromFormat("{%U}", listrepr); Py_DECREF(listrepr); done: Py_ReprLeave((PyObject*)so); return result; } static Py_ssize_t set_len(PyObject *so) { return ((PySetObject *)so)->used; } static int set_merge(PySetObject *so, PyObject *otherset) { PySetObject *other; PyObject *key; Py_ssize_t i; setentry *so_entry; setentry *other_entry; assert (PyAnySet_Check(so)); assert (PyAnySet_Check(otherset)); other = (PySetObject*)otherset; if (other == so || other->used == 0) /* a.update(a) or a.update(set()); nothing to do */ return 0; /* Do one big resize at the start, rather than * incrementally resizing as we insert new keys. Expect * that there will be no (or few) overlapping keys. */ if ((so->fill + other->used)*3 >= so->mask*2) { if (set_table_resize(so, (so->used + other->used)*2) != 0) return -1; } so_entry = so->table; other_entry = other->table; /* If our table is empty, and both tables have the same size, and there are no dummies to eliminate, then just copy the pointers. */ if (so->fill == 0 && so->mask == other->mask && other->fill == other->used) { for (i = 0; i <= other->mask; i++, so_entry++, other_entry++) { key = other_entry->key; if (key != NULL) { assert(so_entry->key == NULL); Py_INCREF(key); so_entry->key = key; so_entry->hash = other_entry->hash; } } so->fill = other->fill; so->used = other->used; return 0; } /* If our table is empty, we can use set_insert_clean() */ if (so->fill == 0) { setentry *newtable = so->table; size_t newmask = (size_t)so->mask; so->fill = other->used; so->used = other->used; for (i = other->mask + 1; i > 0 ; i--, other_entry++) { key = other_entry->key; if (key != NULL && key != dummy) { Py_INCREF(key); set_insert_clean(newtable, newmask, key, other_entry->hash); } } return 0; } /* We can't assure there are no duplicates, so do normal insertions */ for (i = 0; i <= other->mask; i++) { other_entry = &other->table[i]; key = other_entry->key; if (key != NULL && key != dummy) { if (set_add_entry(so, key, other_entry->hash)) return -1; } } return 0; } static PyObject * set_pop(PySetObject *so) { /* Make sure the search finger is in bounds */ Py_ssize_t i = so->finger & so->mask; setentry *entry; PyObject *key; assert (PyAnySet_Check(so)); if (so->used == 0) { PyErr_SetString(PyExc_KeyError, "pop from an empty set"); return NULL; } while ((entry = &so->table[i])->key == NULL || entry->key==dummy) { i++; if (i > so->mask) i = 0; } key = entry->key; entry->key = dummy; entry->hash = -1; so->used--; so->finger = i + 1; /* next place to start */ return key; } PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.\n\ Raises KeyError if the set is empty."); static int set_traverse(PySetObject *so, visitproc visit, void *arg) { Py_ssize_t pos = 0; setentry *entry; while (set_next(so, &pos, &entry)) Py_VISIT(entry->key); return 0; } /* Work to increase the bit dispersion for closely spaced hash values. This is important because some use cases have many combinations of a small number of elements with nearby hashes so that many distinct combinations collapse to only a handful of distinct hash values. */ static Py_uhash_t _shuffle_bits(Py_uhash_t h) { return ((h ^ 89869747UL) ^ (h << 16)) * 3644798167UL; } /* Most of the constants in this hash algorithm are randomly chosen large primes with "interesting bit patterns" and that passed tests for good collision statistics on a variety of problematic datasets including powersets and graph structures (such as David Eppstein's graph recipes in Lib/test/test_set.py) */ static Py_hash_t frozenset_hash(PyObject *self) { PySetObject *so = (PySetObject *)self; Py_uhash_t hash = 0; setentry *entry; if (so->hash != -1) return so->hash; /* Xor-in shuffled bits from every entry's hash field because xor is commutative and a frozenset hash should be independent of order. For speed, include null entries and dummy entries and then subtract out their effect afterwards so that the final hash depends only on active entries. This allows the code to be vectorized by the compiler and it saves the unpredictable branches that would arise when trying to exclude null and dummy entries on every iteration. */ for (entry = so->table; entry <= &so->table[so->mask]; entry++) hash ^= _shuffle_bits(entry->hash); /* Remove the effect of an odd number of NULL entries */ if ((so->mask + 1 - so->fill) & 1) hash ^= _shuffle_bits(0); /* Remove the effect of an odd number of dummy entries */ if ((so->fill - so->used) & 1) hash ^= _shuffle_bits(-1); /* Factor in the number of active entries */ hash ^= ((Py_uhash_t)PySet_GET_SIZE(self) + 1) * 1927868237UL; /* Disperse patterns arising in nested frozensets */ hash ^= (hash >> 11) ^ (hash >> 25); hash = hash * 69069U + 907133923UL; /* -1 is reserved as an error code */ if (hash == (Py_uhash_t)-1) hash = 590923713UL; so->hash = hash; return hash; } /***** Set iterator type ***********************************************/ typedef struct { PyObject_HEAD PySetObject *si_set; /* Set to NULL when iterator is exhausted */ Py_ssize_t si_used; Py_ssize_t si_pos; Py_ssize_t len; } setiterobject; static void setiter_dealloc(setiterobject *si) { /* bpo-31095: UnTrack is needed before calling any callbacks */ _PyObject_GC_UNTRACK(si); Py_XDECREF(si->si_set); PyObject_GC_Del(si); } static int setiter_traverse(setiterobject *si, visitproc visit, void *arg) { Py_VISIT(si->si_set); return 0; } static PyObject * setiter_len(setiterobject *si) { Py_ssize_t len = 0; if (si->si_set != NULL && si->si_used == si->si_set->used) len = si->len; return PyLong_FromSsize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject *setiter_iternext(setiterobject *si); static PyObject * setiter_reduce(setiterobject *si) { PyObject *list; setiterobject tmp; list = PyList_New(0); if (!list) return NULL; /* copy the iterator state */ tmp = *si; Py_XINCREF(tmp.si_set); /* iterate the temporary into a list */ for(;;) { PyObject *element = setiter_iternext(&tmp); if (element) { if (PyList_Append(list, element)) { Py_DECREF(element); Py_DECREF(list); Py_XDECREF(tmp.si_set); return NULL; } Py_DECREF(element); } else break; } Py_XDECREF(tmp.si_set); /* check for error */ if (tmp.si_set != NULL) { /* we have an error */ Py_DECREF(list); return NULL; } return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef setiter_methods[] = { {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)setiter_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; static PyObject *setiter_iternext(setiterobject *si) { PyObject *key; Py_ssize_t i, mask; setentry *entry; PySetObject *so = si->si_set; if (so == NULL) return NULL; assert (PyAnySet_Check(so)); if (si->si_used != so->used) { PyErr_SetString(PyExc_RuntimeError, "Set changed size during iteration"); si->si_used = -1; /* Make this state sticky */ return NULL; } i = si->si_pos; assert(i>=0); entry = so->table; mask = so->mask; while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy)) i++; si->si_pos = i+1; if (i > mask) goto fail; si->len--; key = entry[i].key; Py_INCREF(key); return key; fail: si->si_set = NULL; Py_DECREF(so); return NULL; } PyTypeObject PySetIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "set_iterator", /* tp_name */ sizeof(setiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)setiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)setiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)setiter_iternext, /* tp_iternext */ setiter_methods, /* tp_methods */ 0, }; static PyObject * set_iter(PySetObject *so) { setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type); if (si == NULL) return NULL; Py_INCREF(so); si->si_set = so; si->si_used = so->used; si->si_pos = 0; si->len = so->used; _PyObject_GC_TRACK(si); return (PyObject *)si; } static int set_update_internal(PySetObject *so, PyObject *other) { PyObject *key, *it; if (PyAnySet_Check(other)) return set_merge(so, other); if (PyDict_CheckExact(other)) { PyObject *value; Py_ssize_t pos = 0; Py_hash_t hash; Py_ssize_t dictsize = PyDict_Size(other); /* Do one big resize at the start, rather than * incrementally resizing as we insert new keys. Expect * that there will be no (or few) overlapping keys. */ if (dictsize < 0) return -1; if ((so->fill + dictsize)*3 >= so->mask*2) { if (set_table_resize(so, (so->used + dictsize)*2) != 0) return -1; } while (_PyDict_Next(other, &pos, &key, &value, &hash)) { if (set_add_entry(so, key, hash)) return -1; } return 0; } it = PyObject_GetIter(other); if (it == NULL) return -1; while ((key = PyIter_Next(it)) != NULL) { if (set_add_key(so, key)) { Py_DECREF(it); Py_DECREF(key); return -1; } Py_DECREF(key); } Py_DECREF(it); if (PyErr_Occurred()) return -1; return 0; } static PyObject * set_update(PySetObject *so, PyObject *args) { Py_ssize_t i; for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) { PyObject *other = PyTuple_GET_ITEM(args, i); if (set_update_internal(so, other)) return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(update_doc, "Update a set with the union of itself and others."); /* XXX Todo: If aligned memory allocations become available, make the set object 64 byte aligned so that most of the fields can be retrieved or updated in a single cache line. */ static PyObject * make_new_set(PyTypeObject *type, PyObject *iterable) { PySetObject *so; so = (PySetObject *)type->tp_alloc(type, 0); if (so == NULL) return NULL; so->fill = 0; so->used = 0; so->mask = PySet_MINSIZE - 1; so->table = so->smalltable; so->hash = -1; so->finger = 0; so->weakreflist = NULL; if (iterable != NULL) { if (set_update_internal(so, iterable)) { Py_DECREF(so); return NULL; } } return (PyObject *)so; } static PyObject * make_new_set_basetype(PyTypeObject *type, PyObject *iterable) { if (type != &PySet_Type && type != &PyFrozenSet_Type) { if (PyType_IsSubtype(type, &PySet_Type)) type = &PySet_Type; else type = &PyFrozenSet_Type; } return make_new_set(type, iterable); } /* The empty frozenset is a singleton */ static PyObject *emptyfrozenset = NULL; static PyObject * frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *iterable = NULL, *result; if (kwds != NULL && type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable)) return NULL; if (type != &PyFrozenSet_Type) return make_new_set(type, iterable); if (iterable != NULL) { /* frozenset(f) is idempotent */ if (PyFrozenSet_CheckExact(iterable)) { Py_INCREF(iterable); return iterable; } result = make_new_set(type, iterable); if (result == NULL || PySet_GET_SIZE(result)) return result; Py_DECREF(result); } /* The empty frozenset is a singleton */ if (emptyfrozenset == NULL) emptyfrozenset = make_new_set(type, NULL); Py_XINCREF(emptyfrozenset); return emptyfrozenset; } static PyObject * set_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { return make_new_set(type, NULL); } /* set_swap_bodies() switches the contents of any two sets by moving their internal data pointers and, if needed, copying the internal smalltables. Semantically equivalent to: t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t The function always succeeds and it leaves both objects in a stable state. Useful for operations that update in-place (by allowing an intermediate result to be swapped into one of the original inputs). */ static void set_swap_bodies(PySetObject *a, PySetObject *b) { Py_ssize_t t; setentry *u; setentry tab[PySet_MINSIZE]; Py_hash_t h; t = a->fill; a->fill = b->fill; b->fill = t; t = a->used; a->used = b->used; b->used = t; t = a->mask; a->mask = b->mask; b->mask = t; u = a->table; if (a->table == a->smalltable) u = b->smalltable; a->table = b->table; if (b->table == b->smalltable) a->table = a->smalltable; b->table = u; if (a->table == a->smalltable || b->table == b->smalltable) { memcpy(tab, a->smalltable, sizeof(tab)); memcpy(a->smalltable, b->smalltable, sizeof(tab)); memcpy(b->smalltable, tab, sizeof(tab)); } if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) && PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) { h = a->hash; a->hash = b->hash; b->hash = h; } else { a->hash = -1; b->hash = -1; } } static PyObject * set_copy(PySetObject *so) { return make_new_set_basetype(Py_TYPE(so), (PyObject *)so); } static PyObject * frozenset_copy(PySetObject *so) { if (PyFrozenSet_CheckExact(so)) { Py_INCREF(so); return (PyObject *)so; } return set_copy(so); } PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set."); static PyObject * set_clear(PySetObject *so) { set_clear_internal(so); Py_RETURN_NONE; } PyDoc_STRVAR(clear_doc, "Remove all elements from this set."); static PyObject * set_union(PySetObject *so, PyObject *args) { PySetObject *result; PyObject *other; Py_ssize_t i; result = (PySetObject *)set_copy(so); if (result == NULL) return NULL; for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) { other = PyTuple_GET_ITEM(args, i); if ((PyObject *)so == other) continue; if (set_update_internal(result, other)) { Py_DECREF(result); return NULL; } } return (PyObject *)result; } PyDoc_STRVAR(union_doc, "Return the union of sets as a new set.\n\ \n\ (i.e. all elements that are in either set.)"); static PyObject * set_or(PySetObject *so, PyObject *other) { PySetObject *result; if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) Py_RETURN_NOTIMPLEMENTED; result = (PySetObject *)set_copy(so); if (result == NULL) return NULL; if ((PyObject *)so == other) return (PyObject *)result; if (set_update_internal(result, other)) { Py_DECREF(result); return NULL; } return (PyObject *)result; } static PyObject * set_ior(PySetObject *so, PyObject *other) { if (!PyAnySet_Check(other)) Py_RETURN_NOTIMPLEMENTED; if (set_update_internal(so, other)) return NULL; Py_INCREF(so); return (PyObject *)so; } static PyObject * set_intersection(PySetObject *so, PyObject *other) { PySetObject *result; PyObject *key, *it, *tmp; Py_hash_t hash; int rv; if ((PyObject *)so == other) return set_copy(so); result = (PySetObject *)make_new_set_basetype(Py_TYPE(so), NULL); if (result == NULL) return NULL; if (PyAnySet_Check(other)) { Py_ssize_t pos = 0; setentry *entry; if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) { tmp = (PyObject *)so; so = (PySetObject *)other; other = tmp; } while (set_next((PySetObject *)other, &pos, &entry)) { key = entry->key; hash = entry->hash; rv = set_contains_entry(so, key, hash); if (rv < 0) { Py_DECREF(result); return NULL; } if (rv) { if (set_add_entry(result, key, hash)) { Py_DECREF(result); return NULL; } } } return (PyObject *)result; } it = PyObject_GetIter(other); if (it == NULL) { Py_DECREF(result); return NULL; } while ((key = PyIter_Next(it)) != NULL) { hash = PyObject_Hash(key); if (hash == -1) goto error; rv = set_contains_entry(so, key, hash); if (rv < 0) goto error; if (rv) { if (set_add_entry(result, key, hash)) goto error; } Py_DECREF(key); } Py_DECREF(it); if (PyErr_Occurred()) { Py_DECREF(result); return NULL; } return (PyObject *)result; error: Py_DECREF(it); Py_DECREF(result); Py_DECREF(key); return NULL; } static PyObject * set_intersection_multi(PySetObject *so, PyObject *args) { Py_ssize_t i; PyObject *result = (PyObject *)so; if (PyTuple_GET_SIZE(args) == 0) return set_copy(so); Py_INCREF(so); for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) { PyObject *other = PyTuple_GET_ITEM(args, i); PyObject *newresult = set_intersection((PySetObject *)result, other); if (newresult == NULL) { Py_DECREF(result); return NULL; } Py_DECREF(result); result = newresult; } return result; } PyDoc_STRVAR(intersection_doc, "Return the intersection of two sets as a new set.\n\ \n\ (i.e. all elements that are in both sets.)"); static PyObject * set_intersection_update(PySetObject *so, PyObject *other) { PyObject *tmp; tmp = set_intersection(so, other); if (tmp == NULL) return NULL; set_swap_bodies(so, (PySetObject *)tmp); Py_DECREF(tmp); Py_RETURN_NONE; } static PyObject * set_intersection_update_multi(PySetObject *so, PyObject *args) { PyObject *tmp; tmp = set_intersection_multi(so, args); if (tmp == NULL) return NULL; set_swap_bodies(so, (PySetObject *)tmp); Py_DECREF(tmp); Py_RETURN_NONE; } PyDoc_STRVAR(intersection_update_doc, "Update a set with the intersection of itself and another."); static PyObject * set_and(PySetObject *so, PyObject *other) { if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) Py_RETURN_NOTIMPLEMENTED; return set_intersection(so, other); } static PyObject * set_iand(PySetObject *so, PyObject *other) { PyObject *result; if (!PyAnySet_Check(other)) Py_RETURN_NOTIMPLEMENTED; result = set_intersection_update(so, other); if (result == NULL) return NULL; Py_DECREF(result); Py_INCREF(so); return (PyObject *)so; } static PyObject * set_isdisjoint(PySetObject *so, PyObject *other) { PyObject *key, *it, *tmp; int rv; if ((PyObject *)so == other) { if (PySet_GET_SIZE(so) == 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; } if (PyAnySet_CheckExact(other)) { Py_ssize_t pos = 0; setentry *entry; if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) { tmp = (PyObject *)so; so = (PySetObject *)other; other = tmp; } while (set_next((PySetObject *)other, &pos, &entry)) { rv = set_contains_entry(so, entry->key, entry->hash); if (rv < 0) return NULL; if (rv) Py_RETURN_FALSE; } Py_RETURN_TRUE; } it = PyObject_GetIter(other); if (it == NULL) return NULL; while ((key = PyIter_Next(it)) != NULL) { Py_hash_t hash = PyObject_Hash(key); if (hash == -1) { Py_DECREF(key); Py_DECREF(it); return NULL; } rv = set_contains_entry(so, key, hash); Py_DECREF(key); if (rv < 0) { Py_DECREF(it); return NULL; } if (rv) { Py_DECREF(it); Py_RETURN_FALSE; } } Py_DECREF(it); if (PyErr_Occurred()) return NULL; Py_RETURN_TRUE; } PyDoc_STRVAR(isdisjoint_doc, "Return True if two sets have a null intersection."); static int set_difference_update_internal(PySetObject *so, PyObject *other) { if (PySet_GET_SIZE(so) == 0) { return 0; } if ((PyObject *)so == other) return set_clear_internal(so); if (PyAnySet_Check(other)) { setentry *entry; Py_ssize_t pos = 0; while (set_next((PySetObject *)other, &pos, &entry)) if (set_discard_entry(so, entry->key, entry->hash) < 0) return -1; } else { PyObject *key, *it; it = PyObject_GetIter(other); if (it == NULL) return -1; while ((key = PyIter_Next(it)) != NULL) { if (set_discard_key(so, key) < 0) { Py_DECREF(it); Py_DECREF(key); return -1; } Py_DECREF(key); } Py_DECREF(it); if (PyErr_Occurred()) return -1; } /* If more than 1/4th are dummies, then resize them away. */ if ((size_t)(so->fill - so->used) <= (size_t)so->mask / 4) return 0; return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4); } static PyObject * set_difference_update(PySetObject *so, PyObject *args) { Py_ssize_t i; for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) { PyObject *other = PyTuple_GET_ITEM(args, i); if (set_difference_update_internal(so, other)) return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(difference_update_doc, "Remove all elements of another set from this set."); static PyObject * set_copy_and_difference(PySetObject *so, PyObject *other) { PyObject *result; result = set_copy(so); if (result == NULL) return NULL; if (set_difference_update_internal((PySetObject *) result, other) == 0) return result; Py_DECREF(result); return NULL; } static PyObject * set_difference(PySetObject *so, PyObject *other) { PyObject *result; PyObject *key; Py_hash_t hash; setentry *entry; Py_ssize_t pos = 0, other_size; int rv; if (PySet_GET_SIZE(so) == 0) { return set_copy(so); } if (PyAnySet_Check(other)) { other_size = PySet_GET_SIZE(other); } else if (PyDict_CheckExact(other)) { other_size = PyDict_Size(other); } else { return set_copy_and_difference(so, other); } /* If len(so) much more than len(other), it's more efficient to simply copy * so and then iterate other looking for common elements. */ if ((PySet_GET_SIZE(so) >> 2) > other_size) { return set_copy_and_difference(so, other); } result = make_new_set_basetype(Py_TYPE(so), NULL); if (result == NULL) return NULL; if (PyDict_CheckExact(other)) { while (set_next(so, &pos, &entry)) { key = entry->key; hash = entry->hash; rv = _PyDict_Contains(other, key, hash); if (rv < 0) { Py_DECREF(result); return NULL; } if (!rv) { if (set_add_entry((PySetObject *)result, key, hash)) { Py_DECREF(result); return NULL; } } } return result; } /* Iterate over so, checking for common elements in other. */ while (set_next(so, &pos, &entry)) { key = entry->key; hash = entry->hash; rv = set_contains_entry((PySetObject *)other, key, hash); if (rv < 0) { Py_DECREF(result); return NULL; } if (!rv) { if (set_add_entry((PySetObject *)result, key, hash)) { Py_DECREF(result); return NULL; } } } return result; } static PyObject * set_difference_multi(PySetObject *so, PyObject *args) { Py_ssize_t i; PyObject *result, *other; if (PyTuple_GET_SIZE(args) == 0) return set_copy(so); other = PyTuple_GET_ITEM(args, 0); result = set_difference(so, other); if (result == NULL) return NULL; for (i=1 ; i<PyTuple_GET_SIZE(args) ; i++) { other = PyTuple_GET_ITEM(args, i); if (set_difference_update_internal((PySetObject *)result, other)) { Py_DECREF(result); return NULL; } } return result; } PyDoc_STRVAR(difference_doc, "Return the difference of two or more sets as a new set.\n\ \n\ (i.e. all elements that are in this set but not the others.)"); static PyObject * set_sub(PySetObject *so, PyObject *other) { if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) Py_RETURN_NOTIMPLEMENTED; return set_difference(so, other); } static PyObject * set_isub(PySetObject *so, PyObject *other) { if (!PyAnySet_Check(other)) Py_RETURN_NOTIMPLEMENTED; if (set_difference_update_internal(so, other)) return NULL; Py_INCREF(so); return (PyObject *)so; } static PyObject * set_symmetric_difference_update(PySetObject *so, PyObject *other) { PySetObject *otherset; PyObject *key; Py_ssize_t pos = 0; Py_hash_t hash; setentry *entry; int rv; if ((PyObject *)so == other) return set_clear(so); if (PyDict_CheckExact(other)) { PyObject *value; while (_PyDict_Next(other, &pos, &key, &value, &hash)) { Py_INCREF(key); rv = set_discard_entry(so, key, hash); if (rv < 0) { Py_DECREF(key); return NULL; } if (rv == DISCARD_NOTFOUND) { if (set_add_entry(so, key, hash)) { Py_DECREF(key); return NULL; } } Py_DECREF(key); } Py_RETURN_NONE; } if (PyAnySet_Check(other)) { Py_INCREF(other); otherset = (PySetObject *)other; } else { otherset = (PySetObject *)make_new_set_basetype(Py_TYPE(so), other); if (otherset == NULL) return NULL; } while (set_next(otherset, &pos, &entry)) { key = entry->key; hash = entry->hash; rv = set_discard_entry(so, key, hash); if (rv < 0) { Py_DECREF(otherset); return NULL; } if (rv == DISCARD_NOTFOUND) { if (set_add_entry(so, key, hash)) { Py_DECREF(otherset); return NULL; } } } Py_DECREF(otherset); Py_RETURN_NONE; } PyDoc_STRVAR(symmetric_difference_update_doc, "Update a set with the symmetric difference of itself and another."); static PyObject * set_symmetric_difference(PySetObject *so, PyObject *other) { PyObject *rv; PySetObject *otherset; otherset = (PySetObject *)make_new_set_basetype(Py_TYPE(so), other); if (otherset == NULL) return NULL; rv = set_symmetric_difference_update(otherset, (PyObject *)so); if (rv == NULL) { Py_DECREF(otherset); return NULL; } Py_DECREF(rv); return (PyObject *)otherset; } PyDoc_STRVAR(symmetric_difference_doc, "Return the symmetric difference of two sets as a new set.\n\ \n\ (i.e. all elements that are in exactly one of the sets.)"); static PyObject * set_xor(PySetObject *so, PyObject *other) { if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) Py_RETURN_NOTIMPLEMENTED; return set_symmetric_difference(so, other); } static PyObject * set_ixor(PySetObject *so, PyObject *other) { PyObject *result; if (!PyAnySet_Check(other)) Py_RETURN_NOTIMPLEMENTED; result = set_symmetric_difference_update(so, other); if (result == NULL) return NULL; Py_DECREF(result); Py_INCREF(so); return (PyObject *)so; } static PyObject * set_issubset(PySetObject *so, PyObject *other) { setentry *entry; Py_ssize_t pos = 0; int rv; if (!PyAnySet_Check(other)) { PyObject *tmp, *result; tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) return NULL; result = set_issubset(so, tmp); Py_DECREF(tmp); return result; } if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other)) Py_RETURN_FALSE; while (set_next(so, &pos, &entry)) { rv = set_contains_entry((PySetObject *)other, entry->key, entry->hash); if (rv < 0) return NULL; if (!rv) Py_RETURN_FALSE; } Py_RETURN_TRUE; } PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set."); static PyObject * set_issuperset(PySetObject *so, PyObject *other) { PyObject *tmp, *result; if (!PyAnySet_Check(other)) { tmp = make_new_set(&PySet_Type, other); if (tmp == NULL) return NULL; result = set_issuperset(so, tmp); Py_DECREF(tmp); return result; } return set_issubset((PySetObject *)other, (PyObject *)so); } PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set."); static PyObject * set_richcompare(PySetObject *v, PyObject *w, int op) { PyObject *r1; int r2; if(!PyAnySet_Check(w)) Py_RETURN_NOTIMPLEMENTED; switch (op) { case Py_EQ: if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w)) Py_RETURN_FALSE; if (v->hash != -1 && ((PySetObject *)w)->hash != -1 && v->hash != ((PySetObject *)w)->hash) Py_RETURN_FALSE; return set_issubset(v, w); case Py_NE: r1 = set_richcompare(v, w, Py_EQ); if (r1 == NULL) return NULL; r2 = PyObject_IsTrue(r1); Py_DECREF(r1); if (r2 < 0) return NULL; return PyBool_FromLong(!r2); case Py_LE: return set_issubset(v, w); case Py_GE: return set_issuperset(v, w); case Py_LT: if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w)) Py_RETURN_FALSE; return set_issubset(v, w); case Py_GT: if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w)) Py_RETURN_FALSE; return set_issuperset(v, w); } Py_RETURN_NOTIMPLEMENTED; } static PyObject * set_add(PySetObject *so, PyObject *key) { if (set_add_key(so, key)) return NULL; Py_RETURN_NONE; } PyDoc_STRVAR(add_doc, "Add an element to a set.\n\ \n\ This has no effect if the element is already present."); static int set_contains(PySetObject *so, PyObject *key) { PyObject *tmpkey; int rv; rv = set_contains_key(so, key); if (rv < 0) { if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) return -1; PyErr_Clear(); tmpkey = make_new_set(&PyFrozenSet_Type, key); if (tmpkey == NULL) return -1; rv = set_contains_key(so, tmpkey); Py_DECREF(tmpkey); } return rv; } static PyObject * set_direct_contains(PySetObject *so, PyObject *key) { long result; result = set_contains(so, key); if (result < 0) return NULL; return PyBool_FromLong(result); } PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x."); static PyObject * set_remove(PySetObject *so, PyObject *key) { PyObject *tmpkey; int rv; rv = set_discard_key(so, key); if (rv < 0) { if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) return NULL; PyErr_Clear(); tmpkey = make_new_set(&PyFrozenSet_Type, key); if (tmpkey == NULL) return NULL; rv = set_discard_key(so, tmpkey); Py_DECREF(tmpkey); if (rv < 0) return NULL; } if (rv == DISCARD_NOTFOUND) { _PyErr_SetKeyError(key); return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(remove_doc, "Remove an element from a set; it must be a member.\n\ \n\ If the element is not a member, raise a KeyError."); static PyObject * set_discard(PySetObject *so, PyObject *key) { PyObject *tmpkey; int rv; rv = set_discard_key(so, key); if (rv < 0) { if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError)) return NULL; PyErr_Clear(); tmpkey = make_new_set(&PyFrozenSet_Type, key); if (tmpkey == NULL) return NULL; rv = set_discard_key(so, tmpkey); Py_DECREF(tmpkey); if (rv < 0) return NULL; } Py_RETURN_NONE; } PyDoc_STRVAR(discard_doc, "Remove an element from a set if it is a member.\n\ \n\ If the element is not a member, do nothing."); static PyObject * set_reduce(PySetObject *so) { PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL; _Py_IDENTIFIER(__dict__); keys = PySequence_List((PyObject *)so); if (keys == NULL) goto done; args = PyTuple_Pack(1, keys); if (args == NULL) goto done; dict = _PyObject_GetAttrId((PyObject *)so, &PyId___dict__); if (dict == NULL) { PyErr_Clear(); dict = Py_None; Py_INCREF(dict); } result = PyTuple_Pack(3, Py_TYPE(so), args, dict); done: Py_XDECREF(args); Py_XDECREF(keys); Py_XDECREF(dict); return result; } static PyObject * set_sizeof(PySetObject *so) { Py_ssize_t res; res = _PyObject_SIZE(Py_TYPE(so)); if (so->table != so->smalltable) res = res + (so->mask + 1) * sizeof(setentry); return PyLong_FromSsize_t(res); } PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes"); static int set_init(PySetObject *self, PyObject *args, PyObject *kwds) { PyObject *iterable = NULL; if (kwds != NULL && !_PyArg_NoKeywords("set()", kwds)) return -1; if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable)) return -1; if (self->fill) set_clear_internal(self); self->hash = -1; if (iterable == NULL) return 0; return set_update_internal(self, iterable); } static PySequenceMethods set_as_sequence = { set_len, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ 0, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)set_contains, /* sq_contains */ }; /* set object ********************************************************/ #ifdef Py_DEBUG static PyObject *test_c_api(PySetObject *so); PyDoc_STRVAR(test_c_api_doc, "Exercises C API. Returns True.\n\ All is well if assertions don't fail."); #endif static PyMethodDef set_methods[] = { {"add", (PyCFunction)set_add, METH_O, add_doc}, {"clear", (PyCFunction)set_clear, METH_NOARGS, clear_doc}, {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, contains_doc}, {"copy", (PyCFunction)set_copy, METH_NOARGS, copy_doc}, {"discard", (PyCFunction)set_discard, METH_O, discard_doc}, {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, difference_doc}, {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS, difference_update_doc}, {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS, intersection_doc}, {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS, intersection_update_doc}, {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, isdisjoint_doc}, {"issubset", (PyCFunction)set_issubset, METH_O, issubset_doc}, {"issuperset", (PyCFunction)set_issuperset, METH_O, issuperset_doc}, {"pop", (PyCFunction)set_pop, METH_NOARGS, pop_doc}, {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, reduce_doc}, {"remove", (PyCFunction)set_remove, METH_O, remove_doc}, {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, sizeof_doc}, {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, symmetric_difference_doc}, {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O, symmetric_difference_update_doc}, #ifdef Py_DEBUG {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS, test_c_api_doc}, #endif {"union", (PyCFunction)set_union, METH_VARARGS, union_doc}, {"update", (PyCFunction)set_update, METH_VARARGS, update_doc}, {NULL, NULL} /* sentinel */ }; static PyNumberMethods set_as_number = { 0, /*nb_add*/ (binaryfunc)set_sub, /*nb_subtract*/ 0, /*nb_multiply*/ 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_bool*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ (binaryfunc)set_and, /*nb_and*/ (binaryfunc)set_xor, /*nb_xor*/ (binaryfunc)set_or, /*nb_or*/ 0, /*nb_int*/ 0, /*nb_reserved*/ 0, /*nb_float*/ 0, /*nb_inplace_add*/ (binaryfunc)set_isub, /*nb_inplace_subtract*/ 0, /*nb_inplace_multiply*/ 0, /*nb_inplace_remainder*/ 0, /*nb_inplace_power*/ 0, /*nb_inplace_lshift*/ 0, /*nb_inplace_rshift*/ (binaryfunc)set_iand, /*nb_inplace_and*/ (binaryfunc)set_ixor, /*nb_inplace_xor*/ (binaryfunc)set_ior, /*nb_inplace_or*/ }; PyDoc_STRVAR(set_doc, "set() -> new empty set object\n\ set(iterable) -> new set object\n\ \n\ Build an unordered collection of unique elements."); PyTypeObject PySet_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "set", /* tp_name */ sizeof(PySetObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)set_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)set_repr, /* tp_repr */ &set_as_number, /* tp_as_number */ &set_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ PyObject_HashNotImplemented, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ set_doc, /* tp_doc */ (traverseproc)set_traverse, /* tp_traverse */ (inquiry)set_clear_internal, /* tp_clear */ (richcmpfunc)set_richcompare, /* tp_richcompare */ offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ (getiterfunc)set_iter, /* tp_iter */ 0, /* tp_iternext */ set_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)set_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ set_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; /* frozenset object ********************************************************/ static PyMethodDef frozenset_methods[] = { {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST, contains_doc}, {"copy", (PyCFunction)frozenset_copy, METH_NOARGS, copy_doc}, {"difference", (PyCFunction)set_difference_multi, METH_VARARGS, difference_doc}, {"intersection", (PyCFunction)set_intersection_multi, METH_VARARGS, intersection_doc}, {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O, isdisjoint_doc}, {"issubset", (PyCFunction)set_issubset, METH_O, issubset_doc}, {"issuperset", (PyCFunction)set_issuperset, METH_O, issuperset_doc}, {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS, reduce_doc}, {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS, sizeof_doc}, {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O, symmetric_difference_doc}, {"union", (PyCFunction)set_union, METH_VARARGS, union_doc}, {NULL, NULL} /* sentinel */ }; static PyNumberMethods frozenset_as_number = { 0, /*nb_add*/ (binaryfunc)set_sub, /*nb_subtract*/ 0, /*nb_multiply*/ 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_bool*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ (binaryfunc)set_and, /*nb_and*/ (binaryfunc)set_xor, /*nb_xor*/ (binaryfunc)set_or, /*nb_or*/ }; PyDoc_STRVAR(frozenset_doc, "frozenset() -> empty frozenset object\n\ frozenset(iterable) -> frozenset object\n\ \n\ Build an immutable unordered collection of unique elements."); PyTypeObject PyFrozenSet_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "frozenset", /* tp_name */ sizeof(PySetObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)set_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)set_repr, /* tp_repr */ &frozenset_as_number, /* tp_as_number */ &set_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ frozenset_hash, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ frozenset_doc, /* tp_doc */ (traverseproc)set_traverse, /* tp_traverse */ (inquiry)set_clear_internal, /* tp_clear */ (richcmpfunc)set_richcompare, /* tp_richcompare */ offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */ (getiterfunc)set_iter, /* tp_iter */ 0, /* tp_iternext */ frozenset_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ frozenset_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; /***** C API functions *************************************************/ PyObject * PySet_New(PyObject *iterable) { return make_new_set(&PySet_Type, iterable); } PyObject * PyFrozenSet_New(PyObject *iterable) { return make_new_set(&PyFrozenSet_Type, iterable); } Py_ssize_t PySet_Size(PyObject *anyset) { if (!PyAnySet_Check(anyset)) { PyErr_BadInternalCall(); return -1; } return PySet_GET_SIZE(anyset); } int PySet_Clear(PyObject *set) { if (!PySet_Check(set)) { PyErr_BadInternalCall(); return -1; } return set_clear_internal((PySetObject *)set); } int PySet_Contains(PyObject *anyset, PyObject *key) { if (!PyAnySet_Check(anyset)) { PyErr_BadInternalCall(); return -1; } return set_contains_key((PySetObject *)anyset, key); } int PySet_Discard(PyObject *set, PyObject *key) { if (!PySet_Check(set)) { PyErr_BadInternalCall(); return -1; } return set_discard_key((PySetObject *)set, key); } int PySet_Add(PyObject *anyset, PyObject *key) { if (!PySet_Check(anyset) && (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) { PyErr_BadInternalCall(); return -1; } return set_add_key((PySetObject *)anyset, key); } int PySet_ClearFreeList(void) { return 0; } void PySet_Fini(void) { Py_CLEAR(emptyfrozenset); } int _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash) { setentry *entry; if (!PyAnySet_Check(set)) { PyErr_BadInternalCall(); return -1; } if (set_next((PySetObject *)set, pos, &entry) == 0) return 0; *key = entry->key; *hash = entry->hash; return 1; } PyObject * PySet_Pop(PyObject *set) { if (!PySet_Check(set)) { PyErr_BadInternalCall(); return NULL; } return set_pop((PySetObject *)set); } int _PySet_Update(PyObject *set, PyObject *iterable) { if (!PySet_Check(set)) { PyErr_BadInternalCall(); return -1; } return set_update_internal((PySetObject *)set, iterable); } /* Exported for the gdb plugin's benefit. */ PyObject *_PySet_Dummy = dummy; #ifdef Py_DEBUG /* Test code to be called with any three element set. Returns True and original set is restored. */ #define assertRaises(call_return_value, exception) \ do { \ assert(call_return_value); \ assert(PyErr_ExceptionMatches(exception)); \ PyErr_Clear(); \ } while(0) static PyObject * test_c_api(PySetObject *so) { Py_ssize_t count; char *s; Py_ssize_t i; PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x=NULL; PyObject *ob = (PyObject *)so; Py_hash_t hash; PyObject *str; /* Verify preconditions */ assert(PyAnySet_Check(ob)); assert(PyAnySet_CheckExact(ob)); assert(!PyFrozenSet_CheckExact(ob)); /* so.clear(); so |= set("abc"); */ str = PyUnicode_FromString("abc"); if (str == NULL) return NULL; set_clear_internal(so); if (set_update_internal(so, str)) { Py_DECREF(str); return NULL; } Py_DECREF(str); /* Exercise type/size checks */ assert(PySet_Size(ob) == 3); assert(PySet_GET_SIZE(ob) == 3); /* Raise TypeError for non-iterable constructor arguments */ assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError); assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError); /* Raise TypeError for unhashable key */ dup = PySet_New(ob); assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError); assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError); assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError); /* Exercise successful pop, contains, add, and discard */ elem = PySet_Pop(ob); assert(PySet_Contains(ob, elem) == 0); assert(PySet_GET_SIZE(ob) == 2); assert(PySet_Add(ob, elem) == 0); assert(PySet_Contains(ob, elem) == 1); assert(PySet_GET_SIZE(ob) == 3); assert(PySet_Discard(ob, elem) == 1); assert(PySet_GET_SIZE(ob) == 2); assert(PySet_Discard(ob, elem) == 0); assert(PySet_GET_SIZE(ob) == 2); /* Exercise clear */ dup2 = PySet_New(dup); assert(PySet_Clear(dup2) == 0); assert(PySet_Size(dup2) == 0); Py_DECREF(dup2); /* Raise SystemError on clear or update of frozen set */ f = PyFrozenSet_New(dup); assertRaises(PySet_Clear(f) == -1, PyExc_SystemError); assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError); assert(PySet_Add(f, elem) == 0); Py_INCREF(f); assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError); Py_DECREF(f); Py_DECREF(f); /* Exercise direct iteration */ i = 0, count = 0; while (_PySet_NextEntry((PyObject *)dup, &i, &x, &hash)) { s = PyUnicode_AsUTF8(x); assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c')); count++; } assert(count == 3); /* Exercise updates */ dup2 = PySet_New(NULL); assert(_PySet_Update(dup2, dup) == 0); assert(PySet_Size(dup2) == 3); assert(_PySet_Update(dup2, dup) == 0); assert(PySet_Size(dup2) == 3); Py_DECREF(dup2); /* Raise SystemError when self argument is not a set or frozenset. */ t = PyTuple_New(0); assertRaises(PySet_Size(t) == -1, PyExc_SystemError); assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError); Py_DECREF(t); /* Raise SystemError when self argument is not a set. */ f = PyFrozenSet_New(dup); assert(PySet_Size(f) == 3); assert(PyFrozenSet_CheckExact(f)); assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError); assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError); Py_DECREF(f); /* Raise KeyError when popping from an empty set */ assert(PyNumber_InPlaceSubtract(ob, ob) == ob); Py_DECREF(ob); assert(PySet_GET_SIZE(ob) == 0); assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError); /* Restore the set from the copy using the PyNumber API */ assert(PyNumber_InPlaceOr(ob, dup) == ob); Py_DECREF(ob); /* Verify constructors accept NULL arguments */ f = PySet_New(NULL); assert(f != NULL); assert(PySet_GET_SIZE(f) == 0); Py_DECREF(f); f = PyFrozenSet_New(NULL); assert(f != NULL); assert(PyFrozenSet_CheckExact(f)); assert(PySet_GET_SIZE(f) == 0); Py_DECREF(f); Py_DECREF(elem); Py_DECREF(dup); Py_RETURN_TRUE; } #undef assertRaises #endif /***** Dummy Struct *************************************************/ static PyObject * dummy_repr(PyObject *op) { return PyUnicode_FromString("<dummy key>"); } static void dummy_dealloc(PyObject* ignore) { Py_FatalError("deallocating <dummy key>"); } static PyTypeObject _PySetDummy_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "<dummy key> type", 0, 0, dummy_dealloc, /*tp_dealloc*/ /*never called*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ dummy_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call */ 0, /*tp_str */ 0, /*tp_getattro */ 0, /*tp_setattro */ 0, /*tp_as_buffer */ Py_TPFLAGS_DEFAULT, /*tp_flags */ }; static PyObject _dummy_struct = { _PyObject_EXTRA_INIT 2, &_PySetDummy_Type };
76,184
2,592
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/enumobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/enumobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" /* clang-format off */ typedef struct { PyObject_HEAD Py_ssize_t en_index; /* current index of enumeration */ PyObject* en_sit; /* secondary iterator of enumeration */ PyObject* en_result; /* result tuple */ PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */ } enumobject; static PyObject * enum_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { enumobject *en; PyObject *seq = NULL; PyObject *start = NULL; static char *kwlist[] = {"iterable", "start", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist, &seq, &start)) return NULL; en = (enumobject *)type->tp_alloc(type, 0); if (en == NULL) return NULL; if (start != NULL) { start = PyNumber_Index(start); if (start == NULL) { Py_DECREF(en); return NULL; } assert(PyLong_Check(start)); en->en_index = PyLong_AsSsize_t(start); if (en->en_index == -1 && PyErr_Occurred()) { PyErr_Clear(); en->en_index = PY_SSIZE_T_MAX; en->en_longindex = start; } else { en->en_longindex = NULL; Py_DECREF(start); } } else { en->en_index = 0; en->en_longindex = NULL; } en->en_sit = PyObject_GetIter(seq); if (en->en_sit == NULL) { Py_DECREF(en); return NULL; } en->en_result = PyTuple_Pack(2, Py_None, Py_None); if (en->en_result == NULL) { Py_DECREF(en); return NULL; } return (PyObject *)en; } static void enum_dealloc(enumobject *en) { PyObject_GC_UnTrack(en); Py_XDECREF(en->en_sit); Py_XDECREF(en->en_result); Py_XDECREF(en->en_longindex); Py_TYPE(en)->tp_free(en); } static int enum_traverse(enumobject *en, visitproc visit, void *arg) { Py_VISIT(en->en_sit); Py_VISIT(en->en_result); Py_VISIT(en->en_longindex); return 0; } static PyObject * enum_next_long(enumobject *en, PyObject* next_item) { static PyObject *one = NULL; PyObject *result = en->en_result; PyObject *next_index; PyObject *stepped_up; if (en->en_longindex == NULL) { en->en_longindex = PyLong_FromSsize_t(PY_SSIZE_T_MAX); if (en->en_longindex == NULL) { Py_DECREF(next_item); return NULL; } } if (one == NULL) { one = PyLong_FromLong(1); if (one == NULL) { Py_DECREF(next_item); return NULL; } } next_index = en->en_longindex; assert(next_index != NULL); stepped_up = PyNumber_Add(next_index, one); if (stepped_up == NULL) { Py_DECREF(next_item); return NULL; } en->en_longindex = stepped_up; if (result->ob_refcnt == 1) { Py_INCREF(result); Py_DECREF(PyTuple_GET_ITEM(result, 0)); Py_DECREF(PyTuple_GET_ITEM(result, 1)); } else { result = PyTuple_New(2); if (result == NULL) { Py_DECREF(next_index); Py_DECREF(next_item); return NULL; } } PyTuple_SET_ITEM(result, 0, next_index); PyTuple_SET_ITEM(result, 1, next_item); return result; } static PyObject * enum_next(enumobject *en) { PyObject *next_index; PyObject *next_item; PyObject *result = en->en_result; PyObject *it = en->en_sit; next_item = (*Py_TYPE(it)->tp_iternext)(it); if (next_item == NULL) return NULL; if (en->en_index == PY_SSIZE_T_MAX) return enum_next_long(en, next_item); next_index = PyLong_FromSsize_t(en->en_index); if (next_index == NULL) { Py_DECREF(next_item); return NULL; } en->en_index++; if (result->ob_refcnt == 1) { Py_INCREF(result); Py_DECREF(PyTuple_GET_ITEM(result, 0)); Py_DECREF(PyTuple_GET_ITEM(result, 1)); } else { result = PyTuple_New(2); if (result == NULL) { Py_DECREF(next_index); Py_DECREF(next_item); return NULL; } } PyTuple_SET_ITEM(result, 0, next_index); PyTuple_SET_ITEM(result, 1, next_item); return result; } static PyObject * enum_reduce(enumobject *en) { if (en->en_longindex != NULL) return Py_BuildValue("O(OO)", Py_TYPE(en), en->en_sit, en->en_longindex); else return Py_BuildValue("O(On)", Py_TYPE(en), en->en_sit, en->en_index); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef enum_methods[] = { {"__reduce__", (PyCFunction)enum_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(enum_doc, "enumerate(iterable[, start]) -> iterator for index, value of iterable\n" "\n" "Return an enumerate object. iterable must be another object that supports\n" "iteration. The enumerate object yields pairs containing a count (from\n" "start, which defaults to zero) and a value yielded by the iterable argument.\n" "enumerate is useful for obtaining an indexed list:\n" " (0, seq[0]), (1, seq[1]), (2, seq[2]), ..."); PyTypeObject PyEnum_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "enumerate", /* tp_name */ sizeof(enumobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)enum_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ enum_doc, /* tp_doc */ (traverseproc)enum_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)enum_next, /* tp_iternext */ enum_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ enum_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; /* Reversed Object ***************************************************************/ typedef struct { PyObject_HEAD Py_ssize_t index; PyObject* seq; } reversedobject; static PyObject * reversed_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { Py_ssize_t n; PyObject *seq, *reversed_meth; reversedobject *ro; _Py_IDENTIFIER(__reversed__); if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) ) return NULL; reversed_meth = _PyObject_LookupSpecial(seq, &PyId___reversed__); if (reversed_meth == Py_None) { Py_DECREF(reversed_meth); PyErr_Format(PyExc_TypeError, "'%.200s' object is not reversible", Py_TYPE(seq)->tp_name); return NULL; } if (reversed_meth != NULL) { PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL); Py_DECREF(reversed_meth); return res; } else if (PyErr_Occurred()) return NULL; if (!PySequence_Check(seq)) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not reversible", Py_TYPE(seq)->tp_name); return NULL; } n = PySequence_Size(seq); if (n == -1) return NULL; ro = (reversedobject *)type->tp_alloc(type, 0); if (ro == NULL) return NULL; ro->index = n-1; Py_INCREF(seq); ro->seq = seq; return (PyObject *)ro; } static void reversed_dealloc(reversedobject *ro) { PyObject_GC_UnTrack(ro); Py_XDECREF(ro->seq); Py_TYPE(ro)->tp_free(ro); } static int reversed_traverse(reversedobject *ro, visitproc visit, void *arg) { Py_VISIT(ro->seq); return 0; } static PyObject * reversed_next(reversedobject *ro) { PyObject *item; Py_ssize_t index = ro->index; if (index >= 0) { item = PySequence_GetItem(ro->seq, index); if (item != NULL) { ro->index--; return item; } if (PyErr_ExceptionMatches(PyExc_IndexError) || PyErr_ExceptionMatches(PyExc_StopIteration)) PyErr_Clear(); } ro->index = -1; Py_CLEAR(ro->seq); return NULL; } PyDoc_STRVAR(reversed_doc, "reversed(sequence) -> reverse iterator over values of the sequence\n" "\n" "Return a reverse iterator"); static PyObject * reversed_len(reversedobject *ro) { Py_ssize_t position, seqsize; if (ro->seq == NULL) return PyLong_FromLong(0); seqsize = PySequence_Size(ro->seq); if (seqsize == -1) return NULL; position = ro->index + 1; return PyLong_FromSsize_t((seqsize < position) ? 0 : position); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * reversed_reduce(reversedobject *ro) { if (ro->seq) return Py_BuildValue("O(O)n", Py_TYPE(ro), ro->seq, ro->index); else return Py_BuildValue("O(())", Py_TYPE(ro)); } static PyObject * reversed_setstate(reversedobject *ro, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; if (ro->seq != 0) { Py_ssize_t n = PySequence_Size(ro->seq); if (n < 0) return NULL; if (index < -1) index = -1; else if (index > n-1) index = n-1; ro->index = index; } Py_RETURN_NONE; } PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef reversediter_methods[] = { {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)reversed_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)reversed_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyReversed_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "reversed", /* tp_name */ sizeof(reversedobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)reversed_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ reversed_doc, /* tp_doc */ (traverseproc)reversed_traverse,/* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)reversed_next, /* tp_iternext */ reversediter_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ reversed_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ };
14,698
446
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/fromfd.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ PYTHON_YOINK("io"); PyObject * PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd) { PyObject *io, *stream; _Py_IDENTIFIER(open); io = PyImport_ImportModule("io"); if (io == NULL) return NULL; stream = _PyObject_CallMethodId(io, &PyId_open, "isisssi", fd, mode, buffering, encoding, errors, newline, closefd); Py_DECREF(io); if (stream == NULL) return NULL; /* ignore name attribute because the name attribute of _BufferedIOMixin and TextIOWrapper is read only */ return stream; }
1,767
35
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/namespaceobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/namespaceobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ typedef struct { PyObject_HEAD PyObject *ns_dict; } _PyNamespaceObject; static PyMemberDef namespace_members[] = { {"__dict__", T_OBJECT, offsetof(_PyNamespaceObject, ns_dict), READONLY}, {NULL} }; // Methods static PyObject * namespace_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *self; assert(type != NULL && type->tp_alloc != NULL); self = type->tp_alloc(type, 0); if (self != NULL) { _PyNamespaceObject *ns = (_PyNamespaceObject *)self; ns->ns_dict = PyDict_New(); if (ns->ns_dict == NULL) { Py_DECREF(ns); return NULL; } } return self; } static int namespace_init(_PyNamespaceObject *ns, PyObject *args, PyObject *kwds) { // ignore args if it's NULL or empty if (args != NULL) { Py_ssize_t argcount = PyObject_Size(args); if (argcount < 0) return -1; else if (argcount > 0) { PyErr_Format(PyExc_TypeError, "no positional arguments expected"); return -1; } } if (kwds == NULL) { return 0; } if (!PyArg_ValidateKeywordArguments(kwds)) { return -1; } return PyDict_Update(ns->ns_dict, kwds); } static void namespace_dealloc(_PyNamespaceObject *ns) { PyObject_GC_UnTrack(ns); Py_CLEAR(ns->ns_dict); Py_TYPE(ns)->tp_free((PyObject *)ns); } static PyObject * namespace_repr(PyObject *ns) { int i, loop_error = 0; PyObject *pairs = NULL, *d = NULL, *keys = NULL, *keys_iter = NULL; PyObject *key; PyObject *separator, *pairsrepr, *repr = NULL; const char * name; name = (Py_TYPE(ns) == &_PyNamespace_Type) ? "namespace" : ns->ob_type->tp_name; i = Py_ReprEnter(ns); if (i != 0) { return i > 0 ? PyUnicode_FromFormat("%s(...)", name) : NULL; } pairs = PyList_New(0); if (pairs == NULL) goto error; d = ((_PyNamespaceObject *)ns)->ns_dict; assert(d != NULL); Py_INCREF(d); keys = PyDict_Keys(d); if (keys == NULL) goto error; if (PyList_Sort(keys) != 0) goto error; keys_iter = PyObject_GetIter(keys); if (keys_iter == NULL) goto error; while ((key = PyIter_Next(keys_iter)) != NULL) { if (PyUnicode_Check(key) && PyUnicode_GET_LENGTH(key) > 0) { PyObject *value, *item; value = PyDict_GetItem(d, key); if (value != NULL) { item = PyUnicode_FromFormat("%S=%R", key, value); if (item == NULL) { loop_error = 1; } else { loop_error = PyList_Append(pairs, item); Py_DECREF(item); } } } Py_DECREF(key); if (loop_error) goto error; } separator = PyUnicode_FromString(", "); if (separator == NULL) goto error; pairsrepr = PyUnicode_Join(separator, pairs); Py_DECREF(separator); if (pairsrepr == NULL) goto error; repr = PyUnicode_FromFormat("%s(%S)", name, pairsrepr); Py_DECREF(pairsrepr); error: Py_XDECREF(pairs); Py_XDECREF(d); Py_XDECREF(keys); Py_XDECREF(keys_iter); Py_ReprLeave(ns); return repr; } static int namespace_traverse(_PyNamespaceObject *ns, visitproc visit, void *arg) { Py_VISIT(ns->ns_dict); return 0; } static int namespace_clear(_PyNamespaceObject *ns) { Py_CLEAR(ns->ns_dict); return 0; } static PyObject * namespace_richcompare(PyObject *self, PyObject *other, int op) { if (PyObject_TypeCheck(self, &_PyNamespace_Type) && PyObject_TypeCheck(other, &_PyNamespace_Type)) return PyObject_RichCompare(((_PyNamespaceObject *)self)->ns_dict, ((_PyNamespaceObject *)other)->ns_dict, op); Py_RETURN_NOTIMPLEMENTED; } PyDoc_STRVAR(namespace_reduce__doc__, "Return state information for pickling"); static PyObject * namespace_reduce(_PyNamespaceObject *ns) { PyObject *result, *args = PyTuple_New(0); if (!args) return NULL; result = PyTuple_Pack(3, (PyObject *)Py_TYPE(ns), args, ns->ns_dict); Py_DECREF(args); return result; } static PyMethodDef namespace_methods[] = { {"__reduce__", (PyCFunction)namespace_reduce, METH_NOARGS, namespace_reduce__doc__}, {NULL, NULL} // sentinel }; PyDoc_STRVAR(namespace_doc, "A simple attribute-based namespace.\n\ \n\ SimpleNamespace(**kwargs)"); PyTypeObject _PyNamespace_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "types.SimpleNamespace", /* tp_name */ sizeof(_PyNamespaceObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)namespace_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)namespace_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ namespace_doc, /* tp_doc */ (traverseproc)namespace_traverse, /* tp_traverse */ (inquiry)namespace_clear, /* tp_clear */ namespace_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ namespace_methods, /* tp_methods */ namespace_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(_PyNamespaceObject, ns_dict), /* tp_dictoffset */ (initproc)namespace_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ (newfunc)namespace_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * _PyNamespace_New(PyObject *kwds) { PyObject *ns = namespace_new(&_PyNamespace_Type, NULL, NULL); if (ns == NULL) return NULL; if (kwds == NULL) return ns; if (PyDict_Update(((_PyNamespaceObject *)ns)->ns_dict, kwds) != 0) { Py_DECREF(ns); return NULL; } return (PyObject *)ns; }
8,988
282
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/rangeobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/rangeobject.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ /* Support objects whose length is > PY_SSIZE_T_MAX. This could be sped up for small PyLongs if they fit in a Py_ssize_t. This only matters on Win64. Though we could use long long which would presumably help perf. */ typedef struct { PyObject_HEAD PyObject *start; PyObject *stop; PyObject *step; PyObject *length; } rangeobject; /* Helper function for validating step. Always returns a new reference or NULL on error. */ static PyObject * validate_step(PyObject *step) { /* No step specified, use a step of 1. */ if (!step) return PyLong_FromLong(1); step = PyNumber_Index(step); if (step && _PyLong_Sign(step) == 0) { PyErr_SetString(PyExc_ValueError, "range() arg 3 must not be zero"); Py_CLEAR(step); } return step; } static PyObject * compute_range_length(PyObject *start, PyObject *stop, PyObject *step); static rangeobject * make_range_object(PyTypeObject *type, PyObject *start, PyObject *stop, PyObject *step) { rangeobject *obj = NULL; PyObject *length; length = compute_range_length(start, stop, step); if (length == NULL) { return NULL; } obj = PyObject_New(rangeobject, type); if (obj == NULL) { Py_DECREF(length); return NULL; } obj->start = start; obj->stop = stop; obj->step = step; obj->length = length; return obj; } /* XXX(nnorwitz): should we error check if the user passes any empty ranges? range(-10) range(0, -5) range(0, 5, -1) */ static PyObject * range_new(PyTypeObject *type, PyObject *args, PyObject *kw) { rangeobject *obj; PyObject *start = NULL, *stop = NULL, *step = NULL; if (!_PyArg_NoKeywords("range()", kw)) return NULL; if (PyTuple_Size(args) <= 1) { if (!PyArg_UnpackTuple(args, "range", 1, 1, &stop)) return NULL; stop = PyNumber_Index(stop); if (!stop) return NULL; start = PyLong_FromLong(0); if (!start) { Py_DECREF(stop); return NULL; } step = PyLong_FromLong(1); if (!step) { Py_DECREF(stop); Py_DECREF(start); return NULL; } } else { if (!PyArg_UnpackTuple(args, "range", 2, 3, &start, &stop, &step)) return NULL; /* Convert borrowed refs to owned refs */ start = PyNumber_Index(start); if (!start) return NULL; stop = PyNumber_Index(stop); if (!stop) { Py_DECREF(start); return NULL; } step = validate_step(step); /* Caution, this can clear exceptions */ if (!step) { Py_DECREF(start); Py_DECREF(stop); return NULL; } } obj = make_range_object(type, start, stop, step); if (obj != NULL) return (PyObject *) obj; /* Failed to create object, release attributes */ Py_DECREF(start); Py_DECREF(stop); Py_DECREF(step); return NULL; } PyDoc_STRVAR(range_doc, "range(stop) -> range object\n\ range(start, stop[, step]) -> range object\n\ \n\ Return an object that produces a sequence of integers from start (inclusive)\n\ to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.\n\ start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.\n\ These are exactly the valid indices for a list of 4 elements.\n\ When step is given, it specifies the increment (or decrement)."); static void range_dealloc(rangeobject *r) { Py_DECREF(r->start); Py_DECREF(r->stop); Py_DECREF(r->step); Py_DECREF(r->length); PyObject_Del(r); } /* Return number of items in range (lo, hi, step) as a PyLong object, * when arguments are PyLong objects. Arguments MUST return 1 with * PyLong_Check(). Return NULL when there is an error. */ static PyObject* compute_range_length(PyObject *start, PyObject *stop, PyObject *step) { /* ------------------------------------------------------------- Algorithm is equal to that of get_len_of_range(), but it operates on PyObjects (which are assumed to be PyLong objects). ---------------------------------------------------------------*/ int cmp_result; PyObject *lo, *hi; PyObject *diff = NULL; PyObject *one = NULL; PyObject *tmp1 = NULL, *tmp2 = NULL, *result; /* holds sub-expression evaluations */ PyObject *zero = PyLong_FromLong(0); if (zero == NULL) return NULL; cmp_result = PyObject_RichCompareBool(step, zero, Py_GT); Py_DECREF(zero); if (cmp_result == -1) return NULL; if (cmp_result == 1) { lo = start; hi = stop; Py_INCREF(step); } else { lo = stop; hi = start; step = PyNumber_Negative(step); if (!step) return NULL; } /* if (lo >= hi), return length of 0. */ cmp_result = PyObject_RichCompareBool(lo, hi, Py_GE); if (cmp_result != 0) { Py_DECREF(step); if (cmp_result < 0) return NULL; return PyLong_FromLong(0); } if ((one = PyLong_FromLong(1L)) == NULL) goto Fail; if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL) goto Fail; if ((diff = PyNumber_Subtract(tmp1, one)) == NULL) goto Fail; if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL) goto Fail; if ((result = PyNumber_Add(tmp2, one)) == NULL) goto Fail; Py_DECREF(tmp2); Py_DECREF(diff); Py_DECREF(step); Py_DECREF(tmp1); Py_DECREF(one); return result; Fail: Py_DECREF(step); Py_XDECREF(tmp2); Py_XDECREF(diff); Py_XDECREF(tmp1); Py_XDECREF(one); return NULL; } static Py_ssize_t range_length(rangeobject *r) { return PyLong_AsSsize_t(r->length); } static PyObject * compute_item(rangeobject *r, PyObject *i) { PyObject *incr, *result; /* PyLong equivalent to: * return r->start + (i * r->step) */ incr = PyNumber_Multiply(i, r->step); if (!incr) return NULL; result = PyNumber_Add(r->start, incr); Py_DECREF(incr); return result; } static PyObject * compute_range_item(rangeobject *r, PyObject *arg) { int cmp_result; PyObject *i, *result; PyObject *zero = PyLong_FromLong(0); if (zero == NULL) return NULL; /* PyLong equivalent to: * if (arg < 0) { * i = r->length + arg * } else { * i = arg * } */ cmp_result = PyObject_RichCompareBool(arg, zero, Py_LT); if (cmp_result == -1) { Py_DECREF(zero); return NULL; } if (cmp_result == 1) { i = PyNumber_Add(r->length, arg); if (!i) { Py_DECREF(zero); return NULL; } } else { i = arg; Py_INCREF(i); } /* PyLong equivalent to: * if (i < 0 || i >= r->length) { * <report index out of bounds> * } */ cmp_result = PyObject_RichCompareBool(i, zero, Py_LT); Py_DECREF(zero); if (cmp_result == 0) { cmp_result = PyObject_RichCompareBool(i, r->length, Py_GE); } if (cmp_result == -1) { Py_DECREF(i); return NULL; } if (cmp_result == 1) { Py_DECREF(i); PyErr_SetString(PyExc_IndexError, "range object index out of range"); return NULL; } result = compute_item(r, i); Py_DECREF(i); return result; } static PyObject * range_item(rangeobject *r, Py_ssize_t i) { PyObject *res, *arg = PyLong_FromSsize_t(i); if (!arg) { return NULL; } res = compute_range_item(r, arg); Py_DECREF(arg); return res; } static PyObject * compute_slice(rangeobject *r, PyObject *_slice) { PySliceObject *slice = (PySliceObject *) _slice; rangeobject *result; PyObject *start = NULL, *stop = NULL, *step = NULL; PyObject *substart = NULL, *substop = NULL, *substep = NULL; int error; error = _PySlice_GetLongIndices(slice, r->length, &start, &stop, &step); if (error == -1) return NULL; substep = PyNumber_Multiply(r->step, step); if (substep == NULL) goto fail; Py_CLEAR(step); substart = compute_item(r, start); if (substart == NULL) goto fail; Py_CLEAR(start); substop = compute_item(r, stop); if (substop == NULL) goto fail; Py_CLEAR(stop); result = make_range_object(Py_TYPE(r), substart, substop, substep); if (result != NULL) { return (PyObject *) result; } fail: Py_XDECREF(start); Py_XDECREF(stop); Py_XDECREF(step); Py_XDECREF(substart); Py_XDECREF(substop); Py_XDECREF(substep); return NULL; } /* Assumes (PyLong_CheckExact(ob) || PyBool_Check(ob)) */ static int range_contains_long(rangeobject *r, PyObject *ob) { int cmp1, cmp2, cmp3; PyObject *tmp1 = NULL; PyObject *tmp2 = NULL; PyObject *zero = NULL; int result = -1; zero = PyLong_FromLong(0); if (zero == NULL) /* MemoryError in int(0) */ goto end; /* Check if the value can possibly be in the range. */ cmp1 = PyObject_RichCompareBool(r->step, zero, Py_GT); if (cmp1 == -1) goto end; if (cmp1 == 1) { /* positive steps: start <= ob < stop */ cmp2 = PyObject_RichCompareBool(r->start, ob, Py_LE); cmp3 = PyObject_RichCompareBool(ob, r->stop, Py_LT); } else { /* negative steps: stop < ob <= start */ cmp2 = PyObject_RichCompareBool(ob, r->start, Py_LE); cmp3 = PyObject_RichCompareBool(r->stop, ob, Py_LT); } if (cmp2 == -1 || cmp3 == -1) /* TypeError */ goto end; if (cmp2 == 0 || cmp3 == 0) { /* ob outside of range */ result = 0; goto end; } /* Check that the stride does not invalidate ob's membership. */ tmp1 = PyNumber_Subtract(ob, r->start); if (tmp1 == NULL) goto end; tmp2 = PyNumber_Remainder(tmp1, r->step); if (tmp2 == NULL) goto end; /* result = ((int(ob) - start) % step) == 0 */ result = PyObject_RichCompareBool(tmp2, zero, Py_EQ); end: Py_XDECREF(tmp1); Py_XDECREF(tmp2); Py_XDECREF(zero); return result; } static int range_contains(rangeobject *r, PyObject *ob) { if (PyLong_CheckExact(ob) || PyBool_Check(ob)) return range_contains_long(r, ob); return (int)_PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_CONTAINS); } /* Compare two range objects. Return 1 for equal, 0 for not equal and -1 on error. The algorithm is roughly the C equivalent of if r0 is r1: return True if len(r0) != len(r1): return False if not len(r0): return True if r0.start != r1.start: return False if len(r0) == 1: return True return r0.step == r1.step */ static int range_equals(rangeobject *r0, rangeobject *r1) { int cmp_result; PyObject *one; if (r0 == r1) return 1; cmp_result = PyObject_RichCompareBool(r0->length, r1->length, Py_EQ); /* Return False or error to the caller. */ if (cmp_result != 1) return cmp_result; cmp_result = PyObject_Not(r0->length); /* Return True or error to the caller. */ if (cmp_result != 0) return cmp_result; cmp_result = PyObject_RichCompareBool(r0->start, r1->start, Py_EQ); /* Return False or error to the caller. */ if (cmp_result != 1) return cmp_result; one = PyLong_FromLong(1); if (!one) return -1; cmp_result = PyObject_RichCompareBool(r0->length, one, Py_EQ); Py_DECREF(one); /* Return True or error to the caller. */ if (cmp_result != 0) return cmp_result; return PyObject_RichCompareBool(r0->step, r1->step, Py_EQ); } static PyObject * range_richcompare(PyObject *self, PyObject *other, int op) { int result; if (!PyRange_Check(other)) Py_RETURN_NOTIMPLEMENTED; switch (op) { case Py_NE: case Py_EQ: result = range_equals((rangeobject*)self, (rangeobject*)other); if (result == -1) return NULL; if (op == Py_NE) result = !result; if (result) Py_RETURN_TRUE; else Py_RETURN_FALSE; case Py_LE: case Py_GE: case Py_LT: case Py_GT: Py_RETURN_NOTIMPLEMENTED; default: PyErr_BadArgument(); return NULL; } } /* Hash function for range objects. Rough C equivalent of if not len(r): return hash((len(r), None, None)) if len(r) == 1: return hash((len(r), r.start, None)) return hash((len(r), r.start, r.step)) */ static Py_hash_t range_hash(rangeobject *r) { PyObject *t; Py_hash_t result = -1; int cmp_result; t = PyTuple_New(3); if (!t) return -1; Py_INCREF(r->length); PyTuple_SET_ITEM(t, 0, r->length); cmp_result = PyObject_Not(r->length); if (cmp_result == -1) goto end; if (cmp_result == 1) { Py_INCREF(Py_None); Py_INCREF(Py_None); PyTuple_SET_ITEM(t, 1, Py_None); PyTuple_SET_ITEM(t, 2, Py_None); } else { PyObject *one; Py_INCREF(r->start); PyTuple_SET_ITEM(t, 1, r->start); one = PyLong_FromLong(1); if (!one) goto end; cmp_result = PyObject_RichCompareBool(r->length, one, Py_EQ); Py_DECREF(one); if (cmp_result == -1) goto end; if (cmp_result == 1) { Py_INCREF(Py_None); PyTuple_SET_ITEM(t, 2, Py_None); } else { Py_INCREF(r->step); PyTuple_SET_ITEM(t, 2, r->step); } } result = PyObject_Hash(t); end: Py_DECREF(t); return result; } static PyObject * range_count(rangeobject *r, PyObject *ob) { if (PyLong_CheckExact(ob) || PyBool_Check(ob)) { int result = range_contains_long(r, ob); if (result == -1) return NULL; else if (result) return PyLong_FromLong(1); else return PyLong_FromLong(0); } else { Py_ssize_t count; count = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_COUNT); if (count == -1) return NULL; return PyLong_FromSsize_t(count); } } static PyObject * range_index(rangeobject *r, PyObject *ob) { int contains; if (!PyLong_CheckExact(ob) && !PyBool_Check(ob)) { Py_ssize_t index; index = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_INDEX); if (index == -1) return NULL; return PyLong_FromSsize_t(index); } contains = range_contains_long(r, ob); if (contains == -1) return NULL; if (contains) { PyObject *idx, *tmp = PyNumber_Subtract(ob, r->start); if (tmp == NULL) return NULL; /* idx = (ob - r.start) // r.step */ idx = PyNumber_FloorDivide(tmp, r->step); Py_DECREF(tmp); return idx; } /* object is not in the range */ PyErr_Format(PyExc_ValueError, "%R is not in range", ob); return NULL; } static PySequenceMethods range_as_sequence = { (lenfunc)range_length, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ (ssizeargfunc)range_item, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)range_contains, /* sq_contains */ }; static PyObject * range_repr(rangeobject *r) { Py_ssize_t istep; /* Check for special case values for printing. We don't always need the step value. We don't care about overflow. */ istep = PyNumber_AsSsize_t(r->step, NULL); if (istep == -1 && PyErr_Occurred()) { assert(!PyErr_ExceptionMatches(PyExc_OverflowError)); return NULL; } if (istep == 1) return PyUnicode_FromFormat("range(%R, %R)", r->start, r->stop); else return PyUnicode_FromFormat("range(%R, %R, %R)", r->start, r->stop, r->step); } /* Pickling support */ static PyObject * range_reduce(rangeobject *r, PyObject *args) { return Py_BuildValue("(O(OOO))", Py_TYPE(r), r->start, r->stop, r->step); } static PyObject * range_subscript(rangeobject* self, PyObject* item) { if (PyIndex_Check(item)) { PyObject *i, *result; i = PyNumber_Index(item); if (!i) return NULL; result = compute_range_item(self, i); Py_DECREF(i); return result; } if (PySlice_Check(item)) { return compute_slice(self, item); } PyErr_Format(PyExc_TypeError, "range indices must be integers or slices, not %.200s", item->ob_type->tp_name); return NULL; } static PyMappingMethods range_as_mapping = { (lenfunc)range_length, /* mp_length */ (binaryfunc)range_subscript, /* mp_subscript */ (objobjargproc)0, /* mp_ass_subscript */ }; static int range_bool(rangeobject* self) { return PyObject_IsTrue(self->length); } static PyNumberMethods range_as_number = { .nb_bool = (inquiry)range_bool, }; static PyObject * range_iter(PyObject *seq); static PyObject * range_reverse(PyObject *seq); PyDoc_STRVAR(reverse_doc, "Return a reverse iterator."); PyDoc_STRVAR(count_doc, "rangeobject.count(value) -> integer -- return number of occurrences of value"); PyDoc_STRVAR(index_doc, "rangeobject.index(value, [start, [stop]]) -> integer -- return index of value.\n" "Raise ValueError if the value is not present."); static PyMethodDef range_methods[] = { {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, reverse_doc}, {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS}, {"count", (PyCFunction)range_count, METH_O, count_doc}, {"index", (PyCFunction)range_index, METH_O, index_doc}, {NULL, NULL} /* sentinel */ }; static PyMemberDef range_members[] = { {"start", T_OBJECT_EX, offsetof(rangeobject, start), READONLY}, {"stop", T_OBJECT_EX, offsetof(rangeobject, stop), READONLY}, {"step", T_OBJECT_EX, offsetof(rangeobject, step), READONLY}, {0} }; PyTypeObject PyRange_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "range", /* Name of this type */ sizeof(rangeobject), /* Basic object size */ 0, /* Item size for varobject */ (destructor)range_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)range_repr, /* tp_repr */ &range_as_number, /* tp_as_number */ &range_as_sequence, /* tp_as_sequence */ &range_as_mapping, /* tp_as_mapping */ (hashfunc)range_hash, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ range_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ range_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ range_iter, /* tp_iter */ 0, /* tp_iternext */ range_methods, /* tp_methods */ range_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ range_new, /* tp_new */ }; /*********************** range Iterator **************************/ /* There are 2 types of iterators, one for C longs, the other for Python ints (ie, PyObjects). This should make iteration fast in the normal case, but possible for any numeric value. */ typedef struct { PyObject_HEAD long index; long start; long step; long len; } rangeiterobject; static PyObject * rangeiter_next(rangeiterobject *r) { if (r->index < r->len) /* cast to unsigned to avoid possible signed overflow in intermediate calculations. */ return PyLong_FromLong((long)(r->start + (unsigned long)(r->index++) * r->step)); return NULL; } static PyObject * rangeiter_len(rangeiterobject *r) { return PyLong_FromLong(r->len - r->index); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * rangeiter_reduce(rangeiterobject *r) { PyObject *start=NULL, *stop=NULL, *step=NULL; PyObject *range; /* create a range object for pickling */ start = PyLong_FromLong(r->start); if (start == NULL) goto err; stop = PyLong_FromLong(r->start + r->len * r->step); if (stop == NULL) goto err; step = PyLong_FromLong(r->step); if (step == NULL) goto err; range = (PyObject*)make_range_object(&PyRange_Type, start, stop, step); if (range == NULL) goto err; /* return the result */ return Py_BuildValue("N(N)i", _PyObject_GetBuiltin("iter"), range, r->index); err: Py_XDECREF(start); Py_XDECREF(stop); Py_XDECREF(step); return NULL; } static PyObject * rangeiter_setstate(rangeiterobject *r, PyObject *state) { long index = PyLong_AsLong(state); if (index == -1 && PyErr_Occurred()) return NULL; /* silently clip the index value */ if (index < 0) index = 0; else if (index > r->len) index = r->len; /* exhausted iterator */ r->index = index; Py_RETURN_NONE; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef rangeiter_methods[] = { {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)rangeiter_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)rangeiter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; static PyObject *rangeiter_new(PyTypeObject *, PyObject *args, PyObject *kw); PyTypeObject PyRangeIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "range_iterator", /* tp_name */ sizeof(rangeiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)PyObject_Del, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)rangeiter_next, /* tp_iternext */ rangeiter_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ rangeiter_new, /* tp_new */ }; /* Return number of items in range (lo, hi, step). step != 0 * required. The result always fits in an unsigned long. */ static unsigned long get_len_of_range(long lo, long hi, long step) { /* ------------------------------------------------------------- If step > 0 and lo >= hi, or step < 0 and lo <= hi, the range is empty. Else for step > 0, if n values are in the range, the last one is lo + (n-1)*step, which must be <= hi-1. Rearranging, n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so the RHS is non-negative and so truncation is the same as the floor. Letting M be the largest positive long, the worst case for the RHS numerator is hi=M, lo=-M-1, and then hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough precision to compute the RHS exactly. The analysis for step < 0 is similar. ---------------------------------------------------------------*/ assert(step != 0); if (step > 0 && lo < hi) return 1UL + (hi - 1UL - lo) / step; else if (step < 0 && lo > hi) return 1UL + (lo - 1UL - hi) / (0UL - step); else return 0UL; } /* Initialize a rangeiter object. If the length of the rangeiter object is not representable as a C long, OverflowError is raised. */ static PyObject * fast_range_iter(long start, long stop, long step) { rangeiterobject *it = PyObject_New(rangeiterobject, &PyRangeIter_Type); unsigned long ulen; if (it == NULL) return NULL; it->start = start; it->step = step; ulen = get_len_of_range(start, stop, step); if (ulen > (unsigned long)LONG_MAX) { Py_DECREF(it); PyErr_SetString(PyExc_OverflowError, "range too large to represent as a range_iterator"); return NULL; } it->len = (long)ulen; it->index = 0; return (PyObject *)it; } static PyObject * rangeiter_new(PyTypeObject *type, PyObject *args, PyObject *kw) { long start, stop, step; if (PyErr_WarnEx(PyExc_DeprecationWarning, "range_iterator(): creating instances of range_iterator " "by calling range_iterator type is deprecated", 1)) { return NULL; } if (!_PyArg_NoKeywords("range_iterator()", kw)) { return NULL; } if (!PyArg_ParseTuple(args, "lll;range_iterator() requires 3 int arguments", &start, &stop, &step)) { return NULL; } if (step == 0) { PyErr_SetString(PyExc_ValueError, "range_iterator() arg 3 must not be zero"); return NULL; } return fast_range_iter(start, stop, step); } typedef struct { PyObject_HEAD PyObject *index; PyObject *start; PyObject *step; PyObject *len; } longrangeiterobject; static PyObject * longrangeiter_len(longrangeiterobject *r, PyObject *no_args) { return PyNumber_Subtract(r->len, r->index); } static PyObject * longrangeiter_reduce(longrangeiterobject *r) { PyObject *product, *stop=NULL; PyObject *range; /* create a range object for pickling. Must calculate the "stop" value */ product = PyNumber_Multiply(r->len, r->step); if (product == NULL) return NULL; stop = PyNumber_Add(r->start, product); Py_DECREF(product); if (stop == NULL) return NULL; Py_INCREF(r->start); Py_INCREF(r->step); range = (PyObject*)make_range_object(&PyRange_Type, r->start, stop, r->step); if (range == NULL) { Py_DECREF(r->start); Py_DECREF(stop); Py_DECREF(r->step); return NULL; } /* return the result */ return Py_BuildValue("N(N)O", _PyObject_GetBuiltin("iter"), range, r->index); } static PyObject * longrangeiter_setstate(longrangeiterobject *r, PyObject *state) { int cmp; /* clip the value */ PyObject *zero = PyLong_FromLong(0); if (zero == NULL) return NULL; cmp = PyObject_RichCompareBool(state, zero, Py_LT); if (cmp > 0) { Py_XSETREF(r->index, zero); Py_RETURN_NONE; } Py_DECREF(zero); if (cmp < 0) return NULL; cmp = PyObject_RichCompareBool(r->len, state, Py_LT); if (cmp < 0) return NULL; if (cmp > 0) state = r->len; Py_INCREF(state); Py_XSETREF(r->index, state); Py_RETURN_NONE; } static PyMethodDef longrangeiter_methods[] = { {"__length_hint__", (PyCFunction)longrangeiter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)longrangeiter_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)longrangeiter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; static void longrangeiter_dealloc(longrangeiterobject *r) { Py_XDECREF(r->index); Py_XDECREF(r->start); Py_XDECREF(r->step); Py_XDECREF(r->len); PyObject_Del(r); } static PyObject * longrangeiter_next(longrangeiterobject *r) { PyObject *one, *product, *new_index, *result; if (PyObject_RichCompareBool(r->index, r->len, Py_LT) != 1) return NULL; one = PyLong_FromLong(1); if (!one) return NULL; new_index = PyNumber_Add(r->index, one); Py_DECREF(one); if (!new_index) return NULL; product = PyNumber_Multiply(r->index, r->step); if (!product) { Py_DECREF(new_index); return NULL; } result = PyNumber_Add(r->start, product); Py_DECREF(product); if (result) { Py_SETREF(r->index, new_index); } else { Py_DECREF(new_index); } return result; } PyTypeObject PyLongRangeIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "longrange_iterator", /* tp_name */ sizeof(longrangeiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)longrangeiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)longrangeiter_next, /* tp_iternext */ longrangeiter_methods, /* tp_methods */ 0, }; static PyObject * range_iter(PyObject *seq) { rangeobject *r = (rangeobject *)seq; longrangeiterobject *it; long lstart, lstop, lstep; PyObject *int_it; assert(PyRange_Check(seq)); /* If all three fields and the length convert to long, use the int * version */ lstart = PyLong_AsLong(r->start); if (lstart == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } lstop = PyLong_AsLong(r->stop); if (lstop == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } lstep = PyLong_AsLong(r->step); if (lstep == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } int_it = fast_range_iter(lstart, lstop, lstep); if (int_it == NULL && PyErr_ExceptionMatches(PyExc_OverflowError)) { PyErr_Clear(); goto long_range; } return (PyObject *)int_it; long_range: it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type); if (it == NULL) return NULL; /* Do all initialization here, so we can DECREF on failure. */ it->start = r->start; it->step = r->step; it->len = r->length; Py_INCREF(it->start); Py_INCREF(it->step); Py_INCREF(it->len); it->index = PyLong_FromLong(0); if (!it->index) goto create_failure; return (PyObject *)it; create_failure: Py_DECREF(it); return NULL; } static PyObject * range_reverse(PyObject *seq) { rangeobject *range = (rangeobject*) seq; longrangeiterobject *it; PyObject *one, *sum, *diff, *product; long lstart, lstop, lstep, new_start, new_stop; unsigned long ulen; assert(PyRange_Check(seq)); /* reversed(range(start, stop, step)) can be expressed as range(start+(n-1)*step, start-step, -step), where n is the number of integers in the range. If each of start, stop, step, -step, start-step, and the length of the iterator is representable as a C long, use the int version. This excludes some cases where the reversed range is representable as a range_iterator, but it's good enough for common cases and it makes the checks simple. */ lstart = PyLong_AsLong(range->start); if (lstart == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } lstop = PyLong_AsLong(range->stop); if (lstop == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } lstep = PyLong_AsLong(range->step); if (lstep == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } /* check for possible overflow of -lstep */ if (lstep == LONG_MIN) goto long_range; /* check for overflow of lstart - lstep: for lstep > 0, need only check whether lstart - lstep < LONG_MIN. for lstep < 0, need only check whether lstart - lstep > LONG_MAX Rearrange these inequalities as: lstart - LONG_MIN < lstep (lstep > 0) LONG_MAX - lstart < -lstep (lstep < 0) and compute both sides as unsigned longs, to avoid the possibility of undefined behaviour due to signed overflow. */ if (lstep > 0) { if ((unsigned long)lstart - LONG_MIN < (unsigned long)lstep) goto long_range; } else { if (LONG_MAX - (unsigned long)lstart < 0UL - lstep) goto long_range; } ulen = get_len_of_range(lstart, lstop, lstep); if (ulen > (unsigned long)LONG_MAX) goto long_range; new_stop = lstart - lstep; new_start = (long)(new_stop + ulen * lstep); return fast_range_iter(new_start, new_stop, -lstep); long_range: it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type); if (it == NULL) return NULL; it->index = it->start = it->step = NULL; /* start + (len - 1) * step */ it->len = range->length; Py_INCREF(it->len); one = PyLong_FromLong(1); if (!one) goto create_failure; diff = PyNumber_Subtract(it->len, one); Py_DECREF(one); if (!diff) goto create_failure; product = PyNumber_Multiply(diff, range->step); Py_DECREF(diff); if (!product) goto create_failure; sum = PyNumber_Add(range->start, product); Py_DECREF(product); it->start = sum; if (!it->start) goto create_failure; it->step = PyNumber_Negative(range->step); if (!it->step) goto create_failure; it->index = PyLong_FromLong(0); if (!it->index) goto create_failure; return (PyObject *)it; create_failure: Py_DECREF(it); return NULL; }
39,280
1,312
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/odictobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/odictobject.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Objects/dict-common.h" /* clang-format off */ /* Ordered Dictionary object implementation. This implementation is necessarily explicitly equivalent to the pure Python OrderedDict class in Lib/collections/__init__.py. The strategy there involves using a doubly-linked-list to capture the order. We keep to that strategy, using a lower-level linked-list. About the Linked-List ===================== For the linked list we use a basic doubly-linked-list. Using a circularly- linked-list does have some benefits, but they don't apply so much here since OrderedDict is focused on the ends of the list (for the most part). Furthermore, there are some features of generic linked-lists that we simply don't need for OrderedDict. Thus a simple custom implementation meets our needs. Alternatives to our simple approach include the QCIRCLE_* macros from BSD's queue.h, and the linux's list.h. Getting O(1) Node Lookup ------------------------ One invariant of Python's OrderedDict is that it preserves time complexity of dict's methods, particularly the O(1) operations. Simply adding a linked-list on top of dict is not sufficient here; operations for nodes in the middle of the linked-list implicitly require finding the node first. With a simple linked-list like we're using, that is an O(n) operation. Consequently, methods like __delitem__() would change from O(1) to O(n), which is unacceptable. In order to preserve O(1) performance for node removal (finding nodes), we must do better than just looping through the linked-list. Here are options we've considered: 1. use a second dict to map keys to nodes (a la the pure Python version). 2. keep a simple hash table mirroring the order of dict's, mapping each key to the corresponding node in the linked-list. 3. use a version of shared keys (split dict) that allows non-unicode keys. 4. have the value stored for each key be a (value, node) pair, and adjust __getitem__(), get(), etc. accordingly. The approach with the least performance impact (time and space) is #2, mirroring the key order of dict's dk_entries with an array of node pointers. While lookdict() and friends (dk_lookup) don't give us the index into the array, we make use of pointer arithmetic to get that index. An alternative would be to refactor lookdict() to provide the index, explicitly exposing the implementation detail. We could even just use a custom lookup function for OrderedDict that facilitates our need. However, both approaches are significantly more complicated than just using pointer arithmetic. The catch with mirroring the hash table ordering is that we have to keep the ordering in sync through any dict resizes. However, that order only matters during node lookup. We can simply defer any potential resizing until we need to do a lookup. Linked-List Nodes ----------------- The current implementation stores a pointer to the associated key only. One alternative would be to store a pointer to the PyDictKeyEntry instead. This would save one pointer de-reference per item, which is nice during calls to values() and items(). However, it adds unnecessary overhead otherwise, so we stick with just the key. Linked-List API --------------- As noted, the linked-list implemented here does not have all the bells and whistles. However, we recognize that the implementation may need to change to accommodate performance improvements or extra functionality. To that end, we use a simple API to interact with the linked-list. Here's a summary of the methods/macros: Node info: * _odictnode_KEY(node) * _odictnode_VALUE(od, node) * _odictnode_PREV(node) * _odictnode_NEXT(node) Linked-List info: * _odict_FIRST(od) * _odict_LAST(od) * _odict_EMPTY(od) * _odict_FOREACH(od, node) - used in place of `for (node=...)` For adding nodes: * _odict_add_head(od, node) * _odict_add_tail(od, node) * _odict_add_new_node(od, key, hash) For removing nodes: * _odict_clear_node(od, node, key, hash) * _odict_clear_nodes(od, clear_each) Others: * _odict_find_node_hash(od, key, hash) * _odict_find_node(od, key) * _odict_keys_equal(od1, od2) And here's a look at how the linked-list relates to the OrderedDict API: ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === === method key val prev next mem 1st last empty iter find add rmv clr keq ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === === __del__ ~ X __delitem__ free ~ node __eq__ ~ X __iter__ X X __new__ X X __reduce__ X ~ X __repr__ X X X __reversed__ X X __setitem__ key __sizeof__ size X clear ~ ~ X copy X X X items X X X keys X X move_to_end X X X ~ h/t key pop free key popitem X X free X X node setdefault ~ ? ~ values X X ============ === === ==== ==== ==== === ==== ===== ==== ==== === ==== === === __delitem__ is the only method that directly relies on finding an arbitrary node in the linked-list. Everything else is iteration or relates to the ends of the linked-list. Situation that Endangers Consistency ------------------------------------ Using a raw linked-list for OrderedDict exposes a key situation that can cause problems. If a node is stored in a variable, there is a chance that the node may have been deallocated before the variable gets used, thus potentially leading to a segmentation fault. A key place where this shows up is during iteration through the linked list (via _odict_FOREACH or otherwise). A number of solutions are available to resolve this situation: * defer looking up the node until as late as possible and certainly after any code that could possibly result in a deletion; * if the node is needed both before and after a point where the node might be removed, do a check before using the node at the "after" location to see if the node is still valid; * like the last one, but simply pull the node again to ensure it's right; * keep the key in the variable instead of the node and then look up the node using the key at the point where the node is needed (this is what we do for the iterators). Another related problem, preserving consistent ordering during iteration, is described below. That one is not exclusive to using linked-lists. Challenges from Subclassing dict ================================ OrderedDict subclasses dict, which is an unusual relationship between two builtin types (other than the base object type). Doing so results in some complication and deserves further explanation. There are two things to consider here. First, in what circumstances or with what adjustments can OrderedDict be used as a drop-in replacement for dict (at the C level)? Second, how can the OrderedDict implementation leverage the dict implementation effectively without introducing unnecessary coupling or inefficiencies? This second point is reflected here and in the implementation, so the further focus is on the first point. It is worth noting that for overridden methods, the dict implementation is deferred to as much as possible. Furthermore, coupling is limited to as little as is reasonable. Concrete API Compatibility -------------------------- Use of the concrete C-API for dict (PyDict_*) with OrderedDict is problematic. (See http://bugs.python.org/issue10977.) The concrete API has a number of hard-coded assumptions tied to the dict implementation. This is, in part, due to performance reasons, which is understandable given the part dict plays in Python. Any attempt to replace dict with OrderedDict for any role in the interpreter (e.g. **kwds) faces a challenge. Such any effort must recognize that the instances in affected locations currently interact with the concrete API. Here are some ways to address this challenge: 1. Change the relevant usage of the concrete API in CPython and add PyDict_CheckExact() calls to each of the concrete API functions. 2. Adjust the relevant concrete API functions to explicitly accommodate OrderedDict. 3. As with #1, add the checks, but improve the abstract API with smart fast paths for dict and OrderedDict, and refactor CPython to use the abstract API. Improvements to the abstract API would be valuable regardless. Adding the checks to the concrete API would help make any interpreter switch to OrderedDict less painful for extension modules. However, this won't work. The equivalent C API call to `dict.__setitem__(obj, k, v)` is 'PyDict_SetItem(obj, k, v)`. This illustrates how subclasses in C call the base class's methods, since there is no equivalent of super() in the C API. Calling into Python for parent class API would work, but some extension modules already rely on this feature of the concrete API. For reference, here is a breakdown of some of the dict concrete API: ========================== ============= ======================= concrete API uses abstract API ========================== ============= ======================= PyDict_Check PyMapping_Check (PyDict_CheckExact) - (PyDict_New) - (PyDictProxy_New) - PyDict_Clear - PyDict_Contains PySequence_Contains PyDict_Copy - PyDict_SetItem PyObject_SetItem PyDict_SetItemString PyMapping_SetItemString PyDict_DelItem PyMapping_DelItem PyDict_DelItemString PyMapping_DelItemString PyDict_GetItem - PyDict_GetItemWithError PyObject_GetItem _PyDict_GetItemIdWithError - PyDict_GetItemString PyMapping_GetItemString PyDict_Items PyMapping_Items PyDict_Keys PyMapping_Keys PyDict_Values PyMapping_Values PyDict_Size PyMapping_Size PyMapping_Length PyDict_Next PyIter_Next _PyDict_Next - PyDict_Merge - PyDict_Update - PyDict_MergeFromSeq2 - PyDict_ClearFreeList - - PyMapping_HasKeyString - PyMapping_HasKey ========================== ============= ======================= The dict Interface Relative to OrderedDict ========================================== Since OrderedDict subclasses dict, understanding the various methods and attributes of dict is important for implementing OrderedDict. Relevant Type Slots ------------------- ================= ================ =================== ================ slot attribute object dict ================= ================ =================== ================ tp_dealloc - object_dealloc dict_dealloc tp_repr __repr__ object_repr dict_repr sq_contains __contains__ - dict_contains mp_length __len__ - dict_length mp_subscript __getitem__ - dict_subscript mp_ass_subscript __setitem__ - dict_ass_sub __delitem__ tp_hash __hash__ _Py_HashPointer ..._HashNotImpl tp_str __str__ object_str - tp_getattro __getattribute__ ..._GenericGetAttr (repeated) __getattr__ tp_setattro __setattr__ ..._GenericSetAttr (disabled) tp_doc __doc__ (literal) dictionary_doc tp_traverse - - dict_traverse tp_clear - - dict_tp_clear tp_richcompare __eq__ object_richcompare dict_richcompare __ne__ tp_weaklistoffset (__weakref__) - - tp_iter __iter__ - dict_iter tp_dictoffset (__dict__) - - tp_init __init__ object_init dict_init tp_alloc - PyType_GenericAlloc (repeated) tp_new __new__ object_new dict_new tp_free - PyObject_Del PyObject_GC_Del ================= ================ =================== ================ Relevant Methods ---------------- ================ =================== =============== method object dict ================ =================== =============== __reduce__ object_reduce - __sizeof__ object_sizeof dict_sizeof clear - dict_clear copy - dict_copy fromkeys - dict_fromkeys get - dict_get items - dictitems_new keys - dictkeys_new pop - dict_pop popitem - dict_popitem setdefault - dict_setdefault update - dict_update values - dictvalues_new ================ =================== =============== Pure Python OrderedDict ======================= As already noted, compatibility with the pure Python OrderedDict implementation is a key goal of this C implementation. To further that goal, here's a summary of how OrderedDict-specific methods are implemented in collections/__init__.py. Also provided is an indication of which methods directly mutate or iterate the object, as well as any relationship with the underlying linked-list. ============= ============== == ================ === === ==== method impl used ll uses inq mut iter ============= ============== == ================ === === ==== __contains__ dict - - X __delitem__ OrderedDict Y dict.__delitem__ X __eq__ OrderedDict N OrderedDict ~ dict.__eq__ __iter__ __getitem__ dict - - X __iter__ OrderedDict Y - X __init__ OrderedDict N update __len__ dict - - X __ne__ MutableMapping - __eq__ ~ __reduce__ OrderedDict N OrderedDict ~ __iter__ __getitem__ __repr__ OrderedDict N __class__ ~ items __reversed__ OrderedDict Y - X __setitem__ OrderedDict Y __contains__ X dict.__setitem__ __sizeof__ OrderedDict Y __len__ ~ __dict__ clear OrderedDict Y dict.clear X copy OrderedDict N __class__ __init__ fromkeys OrderedDict N __setitem__ get dict - - ~ items MutableMapping - ItemsView X keys MutableMapping - KeysView X move_to_end OrderedDict Y - X pop OrderedDict N __contains__ X __getitem__ __delitem__ popitem OrderedDict Y dict.pop X setdefault OrderedDict N __contains__ ~ __getitem__ __setitem__ update MutableMapping - __setitem__ ~ values MutableMapping - ValuesView X ============= ============== == ================ === === ==== __reversed__ and move_to_end are both exclusive to OrderedDict. C OrderedDict Implementation ============================ ================= ================ slot impl ================= ================ tp_dealloc odict_dealloc tp_repr odict_repr mp_ass_subscript odict_ass_sub tp_doc odict_doc tp_traverse odict_traverse tp_clear odict_tp_clear tp_richcompare odict_richcompare tp_weaklistoffset (offset) tp_iter odict_iter tp_dictoffset (offset) tp_init odict_init tp_alloc (repeated) ================= ================ ================= ================ method impl ================= ================ __reduce__ odict_reduce __sizeof__ odict_sizeof clear odict_clear copy odict_copy fromkeys odict_fromkeys items odictitems_new keys odictkeys_new pop odict_pop popitem odict_popitem setdefault odict_setdefault update odict_update values odictvalues_new ================= ================ Inherited unchanged from object/dict: ================ ========================== method type field ================ ========================== - tp_free __contains__ tp_as_sequence.sq_contains __getattr__ tp_getattro __getattribute__ tp_getattro __getitem__ tp_as_mapping.mp_subscript __hash__ tp_hash __len__ tp_as_mapping.mp_length __setattr__ tp_setattro __str__ tp_str get - ================ ========================== Other Challenges ================ Preserving Ordering During Iteration ------------------------------------ During iteration through an OrderedDict, it is possible that items could get added, removed, or reordered. For a linked-list implementation, as with some other implementations, that situation may lead to undefined behavior. The documentation for dict mentions this in the `iter()` section of http://docs.python.org/3.4/library/stdtypes.html#dictionary-view-objects. In this implementation we follow dict's lead (as does the pure Python implementation) for __iter__(), keys(), values(), and items(). For internal iteration (using _odict_FOREACH or not), there is still the risk that not all nodes that we expect to be seen in the loop actually get seen. Thus, we are careful in each of those places to ensure that they are. This comes, of course, at a small price at each location. The solutions are much the same as those detailed in the `Situation that Endangers Consistency` section above. Potential Optimizations ======================= * Allocate the nodes as a block via od_fast_nodes instead of individually. - Set node->key to NULL to indicate the node is not-in-use. - Add _odict_EXISTS()? - How to maintain consistency across resizes? Existing node pointers would be invalidated after a resize, which is particularly problematic for the iterators. * Use a more stream-lined implementation of update() and, likely indirectly, __init__(). */ /* TODO sooner: - reentrancy (make sure everything is at a thread-safe state when calling into Python). I've already checked this multiple times, but want to make one more pass. - add unit tests for reentrancy? later: - make the dict views support the full set API (the pure Python impl does) - implement a fuller MutableMapping API in C? - move the MutableMapping implementation to abstract.c? - optimize mutablemapping_update - use PyObject_MALLOC (small object allocator) for odict nodes? - support subclasses better (e.g. in odict_richcompare) */ typedef struct _odictnode _ODictNode; /* PyODictObject */ struct _odictobject { PyDictObject od_dict; /* the underlying dict */ _ODictNode *od_first; /* first node in the linked list, if any */ _ODictNode *od_last; /* last node in the linked list, if any */ /* od_fast_nodes, od_fast_nodes_size and od_resize_sentinel are managed * by _odict_resize(). * Note that we rely on implementation details of dict for both. */ _ODictNode **od_fast_nodes; /* hash table that mirrors the dict table */ Py_ssize_t od_fast_nodes_size; void *od_resize_sentinel; /* changes if odict should be resized */ size_t od_state; /* incremented whenever the LL changes */ PyObject *od_inst_dict; /* OrderedDict().__dict__ */ PyObject *od_weakreflist; /* holds weakrefs to the odict */ }; /* ---------------------------------------------- * odict keys (a simple doubly-linked list) */ struct _odictnode { PyObject *key; Py_hash_t hash; _ODictNode *next; _ODictNode *prev; }; #define _odictnode_KEY(node) \ (node->key) #define _odictnode_HASH(node) \ (node->hash) /* borrowed reference */ #define _odictnode_VALUE(node, od) \ PyODict_GetItemWithError((PyObject *)od, _odictnode_KEY(node)) #define _odictnode_PREV(node) (node->prev) #define _odictnode_NEXT(node) (node->next) #define _odict_FIRST(od) (((PyODictObject *)od)->od_first) #define _odict_LAST(od) (((PyODictObject *)od)->od_last) #define _odict_EMPTY(od) (_odict_FIRST(od) == NULL) #define _odict_FOREACH(od, node) \ for (node = _odict_FIRST(od); node != NULL; node = _odictnode_NEXT(node)) /* Return the index into the hash table, regardless of a valid node. */ static Py_ssize_t _odict_get_index_raw(PyODictObject *od, PyObject *key, Py_hash_t hash) { PyObject **value_addr = NULL; PyDictKeysObject *keys = ((PyDictObject *)od)->ma_keys; Py_ssize_t ix; ix = (keys->dk_lookup)((PyDictObject *)od, key, hash, &value_addr, NULL); if (ix == DKIX_EMPTY) { return keys->dk_nentries; /* index of new entry */ } if (ix < 0) return -1; /* We use pointer arithmetic to get the entry's index into the table. */ return ix; } /* Replace od->od_fast_nodes with a new table matching the size of dict's. */ static int _odict_resize(PyODictObject *od) { Py_ssize_t size, i; _ODictNode **fast_nodes, *node; /* Initialize a new "fast nodes" table. */ size = ((PyDictObject *)od)->ma_keys->dk_size; fast_nodes = PyMem_NEW(_ODictNode *, size); if (fast_nodes == NULL) { PyErr_NoMemory(); return -1; } for (i = 0; i < size; i++) fast_nodes[i] = NULL; /* Copy the current nodes into the table. */ _odict_FOREACH(od, node) { i = _odict_get_index_raw(od, _odictnode_KEY(node), _odictnode_HASH(node)); if (i < 0) { PyMem_FREE(fast_nodes); return -1; } fast_nodes[i] = node; } /* Replace the old fast nodes table. */ PyMem_FREE(od->od_fast_nodes); od->od_fast_nodes = fast_nodes; od->od_fast_nodes_size = size; od->od_resize_sentinel = ((PyDictObject *)od)->ma_keys; return 0; } /* Return the index into the hash table, regardless of a valid node. */ static Py_ssize_t _odict_get_index(PyODictObject *od, PyObject *key, Py_hash_t hash) { PyDictKeysObject *keys; assert(key != NULL); keys = ((PyDictObject *)od)->ma_keys; /* Ensure od_fast_nodes and dk_entries are in sync. */ if (od->od_resize_sentinel != keys || od->od_fast_nodes_size != keys->dk_size) { int resize_res = _odict_resize(od); if (resize_res < 0) return -1; } return _odict_get_index_raw(od, key, hash); } /* Returns NULL if there was some error or the key was not found. */ static _ODictNode * _odict_find_node_hash(PyODictObject *od, PyObject *key, Py_hash_t hash) { Py_ssize_t index; if (_odict_EMPTY(od)) return NULL; index = _odict_get_index(od, key, hash); if (index < 0) return NULL; assert(od->od_fast_nodes != NULL); return od->od_fast_nodes[index]; } static _ODictNode * _odict_find_node(PyODictObject *od, PyObject *key) { Py_ssize_t index; Py_hash_t hash; if (_odict_EMPTY(od)) return NULL; hash = PyObject_Hash(key); if (hash == -1) return NULL; index = _odict_get_index(od, key, hash); if (index < 0) return NULL; assert(od->od_fast_nodes != NULL); return od->od_fast_nodes[index]; } static void _odict_add_head(PyODictObject *od, _ODictNode *node) { _odictnode_PREV(node) = NULL; _odictnode_NEXT(node) = _odict_FIRST(od); if (_odict_FIRST(od) == NULL) _odict_LAST(od) = node; else _odictnode_PREV(_odict_FIRST(od)) = node; _odict_FIRST(od) = node; od->od_state++; } static void _odict_add_tail(PyODictObject *od, _ODictNode *node) { _odictnode_PREV(node) = _odict_LAST(od); _odictnode_NEXT(node) = NULL; if (_odict_LAST(od) == NULL) _odict_FIRST(od) = node; else _odictnode_NEXT(_odict_LAST(od)) = node; _odict_LAST(od) = node; od->od_state++; } /* adds the node to the end of the list */ static int _odict_add_new_node(PyODictObject *od, PyObject *key, Py_hash_t hash) { Py_ssize_t i; _ODictNode *node; Py_INCREF(key); i = _odict_get_index(od, key, hash); if (i < 0) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); return -1; } assert(od->od_fast_nodes != NULL); if (od->od_fast_nodes[i] != NULL) { /* We already have a node for the key so there's no need to add one. */ Py_DECREF(key); return 0; } /* must not be added yet */ node = (_ODictNode *)PyMem_MALLOC(sizeof(_ODictNode)); if (node == NULL) { Py_DECREF(key); PyErr_NoMemory(); return -1; } _odictnode_KEY(node) = key; _odictnode_HASH(node) = hash; _odict_add_tail(od, node); od->od_fast_nodes[i] = node; return 0; } /* Putting the decref after the free causes problems. */ #define _odictnode_DEALLOC(node) \ do { \ Py_DECREF(_odictnode_KEY(node)); \ PyMem_FREE((void *)node); \ } while (0) /* Repeated calls on the same node are no-ops. */ static void _odict_remove_node(PyODictObject *od, _ODictNode *node) { if (_odict_FIRST(od) == node) _odict_FIRST(od) = _odictnode_NEXT(node); else if (_odictnode_PREV(node) != NULL) _odictnode_NEXT(_odictnode_PREV(node)) = _odictnode_NEXT(node); if (_odict_LAST(od) == node) _odict_LAST(od) = _odictnode_PREV(node); else if (_odictnode_NEXT(node) != NULL) _odictnode_PREV(_odictnode_NEXT(node)) = _odictnode_PREV(node); _odictnode_PREV(node) = NULL; _odictnode_NEXT(node) = NULL; od->od_state++; } /* If someone calls PyDict_DelItem() directly on an OrderedDict, we'll get all sorts of problems here. In PyODict_DelItem we make sure to call _odict_clear_node first. This matters in the case of colliding keys. Suppose we add 3 keys: [A, B, C], where the hash of C collides with A and the next possible index in the hash table is occupied by B. If we remove B then for C the dict's looknode func will give us the old index of B instead of the index we got before deleting B. However, the node for C in od_fast_nodes is still at the old dict index of C. Thus to be sure things don't get out of sync, we clear the node in od_fast_nodes *before* calling PyDict_DelItem. The same must be done for any other OrderedDict operations where we modify od_fast_nodes. */ static int _odict_clear_node(PyODictObject *od, _ODictNode *node, PyObject *key, Py_hash_t hash) { Py_ssize_t i; assert(key != NULL); if (_odict_EMPTY(od)) { /* Let later code decide if this is a KeyError. */ return 0; } i = _odict_get_index(od, key, hash); if (i < 0) return PyErr_Occurred() ? -1 : 0; assert(od->od_fast_nodes != NULL); if (node == NULL) node = od->od_fast_nodes[i]; assert(node == od->od_fast_nodes[i]); if (node == NULL) { /* Let later code decide if this is a KeyError. */ return 0; } // Now clear the node. od->od_fast_nodes[i] = NULL; _odict_remove_node(od, node); _odictnode_DEALLOC(node); return 0; } static void _odict_clear_nodes(PyODictObject *od) { _ODictNode *node, *next; PyMem_FREE(od->od_fast_nodes); od->od_fast_nodes = NULL; od->od_fast_nodes_size = 0; od->od_resize_sentinel = NULL; node = _odict_FIRST(od); _odict_FIRST(od) = NULL; _odict_LAST(od) = NULL; while (node != NULL) { next = _odictnode_NEXT(node); _odictnode_DEALLOC(node); node = next; } } /* There isn't any memory management of nodes past this point. */ #undef _odictnode_DEALLOC static int _odict_keys_equal(PyODictObject *a, PyODictObject *b) { _ODictNode *node_a, *node_b; node_a = _odict_FIRST(a); node_b = _odict_FIRST(b); while (1) { if (node_a == NULL && node_b == NULL) /* success: hit the end of each at the same time */ return 1; else if (node_a == NULL || node_b == NULL) /* unequal length */ return 0; else { int res = PyObject_RichCompareBool( (PyObject *)_odictnode_KEY(node_a), (PyObject *)_odictnode_KEY(node_b), Py_EQ); if (res < 0) return res; else if (res == 0) return 0; /* otherwise it must match, so move on to the next one */ node_a = _odictnode_NEXT(node_a); node_b = _odictnode_NEXT(node_b); } } } /* ---------------------------------------------- * OrderedDict mapping methods */ /* mp_ass_subscript: __setitem__() and __delitem__() */ static int odict_mp_ass_sub(PyODictObject *od, PyObject *v, PyObject *w) { if (w == NULL) return PyODict_DelItem((PyObject *)od, v); else return PyODict_SetItem((PyObject *)od, v, w); } /* tp_as_mapping */ static PyMappingMethods odict_as_mapping = { 0, /*mp_length*/ 0, /*mp_subscript*/ (objobjargproc)odict_mp_ass_sub, /*mp_ass_subscript*/ }; /* ---------------------------------------------- * OrderedDict methods */ /* __delitem__() */ PyDoc_STRVAR(odict_delitem__doc__, "od.__delitem__(y) <==> del od[y]"); /* __eq__() */ PyDoc_STRVAR(odict_eq__doc__, "od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive \n\ while comparison to a regular mapping is order-insensitive.\n\ "); /* forward */ static PyObject * odict_richcompare(PyObject *v, PyObject *w, int op); static PyObject * odict_eq(PyObject *a, PyObject *b) { return odict_richcompare(a, b, Py_EQ); } /* __init__() */ PyDoc_STRVAR(odict_init__doc__, "Initialize an ordered dictionary. The signature is the same as\n\ regular dictionaries. Keyword argument order is preserved.\n\ \n\ "); /* forward */ static int odict_init(PyObject *self, PyObject *args, PyObject *kwds); /* __iter__() */ PyDoc_STRVAR(odict_iter__doc__, "od.__iter__() <==> iter(od)"); static PyObject * odict_iter(PyODictObject *self); /* forward */ /* __ne__() */ /* Mapping.__ne__() does not have a docstring. */ PyDoc_STRVAR(odict_ne__doc__, ""); static PyObject * odict_ne(PyObject *a, PyObject *b) { return odict_richcompare(a, b, Py_NE); } /* __repr__() */ PyDoc_STRVAR(odict_repr__doc__, "od.__repr__() <==> repr(od)"); static PyObject * odict_repr(PyODictObject *self); /* forward */ /* __setitem__() */ PyDoc_STRVAR(odict_setitem__doc__, "od.__setitem__(i, y) <==> od[i]=y"); /* fromkeys() */ PyDoc_STRVAR(odict_fromkeys__doc__, "OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.\n\ If not specified, the value defaults to None.\n\ \n\ "); static PyObject * odict_fromkeys(PyObject *cls, PyObject *args, PyObject *kwargs) { static char *kwlist[] = {"iterable", "value", 0}; PyObject *seq; PyObject *value = Py_None; /* both borrowed */ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:fromkeys", kwlist, &seq, &value)) { return NULL; } return _PyDict_FromKeys(cls, seq, value); } /* __sizeof__() */ /* OrderedDict.__sizeof__() does not have a docstring. */ PyDoc_STRVAR(odict_sizeof__doc__, ""); static PyObject * odict_sizeof(PyODictObject *od) { Py_ssize_t res = _PyDict_SizeOf((PyDictObject *)od); res += sizeof(_ODictNode *) * od->od_fast_nodes_size; /* od_fast_nodes */ if (!_odict_EMPTY(od)) { res += sizeof(_ODictNode) * PyODict_SIZE(od); /* linked-list */ } return PyLong_FromSsize_t(res); } /* __reduce__() */ PyDoc_STRVAR(odict_reduce__doc__, "Return state information for pickling"); static PyObject * odict_reduce(register PyODictObject *od) { _Py_IDENTIFIER(__dict__); _Py_IDENTIFIER(items); PyObject *dict = NULL, *result = NULL; PyObject *items_iter, *items, *args = NULL; /* capture any instance state */ dict = _PyObject_GetAttrId((PyObject *)od, &PyId___dict__); if (dict == NULL) goto Done; else { /* od.__dict__ isn't necessarily a dict... */ Py_ssize_t dict_len = PyObject_Length(dict); if (dict_len == -1) goto Done; if (!dict_len) { /* nothing to pickle in od.__dict__ */ Py_CLEAR(dict); } } /* build the result */ args = PyTuple_New(0); if (args == NULL) goto Done; items = _PyObject_CallMethodIdObjArgs((PyObject *)od, &PyId_items, NULL); if (items == NULL) goto Done; items_iter = PyObject_GetIter(items); Py_DECREF(items); if (items_iter == NULL) goto Done; result = PyTuple_Pack(5, Py_TYPE(od), args, dict ? dict : Py_None, Py_None, items_iter); Py_DECREF(items_iter); Done: Py_XDECREF(dict); Py_XDECREF(args); return result; } /* setdefault() */ PyDoc_STRVAR(odict_setdefault__doc__, "od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od"); /* Skips __missing__() calls. */ static PyObject * odict_setdefault(register PyODictObject *od, PyObject *args, PyObject *kwargs) { static char *kwlist[] = {"key", "default", 0}; PyObject *key, *result = NULL; PyObject *failobj = Py_None; /* both borrowed */ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:setdefault", kwlist, &key, &failobj)) { return NULL; } if (PyODict_CheckExact(od)) { result = PyODict_GetItemWithError(od, key); /* borrowed */ if (result == NULL) { if (PyErr_Occurred()) return NULL; assert(_odict_find_node(od, key) == NULL); if (PyODict_SetItem((PyObject *)od, key, failobj) >= 0) { result = failobj; Py_INCREF(failobj); } } else { Py_INCREF(result); } } else { int exists = PySequence_Contains((PyObject *)od, key); if (exists < 0) { return NULL; } else if (exists) { result = PyObject_GetItem((PyObject *)od, key); } else if (PyObject_SetItem((PyObject *)od, key, failobj) >= 0) { result = failobj; Py_INCREF(failobj); } } return result; } /* pop() */ PyDoc_STRVAR(odict_pop__doc__, "od.pop(k[,d]) -> v, remove specified key and return the corresponding\n\ value. If key is not found, d is returned if given, otherwise KeyError\n\ is raised.\n\ \n\ "); /* forward */ static PyObject * _odict_popkey(PyObject *, PyObject *, PyObject *); /* Skips __missing__() calls. */ static PyObject * odict_pop(PyObject *od, PyObject *args, PyObject *kwargs) { static char *kwlist[] = {"key", "default", 0}; PyObject *key, *failobj = NULL; /* borrowed */ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:pop", kwlist, &key, &failobj)) { return NULL; } return _odict_popkey(od, key, failobj); } static PyObject * _odict_popkey_hash(PyObject *od, PyObject *key, PyObject *failobj, Py_hash_t hash) { _ODictNode *node; PyObject *value = NULL; /* Pop the node first to avoid a possible dict resize (due to eval loop reentrancy) and complications due to hash collision resolution. */ node = _odict_find_node_hash((PyODictObject *)od, key, hash); if (node == NULL) { if (PyErr_Occurred()) return NULL; } else { int res = _odict_clear_node((PyODictObject *)od, node, key, hash); if (res < 0) { return NULL; } } /* Now delete the value from the dict. */ if (PyODict_CheckExact(od)) { if (node != NULL) { value = _PyDict_GetItem_KnownHash(od, key, hash); /* borrowed */ if (value != NULL) { Py_INCREF(value); if (_PyDict_DelItem_KnownHash(od, key, hash) < 0) { Py_DECREF(value); return NULL; } } } } else { int exists = PySequence_Contains(od, key); if (exists < 0) return NULL; if (exists) { value = PyObject_GetItem(od, key); if (value != NULL) { if (PyObject_DelItem(od, key) == -1) { Py_CLEAR(value); } } } } /* Apply the fallback value, if necessary. */ if (value == NULL && !PyErr_Occurred()) { if (failobj) { value = failobj; Py_INCREF(failobj); } else { PyErr_SetObject(PyExc_KeyError, key); } } return value; } static PyObject * _odict_popkey(PyObject *od, PyObject *key, PyObject *failobj) { Py_hash_t hash = PyObject_Hash(key); if (hash == -1) return NULL; return _odict_popkey_hash(od, key, failobj, hash); } /* popitem() */ PyDoc_STRVAR(odict_popitem__doc__, "popitem($self, /, last=True)\n" "--\n" "\n" "Remove and return a (key, value) pair from the dictionary.\n" "\n" "Pairs are returned in LIFO order if last is true or FIFO order if false."); static PyObject * odict_popitem(PyObject *od, PyObject *args, PyObject *kwargs) { static char *kwlist[] = {"last", 0}; PyObject *key, *value, *item = NULL; _ODictNode *node; int last = 1; /* pull the item */ /* borrowed */ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|p:popitem", kwlist, &last)) { return NULL; } if (_odict_EMPTY(od)) { PyErr_SetString(PyExc_KeyError, "dictionary is empty"); return NULL; } node = last ? _odict_LAST(od) : _odict_FIRST(od); key = _odictnode_KEY(node); Py_INCREF(key); value = _odict_popkey_hash(od, key, NULL, _odictnode_HASH(node)); if (value == NULL) return NULL; item = PyTuple_Pack(2, key, value); Py_DECREF(key); Py_DECREF(value); return item; } /* keys() */ /* MutableMapping.keys() does not have a docstring. */ PyDoc_STRVAR(odict_keys__doc__, ""); static PyObject * odictkeys_new(PyObject *od); /* forward */ /* values() */ /* MutableMapping.values() does not have a docstring. */ PyDoc_STRVAR(odict_values__doc__, ""); static PyObject * odictvalues_new(PyObject *od); /* forward */ /* items() */ /* MutableMapping.items() does not have a docstring. */ PyDoc_STRVAR(odict_items__doc__, ""); static PyObject * odictitems_new(PyObject *od); /* forward */ /* update() */ /* MutableMapping.update() does not have a docstring. */ PyDoc_STRVAR(odict_update__doc__, ""); /* forward */ static PyObject * mutablemapping_update(PyObject *, PyObject *, PyObject *); #define odict_update mutablemapping_update /* clear() */ PyDoc_STRVAR(odict_clear__doc__, "od.clear() -> None. Remove all items from od."); static PyObject * odict_clear(register PyODictObject *od, PyObject *Py_UNUSED(ignored)) { PyDict_Clear((PyObject *)od); _odict_clear_nodes(od); Py_RETURN_NONE; } /* copy() */ /* forward */ static int _PyODict_SetItem_KnownHash(PyObject *, PyObject *, PyObject *, Py_hash_t); PyDoc_STRVAR(odict_copy__doc__, "od.copy() -> a shallow copy of od"); static PyObject * odict_copy(register PyODictObject *od) { _ODictNode *node; PyObject *od_copy; if (PyODict_CheckExact(od)) od_copy = PyODict_New(); else od_copy = PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(od), NULL); if (od_copy == NULL) return NULL; if (PyODict_CheckExact(od)) { _odict_FOREACH(od, node) { PyObject *key = _odictnode_KEY(node); PyObject *value = _odictnode_VALUE(node, od); if (value == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); goto fail; } if (_PyODict_SetItem_KnownHash((PyObject *)od_copy, key, value, _odictnode_HASH(node)) != 0) goto fail; } } else { _odict_FOREACH(od, node) { int res; PyObject *value = PyObject_GetItem((PyObject *)od, _odictnode_KEY(node)); if (value == NULL) goto fail; res = PyObject_SetItem((PyObject *)od_copy, _odictnode_KEY(node), value); Py_DECREF(value); if (res != 0) goto fail; } } return od_copy; fail: Py_DECREF(od_copy); return NULL; } /* __reversed__() */ PyDoc_STRVAR(odict_reversed__doc__, "od.__reversed__() <==> reversed(od)"); #define _odict_ITER_REVERSED 1 #define _odict_ITER_KEYS 2 #define _odict_ITER_VALUES 4 /* forward */ static PyObject * odictiter_new(PyODictObject *, int); static PyObject * odict_reversed(PyODictObject *od) { return odictiter_new(od, _odict_ITER_KEYS|_odict_ITER_REVERSED); } /* move_to_end() */ PyDoc_STRVAR(odict_move_to_end__doc__, "Move an existing element to the end (or beginning if last==False).\n\ \n\ Raises KeyError if the element does not exist.\n\ When last=True, acts like a fast version of self[key]=self.pop(key).\n\ \n\ "); static PyObject * odict_move_to_end(PyODictObject *od, PyObject *args, PyObject *kwargs) { static char *kwlist[] = {"key", "last", 0}; PyObject *key; int last = 1; _ODictNode *node; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|p:move_to_end", kwlist, &key, &last)) { return NULL; } if (_odict_EMPTY(od)) { PyErr_SetObject(PyExc_KeyError, key); return NULL; } node = last ? _odict_LAST(od) : _odict_FIRST(od); if (key != _odictnode_KEY(node)) { node = _odict_find_node(od, key); if (node == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); return NULL; } if (last) { /* Only move if not already the last one. */ if (node != _odict_LAST(od)) { _odict_remove_node(od, node); _odict_add_tail(od, node); } } else { /* Only move if not already the first one. */ if (node != _odict_FIRST(od)) { _odict_remove_node(od, node); _odict_add_head(od, node); } } } Py_RETURN_NONE; } /* tp_methods */ static PyMethodDef odict_methods[] = { /* explicitly defined so we can align docstrings with * collections.OrderedDict */ {"__delitem__", (PyCFunction)odict_mp_ass_sub, METH_NOARGS, odict_delitem__doc__}, {"__eq__", (PyCFunction)odict_eq, METH_NOARGS, odict_eq__doc__}, {"__init__", (PyCFunction)odict_init, METH_NOARGS, odict_init__doc__}, {"__iter__", (PyCFunction)odict_iter, METH_NOARGS, odict_iter__doc__}, {"__ne__", (PyCFunction)odict_ne, METH_NOARGS, odict_ne__doc__}, {"__repr__", (PyCFunction)odict_repr, METH_NOARGS, odict_repr__doc__}, {"__setitem__", (PyCFunction)odict_mp_ass_sub, METH_NOARGS, odict_setitem__doc__}, {"fromkeys", (PyCFunction)odict_fromkeys, METH_VARARGS | METH_KEYWORDS | METH_CLASS, odict_fromkeys__doc__}, /* overridden dict methods */ {"__sizeof__", (PyCFunction)odict_sizeof, METH_NOARGS, odict_sizeof__doc__}, {"__reduce__", (PyCFunction)odict_reduce, METH_NOARGS, odict_reduce__doc__}, {"setdefault", (PyCFunction)odict_setdefault, METH_VARARGS | METH_KEYWORDS, odict_setdefault__doc__}, {"pop", (PyCFunction)odict_pop, METH_VARARGS | METH_KEYWORDS, odict_pop__doc__}, {"popitem", (PyCFunction)odict_popitem, METH_VARARGS | METH_KEYWORDS, odict_popitem__doc__}, {"keys", (PyCFunction)odictkeys_new, METH_NOARGS, odict_keys__doc__}, {"values", (PyCFunction)odictvalues_new, METH_NOARGS, odict_values__doc__}, {"items", (PyCFunction)odictitems_new, METH_NOARGS, odict_items__doc__}, {"update", (PyCFunction)odict_update, METH_VARARGS | METH_KEYWORDS, odict_update__doc__}, {"clear", (PyCFunction)odict_clear, METH_NOARGS, odict_clear__doc__}, {"copy", (PyCFunction)odict_copy, METH_NOARGS, odict_copy__doc__}, /* new methods */ {"__reversed__", (PyCFunction)odict_reversed, METH_NOARGS, odict_reversed__doc__}, {"move_to_end", (PyCFunction)odict_move_to_end, METH_VARARGS | METH_KEYWORDS, odict_move_to_end__doc__}, {NULL, NULL} /* sentinel */ }; /* ---------------------------------------------- * OrderedDict members */ /* tp_getset */ static PyGetSetDef odict_getset[] = { {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, {NULL} }; /* ---------------------------------------------- * OrderedDict type slot methods */ /* tp_dealloc */ static void odict_dealloc(PyODictObject *self) { PyThreadState *tstate = PyThreadState_GET(); PyObject_GC_UnTrack(self); Py_TRASHCAN_SAFE_BEGIN(self) Py_XDECREF(self->od_inst_dict); if (self->od_weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *)self); _odict_clear_nodes(self); /* Call the base tp_dealloc(). Since it too uses the trashcan mechanism, * temporarily decrement trash_delete_nesting to prevent triggering it * and putting the partially deallocated object on the trashcan's * to-be-deleted-later list. */ --tstate->trash_delete_nesting; assert(_tstate->trash_delete_nesting < PyTrash_UNWIND_LEVEL); PyDict_Type.tp_dealloc((PyObject *)self); ++tstate->trash_delete_nesting; Py_TRASHCAN_SAFE_END(self) } /* tp_repr */ static PyObject * odict_repr(PyODictObject *self) { int i; _Py_IDENTIFIER(items); PyObject *pieces = NULL, *result = NULL; const char *classname; classname = strrchr(Py_TYPE(self)->tp_name, '.'); if (classname == NULL) classname = Py_TYPE(self)->tp_name; else classname++; if (PyODict_SIZE(self) == 0) return PyUnicode_FromFormat("%s()", classname); i = Py_ReprEnter((PyObject *)self); if (i != 0) { return i > 0 ? PyUnicode_FromString("...") : NULL; } if (PyODict_CheckExact(self)) { Py_ssize_t count = 0; _ODictNode *node; pieces = PyList_New(PyODict_SIZE(self)); if (pieces == NULL) goto Done; _odict_FOREACH(self, node) { PyObject *pair; PyObject *key = _odictnode_KEY(node); PyObject *value = _odictnode_VALUE(node, self); if (value == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); goto Done; } pair = PyTuple_Pack(2, key, value); if (pair == NULL) goto Done; if (count < PyList_GET_SIZE(pieces)) PyList_SET_ITEM(pieces, count, pair); /* steals reference */ else { if (PyList_Append(pieces, pair) < 0) { Py_DECREF(pair); goto Done; } Py_DECREF(pair); } count++; } if (count < PyList_GET_SIZE(pieces)) PyList_GET_SIZE(pieces) = count; } else { PyObject *items = _PyObject_CallMethodIdObjArgs((PyObject *)self, &PyId_items, NULL); if (items == NULL) goto Done; pieces = PySequence_List(items); Py_DECREF(items); if (pieces == NULL) goto Done; } result = PyUnicode_FromFormat("%s(%R)", classname, pieces); Done: Py_XDECREF(pieces); Py_ReprLeave((PyObject *)self); return result; } /* tp_doc */ PyDoc_STRVAR(odict_doc, "Dictionary that remembers insertion order"); /* tp_traverse */ static int odict_traverse(PyODictObject *od, visitproc visit, void *arg) { _ODictNode *node; Py_VISIT(od->od_inst_dict); Py_VISIT(od->od_weakreflist); _odict_FOREACH(od, node) { Py_VISIT(_odictnode_KEY(node)); } return PyDict_Type.tp_traverse((PyObject *)od, visit, arg); } /* tp_clear */ static int odict_tp_clear(PyODictObject *od) { Py_CLEAR(od->od_inst_dict); Py_CLEAR(od->od_weakreflist); PyDict_Clear((PyObject *)od); _odict_clear_nodes(od); return 0; } /* tp_richcompare */ static PyObject * odict_richcompare(PyObject *v, PyObject *w, int op) { if (!PyODict_Check(v) || !PyDict_Check(w)) { Py_RETURN_NOTIMPLEMENTED; } if (op == Py_EQ || op == Py_NE) { PyObject *res, *cmp; int eq; cmp = PyDict_Type.tp_richcompare(v, w, op); if (cmp == NULL) return NULL; if (!PyODict_Check(w)) return cmp; if (op == Py_EQ && cmp == Py_False) return cmp; if (op == Py_NE && cmp == Py_True) return cmp; Py_DECREF(cmp); /* Try comparing odict keys. */ eq = _odict_keys_equal((PyODictObject *)v, (PyODictObject *)w); if (eq < 0) return NULL; res = (eq == (op == Py_EQ)) ? Py_True : Py_False; Py_INCREF(res); return res; } else { Py_RETURN_NOTIMPLEMENTED; } } /* tp_iter */ static PyObject * odict_iter(PyODictObject *od) { return odictiter_new(od, _odict_ITER_KEYS); } /* tp_init */ static int odict_init(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *res; Py_ssize_t len = PyObject_Length(args); if (len == -1) return -1; if (len > 1) { char *msg = "expected at most 1 arguments, got %d"; PyErr_Format(PyExc_TypeError, msg, len); return -1; } /* __init__() triggering update() is just the way things are! */ res = odict_update(self, args, kwds); if (res == NULL) { return -1; } else { Py_DECREF(res); return 0; } } /* PyODict_Type */ PyTypeObject PyODict_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "collections.OrderedDict", /* tp_name */ sizeof(PyODictObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)odict_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)odict_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ &odict_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,/* tp_flags */ odict_doc, /* tp_doc */ (traverseproc)odict_traverse, /* tp_traverse */ (inquiry)odict_tp_clear, /* tp_clear */ (richcmpfunc)odict_richcompare, /* tp_richcompare */ offsetof(PyODictObject, od_weakreflist), /* tp_weaklistoffset */ (getiterfunc)odict_iter, /* tp_iter */ 0, /* tp_iternext */ odict_methods, /* tp_methods */ 0, /* tp_members */ odict_getset, /* tp_getset */ &PyDict_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyODictObject, od_inst_dict), /* tp_dictoffset */ (initproc)odict_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ }; /* ---------------------------------------------- * the public OrderedDict API */ PyObject * PyODict_New(void) { return PyDict_Type.tp_new(&PyODict_Type, NULL, NULL); } static int _PyODict_SetItem_KnownHash(PyObject *od, PyObject *key, PyObject *value, Py_hash_t hash) { int res = _PyDict_SetItem_KnownHash(od, key, value, hash); if (res == 0) { res = _odict_add_new_node((PyODictObject *)od, key, hash); if (res < 0) { /* Revert setting the value on the dict */ PyObject *exc, *val, *tb; PyErr_Fetch(&exc, &val, &tb); (void) _PyDict_DelItem_KnownHash(od, key, hash); _PyErr_ChainExceptions(exc, val, tb); } } return res; } int PyODict_SetItem(PyObject *od, PyObject *key, PyObject *value) { Py_hash_t hash = PyObject_Hash(key); if (hash == -1) return -1; return _PyODict_SetItem_KnownHash(od, key, value, hash); } int PyODict_DelItem(PyObject *od, PyObject *key) { int res; Py_hash_t hash = PyObject_Hash(key); if (hash == -1) return -1; res = _odict_clear_node((PyODictObject *)od, NULL, key, hash); if (res < 0) return -1; return _PyDict_DelItem_KnownHash(od, key, hash); } /* ------------------------------------------- * The OrderedDict views (keys/values/items) */ typedef struct { PyObject_HEAD int kind; PyODictObject *di_odict; Py_ssize_t di_size; size_t di_state; PyObject *di_current; PyObject *di_result; /* reusable result tuple for iteritems */ } odictiterobject; static void odictiter_dealloc(odictiterobject *di) { _PyObject_GC_UNTRACK(di); Py_XDECREF(di->di_odict); Py_XDECREF(di->di_current); if (di->kind & (_odict_ITER_KEYS | _odict_ITER_VALUES)) { Py_DECREF(di->di_result); } PyObject_GC_Del(di); } static int odictiter_traverse(odictiterobject *di, visitproc visit, void *arg) { Py_VISIT(di->di_odict); Py_VISIT(di->di_current); /* A key could be any type, not just str. */ Py_VISIT(di->di_result); return 0; } /* In order to protect against modifications during iteration, we track * the current key instead of the current node. */ static PyObject * odictiter_nextkey(odictiterobject *di) { PyObject *key = NULL; _ODictNode *node; int reversed = di->kind & _odict_ITER_REVERSED; if (di->di_odict == NULL) return NULL; if (di->di_current == NULL) goto done; /* We're already done. */ /* Check for unsupported changes. */ if (di->di_odict->od_state != di->di_state) { PyErr_SetString(PyExc_RuntimeError, "OrderedDict mutated during iteration"); goto done; } if (di->di_size != PyODict_SIZE(di->di_odict)) { PyErr_SetString(PyExc_RuntimeError, "OrderedDict changed size during iteration"); di->di_size = -1; /* Make this state sticky */ return NULL; } /* Get the key. */ node = _odict_find_node(di->di_odict, di->di_current); if (node == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, di->di_current); /* Must have been deleted. */ Py_CLEAR(di->di_current); return NULL; } key = di->di_current; /* Advance to the next key. */ node = reversed ? _odictnode_PREV(node) : _odictnode_NEXT(node); if (node == NULL) { /* Reached the end. */ di->di_current = NULL; } else { di->di_current = _odictnode_KEY(node); Py_INCREF(di->di_current); } return key; done: Py_CLEAR(di->di_odict); return key; } static PyObject * odictiter_iternext(odictiterobject *di) { PyObject *result, *value; PyObject *key = odictiter_nextkey(di); /* new reference */ if (key == NULL) return NULL; /* Handle the keys case. */ if (! (di->kind & _odict_ITER_VALUES)) { return key; } value = PyODict_GetItem((PyObject *)di->di_odict, key); /* borrowed */ if (value == NULL) { if (!PyErr_Occurred()) PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); goto done; } Py_INCREF(value); /* Handle the values case. */ if (!(di->kind & _odict_ITER_KEYS)) { Py_DECREF(key); return value; } /* Handle the items case. */ result = di->di_result; if (Py_REFCNT(result) == 1) { /* not in use so we can reuse it * (the common case during iteration) */ Py_INCREF(result); Py_DECREF(PyTuple_GET_ITEM(result, 0)); /* borrowed */ Py_DECREF(PyTuple_GET_ITEM(result, 1)); /* borrowed */ } else { result = PyTuple_New(2); if (result == NULL) { Py_DECREF(key); Py_DECREF(value); goto done; } } PyTuple_SET_ITEM(result, 0, key); /* steals reference */ PyTuple_SET_ITEM(result, 1, value); /* steals reference */ return result; done: Py_CLEAR(di->di_current); Py_CLEAR(di->di_odict); return NULL; } /* No need for tp_clear because odictiterobject is not mutable. */ PyDoc_STRVAR(reduce_doc, "Return state information for pickling"); static PyObject * odictiter_reduce(odictiterobject *di, PyObject *Py_UNUSED(ignored)) { /* copy the iterator state */ odictiterobject tmp = *di; Py_XINCREF(tmp.di_odict); Py_XINCREF(tmp.di_current); /* iterate the temporary into a list */ PyObject *list = PySequence_List((PyObject*)&tmp); Py_XDECREF(tmp.di_odict); Py_XDECREF(tmp.di_current); if (list == NULL) { return NULL; } return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list); } static PyMethodDef odictiter_methods[] = { {"__reduce__", (PyCFunction)odictiter_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyODictIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "odict_iterator", /* tp_name */ sizeof(odictiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)odictiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)odictiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)odictiter_iternext, /* tp_iternext */ odictiter_methods, /* tp_methods */ 0, }; static PyObject * odictiter_new(PyODictObject *od, int kind) { odictiterobject *di; _ODictNode *node; int reversed = kind & _odict_ITER_REVERSED; di = PyObject_GC_New(odictiterobject, &PyODictIter_Type); if (di == NULL) return NULL; if (kind & (_odict_ITER_KEYS | _odict_ITER_VALUES)){ di->di_result = PyTuple_Pack(2, Py_None, Py_None); if (di->di_result == NULL) { Py_DECREF(di); return NULL; } } else di->di_result = NULL; di->kind = kind; node = reversed ? _odict_LAST(od) : _odict_FIRST(od); di->di_current = node ? _odictnode_KEY(node) : NULL; Py_XINCREF(di->di_current); di->di_size = PyODict_SIZE(od); di->di_state = od->od_state; di->di_odict = od; Py_INCREF(od); _PyObject_GC_TRACK(di); return (PyObject *)di; } /* keys() */ static PyObject * odictkeys_iter(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new((PyODictObject *)dv->dv_dict, _odict_ITER_KEYS); } static PyObject * odictkeys_reversed(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new((PyODictObject *)dv->dv_dict, _odict_ITER_KEYS|_odict_ITER_REVERSED); } static PyMethodDef odictkeys_methods[] = { {"__reversed__", (PyCFunction)odictkeys_reversed, METH_NOARGS, NULL}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyODictKeys_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "odict_keys", /* tp_name */ 0, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)odictkeys_iter, /* tp_iter */ 0, /* tp_iternext */ odictkeys_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyDictKeys_Type, /* tp_base */ }; static PyObject * odictkeys_new(PyObject *od) { return _PyDictView_New(od, &PyODictKeys_Type); } /* items() */ static PyObject * odictitems_iter(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new((PyODictObject *)dv->dv_dict, _odict_ITER_KEYS|_odict_ITER_VALUES); } static PyObject * odictitems_reversed(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new((PyODictObject *)dv->dv_dict, _odict_ITER_KEYS|_odict_ITER_VALUES|_odict_ITER_REVERSED); } static PyMethodDef odictitems_methods[] = { {"__reversed__", (PyCFunction)odictitems_reversed, METH_NOARGS, NULL}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyODictItems_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "odict_items", /* tp_name */ 0, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)odictitems_iter, /* tp_iter */ 0, /* tp_iternext */ odictitems_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyDictItems_Type, /* tp_base */ }; static PyObject * odictitems_new(PyObject *od) { return _PyDictView_New(od, &PyODictItems_Type); } /* values() */ static PyObject * odictvalues_iter(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new((PyODictObject *)dv->dv_dict, _odict_ITER_VALUES); } static PyObject * odictvalues_reversed(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return odictiter_new((PyODictObject *)dv->dv_dict, _odict_ITER_VALUES|_odict_ITER_REVERSED); } static PyMethodDef odictvalues_methods[] = { {"__reversed__", (PyCFunction)odictvalues_reversed, METH_NOARGS, NULL}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyODictValues_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "odict_values", /* tp_name */ 0, /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)odictvalues_iter, /* tp_iter */ 0, /* tp_iternext */ odictvalues_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyDictValues_Type, /* tp_base */ }; static PyObject * odictvalues_new(PyObject *od) { return _PyDictView_New(od, &PyODictValues_Type); } /* ---------------------------------------------- MutableMapping implementations Mapping: ============ =========== method uses ============ =========== __contains__ __getitem__ __eq__ items __getitem__ + __iter__ + __len__ + __ne__ __eq__ get __getitem__ items ItemsView keys KeysView values ValuesView ============ =========== ItemsView uses __len__, __iter__, and __getitem__. KeysView uses __len__, __iter__, and __contains__. ValuesView uses __len__, __iter__, and __getitem__. MutableMapping: ============ =========== method uses ============ =========== __delitem__ + __setitem__ + clear popitem pop __getitem__ __delitem__ popitem __iter__ _getitem__ __delitem__ setdefault __getitem__ __setitem__ update __setitem__ ============ =========== */ static int mutablemapping_add_pairs(PyObject *self, PyObject *pairs) { PyObject *pair, *iterator, *unexpected; int res = 0; iterator = PyObject_GetIter(pairs); if (iterator == NULL) return -1; PyErr_Clear(); while ((pair = PyIter_Next(iterator)) != NULL) { /* could be more efficient (see UNPACK_SEQUENCE in ceval.c) */ PyObject *key = NULL, *value = NULL; PyObject *pair_iterator = PyObject_GetIter(pair); if (pair_iterator == NULL) goto Done; key = PyIter_Next(pair_iterator); if (key == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "need more than 0 values to unpack"); goto Done; } value = PyIter_Next(pair_iterator); if (value == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "need more than 1 value to unpack"); goto Done; } unexpected = PyIter_Next(pair_iterator); if (unexpected != NULL) { Py_DECREF(unexpected); PyErr_SetString(PyExc_ValueError, "too many values to unpack (expected 2)"); goto Done; } else if (PyErr_Occurred()) goto Done; res = PyObject_SetItem(self, key, value); Done: Py_DECREF(pair); Py_XDECREF(pair_iterator); Py_XDECREF(key); Py_XDECREF(value); if (PyErr_Occurred()) break; } Py_DECREF(iterator); if (res < 0 || PyErr_Occurred() != NULL) return -1; else return 0; } static PyObject * mutablemapping_update(PyObject *self, PyObject *args, PyObject *kwargs) { int res = 0; Py_ssize_t len; _Py_IDENTIFIER(items); _Py_IDENTIFIER(keys); /* first handle args, if any */ assert(args == NULL || PyTuple_Check(args)); len = (args != NULL) ? PyTuple_GET_SIZE(args) : 0; if (len > 1) { char *msg = "update() takes at most 1 positional argument (%d given)"; PyErr_Format(PyExc_TypeError, msg, len); return NULL; } if (len) { PyObject *other = PyTuple_GET_ITEM(args, 0); /* borrowed reference */ assert(other != NULL); Py_INCREF(other); if PyDict_CheckExact(other) { PyObject *items; if (PyDict_CheckExact(other)) items = PyDict_Items(other); else items = _PyObject_CallMethodId(other, &PyId_items, NULL); Py_DECREF(other); if (items == NULL) return NULL; res = mutablemapping_add_pairs(self, items); Py_DECREF(items); if (res == -1) return NULL; } else if (_PyObject_HasAttrId(other, &PyId_keys)) { /* never fails */ PyObject *keys, *iterator, *key; keys = _PyObject_CallMethodIdObjArgs(other, &PyId_keys, NULL); if (keys == NULL) { Py_DECREF(other); return NULL; } iterator = PyObject_GetIter(keys); Py_DECREF(keys); if (iterator == NULL) { Py_DECREF(other); return NULL; } while (res == 0 && (key = PyIter_Next(iterator))) { PyObject *value = PyObject_GetItem(other, key); if (value != NULL) { res = PyObject_SetItem(self, key, value); Py_DECREF(value); } else { res = -1; } Py_DECREF(key); } Py_DECREF(other); Py_DECREF(iterator); if (res != 0 || PyErr_Occurred()) return NULL; } else if (_PyObject_HasAttrId(other, &PyId_items)) { /* never fails */ PyObject *items; if (PyDict_CheckExact(other)) items = PyDict_Items(other); else items = _PyObject_CallMethodId(other, &PyId_items, NULL); Py_DECREF(other); if (items == NULL) return NULL; res = mutablemapping_add_pairs(self, items); Py_DECREF(items); if (res == -1) return NULL; } else { res = mutablemapping_add_pairs(self, other); Py_DECREF(other); if (res != 0) return NULL; } } /* now handle kwargs */ assert(kwargs == NULL || PyDict_Check(kwargs)); len = (kwargs != NULL) ? PyDict_Size(kwargs) : 0; if (len > 0) { PyObject *items = PyDict_Items(kwargs); if (items == NULL) return NULL; res = mutablemapping_add_pairs(self, items); Py_DECREF(items); if (res == -1) return NULL; } Py_RETURN_NONE; }
79,119
2,406
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/tupleobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/accu.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/tupleobject.h" /* clang-format off */ /* Tuple object implementation */ /* Speed optimization to avoid frequent malloc/free of small tuples */ #ifndef PyTuple_MAXSAVESIZE #define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */ #endif #ifndef PyTuple_MAXFREELIST #define PyTuple_MAXFREELIST 2000 /* Maximum number of tuples of each size to save */ #endif #if PyTuple_MAXSAVESIZE > 0 /* Entries 1 up to PyTuple_MAXSAVESIZE are free lists, entry 0 is the empty tuple () of which at most one instance will be allocated. */ static PyTupleObject *free_list[PyTuple_MAXSAVESIZE]; static int numfree[PyTuple_MAXSAVESIZE]; #endif #ifdef COUNT_ALLOCS Py_ssize_t fast_tuple_allocs; Py_ssize_t tuple_zero_allocs; #endif /* Debug statistic to count GC tracking of tuples. Please note that tuples are only untracked when considered by the GC, and many of them will be dead before. Therefore, a tracking rate close to 100% does not necessarily prove that the heuristic is inefficient. */ #ifdef SHOW_TRACK_COUNT static Py_ssize_t count_untracked = 0; static Py_ssize_t count_tracked = 0; static void show_track(void) { PyObject *xoptions, *value; _Py_IDENTIFIER(showalloccount); xoptions = PySys_GetXOptions(); if (xoptions == NULL) return; value = _PyDict_GetItemId(xoptions, &PyId_showalloccount); if (value != Py_True) return; fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n", count_tracked + count_untracked); fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T "d\n", count_tracked); fprintf(stderr, "%.2f%% tuple tracking rate\n\n", (100.0*count_tracked/(count_untracked+count_tracked))); } #endif /* Print summary info about the state of the optimized allocator */ void _PyTuple_DebugMallocStats(FILE *out) { #if PyTuple_MAXSAVESIZE > 0 int i; char buf[128]; for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { PyOS_snprintf(buf, sizeof(buf), "free %d-sized PyTupleObject", i); _PyDebugAllocatorStats(out, buf, numfree[i], _PyObject_VAR_SIZE(&PyTuple_Type, i)); } #endif } PyObject * PyTuple_New(Py_ssize_t size) { PyTupleObject *op; Py_ssize_t i; if (size < 0) { PyErr_BadInternalCall(); return NULL; } #if PyTuple_MAXSAVESIZE > 0 if (size == 0 && free_list[0]) { op = free_list[0]; Py_INCREF(op); #ifdef COUNT_ALLOCS tuple_zero_allocs++; #endif return (PyObject *) op; } if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) { free_list[size] = (PyTupleObject *) op->ob_item[0]; numfree[size]--; #ifdef COUNT_ALLOCS fast_tuple_allocs++; #endif /* Inline PyObject_InitVar */ #ifdef Py_TRACE_REFS Py_SIZE(op) = size; Py_TYPE(op) = &PyTuple_Type; #endif _Py_NewReference((PyObject *)op); } else #endif { /* Check for overflow */ if ((size_t)size > ((size_t)PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *)) / sizeof(PyObject *)) { return PyErr_NoMemory(); } op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size); if (op == NULL) return NULL; } for (i=0; i < size; i++) op->ob_item[i] = NULL; #if PyTuple_MAXSAVESIZE > 0 if (size == 0) { free_list[0] = op; ++numfree[0]; Py_INCREF(op); /* extra INCREF so that this is never freed */ } #endif #ifdef SHOW_TRACK_COUNT count_tracked++; #endif _PyObject_GC_TRACK(op); return (PyObject *) op; } Py_ssize_t PyTuple_Size(PyObject *op) { if (!PyTuple_Check(op)) { PyErr_BadInternalCall(); return -1; } else return Py_SIZE(op); } /** * Returns object at position 𝑖 in the tuple pointed to by 𝑝. * * @return borrowed reference, or NULL if 𝑖 is out of bounds */ PyObject * PyTuple_GetItem(PyObject *p, Py_ssize_t i) { if (!PyTuple_Check(p)) { PyErr_BadInternalCall(); return NULL; } if (i < 0 || i >= Py_SIZE(p)) { PyErr_SetString(PyExc_IndexError, "tuple index out of range"); return NULL; } return ((PyTupleObject *)p) -> ob_item[i]; } int PyTuple_SetItem(PyObject *op, Py_ssize_t i, PyObject *newitem) { PyObject **p; if (!PyTuple_Check(op) || op->ob_refcnt != 1) { Py_XDECREF(newitem); PyErr_BadInternalCall(); return -1; } if (i < 0 || i >= Py_SIZE(op)) { Py_XDECREF(newitem); PyErr_SetString(PyExc_IndexError, "tuple assignment index out of range"); return -1; } p = ((PyTupleObject *)op) -> ob_item + i; Py_XSETREF(*p, newitem); return 0; } void _PyTuple_MaybeUntrack(PyObject *op) { PyTupleObject *t; Py_ssize_t i, n; if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) return; t = (PyTupleObject *) op; n = Py_SIZE(t); for (i = 0; i < n; i++) { PyObject *elt = PyTuple_GET_ITEM(t, i); /* Tuple with NULL elements aren't fully constructed, don't untrack them yet. */ if (!elt || _PyObject_GC_MAY_BE_TRACKED(elt)) return; } #ifdef SHOW_TRACK_COUNT count_tracked--; count_untracked++; #endif _PyObject_GC_UNTRACK(op); } PyObject * PyTuple_Pack(Py_ssize_t n, ...) { Py_ssize_t i; PyObject *o; PyObject *result; PyObject **items; va_list vargs; va_start(vargs, n); result = PyTuple_New(n); if (result == NULL) { va_end(vargs); return NULL; } items = ((PyTupleObject *)result)->ob_item; for (i = 0; i < n; i++) { o = va_arg(vargs, PyObject *); Py_INCREF(o); items[i] = o; } va_end(vargs); return result; } /* Methods */ static void tupledealloc(PyTupleObject *op) { Py_ssize_t i; Py_ssize_t len = Py_SIZE(op); PyObject_GC_UnTrack(op); Py_TRASHCAN_SAFE_BEGIN(op) if (len > 0) { i = len; while (--i >= 0) Py_XDECREF(op->ob_item[i]); #if PyTuple_MAXSAVESIZE > 0 if (len < PyTuple_MAXSAVESIZE && numfree[len] < PyTuple_MAXFREELIST && Py_TYPE(op) == &PyTuple_Type) { op->ob_item[0] = (PyObject *) free_list[len]; numfree[len]++; free_list[len] = op; goto done; /* return */ } #endif } Py_TYPE(op)->tp_free((PyObject *)op); done: Py_TRASHCAN_SAFE_END(op) } static PyObject * tuplerepr(PyTupleObject *v) { Py_ssize_t i, n; _PyUnicodeWriter writer; n = Py_SIZE(v); if (n == 0) return PyUnicode_FromString("()"); /* While not mutable, it is still possible to end up with a cycle in a tuple through an object that stores itself within a tuple (and thus infinitely asks for the repr of itself). This should only be possible within a type. */ i = Py_ReprEnter((PyObject *)v); if (i != 0) { return i > 0 ? PyUnicode_FromString("(...)") : NULL; } _PyUnicodeWriter_Init(&writer); writer.overallocate = 1; if (Py_SIZE(v) > 1) { /* "(" + "1" + ", 2" * (len - 1) + ")" */ writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1; } else { /* "(1,)" */ writer.min_length = 4; } if (_PyUnicodeWriter_WriteChar(&writer, '(') < 0) goto error; /* Do repr() on each element. */ for (i = 0; i < n; ++i) { PyObject *s; if (i > 0) { if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) goto error; } s = PyObject_Repr(v->ob_item[i]); if (s == NULL) goto error; if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) { Py_DECREF(s); goto error; } Py_DECREF(s); } writer.overallocate = 0; if (n > 1) { if (_PyUnicodeWriter_WriteChar(&writer, ')') < 0) goto error; } else { if (_PyUnicodeWriter_WriteASCIIString(&writer, ",)", 2) < 0) goto error; } Py_ReprLeave((PyObject *)v); return _PyUnicodeWriter_Finish(&writer); error: _PyUnicodeWriter_Dealloc(&writer); Py_ReprLeave((PyObject *)v); return NULL; } /* The addend 82520, was selected from the range(0, 1000000) for generating the greatest number of prime multipliers for tuples up to length eight: 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533, 1330111, 1412633, 1165069, 1247599, 1495177, 1577699 Tests have shown that it's not worth to cache the hash value, see issue #9685. */ static Py_hash_t tuplehash(PyTupleObject *v) { Py_uhash_t x; /* Unsigned for defined overflow behavior. */ Py_hash_t y; Py_ssize_t len = Py_SIZE(v); PyObject **p; Py_uhash_t mult = _PyHASH_MULTIPLIER; x = 0x345678UL; p = v->ob_item; while (--len >= 0) { y = PyObject_Hash(*p++); if (y == -1) return -1; x = (x ^ y) * mult; /* the cast might truncate len; that doesn't change hash stability */ mult += (Py_hash_t)(82520UL + len + len); } x += 97531UL; if (x == (Py_uhash_t)-1) x = -2; return x; } static Py_ssize_t tuplelength(PyTupleObject *a) { return Py_SIZE(a); } static int tuplecontains(PyTupleObject *a, PyObject *el) { Py_ssize_t i; int cmp; for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i), Py_EQ); return cmp; } static PyObject * tupleitem(PyTupleObject *a, Py_ssize_t i) { if (i < 0 || i >= Py_SIZE(a)) { PyErr_SetString(PyExc_IndexError, "tuple index out of range"); return NULL; } Py_INCREF(a->ob_item[i]); return a->ob_item[i]; } static PyObject * tupleslice(PyTupleObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { PyTupleObject *np; PyObject **src, **dest; Py_ssize_t i; Py_ssize_t len; if (ilow < 0) ilow = 0; if (ihigh > Py_SIZE(a)) ihigh = Py_SIZE(a); if (ihigh < ilow) ihigh = ilow; if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) { Py_INCREF(a); return (PyObject *)a; } len = ihigh - ilow; np = (PyTupleObject *)PyTuple_New(len); if (np == NULL) return NULL; src = a->ob_item + ilow; dest = np->ob_item; for (i = 0; i < len; i++) { PyObject *v = src[i]; Py_INCREF(v); dest[i] = v; } return (PyObject *)np; } PyObject * PyTuple_GetSlice(PyObject *op, Py_ssize_t i, Py_ssize_t j) { if (op == NULL || !PyTuple_Check(op)) { PyErr_BadInternalCall(); return NULL; } return tupleslice((PyTupleObject *)op, i, j); } static PyObject * tupleconcat(PyTupleObject *a, PyObject *bb) { Py_ssize_t size; Py_ssize_t i; PyObject **src, **dest; PyTupleObject *np; if (!PyTuple_Check(bb)) { PyErr_Format(PyExc_TypeError, "can only concatenate tuple (not \"%.200s\") to tuple", Py_TYPE(bb)->tp_name); return NULL; } #define b ((PyTupleObject *)bb) if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) return PyErr_NoMemory(); size = Py_SIZE(a) + Py_SIZE(b); np = (PyTupleObject *) PyTuple_New(size); if (np == NULL) { return NULL; } src = a->ob_item; dest = np->ob_item; for (i = 0; i < Py_SIZE(a); i++) { PyObject *v = src[i]; Py_INCREF(v); dest[i] = v; } src = b->ob_item; dest = np->ob_item + Py_SIZE(a); for (i = 0; i < Py_SIZE(b); i++) { PyObject *v = src[i]; Py_INCREF(v); dest[i] = v; } return (PyObject *)np; #undef b } static PyObject * tuplerepeat(PyTupleObject *a, Py_ssize_t n) { Py_ssize_t i, j; Py_ssize_t size; PyTupleObject *np; PyObject **p, **items; if (n < 0) n = 0; if (Py_SIZE(a) == 0 || n == 1) { if (PyTuple_CheckExact(a)) { /* Since tuples are immutable, we can return a shared copy in this case */ Py_INCREF(a); return (PyObject *)a; } if (Py_SIZE(a) == 0) return PyTuple_New(0); } if (n > PY_SSIZE_T_MAX / Py_SIZE(a)) return PyErr_NoMemory(); size = Py_SIZE(a) * n; np = (PyTupleObject *) PyTuple_New(size); if (np == NULL) return NULL; p = np->ob_item; items = a->ob_item; for (i = 0; i < n; i++) { for (j = 0; j < Py_SIZE(a); j++) { *p = items[j]; Py_INCREF(*p); p++; } } return (PyObject *) np; } static PyObject * tupleindex(PyTupleObject *self, PyObject *args) { Py_ssize_t i, start=0, stop=Py_SIZE(self); PyObject *v; if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, _PyEval_SliceIndexNotNone, &start, _PyEval_SliceIndexNotNone, &stop)) return NULL; if (start < 0) { start += Py_SIZE(self); if (start < 0) start = 0; } if (stop < 0) { stop += Py_SIZE(self); if (stop < 0) stop = 0; } for (i = start; i < stop && i < Py_SIZE(self); i++) { int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); if (cmp > 0) return PyLong_FromSsize_t(i); else if (cmp < 0) return NULL; } PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple"); return NULL; } static PyObject * tuplecount(PyTupleObject *self, PyObject *v) { Py_ssize_t count = 0; Py_ssize_t i; for (i = 0; i < Py_SIZE(self); i++) { int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); if (cmp > 0) count++; else if (cmp < 0) return NULL; } return PyLong_FromSsize_t(count); } static int tupletraverse(PyTupleObject *o, visitproc visit, void *arg) { Py_ssize_t i; for (i = Py_SIZE(o); --i >= 0; ) Py_VISIT(o->ob_item[i]); return 0; } static PyObject * tuplerichcompare(PyObject *v, PyObject *w, int op) { PyTupleObject *vt, *wt; Py_ssize_t i; Py_ssize_t vlen, wlen; if (!PyTuple_Check(v) || !PyTuple_Check(w)) Py_RETURN_NOTIMPLEMENTED; vt = (PyTupleObject *)v; wt = (PyTupleObject *)w; vlen = Py_SIZE(vt); wlen = Py_SIZE(wt); /* Note: the corresponding code for lists has an "early out" test * here when op is EQ or NE and the lengths differ. That pays there, * but Tim was unable to find any real code where EQ/NE tuple * compares don't have the same length, so testing for it here would * have cost without benefit. */ /* Search for the first index where items are different. * Note that because tuples are immutable, it's safe to reuse * vlen and wlen across the comparison calls. */ for (i = 0; i < vlen && i < wlen; i++) { int k = PyObject_RichCompareBool(vt->ob_item[i], wt->ob_item[i], Py_EQ); if (k < 0) return NULL; if (!k) break; } if (i >= vlen || i >= wlen) { /* No more items to compare -- compare sizes */ int cmp; PyObject *res; switch (op) { case Py_LT: cmp = vlen < wlen; break; case Py_LE: cmp = vlen <= wlen; break; case Py_EQ: cmp = vlen == wlen; break; case Py_NE: cmp = vlen != wlen; break; case Py_GT: cmp = vlen > wlen; break; case Py_GE: cmp = vlen >= wlen; break; default: return NULL; /* cannot happen */ } if (cmp) res = Py_True; else res = Py_False; Py_INCREF(res); return res; } /* We have an item that differs -- shortcuts for EQ/NE */ if (op == Py_EQ) { Py_INCREF(Py_False); return Py_False; } if (op == Py_NE) { Py_INCREF(Py_True); return Py_True; } /* Compare the final item again using the proper operator */ return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op); } static PyObject * tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject * tuple_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *arg = NULL; static char *kwlist[] = {"sequence", 0}; if (type != &PyTuple_Type) return tuple_subtype_new(type, args, kwds); if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg)) return NULL; if (arg == NULL) return PyTuple_New(0); else return PySequence_Tuple(arg); } static PyObject * tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *tmp, *newobj, *item; Py_ssize_t i, n; assert(PyType_IsSubtype(type, &PyTuple_Type)); tmp = tuple_new(&PyTuple_Type, args, kwds); if (tmp == NULL) return NULL; assert(PyTuple_Check(tmp)); newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp)); if (newobj == NULL) return NULL; for (i = 0; i < n; i++) { item = PyTuple_GET_ITEM(tmp, i); Py_INCREF(item); PyTuple_SET_ITEM(newobj, i, item); } Py_DECREF(tmp); return newobj; } PyDoc_STRVAR(tuple_doc, "tuple() -> empty tuple\n\ tuple(iterable) -> tuple initialized from iterable's items\n\ \n\ If the argument is a tuple, the return value is the same object."); static PySequenceMethods tuple_as_sequence = { (lenfunc)tuplelength, /* sq_length */ (binaryfunc)tupleconcat, /* sq_concat */ (ssizeargfunc)tuplerepeat, /* sq_repeat */ (ssizeargfunc)tupleitem, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)tuplecontains, /* sq_contains */ }; static PyObject* tuplesubscript(PyTupleObject* self, PyObject* item) { if (PyIndex_Check(item)) { Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return NULL; if (i < 0) i += PyTuple_GET_SIZE(self); return tupleitem(self, i); } else if (PySlice_Check(item)) { Py_ssize_t start, stop, step, slicelength, cur, i; PyObject* result; PyObject* it; PyObject **src, **dest; if (PySlice_Unpack(item, &start, &stop, &step) < 0) { return NULL; } slicelength = PySlice_AdjustIndices(PyTuple_GET_SIZE(self), &start, &stop, step); if (slicelength <= 0) { return PyTuple_New(0); } else if (start == 0 && step == 1 && slicelength == PyTuple_GET_SIZE(self) && PyTuple_CheckExact(self)) { Py_INCREF(self); return (PyObject *)self; } else { result = PyTuple_New(slicelength); if (!result) return NULL; src = self->ob_item; dest = ((PyTupleObject *)result)->ob_item; for (cur = start, i = 0; i < slicelength; cur += step, i++) { it = src[cur]; Py_INCREF(it); dest[i] = it; } return result; } } else { PyErr_Format(PyExc_TypeError, "tuple indices must be integers or slices, not %.200s", Py_TYPE(item)->tp_name); return NULL; } } static PyObject * tuple_getnewargs(PyTupleObject *v) { return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v))); } PyDoc_STRVAR(index_doc, "T.index(value, [start, [stop]]) -> integer -- return first index of value.\n" "Raises ValueError if the value is not present." ); PyDoc_STRVAR(count_doc, "T.count(value) -> integer -- return number of occurrences of value"); static PyMethodDef tuple_methods[] = { {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS}, {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc}, {"count", (PyCFunction)tuplecount, METH_O, count_doc}, {NULL, NULL} /* sentinel */ }; static PyMappingMethods tuple_as_mapping = { (lenfunc)tuplelength, (binaryfunc)tuplesubscript, 0 }; static PyObject *tuple_iter(PyObject *seq); PyTypeObject PyTuple_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "tuple", sizeof(PyTupleObject) - sizeof(PyObject *), sizeof(PyObject *), (destructor)tupledealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)tuplerepr, /* tp_repr */ 0, /* tp_as_number */ &tuple_as_sequence, /* tp_as_sequence */ &tuple_as_mapping, /* tp_as_mapping */ (hashfunc)tuplehash, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */ tuple_doc, /* tp_doc */ (traverseproc)tupletraverse, /* tp_traverse */ 0, /* tp_clear */ tuplerichcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ tuple_iter, /* tp_iter */ 0, /* tp_iternext */ tuple_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ tuple_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; /* The following function breaks the notion that tuples are immutable: it changes the size of a tuple. We get away with this only if there is only one module referencing the object. You can also think of it as creating a new tuple object and destroying the old one, only more efficiently. In any case, don't use this if the tuple may already be known to some other part of the code. */ int _PyTuple_Resize(PyObject **pv, Py_ssize_t newsize) { PyTupleObject *v; PyTupleObject *sv; Py_ssize_t i; Py_ssize_t oldsize; v = (PyTupleObject *) *pv; if (v == NULL || Py_TYPE(v) != &PyTuple_Type || (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) { *pv = 0; Py_XDECREF(v); PyErr_BadInternalCall(); return -1; } oldsize = Py_SIZE(v); if (oldsize == newsize) return 0; if (oldsize == 0) { /* Empty tuples are often shared, so we should never resize them in-place even if we do own the only (current) reference */ Py_DECREF(v); *pv = PyTuple_New(newsize); return *pv == NULL ? -1 : 0; } /* XXX UNREF/NEWREF interface should be more symmetrical */ _Py_DEC_REFTOTAL; if (_PyObject_GC_IS_TRACKED(v)) _PyObject_GC_UNTRACK(v); _Py_ForgetReference((PyObject *) v); /* DECREF items deleted by shrinkage */ for (i = newsize; i < oldsize; i++) { Py_CLEAR(v->ob_item[i]); } sv = PyObject_GC_Resize(PyTupleObject, v, newsize); if (sv == NULL) { *pv = NULL; PyObject_GC_Del(v); return -1; } _Py_NewReference((PyObject *) sv); /* Zero out items added by growing */ if (newsize > oldsize) bzero(&sv->ob_item[oldsize], sizeof(*sv->ob_item) * (newsize - oldsize)); *pv = (PyObject *) sv; _PyObject_GC_TRACK(sv); return 0; } int PyTuple_ClearFreeList(void) { int freelist_size = 0; #if PyTuple_MAXSAVESIZE > 0 int i; for (i = 1; i < PyTuple_MAXSAVESIZE; i++) { PyTupleObject *p, *q; p = free_list[i]; freelist_size += numfree[i]; free_list[i] = NULL; numfree[i] = 0; while (p) { q = p; p = (PyTupleObject *)(p->ob_item[0]); PyObject_GC_Del(q); } } #endif return freelist_size; } void PyTuple_Fini(void) { #if PyTuple_MAXSAVESIZE > 0 /* empty tuples are used all over the place and applications may * rely on the fact that an empty tuple is a singleton. */ Py_CLEAR(free_list[0]); (void)PyTuple_ClearFreeList(); #endif #ifdef SHOW_TRACK_COUNT show_track(); #endif } /*********************** Tuple Iterator **************************/ typedef struct { PyObject_HEAD Py_ssize_t it_index; PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */ } tupleiterobject; static void tupleiter_dealloc(tupleiterobject *it) { _PyObject_GC_UNTRACK(it); Py_XDECREF(it->it_seq); PyObject_GC_Del(it); } static int tupleiter_traverse(tupleiterobject *it, visitproc visit, void *arg) { Py_VISIT(it->it_seq); return 0; } static PyObject * tupleiter_next(tupleiterobject *it) { PyTupleObject *seq; PyObject *item; assert(it != NULL); seq = it->it_seq; if (seq == NULL) return NULL; assert(PyTuple_Check(seq)); if (it->it_index < PyTuple_GET_SIZE(seq)) { item = PyTuple_GET_ITEM(seq, it->it_index); ++it->it_index; Py_INCREF(item); return item; } it->it_seq = NULL; Py_DECREF(seq); return NULL; } static PyObject * tupleiter_len(tupleiterobject *it) { Py_ssize_t len = 0; if (it->it_seq) len = PyTuple_GET_SIZE(it->it_seq) - it->it_index; return PyLong_FromSsize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * tupleiter_reduce(tupleiterobject *it) { if (it->it_seq) return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"), it->it_seq, it->it_index); else return Py_BuildValue("N(())", _PyObject_GetBuiltin("iter")); } static PyObject * tupleiter_setstate(tupleiterobject *it, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; if (it->it_seq != NULL) { if (index < 0) index = 0; else if (index > PyTuple_GET_SIZE(it->it_seq)) index = PyTuple_GET_SIZE(it->it_seq); /* exhausted iterator */ it->it_index = index; } Py_RETURN_NONE; } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef tupleiter_methods[] = { {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)tupleiter_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)tupleiter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyTupleIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "tuple_iterator", /* tp_name */ sizeof(tupleiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)tupleiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)tupleiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)tupleiter_next, /* tp_iternext */ tupleiter_methods, /* tp_methods */ 0, }; static PyObject * tuple_iter(PyObject *seq) { tupleiterobject *it; if (!PyTuple_Check(seq)) { PyErr_BadInternalCall(); return NULL; } it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type); if (it == NULL) return NULL; it->it_index = 0; Py_INCREF(seq); it->it_seq = (PyTupleObject *)seq; _PyObject_GC_TRACK(it); return (PyObject *)it; }
32,165
1,096
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/abstract.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/log/log.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/iterobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longintrepr.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ /* Abstract Object Interface (many thanks to Jim Fulton) */ /* Shorthands to return certain errors */ static PyObject * type_error(const char *msg, PyObject *obj) { PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name); return NULL; } static PyObject * null_error(void) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_SystemError, "null argument to internal routine"); return NULL; } /* Operations on any object */ PyObject * PyObject_Type(PyObject *o) { PyObject *v; if (o == NULL) { return null_error(); } v = (PyObject *)o->ob_type; Py_INCREF(v); return v; } Py_ssize_t PyObject_Size(PyObject *o) { PySequenceMethods *m; if (o == NULL) { null_error(); return -1; } m = o->ob_type->tp_as_sequence; if (m && m->sq_length) return m->sq_length(o); return PyMapping_Size(o); } #undef PyObject_Length Py_ssize_t PyObject_Length(PyObject *o) { return PyObject_Size(o); } #define PyObject_Length PyObject_Size int _PyObject_HasLen(PyObject *o) { return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) || (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length); } /* The length hint function returns a non-negative value from o.__len__() or o.__length_hint__(). If those methods aren't found the defaultvalue is returned. If one of the calls fails with an exception other than TypeError this function returns -1. */ Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue) { PyObject *hint, *result; Py_ssize_t res; _Py_IDENTIFIER(__length_hint__); if (_PyObject_HasLen(o)) { res = PyObject_Length(o); if (res < 0 && PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_TypeError)) { return -1; } PyErr_Clear(); } else { return res; } } hint = _PyObject_LookupSpecial(o, &PyId___length_hint__); if (hint == NULL) { if (PyErr_Occurred()) { return -1; } return defaultvalue; } result = _PyObject_CallNoArg(hint); Py_DECREF(hint); if (result == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); return defaultvalue; } return -1; } else if (result == Py_NotImplemented) { Py_DECREF(result); return defaultvalue; } if (!PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s", Py_TYPE(result)->tp_name); Py_DECREF(result); return -1; } res = PyLong_AsSsize_t(result); Py_DECREF(result); if (res < 0 && PyErr_Occurred()) { return -1; } if (res < 0) { PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0"); return -1; } return res; } PyObject * PyObject_GetItem(PyObject *o, PyObject *key) { PyMappingMethods *m; if (o == NULL || key == NULL) { return null_error(); } m = o->ob_type->tp_as_mapping; if (m && m->mp_subscript) { PyObject *item = m->mp_subscript(o, key); assert((item != NULL) ^ (PyErr_Occurred() != NULL)); return item; } if (o->ob_type->tp_as_sequence) { if (PyIndex_Check(key)) { Py_ssize_t key_value; key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); if (key_value == -1 && PyErr_Occurred()) return NULL; return PySequence_GetItem(o, key_value); } else if (o->ob_type->tp_as_sequence->sq_item) return type_error("sequence index must " "be integer, not '%.200s'", key); } return type_error("'%.200s' object is not subscriptable", o); } int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value) { PyMappingMethods *m; if (o == NULL || key == NULL || value == NULL) { null_error(); return -1; } m = o->ob_type->tp_as_mapping; if (m && m->mp_ass_subscript) return m->mp_ass_subscript(o, key, value); if (o->ob_type->tp_as_sequence) { if (PyIndex_Check(key)) { Py_ssize_t key_value; key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); if (key_value == -1 && PyErr_Occurred()) return -1; return PySequence_SetItem(o, key_value, value); } else if (o->ob_type->tp_as_sequence->sq_ass_item) { type_error("sequence index must be " "integer, not '%.200s'", key); return -1; } } type_error("'%.200s' object does not support item assignment", o); return -1; } int PyObject_DelItem(PyObject *o, PyObject *key) { PyMappingMethods *m; if (o == NULL || key == NULL) { null_error(); return -1; } m = o->ob_type->tp_as_mapping; if (m && m->mp_ass_subscript) return m->mp_ass_subscript(o, key, (PyObject*)NULL); if (o->ob_type->tp_as_sequence) { if (PyIndex_Check(key)) { Py_ssize_t key_value; key_value = PyNumber_AsSsize_t(key, PyExc_IndexError); if (key_value == -1 && PyErr_Occurred()) return -1; return PySequence_DelItem(o, key_value); } else if (o->ob_type->tp_as_sequence->sq_ass_item) { type_error("sequence index must be " "integer, not '%.200s'", key); return -1; } } type_error("'%.200s' object does not support item deletion", o); return -1; } int PyObject_DelItemString(PyObject *o, const char *key) { PyObject *okey; int ret; if (o == NULL || key == NULL) { null_error(); return -1; } okey = PyUnicode_FromString(key); if (okey == NULL) return -1; ret = PyObject_DelItem(o, okey); Py_DECREF(okey); return ret; } /* We release the buffer right after use of this function which could cause issues later on. Don't use these functions in new code. */ int PyObject_CheckReadBuffer(PyObject *obj) { PyBufferProcs *pb = obj->ob_type->tp_as_buffer; Py_buffer view; if (pb == NULL || pb->bf_getbuffer == NULL) return 0; if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) { PyErr_Clear(); return 0; } PyBuffer_Release(&view); return 1; } static int as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) { Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); return -1; } if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0) return -1; *buffer = view.buf; *buffer_len = view.len; PyBuffer_Release(&view); return 0; } int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len) { return as_read_buffer(obj, (const void **)buffer, buffer_len); } int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) { return as_read_buffer(obj, buffer, buffer_len); } int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) { PyBufferProcs *pb; Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); return -1; } pb = obj->ob_type->tp_as_buffer; if (pb == NULL || pb->bf_getbuffer == NULL || ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { PyErr_SetString(PyExc_TypeError, "expected a writable bytes-like object"); return -1; } *buffer = view.buf; *buffer_len = view.len; PyBuffer_Release(&view); return 0; } /* Buffer C-API for Python 3.0 */ int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { PyBufferProcs *pb = obj->ob_type->tp_as_buffer; if (pb == NULL || pb->bf_getbuffer == NULL) { PyErr_Format(PyExc_TypeError, "a bytes-like object is required, not '%.100s'", Py_TYPE(obj)->tp_name); return -1; } return (*pb->bf_getbuffer)(obj, view, flags); } static int _IsFortranContiguous(const Py_buffer *view) { Py_ssize_t sd, dim; int i; /* 1) len = product(shape) * itemsize 2) itemsize > 0 3) len = 0 <==> exists i: shape[i] = 0 */ if (view->len == 0) return 1; if (view->strides == NULL) { /* C-contiguous by definition */ /* Trivially F-contiguous */ if (view->ndim <= 1) return 1; /* ndim > 1 implies shape != NULL */ assert(view->shape != NULL); /* Effectively 1-d */ sd = 0; for (i=0; i<view->ndim; i++) { if (view->shape[i] > 1) sd += 1; } return sd <= 1; } /* strides != NULL implies both of these */ assert(view->ndim > 0); assert(view->shape != NULL); sd = view->itemsize; for (i=0; i<view->ndim; i++) { dim = view->shape[i]; if (dim > 1 && view->strides[i] != sd) { return 0; } sd *= dim; } return 1; } static int _IsCContiguous(const Py_buffer *view) { Py_ssize_t sd, dim; int i; /* 1) len = product(shape) * itemsize 2) itemsize > 0 3) len = 0 <==> exists i: shape[i] = 0 */ if (view->len == 0) return 1; if (view->strides == NULL) return 1; /* C-contiguous by definition */ /* strides != NULL implies both of these */ assert(view->ndim > 0); assert(view->shape != NULL); sd = view->itemsize; for (i=view->ndim-1; i>=0; i--) { dim = view->shape[i]; if (dim > 1 && view->strides[i] != sd) { return 0; } sd *= dim; } return 1; } int PyBuffer_IsContiguous(const Py_buffer *view, char order) { if (view->suboffsets != NULL) return 0; if (order == 'C') return _IsCContiguous(view); else if (order == 'F') return _IsFortranContiguous(view); else if (order == 'A') return (_IsCContiguous(view) || _IsFortranContiguous(view)); return 0; } void* PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices) { char* pointer; int i; pointer = (char *)view->buf; for (i = 0; i < view->ndim; i++) { pointer += view->strides[i]*indices[i]; if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) { pointer = *((char**)pointer) + view->suboffsets[i]; } } return (void*)pointer; } void _Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape) { int k; for (k=0; k<nd; k++) { if (index[k] < shape[k]-1) { index[k]++; break; } else { index[k] = 0; } } } void _Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape) { int k; for (k=nd-1; k>=0; k--) { if (index[k] < shape[k]-1) { index[k]++; break; } else { index[k] = 0; } } } int PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort) { int k; void (*addone)(int, Py_ssize_t *, const Py_ssize_t *); Py_ssize_t *indices, elements; char *src, *ptr; if (len > view->len) { len = view->len; } if (PyBuffer_IsContiguous(view, fort)) { /* simplest copy is all that is needed */ memcpy(view->buf, buf, len); return 0; } /* Otherwise a more elaborate scheme is needed */ /* view->ndim <= 64 */ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim)); if (indices == NULL) { PyErr_NoMemory(); return -1; } for (k=0; k<view->ndim;k++) { indices[k] = 0; } if (fort == 'F') { addone = _Py_add_one_to_index_F; } else { addone = _Py_add_one_to_index_C; } src = buf; /* XXX : This is not going to be the fastest code in the world several optimizations are possible. */ elements = len / view->itemsize; while (elements--) { ptr = PyBuffer_GetPointer(view, indices); memcpy(ptr, src, view->itemsize); src += view->itemsize; addone(view->ndim, indices, view->shape); } PyMem_Free(indices); return 0; } int PyObject_CopyData(PyObject *dest, PyObject *src) { Py_buffer view_dest, view_src; int k; Py_ssize_t *indices, elements; char *dptr, *sptr; if (!PyObject_CheckBuffer(dest) || !PyObject_CheckBuffer(src)) { PyErr_SetString(PyExc_TypeError, "both destination and source must be "\ "bytes-like objects"); return -1; } if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1; if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) { PyBuffer_Release(&view_dest); return -1; } if (view_dest.len < view_src.len) { PyErr_SetString(PyExc_BufferError, "destination is too small to receive data from source"); PyBuffer_Release(&view_dest); PyBuffer_Release(&view_src); return -1; } if ((PyBuffer_IsContiguous(&view_dest, 'C') && PyBuffer_IsContiguous(&view_src, 'C')) || (PyBuffer_IsContiguous(&view_dest, 'F') && PyBuffer_IsContiguous(&view_src, 'F'))) { /* simplest copy is all that is needed */ memcpy(view_dest.buf, view_src.buf, view_src.len); PyBuffer_Release(&view_dest); PyBuffer_Release(&view_src); return 0; } /* Otherwise a more elaborate copy scheme is needed */ /* XXX(nnorwitz): need to check for overflow! */ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim); if (indices == NULL) { PyErr_NoMemory(); PyBuffer_Release(&view_dest); PyBuffer_Release(&view_src); return -1; } for (k=0; k<view_src.ndim;k++) { indices[k] = 0; } elements = 1; for (k=0; k<view_src.ndim; k++) { /* XXX(nnorwitz): can this overflow? */ elements *= view_src.shape[k]; } while (elements--) { _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape); dptr = PyBuffer_GetPointer(&view_dest, indices); sptr = PyBuffer_GetPointer(&view_src, indices); memcpy(dptr, sptr, view_src.itemsize); } PyMem_Free(indices); PyBuffer_Release(&view_dest); PyBuffer_Release(&view_src); return 0; } void PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char fort) { int k; Py_ssize_t sd; sd = itemsize; if (fort == 'F') { for (k=0; k<nd; k++) { strides[k] = sd; sd *= shape[k]; } } else { for (k=nd-1; k>=0; k--) { strides[k] = sd; sd *= shape[k]; } } return; } int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int flags) { if (view == NULL) { PyErr_SetString(PyExc_BufferError, "PyBuffer_FillInfo: view==NULL argument is obsolete"); return -1; } if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && (readonly == 1)) { PyErr_SetString(PyExc_BufferError, "Object is not writable."); return -1; } view->obj = obj; if (obj) Py_INCREF(obj); view->buf = buf; view->len = len; view->readonly = readonly; view->itemsize = 1; view->format = NULL; if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) view->format = "B"; view->ndim = 1; view->shape = NULL; if ((flags & PyBUF_ND) == PyBUF_ND) view->shape = &(view->len); view->strides = NULL; if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) view->strides = &(view->itemsize); view->suboffsets = NULL; view->internal = NULL; return 0; } void PyBuffer_Release(Py_buffer *view) { PyObject *obj = view->obj; PyBufferProcs *pb; if (obj == NULL) return; pb = Py_TYPE(obj)->tp_as_buffer; if (pb && pb->bf_releasebuffer) pb->bf_releasebuffer(obj, view); view->obj = NULL; Py_DECREF(obj); } PyObject * PyObject_Format(PyObject *obj, PyObject *format_spec) { PyObject *meth; PyObject *empty = NULL; PyObject *result = NULL; _Py_IDENTIFIER(__format__); if (format_spec != NULL && !PyUnicode_Check(format_spec)) { PyErr_Format(PyExc_SystemError, "Format specifier must be a string, not %.200s", Py_TYPE(format_spec)->tp_name); return NULL; } /* Fast path for common types. */ if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) { if (PyUnicode_CheckExact(obj)) { Py_INCREF(obj); return obj; } if (PyLong_CheckExact(obj)) { return PyObject_Str(obj); } } /* If no format_spec is provided, use an empty string */ if (format_spec == NULL) { empty = PyUnicode_New(0, 0); format_spec = empty; } /* Find the (unbound!) __format__ method */ meth = _PyObject_LookupSpecial(obj, &PyId___format__); if (meth == NULL) { if (!PyErr_Occurred()) PyErr_Format(PyExc_TypeError, "Type %.100s doesn't define __format__", Py_TYPE(obj)->tp_name); goto done; } /* And call it. */ result = PyObject_CallFunctionObjArgs(meth, format_spec, NULL); Py_DECREF(meth); if (result && !PyUnicode_Check(result)) { PyErr_Format(PyExc_TypeError, "__format__ must return a str, not %.200s", Py_TYPE(result)->tp_name); Py_DECREF(result); result = NULL; goto done; } done: Py_XDECREF(empty); return result; } /* Operations on numbers */ int PyNumber_Check(PyObject *o) { return o && o->ob_type->tp_as_number && (o->ob_type->tp_as_number->nb_int || o->ob_type->tp_as_number->nb_float); } /* Binary operators */ #define NB_SLOT(x) offsetof(PyNumberMethods, x) #define NB_BINOP(nb_methods, slot) \ (*(binaryfunc*)(& ((char*)nb_methods)[slot])) #define NB_TERNOP(nb_methods, slot) \ (*(ternaryfunc*)(& ((char*)nb_methods)[slot])) /* Calling scheme used for binary operations: Order operations are tried until either a valid result or error: w.op(v,w)[*], v.op(v,w), w.op(v,w) [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of v->ob_type */ static PyObject * binary_op1(PyObject *v, PyObject *w, const int op_slot) { PyObject *x; binaryfunc slotv = NULL; binaryfunc slotw = NULL; if (v->ob_type->tp_as_number != NULL) slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); if (w->ob_type != v->ob_type && w->ob_type->tp_as_number != NULL) { slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); if (slotw == slotv) slotw = NULL; } if (slotv) { if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { x = slotw(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ slotw = NULL; } x = slotv(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ } if (slotw) { x = slotw(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ } Py_RETURN_NOTIMPLEMENTED; } static PyObject * binop_type_error(PyObject *v, PyObject *w, const char *op_name) { PyErr_Format(PyExc_TypeError, "unsupported operand type(s) for %.100s: " "'%.100s' and '%.100s'", op_name, v->ob_type->tp_name, w->ob_type->tp_name); return NULL; } static PyObject * binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name) { PyObject *result = binary_op1(v, w, op_slot); if (result == Py_NotImplemented) { Py_DECREF(result); return binop_type_error(v, w, op_name); } return result; } /* Calling scheme used for ternary operations: Order operations are tried until either a valid result or error: v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) */ static PyObject * ternary_op(PyObject *v, PyObject *w, PyObject *z, const int op_slot, const char *op_name) { PyNumberMethods *mv, *mw, *mz; PyObject *x = NULL; ternaryfunc slotv = NULL; ternaryfunc slotw = NULL; ternaryfunc slotz = NULL; mv = v->ob_type->tp_as_number; mw = w->ob_type->tp_as_number; if (mv != NULL) slotv = NB_TERNOP(mv, op_slot); if (w->ob_type != v->ob_type && mw != NULL) { slotw = NB_TERNOP(mw, op_slot); if (slotw == slotv) slotw = NULL; } if (slotv) { if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { x = slotw(v, w, z); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ slotw = NULL; } x = slotv(v, w, z); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ } if (slotw) { x = slotw(v, w, z); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ } mz = z->ob_type->tp_as_number; if (mz != NULL) { slotz = NB_TERNOP(mz, op_slot); if (slotz == slotv || slotz == slotw) slotz = NULL; if (slotz) { x = slotz(v, w, z); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it */ } } if (z == Py_None) PyErr_Format( PyExc_TypeError, "unsupported operand type(s) for ** or pow(): " "'%.100s' and '%.100s'", v->ob_type->tp_name, w->ob_type->tp_name); else PyErr_Format( PyExc_TypeError, "unsupported operand type(s) for pow(): " "'%.100s', '%.100s', '%.100s'", v->ob_type->tp_name, w->ob_type->tp_name, z->ob_type->tp_name); return NULL; } #define BINARY_FUNC(func, op, op_name) \ PyObject * \ func(PyObject *v, PyObject *w) { \ return binary_op(v, w, NB_SLOT(op), op_name); \ } BINARY_FUNC(PyNumber_Or, nb_or, "|") BINARY_FUNC(PyNumber_Xor, nb_xor, "^") BINARY_FUNC(PyNumber_And, nb_and, "&") BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<") BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>") BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-") BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()") PyObject * PyNumber_Add(PyObject *v, PyObject *w) { PyObject *result = binary_op1(v, w, NB_SLOT(nb_add)); if (result == Py_NotImplemented) { PySequenceMethods *m = v->ob_type->tp_as_sequence; Py_DECREF(result); if (m && m->sq_concat) { return (*m->sq_concat)(v, w); } result = binop_type_error(v, w, "+"); } return result; } static PyObject * sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n) { Py_ssize_t count; if (PyIndex_Check(n)) { count = PyNumber_AsSsize_t(n, PyExc_OverflowError); if (count == -1 && PyErr_Occurred()) return NULL; } else { return type_error("can't multiply sequence by " "non-int of type '%.200s'", n); } return (*repeatfunc)(seq, count); } PyObject * PyNumber_Multiply(PyObject *v, PyObject *w) { PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply)); if (result == Py_NotImplemented) { PySequenceMethods *mv = v->ob_type->tp_as_sequence; PySequenceMethods *mw = w->ob_type->tp_as_sequence; Py_DECREF(result); if (mv && mv->sq_repeat) { return sequence_repeat(mv->sq_repeat, v, w); } else if (mw && mw->sq_repeat) { return sequence_repeat(mw->sq_repeat, w, v); } result = binop_type_error(v, w, "*"); } return result; } PyObject * PyNumber_MatrixMultiply(PyObject *v, PyObject *w) { return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@"); } PyObject * PyNumber_FloorDivide(PyObject *v, PyObject *w) { return binary_op(v, w, NB_SLOT(nb_floor_divide), "//"); } PyObject * PyNumber_TrueDivide(PyObject *v, PyObject *w) { return binary_op(v, w, NB_SLOT(nb_true_divide), "/"); } PyObject * PyNumber_Remainder(PyObject *v, PyObject *w) { return binary_op(v, w, NB_SLOT(nb_remainder), "%"); } PyObject * PyNumber_Power(PyObject *v, PyObject *w, PyObject *z) { return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); } /* Binary in-place operators */ /* The in-place operators are defined to fall back to the 'normal', non in-place operations, if the in-place methods are not in place. - If the left hand object has the appropriate struct members, and they are filled, call the appropriate function and return the result. No coercion is done on the arguments; the left-hand object is the one the operation is performed on, and it's up to the function to deal with the right-hand object. - Otherwise, in-place modification is not supported. Handle it exactly as a non in-place operation of the same kind. */ static PyObject * binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot) { PyNumberMethods *mv = v->ob_type->tp_as_number; if (mv != NULL) { binaryfunc slot = NB_BINOP(mv, iop_slot); if (slot) { PyObject *x = (slot)(v, w); if (x != Py_NotImplemented) { return x; } Py_DECREF(x); } } return binary_op1(v, w, op_slot); } static PyObject * binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot, const char *op_name) { PyObject *result = binary_iop1(v, w, iop_slot, op_slot); if (result == Py_NotImplemented) { Py_DECREF(result); return binop_type_error(v, w, op_name); } return result; } #define INPLACE_BINOP(func, iop, op, op_name) \ PyObject * \ func(PyObject *v, PyObject *w) { \ return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \ } INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=") INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=") INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=") INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=") INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=") INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=") INPLACE_BINOP(PyNumber_InMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=") PyObject * PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w) { return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide), NB_SLOT(nb_floor_divide), "//="); } PyObject * PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w) { return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide), NB_SLOT(nb_true_divide), "/="); } PyObject * PyNumber_InPlaceAdd(PyObject *v, PyObject *w) { PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add), NB_SLOT(nb_add)); if (result == Py_NotImplemented) { PySequenceMethods *m = v->ob_type->tp_as_sequence; Py_DECREF(result); if (m != NULL) { binaryfunc f = NULL; f = m->sq_inplace_concat; if (f == NULL) f = m->sq_concat; if (f != NULL) return (*f)(v, w); } result = binop_type_error(v, w, "+="); } return result; } PyObject * PyNumber_InPlaceMultiply(PyObject *v, PyObject *w) { PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply), NB_SLOT(nb_multiply)); if (result == Py_NotImplemented) { ssizeargfunc f = NULL; PySequenceMethods *mv = v->ob_type->tp_as_sequence; PySequenceMethods *mw = w->ob_type->tp_as_sequence; Py_DECREF(result); if (mv != NULL) { f = mv->sq_inplace_repeat; if (f == NULL) f = mv->sq_repeat; if (f != NULL) return sequence_repeat(f, v, w); } else if (mw != NULL) { /* Note that the right hand operand should not be * mutated in this case so sq_inplace_repeat is not * used. */ if (mw->sq_repeat) return sequence_repeat(mw->sq_repeat, w, v); } result = binop_type_error(v, w, "*="); } return result; } PyObject * PyNumber_InPlaceMatrixMultiply(PyObject *v, PyObject *w) { return binary_iop(v, w, NB_SLOT(nb_inplace_matrix_multiply), NB_SLOT(nb_matrix_multiply), "@="); } PyObject * PyNumber_InPlaceRemainder(PyObject *v, PyObject *w) { return binary_iop(v, w, NB_SLOT(nb_inplace_remainder), NB_SLOT(nb_remainder), "%="); } PyObject * PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z) { if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_inplace_power != NULL) { return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**="); } else { return ternary_op(v, w, z, NB_SLOT(nb_power), "**="); } } /* Unary operators and functions */ PyObject * PyNumber_Negative(PyObject *o) { PyNumberMethods *m; if (o == NULL) { return null_error(); } m = o->ob_type->tp_as_number; if (m && m->nb_negative) return (*m->nb_negative)(o); return type_error("bad operand type for unary -: '%.200s'", o); } PyObject * PyNumber_Positive(PyObject *o) { PyNumberMethods *m; if (o == NULL) { return null_error(); } m = o->ob_type->tp_as_number; if (m && m->nb_positive) return (*m->nb_positive)(o); return type_error("bad operand type for unary +: '%.200s'", o); } PyObject * PyNumber_Invert(PyObject *o) { PyNumberMethods *m; if (o == NULL) { return null_error(); } m = o->ob_type->tp_as_number; if (m && m->nb_invert) return (*m->nb_invert)(o); return type_error("bad operand type for unary ~: '%.200s'", o); } PyObject * PyNumber_Absolute(PyObject *o) { PyNumberMethods *m; if (o == NULL) { return null_error(); } m = o->ob_type->tp_as_number; if (m && m->nb_absolute) return m->nb_absolute(o); return type_error("bad operand type for abs(): '%.200s'", o); } /* Return a Python int from the object item. Raise TypeError if the result is not an int or if the object cannot be interpreted as an index. */ PyObject * PyNumber_Index(PyObject *item) { PyObject *result = NULL; if (item == NULL) { return null_error(); } if (PyLong_Check(item)) { Py_INCREF(item); return item; } if (!PyIndex_Check(item)) { PyErr_Format(PyExc_TypeError, "'%.200s' object cannot be interpreted " "as an integer", item->ob_type->tp_name); return NULL; } result = item->ob_type->tp_as_number->nb_index(item); if (!result || PyLong_CheckExact(result)) return result; if (!PyLong_Check(result)) { PyErr_Format(PyExc_TypeError, "__index__ returned non-int (type %.200s)", result->ob_type->tp_name); Py_DECREF(result); return NULL; } /* Issue #17576: warn if 'result' not of exact type int. */ if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__index__ returned non-int (type %.200s). " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", result->ob_type->tp_name)) { Py_DECREF(result); return NULL; } return result; } /* Return an error on Overflow only if err is not NULL*/ Py_ssize_t PyNumber_AsSsize_t(PyObject *item, PyObject *err) { Py_ssize_t result; PyObject *runerr; PyObject *value = PyNumber_Index(item); if (value == NULL) return -1; /* We're done if PyLong_AsSsize_t() returns without error. */ result = PyLong_AsSsize_t(value); if (result != -1 || !(runerr = PyErr_Occurred())) goto finish; /* Error handling code -- only manage OverflowError differently */ if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) goto finish; PyErr_Clear(); /* If no error-handling desired then the default clipping is sufficient. */ if (!err) { assert(PyLong_Check(value)); /* Whether or not it is less than or equal to zero is determined by the sign of ob_size */ if (_PyLong_Sign(value) < 0) result = PY_SSIZE_T_MIN; else result = PY_SSIZE_T_MAX; } else { /* Otherwise replace the error with caller's error object. */ PyErr_Format(err, "cannot fit '%.200s' into an index-sized integer", item->ob_type->tp_name); } finish: Py_DECREF(value); return result; } PyObject * PyNumber_Long(PyObject *o) { PyObject *result; PyNumberMethods *m; PyObject *trunc_func; Py_buffer view; _Py_IDENTIFIER(__trunc__); if (o == NULL) { return null_error(); } if (PyLong_CheckExact(o)) { Py_INCREF(o); return o; } m = o->ob_type->tp_as_number; if (m && m->nb_int) { /* This should include subclasses of int */ result = (PyObject *)_PyLong_FromNbInt(o); if (result != NULL && !PyLong_CheckExact(result)) { Py_SETREF(result, _PyLong_Copy((PyLongObject *)result)); } return result; } trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__); if (trunc_func) { result = PyEval_CallObject(trunc_func, NULL); Py_DECREF(trunc_func); if (result == NULL || PyLong_CheckExact(result)) { return result; } if (PyLong_Check(result)) { Py_SETREF(result, _PyLong_Copy((PyLongObject *)result)); return result; } /* __trunc__ is specified to return an Integral type, but int() needs to return an int. */ m = result->ob_type->tp_as_number; if (m == NULL || m->nb_int == NULL) { PyErr_Format( PyExc_TypeError, "__trunc__ returned non-Integral (type %.200s)", result->ob_type->tp_name); Py_DECREF(result); return NULL; } Py_SETREF(result, (PyObject *)_PyLong_FromNbInt(result)); if (result != NULL && !PyLong_CheckExact(result)) { Py_SETREF(result, _PyLong_Copy((PyLongObject *)result)); } return result; } if (PyErr_Occurred()) return NULL; if (PyUnicode_Check(o)) /* The below check is done in PyLong_FromUnicode(). */ return PyLong_FromUnicodeObject(o, 10); if (PyBytes_Check(o)) /* need to do extra error checking that PyLong_FromString() * doesn't do. In particular int('9\x005') must raise an * exception, not truncate at the null. */ return _PyLong_FromBytes(PyBytes_AS_STRING(o), PyBytes_GET_SIZE(o), 10); if (PyByteArray_Check(o)) return _PyLong_FromBytes(PyByteArray_AS_STRING(o), PyByteArray_GET_SIZE(o), 10); if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) { PyObject *bytes; /* Copy to NUL-terminated buffer. */ bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len); if (bytes == NULL) { PyBuffer_Release(&view); return NULL; } result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes), 10); Py_DECREF(bytes); PyBuffer_Release(&view); return result; } return type_error("int() argument must be a string, a bytes-like object " "or a number, not '%.200s'", o); } PyObject * PyNumber_Float(PyObject *o) { PyNumberMethods *m; if (o == NULL) { return null_error(); } if (PyFloat_CheckExact(o)) { Py_INCREF(o); return o; } m = o->ob_type->tp_as_number; if (m && m->nb_float) { /* This should include subclasses of float */ PyObject *res = m->nb_float(o); double val; if (!res || PyFloat_CheckExact(res)) { return res; } if (!PyFloat_Check(res)) { PyErr_Format(PyExc_TypeError, "%.50s.__float__ returned non-float (type %.50s)", o->ob_type->tp_name, res->ob_type->tp_name); Py_DECREF(res); return NULL; } /* Issue #26983: warn if 'res' not of exact type float. */ if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "%.50s.__float__ returned non-float (type %.50s). " "The ability to return an instance of a strict subclass of float " "is deprecated, and may be removed in a future version of Python.", o->ob_type->tp_name, res->ob_type->tp_name)) { Py_DECREF(res); return NULL; } val = PyFloat_AS_DOUBLE(res); Py_DECREF(res); return PyFloat_FromDouble(val); } if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */ return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o)); } return PyFloat_FromString(o); } PyObject * PyNumber_ToBase(PyObject *n, int base) { PyObject *res = NULL; PyObject *index = PyNumber_Index(n); if (!index) return NULL; if (PyLong_Check(index)) res = _PyLong_Format(index, base); else /* It should not be possible to get here, as PyNumber_Index already has a check for the same condition */ PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not int"); Py_DECREF(index); return res; } /* Operations on sequences */ int PySequence_Check(PyObject *s) { if (PyDict_Check(s)) return 0; return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } Py_ssize_t PySequence_Size(PyObject *s) { PySequenceMethods *m; if (s == NULL) { null_error(); return -1; } m = s->ob_type->tp_as_sequence; if (m && m->sq_length) return m->sq_length(s); type_error("object of type '%.200s' has no len()", s); return -1; } #undef PySequence_Length Py_ssize_t PySequence_Length(PyObject *s) { return PySequence_Size(s); } #define PySequence_Length PySequence_Size PyObject * PySequence_Concat(PyObject *s, PyObject *o) { PySequenceMethods *m; if (s == NULL || o == NULL) { return null_error(); } m = s->ob_type->tp_as_sequence; if (m && m->sq_concat) return m->sq_concat(s, o); /* Instances of user classes defining an __add__() method only have an nb_add slot, not an sq_concat slot. So we fall back to nb_add if both arguments appear to be sequences. */ if (PySequence_Check(s) && PySequence_Check(o)) { PyObject *result = binary_op1(s, o, NB_SLOT(nb_add)); if (result != Py_NotImplemented) return result; Py_DECREF(result); } return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_Repeat(PyObject *o, Py_ssize_t count) { PySequenceMethods *m; if (o == NULL) { return null_error(); } m = o->ob_type->tp_as_sequence; if (m && m->sq_repeat) return m->sq_repeat(o, count); /* Instances of user classes defining a __mul__() method only have an nb_multiply slot, not an sq_repeat slot. so we fall back to nb_multiply if o appears to be a sequence. */ if (PySequence_Check(o)) { PyObject *n, *result; n = PyLong_FromSsize_t(count); if (n == NULL) return NULL; result = binary_op1(o, n, NB_SLOT(nb_multiply)); Py_DECREF(n); if (result != Py_NotImplemented) return result; Py_DECREF(result); } return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_InPlaceConcat(PyObject *s, PyObject *o) { PySequenceMethods *m; if (s == NULL || o == NULL) { return null_error(); } m = s->ob_type->tp_as_sequence; if (m && m->sq_inplace_concat) return m->sq_inplace_concat(s, o); if (m && m->sq_concat) return m->sq_concat(s, o); if (PySequence_Check(s) && PySequence_Check(o)) { PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add), NB_SLOT(nb_add)); if (result != Py_NotImplemented) return result; Py_DECREF(result); } return type_error("'%.200s' object can't be concatenated", s); } PyObject * PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count) { PySequenceMethods *m; if (o == NULL) { return null_error(); } m = o->ob_type->tp_as_sequence; if (m && m->sq_inplace_repeat) return m->sq_inplace_repeat(o, count); if (m && m->sq_repeat) return m->sq_repeat(o, count); if (PySequence_Check(o)) { PyObject *n, *result; n = PyLong_FromSsize_t(count); if (n == NULL) return NULL; result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply), NB_SLOT(nb_multiply)); Py_DECREF(n); if (result != Py_NotImplemented) return result; Py_DECREF(result); } return type_error("'%.200s' object can't be repeated", o); } PyObject * PySequence_GetItem(PyObject *s, Py_ssize_t i) { PySequenceMethods *m; if (s == NULL) { return null_error(); } m = s->ob_type->tp_as_sequence; if (m && m->sq_item) { if (i < 0) { if (m->sq_length) { Py_ssize_t l = (*m->sq_length)(s); if (l < 0) { assert(PyErr_Occurred()); return NULL; } i += l; } } return m->sq_item(s, i); } return type_error("'%.200s' object does not support indexing", s); } PyObject * PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { PyMappingMethods *mp; if (!s) { return null_error(); } mp = s->ob_type->tp_as_mapping; if (mp && mp->mp_subscript) { PyObject *res; PyObject *slice = _PySlice_FromIndices(i1, i2); if (!slice) return NULL; res = mp->mp_subscript(s, slice); Py_DECREF(slice); return res; } return type_error("'%.200s' object is unsliceable", s); } int PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o) { PySequenceMethods *m; if (s == NULL) { null_error(); return -1; } m = s->ob_type->tp_as_sequence; if (m && m->sq_ass_item) { if (i < 0) { if (m->sq_length) { Py_ssize_t l = (*m->sq_length)(s); if (l < 0) return -1; i += l; } } return m->sq_ass_item(s, i, o); } type_error("'%.200s' object does not support item assignment", s); return -1; } int PySequence_DelItem(PyObject *s, Py_ssize_t i) { PySequenceMethods *m; if (s == NULL) { null_error(); return -1; } m = s->ob_type->tp_as_sequence; if (m && m->sq_ass_item) { if (i < 0) { if (m->sq_length) { Py_ssize_t l = (*m->sq_length)(s); if (l < 0) return -1; i += l; } } return m->sq_ass_item(s, i, (PyObject *)NULL); } type_error("'%.200s' object doesn't support item deletion", s); return -1; } int PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o) { PyMappingMethods *mp; if (s == NULL) { null_error(); return -1; } mp = s->ob_type->tp_as_mapping; if (mp && mp->mp_ass_subscript) { int res; PyObject *slice = _PySlice_FromIndices(i1, i2); if (!slice) return -1; res = mp->mp_ass_subscript(s, slice, o); Py_DECREF(slice); return res; } type_error("'%.200s' object doesn't support slice assignment", s); return -1; } int PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2) { PyMappingMethods *mp; if (s == NULL) { null_error(); return -1; } mp = s->ob_type->tp_as_mapping; if (mp && mp->mp_ass_subscript) { int res; PyObject *slice = _PySlice_FromIndices(i1, i2); if (!slice) return -1; res = mp->mp_ass_subscript(s, slice, NULL); Py_DECREF(slice); return res; } type_error("'%.200s' object doesn't support slice deletion", s); return -1; } PyObject * PySequence_Tuple(PyObject *v) { PyObject *it; /* iter(v) */ Py_ssize_t n; /* guess for result tuple size */ PyObject *result = NULL; Py_ssize_t j; if (v == NULL) { return null_error(); } /* Special-case the common tuple and list cases, for efficiency. */ if (PyTuple_CheckExact(v)) { /* Note that we can't know whether it's safe to return a tuple *subclass* instance as-is, hence the restriction to exact tuples here. In contrast, lists always make a copy, so there's no need for exactness below. */ Py_INCREF(v); return v; } if (PyList_CheckExact(v)) return PyList_AsTuple(v); /* Get iterator. */ it = PyObject_GetIter(v); if (it == NULL) return NULL; /* Guess result size and allocate space. */ n = PyObject_LengthHint(v, 10); if (n == -1) goto Fail; result = PyTuple_New(n); if (result == NULL) goto Fail; /* Fill the tuple. */ for (j = 0; ; ++j) { PyObject *item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) goto Fail; break; } if (j >= n) { size_t newn = (size_t)n; /* The over-allocation strategy can grow a bit faster than for lists because unlike lists the over-allocation isn't permanent -- we reclaim the excess before the end of this routine. So, grow by ten and then add 25%. */ newn += 10u; newn += newn >> 2; if (newn > PY_SSIZE_T_MAX) { /* Check for overflow */ PyErr_NoMemory(); Py_DECREF(item); goto Fail; } n = (Py_ssize_t)newn; if (_PyTuple_Resize(&result, n) != 0) { Py_DECREF(item); goto Fail; } } PyTuple_SET_ITEM(result, j, item); } /* Cut tuple back if guess was too large. */ if (j < n && _PyTuple_Resize(&result, j) != 0) goto Fail; Py_DECREF(it); return result; Fail: Py_XDECREF(result); Py_DECREF(it); return NULL; } PyObject * PySequence_List(PyObject *v) { PyObject *result; /* result list */ PyObject *rv; /* return value from PyList_Extend */ if (v == NULL) { return null_error(); } result = PyList_New(0); if (result == NULL) return NULL; rv = _PyList_Extend((PyListObject *)result, v); if (rv == NULL) { Py_DECREF(result); return NULL; } Py_DECREF(rv); return result; } PyObject * PySequence_Fast(PyObject *v, const char *m) { PyObject *it; if (v == NULL) { return null_error(); } if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) { Py_INCREF(v); return v; } it = PyObject_GetIter(v); if (it == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) PyErr_SetString(PyExc_TypeError, m); return NULL; } v = PySequence_List(it); Py_DECREF(it); return v; } /* Iterate over seq. Result depends on the operation: PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq. PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq; set ValueError and return -1 if none found; also return -1 on error. Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error. */ Py_ssize_t _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation) { Py_ssize_t n; int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */ PyObject *it; /* iter(seq) */ if (seq == NULL || obj == NULL) { null_error(); return -1; } it = PyObject_GetIter(seq); if (it == NULL) { type_error("argument of type '%.200s' is not iterable", seq); return -1; } n = wrapped = 0; for (;;) { int cmp; PyObject *item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) goto Fail; break; } cmp = PyObject_RichCompareBool(obj, item, Py_EQ); Py_DECREF(item); if (cmp < 0) goto Fail; if (cmp > 0) { switch (operation) { case PY_ITERSEARCH_COUNT: if (n == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "count exceeds C integer size"); goto Fail; } ++n; break; case PY_ITERSEARCH_INDEX: if (wrapped) { PyErr_SetString(PyExc_OverflowError, "index exceeds C integer size"); goto Fail; } goto Done; case PY_ITERSEARCH_CONTAINS: n = 1; goto Done; default: assert(!"unknown operation"); } } if (operation == PY_ITERSEARCH_INDEX) { if (n == PY_SSIZE_T_MAX) wrapped = 1; ++n; } } if (operation != PY_ITERSEARCH_INDEX) goto Done; PyErr_SetString(PyExc_ValueError, "sequence.index(x): x not in sequence"); /* fall into failure code */ Fail: n = -1; /* fall through */ Done: Py_DECREF(it); return n; } /* Return # of times o appears in s. */ Py_ssize_t PySequence_Count(PyObject *s, PyObject *o) { return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT); } /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq. * Use sq_contains if possible, else defer to _PySequence_IterSearch(). */ int PySequence_Contains(PyObject *seq, PyObject *ob) { Py_ssize_t result; PySequenceMethods *sqm = seq->ob_type->tp_as_sequence; if (sqm != NULL && sqm->sq_contains != NULL) return (*sqm->sq_contains)(seq, ob); result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS); return Py_SAFE_DOWNCAST(result, Py_ssize_t, int); } /* Backwards compatibility */ #undef PySequence_In int PySequence_In(PyObject *w, PyObject *v) { return PySequence_Contains(w, v); } Py_ssize_t PySequence_Index(PyObject *s, PyObject *o) { return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX); } /* Operations on mappings */ int PyMapping_Check(PyObject *o) { return o && o->ob_type->tp_as_mapping && o->ob_type->tp_as_mapping->mp_subscript; } Py_ssize_t PyMapping_Size(PyObject *o) { PyMappingMethods *m; if (o == NULL) { null_error(); return -1; } m = o->ob_type->tp_as_mapping; if (m && m->mp_length) return m->mp_length(o); type_error("object of type '%.200s' has no len()", o); return -1; } #undef PyMapping_Length Py_ssize_t PyMapping_Length(PyObject *o) { return PyMapping_Size(o); } #define PyMapping_Length PyMapping_Size PyObject * PyMapping_GetItemString(PyObject *o, const char *key) { PyObject *okey, *r; if (key == NULL) { return null_error(); } okey = PyUnicode_FromString(key); if (okey == NULL) return NULL; r = PyObject_GetItem(o, okey); Py_DECREF(okey); return r; } int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value) { PyObject *okey; int r; if (key == NULL) { null_error(); return -1; } okey = PyUnicode_FromString(key); if (okey == NULL) return -1; r = PyObject_SetItem(o, okey, value); Py_DECREF(okey); return r; } int PyMapping_HasKeyString(PyObject *o, const char *key) { PyObject *v; v = PyMapping_GetItemString(o, key); if (v) { Py_DECREF(v); return 1; } PyErr_Clear(); return 0; } int PyMapping_HasKey(PyObject *o, PyObject *key) { PyObject *v; v = PyObject_GetItem(o, key); if (v) { Py_DECREF(v); return 1; } PyErr_Clear(); return 0; } PyObject * PyMapping_Keys(PyObject *o) { PyObject *keys; PyObject *fast; _Py_IDENTIFIER(keys); if (PyDict_CheckExact(o)) return PyDict_Keys(o); keys = _PyObject_CallMethodId(o, &PyId_keys, NULL); if (keys == NULL) return NULL; fast = PySequence_Fast(keys, "o.keys() are not iterable"); Py_DECREF(keys); return fast; } PyObject * PyMapping_Items(PyObject *o) { PyObject *items; PyObject *fast; _Py_IDENTIFIER(items); if (PyDict_CheckExact(o)) return PyDict_Items(o); items = _PyObject_CallMethodId(o, &PyId_items, NULL); if (items == NULL) return NULL; fast = PySequence_Fast(items, "o.items() are not iterable"); Py_DECREF(items); return fast; } PyObject * PyMapping_Values(PyObject *o) { PyObject *values; PyObject *fast; _Py_IDENTIFIER(values); if (PyDict_CheckExact(o)) return PyDict_Values(o); values = _PyObject_CallMethodId(o, &PyId_values, NULL); if (values == NULL) return NULL; fast = PySequence_Fast(values, "o.values() are not iterable"); Py_DECREF(values); return fast; } /* isinstance(), issubclass() */ /* abstract_get_bases() has logically 4 return states: * * 1. getattr(cls, '__bases__') could raise an AttributeError * 2. getattr(cls, '__bases__') could raise some other exception * 3. getattr(cls, '__bases__') could return a tuple * 4. getattr(cls, '__bases__') could return something other than a tuple * * Only state #3 is a non-error state and only it returns a non-NULL object * (it returns the retrieved tuple). * * Any raised AttributeErrors are masked by clearing the exception and * returning NULL. If an object other than a tuple comes out of __bases__, * then again, the return value is NULL. So yes, these two situations * produce exactly the same results: NULL is returned and no error is set. * * If some exception other than AttributeError is raised, then NULL is also * returned, but the exception is not cleared. That's because we want the * exception to be propagated along. * * Callers are expected to test for PyErr_Occurred() when the return value * is NULL to decide whether a valid exception should be propagated or not. * When there's no exception to propagate, it's customary for the caller to * set a TypeError. */ static PyObject * abstract_get_bases(PyObject *cls) { _Py_IDENTIFIER(__bases__); PyObject *bases; Py_ALLOW_RECURSION bases = _PyObject_GetAttrId(cls, &PyId___bases__); Py_END_ALLOW_RECURSION if (bases == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); return NULL; } if (!PyTuple_Check(bases)) { Py_DECREF(bases); return NULL; } return bases; } static int abstract_issubclass(PyObject *derived, PyObject *cls) { PyObject *bases = NULL; Py_ssize_t i, n; int r = 0; while (1) { if (derived == cls) return 1; bases = abstract_get_bases(derived); if (bases == NULL) { if (PyErr_Occurred()) return -1; return 0; } n = PyTuple_GET_SIZE(bases); if (n == 0) { Py_DECREF(bases); return 0; } /* Avoid recursivity in the single inheritance case */ if (n == 1) { derived = PyTuple_GET_ITEM(bases, 0); Py_DECREF(bases); continue; } for (i = 0; i < n; i++) { r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls); if (r != 0) break; } Py_DECREF(bases); return r; } } static int check_class(PyObject *cls, const char *error) { PyObject *bases = abstract_get_bases(cls); if (bases == NULL) { /* Do not mask errors. */ if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, error); return 0; } Py_DECREF(bases); return -1; } static int recursive_isinstance(PyObject *inst, PyObject *cls) { PyObject *icls; int retval = 0; _Py_IDENTIFIER(__class__); if (PyType_Check(cls)) { retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls); if (retval == 0) { PyObject *c = _PyObject_GetAttrId(inst, &PyId___class__); if (c == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); else retval = -1; } else { if (c != (PyObject *)(inst->ob_type) && PyType_Check(c)) retval = PyType_IsSubtype( (PyTypeObject *)c, (PyTypeObject *)cls); Py_DECREF(c); } } } else { if (!check_class(cls, "isinstance() arg 2 must be a type or tuple of types")) return -1; icls = _PyObject_GetAttrId(inst, &PyId___class__); if (icls == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); else retval = -1; } else { retval = abstract_issubclass(icls, cls); Py_DECREF(icls); } } return retval; } int PyObject_IsInstance(PyObject *inst, PyObject *cls) { _Py_IDENTIFIER(__instancecheck__); PyObject *checker; /* Quick test for an exact match */ if (Py_TYPE(inst) == (PyTypeObject *)cls) return 1; /* We know what type's __instancecheck__ does. */ if (PyType_CheckExact(cls)) { return recursive_isinstance(inst, cls); } if (PyTuple_Check(cls)) { Py_ssize_t i; Py_ssize_t n; int r = 0; if (Py_EnterRecursiveCall(" in __instancecheck__")) return -1; n = PyTuple_GET_SIZE(cls); for (i = 0; i < n; ++i) { PyObject *item = PyTuple_GET_ITEM(cls, i); r = PyObject_IsInstance(inst, item); if (r != 0) /* either found it, or got an error */ break; } Py_LeaveRecursiveCall(); return r; } checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__); if (checker != NULL) { PyObject *res; int ok = -1; if (Py_EnterRecursiveCall(" in __instancecheck__")) { Py_DECREF(checker); return ok; } res = PyObject_CallFunctionObjArgs(checker, inst, NULL); Py_LeaveRecursiveCall(); Py_DECREF(checker); if (res != NULL) { ok = PyObject_IsTrue(res); Py_DECREF(res); } return ok; } else if (PyErr_Occurred()) return -1; /* Probably never reached anymore. */ return recursive_isinstance(inst, cls); } static int recursive_issubclass(PyObject *derived, PyObject *cls) { if (PyType_Check(cls) && PyType_Check(derived)) { /* Fast path (non-recursive) */ return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls); } if (!check_class(derived, "issubclass() arg 1 must be a class")) return -1; if (!check_class(cls, "issubclass() arg 2 must be a class" " or tuple of classes")) return -1; return abstract_issubclass(derived, cls); } int PyObject_IsSubclass(PyObject *derived, PyObject *cls) { _Py_IDENTIFIER(__subclasscheck__); PyObject *checker; /* We know what type's __subclasscheck__ does. */ if (PyType_CheckExact(cls)) { /* Quick test for an exact match */ if (derived == cls) return 1; return recursive_issubclass(derived, cls); } if (PyTuple_Check(cls)) { Py_ssize_t i; Py_ssize_t n; int r = 0; if (Py_EnterRecursiveCall(" in __subclasscheck__")) return -1; n = PyTuple_GET_SIZE(cls); for (i = 0; i < n; ++i) { PyObject *item = PyTuple_GET_ITEM(cls, i); r = PyObject_IsSubclass(derived, item); if (r != 0) /* either found it, or got an error */ break; } Py_LeaveRecursiveCall(); return r; } checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__); if (checker != NULL) { PyObject *res; int ok = -1; if (Py_EnterRecursiveCall(" in __subclasscheck__")) { Py_DECREF(checker); return ok; } res = PyObject_CallFunctionObjArgs(checker, derived, NULL); Py_LeaveRecursiveCall(); Py_DECREF(checker); if (res != NULL) { ok = PyObject_IsTrue(res); Py_DECREF(res); } return ok; } else if (PyErr_Occurred()) return -1; /* Probably never reached anymore. */ return recursive_issubclass(derived, cls); } int _PyObject_RealIsInstance(PyObject *inst, PyObject *cls) { return recursive_isinstance(inst, cls); } int _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls) { return recursive_issubclass(derived, cls); } PyObject * PyObject_GetIter(PyObject *o) { PyTypeObject *t = o->ob_type; getiterfunc f; f = t->tp_iter; if (f == NULL) { if (PySequence_Check(o)) return PySeqIter_New(o); return type_error("'%.200s' object is not iterable", o); } else { PyObject *res = (*f)(o); if (res != NULL && !PyIter_Check(res)) { PyErr_Format(PyExc_TypeError, "iter() returned non-iterator " "of type '%.100s'", res->ob_type->tp_name); Py_DECREF(res); res = NULL; } return res; } } /* Return next item. * If an error occurs, return NULL. PyErr_Occurred() will be true. * If the iteration terminates normally, return NULL and clear the * PyExc_StopIteration exception (if it was set). PyErr_Occurred() * will be false. * Else return the next object. PyErr_Occurred() will be false. */ PyObject * PyIter_Next(PyObject *iter) { PyObject *result; result = (*iter->ob_type->tp_iternext)(iter); if (result == NULL && PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_StopIteration)) PyErr_Clear(); return result; } /* * Flatten a sequence of bytes() objects into a C array of * NULL terminated string pointers with a NULL char* terminating the array. * (ie: an argv or env list) * * Memory allocated for the returned list is allocated using PyMem_Malloc() * and MUST be freed by _Py_FreeCharPArray(). */ char *const * _PySequence_BytesToCharpArray(PyObject* self) { char **array; Py_ssize_t i, argc; PyObject *item = NULL; Py_ssize_t size; argc = PySequence_Size(self); if (argc == -1) return NULL; assert(argc >= 0); if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) { PyErr_NoMemory(); return NULL; } array = PyMem_Malloc((argc + 1) * sizeof(char *)); if (array == NULL) { PyErr_NoMemory(); return NULL; } for (i = 0; i < argc; ++i) { char *data; item = PySequence_GetItem(self, i); if (item == NULL) { /* NULL terminate before freeing. */ array[i] = NULL; goto fail; } data = PyBytes_AsString(item); if (data == NULL) { /* NULL terminate before freeing. */ array[i] = NULL; goto fail; } size = PyBytes_GET_SIZE(item) + 1; array[i] = PyMem_Malloc(size); if (!array[i]) { PyErr_NoMemory(); goto fail; } memcpy(array[i], data, size); Py_DECREF(item); } array[argc] = NULL; return array; fail: Py_XDECREF(item); _Py_FreeCharPArray(array); return NULL; } /* Free's a NULL terminated char** array of C strings. */ void _Py_FreeCharPArray(char *const array[]) { Py_ssize_t i; for (i = 0; array[i] != NULL; ++i) { PyMem_Free(array[i]); } PyMem_Free((void*)array); }
68,527
2,605
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/dict-common.h
#ifndef Py_DICT_COMMON_H #define Py_DICT_COMMON_H #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/object.h" /* clang-format off */ typedef struct { /* Cached hash code of me_key. */ Py_hash_t me_hash; PyObject *me_key; PyObject *me_value; /* This field is only meaningful for combined tables */ } PyDictKeyEntry; /* dict_lookup_func() returns index of entry which can be used like * DK_ENTRIES(dk)[index]. -1 when no entry found, -3 when compare raises * error. */ typedef Py_ssize_t (*dict_lookup_func) (PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos); #define DKIX_EMPTY (-1) #define DKIX_DUMMY (-2) /* Used internally */ #define DKIX_ERROR (-3) /* See dictobject.c for actual layout of DictKeysObject */ struct _dictkeysobject { Py_ssize_t dk_refcnt; /* Size of the hash table (dk_indices). It must be a power of 2. */ Py_ssize_t dk_size; /* Function to lookup in the hash table (dk_indices): - lookdict(): general-purpose, and may return DKIX_ERROR if (and only if) a comparison raises an exception. - lookdict_unicode(): specialized to Unicode string keys, comparison of which can never raise an exception; that function can never return DKIX_ERROR. - lookdict_unicode_nodummy(): similar to lookdict_unicode() but further specialized for Unicode string keys that cannot be the <dummy> value. - lookdict_split(): Version of lookdict() for split tables. */ dict_lookup_func dk_lookup; /* Number of usable entries in dk_entries. */ Py_ssize_t dk_usable; /* Number of used entries in dk_entries. */ Py_ssize_t dk_nentries; /* Actual hash table of dk_size entries. It holds indices in dk_entries, or DKIX_EMPTY(-1) or DKIX_DUMMY(-2). Indices must be: 0 <= indice < USABLE_FRACTION(dk_size). The size in bytes of an indice depends on dk_size: - 1 byte if dk_size <= 0xff (char*) - 2 bytes if dk_size <= 0xffff (int16_t*) - 4 bytes if dk_size <= 0xffffffff (int32_t*) - 8 bytes otherwise (int64_t*) Dynamically sized, SIZEOF_VOID_P is minimum. */ char dk_indices[]; /* char is required to avoid strict aliasing. */ /* "PyDictKeyEntry dk_entries[dk_usable];" array follows: see the DK_ENTRIES() macro */ }; #endif
2,413
74
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/boolobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/longintrepr.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/pymacro.h" /* clang-format off */ /* Boolean type, a subtype of int */ /* We define bool_repr to return "False" or "True" */ static PyObject *false_str = NULL; static PyObject *true_str = NULL; static PyObject * bool_repr(PyObject *self) { PyObject *s; if (self == Py_True) s = true_str ? true_str : (true_str = PyUnicode_InternFromString("True")); else s = false_str ? false_str : (false_str = PyUnicode_InternFromString("False")); Py_XINCREF(s); return s; } /* Function to return a bool from a C long */ PyObject *PyBool_FromLong(long ok) { PyObject *result; if (ok) result = Py_True; else result = Py_False; Py_INCREF(result); return result; } /* We define bool_new to always return either Py_True or Py_False */ static PyObject * bool_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"x", 0}; PyObject *x = Py_False; long ok; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x)) return NULL; ok = PyObject_IsTrue(x); if (ok < 0) return NULL; return PyBool_FromLong(ok); } /* Arithmetic operations redefined to return bool if both args are bool. */ static PyObject * bool_and(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) return PyLong_Type.tp_as_number->nb_and(a, b); return PyBool_FromLong((a == Py_True) & (b == Py_True)); } static PyObject * bool_or(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) return PyLong_Type.tp_as_number->nb_or(a, b); return PyBool_FromLong((a == Py_True) | (b == Py_True)); } static PyObject * bool_xor(PyObject *a, PyObject *b) { if (!PyBool_Check(a) || !PyBool_Check(b)) return PyLong_Type.tp_as_number->nb_xor(a, b); return PyBool_FromLong((a == Py_True) ^ (b == Py_True)); } /* Doc string */ PyDoc_STRVAR(bool_doc, "bool(x) -> bool\n\ \n\ Returns True when the argument x is true, False otherwise.\n\ The builtins True and False are the only two instances of the class bool.\n\ The class bool is a subclass of the class int, and cannot be subclassed."); /* Arithmetic methods -- only so we can override &, |, ^. */ static PyNumberMethods bool_as_number = { 0, /* nb_add */ 0, /* nb_subtract */ 0, /* nb_multiply */ 0, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ 0, /* nb_bool */ 0, /* nb_invert */ 0, /* nb_lshift */ 0, /* nb_rshift */ bool_and, /* nb_and */ bool_xor, /* nb_xor */ bool_or, /* nb_or */ 0, /* nb_int */ 0, /* nb_reserved */ 0, /* nb_float */ 0, /* nb_inplace_add */ 0, /* nb_inplace_subtract */ 0, /* nb_inplace_multiply */ 0, /* nb_inplace_remainder */ 0, /* nb_inplace_power */ 0, /* nb_inplace_lshift */ 0, /* nb_inplace_rshift */ 0, /* nb_inplace_and */ 0, /* nb_inplace_xor */ 0, /* nb_inplace_or */ 0, /* nb_floor_divide */ 0, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ 0, /* nb_index */ }; /* The type object for bool. Note that this cannot be subclassed! */ PyTypeObject PyBool_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "bool", sizeof(struct _longobject), 0, 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ bool_repr, /* tp_repr */ &bool_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ bool_repr, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ bool_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyLong_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ bool_new, /* tp_new */ }; /* The objects representing bool values False and True */ struct _longobject _Py_FalseStruct = { PyVarObject_HEAD_INIT(&PyBool_Type, 0) { 0 } }; struct _longobject _Py_TrueStruct = { PyVarObject_HEAD_INIT(&PyBool_Type, 1) { 1 } };
7,695
194
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/call.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/log/log.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/eval.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/iterobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longintrepr.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ int _PyObject_HasFastCall(PyObject *callable) { if (PyFunction_Check(callable)) { return 1; } else if (PyCFunction_Check(callable)) { return !(PyCFunction_GET_FLAGS(callable) & METH_VARARGS); } else { assert (PyCallable_Check(callable)); return 0; } } static PyObject * null_error(void) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_SystemError, "null argument to internal routine"); return NULL; } PyObject* (_Py_CheckFunctionResult)(PyObject *callable, PyObject *result, const char *where) { int err_occurred = (PyErr_Occurred() != NULL); assert((callable != NULL) ^ (where != NULL)); if (result == NULL) { if (!err_occurred) { if (callable) PyErr_Format(PyExc_SystemError, "%R returned NULL without setting an error", callable); else PyErr_Format(PyExc_SystemError, "%s returned NULL without setting an error", where); #ifdef Py_DEBUG /* Ensure that the bug is caught in debug mode */ Py_FatalError("a function returned NULL without setting an error"); #endif return NULL; } } else { if (err_occurred) { Py_DECREF(result); if (callable) { _PyErr_FormatFromCause(PyExc_SystemError, "%R returned a result with an error set", callable); } else { _PyErr_FormatFromCause(PyExc_SystemError, "%s returned a result with an error set", where); } #ifdef Py_DEBUG /* Ensure that the bug is caught in debug mode */ Py_FatalError("a function returned a result with an error set"); #endif return NULL; } } return result; } /* --- Core PyObject call functions ------------------------------- */ PyObject * _PyObject_FastCallDict(PyObject *callable, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { /* _PyObject_FastCallDict() must not be called with an exception set, because it can clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); assert(callable != NULL); assert(nargs >= 0); assert(nargs == 0 || args != NULL); assert(kwargs == NULL || PyDict_Check(kwargs)); if (PyFunction_Check(callable)) { return _PyFunction_FastCallDict(callable, args, nargs, kwargs); } else if (PyCFunction_Check(callable)) { return _PyCFunction_FastCallDict(callable, args, nargs, kwargs); } else { PyObject *argstuple, *result; ternaryfunc call; /* Slow-path: build a temporary tuple */ call = callable->ob_type->tp_call; if (call == NULL) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", callable->ob_type->tp_name); return NULL; } argstuple = _PyStack_AsTuple(args, nargs); if (argstuple == NULL) { return NULL; } if (Py_EnterRecursiveCall(" while calling a Python object")) { Py_DECREF(argstuple); return NULL; } result = (*call)(callable, argstuple, kwargs); Py_LeaveRecursiveCall(); Py_DECREF(argstuple); result = _Py_CheckFunctionResult(callable, result, NULL); return result; } } PyObject * _PyObject_FastCallKeywords(PyObject *callable, PyObject **stack, Py_ssize_t nargs, PyObject *kwnames) { /* _PyObject_FastCallKeywords() must not be called with an exception set, because it can clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); assert(nargs >= 0); assert(kwnames == NULL || PyTuple_CheckExact(kwnames)); /* kwnames must only contains str strings, no subclass, and all keys must be unique: these checks are implemented in Python/ceval.c and _PyArg_ParseStackAndKeywords(). */ if (PyFunction_Check(callable)) { return _PyFunction_FastCallKeywords(callable, stack, nargs, kwnames); } if (PyCFunction_Check(callable)) { return _PyCFunction_FastCallKeywords(callable, stack, nargs, kwnames); } else { /* Slow-path: build a temporary tuple for positional arguments and a temporary dictionary for keyword arguments (if any) */ ternaryfunc call; PyObject *argstuple; PyObject *kwdict, *result; Py_ssize_t nkwargs; nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames); assert((nargs == 0 && nkwargs == 0) || stack != NULL); call = callable->ob_type->tp_call; if (call == NULL) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", callable->ob_type->tp_name); return NULL; } argstuple = _PyStack_AsTuple(stack, nargs); if (argstuple == NULL) { return NULL; } if (nkwargs > 0) { kwdict = _PyStack_AsDict(stack + nargs, kwnames); if (kwdict == NULL) { Py_DECREF(argstuple); return NULL; } } else { kwdict = NULL; } if (Py_EnterRecursiveCall(" while calling a Python object")) { Py_DECREF(argstuple); Py_XDECREF(kwdict); return NULL; } result = (*call)(callable, argstuple, kwdict); Py_LeaveRecursiveCall(); Py_DECREF(argstuple); Py_XDECREF(kwdict); result = _Py_CheckFunctionResult(callable, result, NULL); return result; } } PyObject * PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs) { ternaryfunc call; PyObject *result; /* PyObject_Call() must not be called with an exception set, because it can clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); assert(PyTuple_Check(args)); assert(kwargs == NULL || PyDict_Check(kwargs)); if (PyFunction_Check(callable)) { return _PyFunction_FastCallDict(callable, &PyTuple_GET_ITEM(args, 0), PyTuple_GET_SIZE(args), kwargs); } else if (PyCFunction_Check(callable)) { return PyCFunction_Call(callable, args, kwargs); } else { call = callable->ob_type->tp_call; if (call == NULL) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable", callable->ob_type->tp_name); return NULL; } if (Py_EnterRecursiveCall(" while calling a Python object")) return NULL; result = (*call)(callable, args, kwargs); Py_LeaveRecursiveCall(); return _Py_CheckFunctionResult(callable, result, NULL); } } /* --- PyFunction call functions ---------------------------------- */ static PyObject* _Py_HOT_FUNCTION function_code_fastcall(PyCodeObject *co, PyObject **args, Py_ssize_t nargs, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = PyThreadState_GET(); PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized _PyFrame_New_NoTrack() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = _PyFrame_New_NoTrack(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = f->f_localsplus; for (i = 0; i < nargs; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); if (Py_REFCNT(f) > 1) { Py_DECREF(f); _PyObject_GC_TRACK(f); } else { ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; } return result; } PyObject * _PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *kwdefs, *closure, *name, *qualname; PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd, nk; PyObject *result; assert(func != NULL); assert(nargs >= 0); assert(nargs == 0 || args != NULL); assert(kwargs == NULL || PyDict_Check(kwargs)); if (co->co_kwonlyargcount == 0 && (kwargs == NULL || PyDict_GET_SIZE(kwargs) == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { /* Fast paths */ if (argdefs == NULL && co->co_argcount == nargs) { return function_code_fastcall(co, args, nargs, globals); } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); return function_code_fastcall(co, args, Py_SIZE(argdefs), globals); } } nk = (kwargs != NULL) ? PyDict_GET_SIZE(kwargs) : 0; if (nk != 0) { Py_ssize_t pos, i; /* Issue #29318: Caller and callee functions must not share the dictionary: kwargs must be copied. */ kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { return NULL; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { /* We must hold strong references because keyword arguments can be indirectly modified while the function is called: see issue #2016 and test_extcall */ Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } kwdefs = PyFunction_GET_KW_DEFAULTS(func); closure = PyFunction_GET_CLOSURE(func); name = ((PyFunctionObject *)func) -> func_name; qualname = ((PyFunctionObject *)func) -> func_qualname; if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } result = _PyEval_EvalCodeWithName((PyObject*)co, globals, (PyObject *)NULL, args, nargs, k, k != NULL ? k + 1 : NULL, nk, 2, d, nd, kwdefs, closure, name, qualname); Py_XDECREF(kwtuple); return result; } PyObject * _PyFunction_FastCallKeywords(PyObject *func, PyObject **stack, Py_ssize_t nargs, PyObject *kwnames) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *kwdefs, *closure, *name, *qualname; PyObject **d; Py_ssize_t nkwargs = (kwnames == NULL) ? 0 : PyTuple_GET_SIZE(kwnames); Py_ssize_t nd; assert(PyFunction_Check(func)); assert(nargs >= 0); assert(kwnames == NULL || PyTuple_CheckExact(kwnames)); assert((nargs == 0 && nkwargs == 0) || stack != NULL); /* kwnames must only contains str strings, no subclass, and all keys must be unique */ if (co->co_kwonlyargcount == 0 && nkwargs == 0 && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { return function_code_fastcall(co, stack, nargs, globals); } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ stack = &PyTuple_GET_ITEM(argdefs, 0); return function_code_fastcall(co, stack, Py_SIZE(argdefs), globals); } } kwdefs = PyFunction_GET_KW_DEFAULTS(func); closure = PyFunction_GET_CLOSURE(func); name = ((PyFunctionObject *)func) -> func_name; qualname = ((PyFunctionObject *)func) -> func_qualname; if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } return _PyEval_EvalCodeWithName((PyObject*)co, globals, (PyObject *)NULL, stack, nargs, nkwargs ? &PyTuple_GET_ITEM(kwnames, 0) : NULL, stack + nargs, nkwargs, 1, d, (int)nd, kwdefs, closure, name, qualname); } /* --- PyCFunction call functions --------------------------------- */ PyObject * _PyMethodDef_RawFastCallDict(PyMethodDef *method, PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { /* _PyMethodDef_RawFastCallDict() must not be called with an exception set, because it can clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); assert(method != NULL); assert(nargs >= 0); assert(nargs == 0 || args != NULL); assert(kwargs == NULL || PyDict_Check(kwargs)); PyCFunction meth = method->ml_meth; int flags = method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST); PyObject *result = NULL; if (Py_EnterRecursiveCall(" while calling a Python object")) { return NULL; } switch (flags) { case METH_NOARGS: if (nargs != 0) { PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments (%zd given)", method->ml_name, nargs); goto exit; } if (kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) { goto no_keyword_error; } result = (*meth) (self, NULL); break; case METH_O: if (nargs != 1) { PyErr_Format(PyExc_TypeError, "%.200s() takes exactly one argument (%zd given)", method->ml_name, nargs); goto exit; } if (kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) { goto no_keyword_error; } result = (*meth) (self, args[0]); break; case METH_VARARGS: if (!(flags & METH_KEYWORDS) && kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) { goto no_keyword_error; } /* fall through next case */ case METH_VARARGS | METH_KEYWORDS: { /* Slow-path: create a temporary tuple for positional arguments */ PyObject *argstuple = _PyStack_AsTuple(args, nargs); if (argstuple == NULL) { goto exit; } if (flags & METH_KEYWORDS) { result = (*(PyCFunctionWithKeywords)meth) (self, argstuple, kwargs); } else { result = (*meth) (self, argstuple); } Py_DECREF(argstuple); break; } case METH_FASTCALL: { if (kwargs != NULL && PyDict_GET_SIZE(kwargs) != 0) { goto no_keyword_error; } result = (*(_PyCFunctionFast)meth) (self, args, nargs); break; } case METH_FASTCALL | METH_KEYWORDS: { PyObject **stack; PyObject *kwnames; _PyCFunctionFastWithKeywords fastmeth = (_PyCFunctionFastWithKeywords)meth; if (_PyStack_UnpackDict(args, nargs, kwargs, &stack, &kwnames) < 0) { goto exit; } result = (*fastmeth) (self, stack, nargs, kwnames); if (stack != args) { PyMem_Free(stack); } Py_XDECREF(kwnames); break; } default: PyErr_SetString(PyExc_SystemError, "Bad call flags in _PyMethodDef_RawFastCallDict. " "METH_OLDARGS is no longer supported!"); goto exit; } goto exit; no_keyword_error: PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", method->ml_name, nargs); exit: Py_LeaveRecursiveCall(); return result; } PyObject * _PyCFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { PyObject *result; assert(func != NULL); assert(PyCFunction_Check(func)); result = _PyMethodDef_RawFastCallDict(((PyCFunctionObject*)func)->m_ml, PyCFunction_GET_SELF(func), args, nargs, kwargs); result = _Py_CheckFunctionResult(func, result, NULL); return result; } PyObject * _PyMethodDef_RawFastCallKeywords(PyMethodDef *method, PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { /* _PyMethodDef_RawFastCallKeywords() must not be called with an exception set, because it can clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); assert(method != NULL); assert(nargs >= 0); assert(kwnames == NULL || PyTuple_CheckExact(kwnames)); /* kwnames must only contains str strings, no subclass, and all keys must be unique */ PyCFunction meth = method->ml_meth; int flags = method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST); Py_ssize_t nkwargs = kwnames == NULL ? 0 : PyTuple_Size(kwnames); PyObject *result = NULL; if (Py_EnterRecursiveCall(" while calling a Python object")) { return NULL; } switch (flags) { case METH_NOARGS: if (nargs != 0) { PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments (%zd given)", method->ml_name, nargs); goto exit; } if (nkwargs) { goto no_keyword_error; } result = (*meth) (self, NULL); break; case METH_O: if (nargs != 1) { PyErr_Format(PyExc_TypeError, "%.200s() takes exactly one argument (%zd given)", method->ml_name, nargs); goto exit; } if (nkwargs) { goto no_keyword_error; } result = (*meth) (self, args[0]); break; case METH_FASTCALL: if (nkwargs) { goto no_keyword_error; } result = ((_PyCFunctionFast)meth) (self, args, nargs); break; case METH_FASTCALL | METH_KEYWORDS: /* Fast-path: avoid temporary dict to pass keyword arguments */ result = ((_PyCFunctionFastWithKeywords)meth) (self, args, nargs, kwnames); break; case METH_VARARGS: if (nkwargs) { goto no_keyword_error; } /* fall through next case */ case METH_VARARGS | METH_KEYWORDS: { /* Slow-path: create a temporary tuple for positional arguments and a temporary dict for keyword arguments */ PyObject *argtuple; argtuple = _PyStack_AsTuple(args, nargs); if (argtuple == NULL) { goto exit; } if (flags & METH_KEYWORDS) { PyObject *kwdict; if (nkwargs > 0) { kwdict = _PyStack_AsDict(args + nargs, kwnames); if (kwdict == NULL) { Py_DECREF(argtuple); goto exit; } } else { kwdict = NULL; } result = (*(PyCFunctionWithKeywords)meth) (self, argtuple, kwdict); Py_XDECREF(kwdict); } else { result = (*meth) (self, argtuple); } Py_DECREF(argtuple); break; } default: PyErr_SetString(PyExc_SystemError, "Bad call flags in _PyCFunction_FastCallKeywords. " "METH_OLDARGS is no longer supported!"); goto exit; } goto exit; no_keyword_error: PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", method->ml_name); exit: Py_LeaveRecursiveCall(); return result; } PyObject * _PyCFunction_FastCallKeywords(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *result; assert(func != NULL); assert(PyCFunction_Check(func)); result = _PyMethodDef_RawFastCallKeywords(((PyCFunctionObject*)func)->m_ml, PyCFunction_GET_SELF(func), args, nargs, kwnames); result = _Py_CheckFunctionResult(func, result, NULL); return result; } static PyObject * cfunction_call_varargs(PyObject *func, PyObject *args, PyObject *kwargs) { assert(!PyErr_Occurred()); PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); PyObject *result; if (PyCFunction_GET_FLAGS(func) & METH_KEYWORDS) { if (Py_EnterRecursiveCall(" while calling a Python object")) { return NULL; } result = (*(PyCFunctionWithKeywords)meth)(self, args, kwargs); Py_LeaveRecursiveCall(); } else { if (kwargs != NULL && PyDict_Size(kwargs) != 0) { PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", ((PyCFunctionObject*)func)->m_ml->ml_name); return NULL; } if (Py_EnterRecursiveCall(" while calling a Python object")) { return NULL; } result = (*meth)(self, args); Py_LeaveRecursiveCall(); } return _Py_CheckFunctionResult(func, result, NULL); } PyObject * PyCFunction_Call(PyObject *func, PyObject *args, PyObject *kwargs) { /* first try METH_VARARGS to pass directly args tuple unchanged. _PyMethodDef_RawFastCallDict() creates a new temporary tuple for METH_VARARGS. */ if (PyCFunction_GET_FLAGS(func) & METH_VARARGS) { return cfunction_call_varargs(func, args, kwargs); } else { return _PyCFunction_FastCallDict(func, &PyTuple_GET_ITEM(args, 0), PyTuple_GET_SIZE(args), kwargs); } } /* --- More complex call functions -------------------------------- */ /* External interface to call any callable object. The args must be a tuple or NULL. The kwargs must be a dict or NULL. */ PyObject * PyEval_CallObjectWithKeywords(PyObject *callable, PyObject *args, PyObject *kwargs) { #ifdef Py_DEBUG /* PyEval_CallObjectWithKeywords() must not be called with an exception set. It raises a new exception if parameters are invalid or if PyTuple_New() fails, and so the original exception is lost. */ assert(!PyErr_Occurred()); #endif if (args == NULL) { return _PyObject_FastCallDict(callable, NULL, 0, kwargs); } if (!PyTuple_Check(args)) { PyErr_SetString(PyExc_TypeError, "argument list must be a tuple"); return NULL; } if (kwargs != NULL && !PyDict_Check(kwargs)) { PyErr_SetString(PyExc_TypeError, "keyword list must be a dictionary"); return NULL; } return PyObject_Call(callable, args, kwargs); } PyObject * PyObject_CallObject(PyObject *callable, PyObject *args) { return PyEval_CallObjectWithKeywords(callable, args, NULL); } /* Positional arguments are obj followed by args: call callable(obj, *args, **kwargs) */ PyObject * _PyObject_FastCall_Prepend(PyObject *callable, PyObject *obj, PyObject **args, Py_ssize_t nargs) { PyObject *small_stack[_PY_FASTCALL_SMALL_STACK]; PyObject **args2; PyObject *result; nargs++; if (nargs <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) { args2 = small_stack; } else { args2 = PyMem_Malloc(nargs * sizeof(PyObject *)); if (args2 == NULL) { PyErr_NoMemory(); return NULL; } } /* use borrowed references */ args2[0] = obj; if (nargs > 1) { memcpy(&args2[1], args, (nargs - 1) * sizeof(PyObject *)); } result = _PyObject_FastCall(callable, args2, nargs); if (args2 != small_stack) { PyMem_Free(args2); } return result; } /* Call callable(obj, *args, **kwargs). */ PyObject * _PyObject_Call_Prepend(PyObject *callable, PyObject *obj, PyObject *args, PyObject *kwargs) { PyObject *small_stack[_PY_FASTCALL_SMALL_STACK]; PyObject **stack; Py_ssize_t argcount; PyObject *result; assert(PyTuple_Check(args)); argcount = PyTuple_GET_SIZE(args); if (argcount + 1 <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) { stack = small_stack; } else { stack = PyMem_Malloc((argcount + 1) * sizeof(PyObject *)); if (stack == NULL) { PyErr_NoMemory(); return NULL; } } /* use borrowed references */ stack[0] = obj; memcpy(&stack[1], &PyTuple_GET_ITEM(args, 0), argcount * sizeof(PyObject *)); result = _PyObject_FastCallDict(callable, stack, argcount + 1, kwargs); if (stack != small_stack) { PyMem_Free(stack); } return result; } /* --- Call with a format string ---------------------------------- */ static PyObject * _PyObject_CallFunctionVa(PyObject *callable, const char *format, va_list va, int is_size_t) { PyObject* small_stack[_PY_FASTCALL_SMALL_STACK]; const Py_ssize_t small_stack_len = Py_ARRAY_LENGTH(small_stack); PyObject **stack; Py_ssize_t nargs, i; PyObject *result; if (callable == NULL) { return null_error(); } if (!format || !*format) { return _PyObject_CallNoArg(callable); } if (is_size_t) { stack = _Py_VaBuildStack_SizeT(small_stack, small_stack_len, format, va, &nargs); } else { stack = _Py_VaBuildStack(small_stack, small_stack_len, format, va, &nargs); } if (stack == NULL) { return NULL; } if (nargs == 1 && PyTuple_Check(stack[0])) { /* Special cases for backward compatibility: - PyObject_CallFunction(func, "O", tuple) calls func(*tuple) - PyObject_CallFunction(func, "(OOO)", arg1, arg2, arg3) calls func(*(arg1, arg2, arg3)): func(arg1, arg2, arg3) */ PyObject *args = stack[0]; result = _PyObject_FastCall(callable, &PyTuple_GET_ITEM(args, 0), PyTuple_GET_SIZE(args)); } else { result = _PyObject_FastCall(callable, stack, nargs); } for (i = 0; i < nargs; ++i) { Py_DECREF(stack[i]); } if (stack != small_stack) { PyMem_Free(stack); } return result; } PyObject * PyObject_CallFunction(PyObject *callable, const char *format, ...) { va_list va; PyObject *result; va_start(va, format); result = _PyObject_CallFunctionVa(callable, format, va, 0); va_end(va); return result; } PyObject * PyEval_CallFunction(PyObject *callable, const char *format, ...) { va_list vargs; PyObject *args; PyObject *res; va_start(vargs, format); args = Py_VaBuildValue(format, vargs); va_end(vargs); if (args == NULL) return NULL; res = PyEval_CallObject(callable, args); Py_DECREF(args); return res; } PyObject * _PyObject_CallFunction_SizeT(PyObject *callable, const char *format, ...) { va_list va; PyObject *result; va_start(va, format); result = _PyObject_CallFunctionVa(callable, format, va, 1); va_end(va); return result; } static PyObject* callmethod(PyObject* callable, const char *format, va_list va, int is_size_t) { assert(callable != NULL); if (!PyCallable_Check(callable)) { PyErr_Format(PyExc_TypeError, "attribute of type '%.200s' is not callable", Py_TYPE(callable)->tp_name); return NULL; } return _PyObject_CallFunctionVa(callable, format, va, is_size_t); } PyObject * PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...) { va_list va; PyObject *callable, *retval; if (obj == NULL || name == NULL) { return null_error(); } callable = PyObject_GetAttrString(obj, name); if (callable == NULL) return NULL; va_start(va, format); retval = callmethod(callable, format, va, 0); va_end(va); Py_DECREF(callable); return retval; } PyObject * PyEval_CallMethod(PyObject *obj, const char *name, const char *format, ...) { va_list vargs; PyObject *meth; PyObject *args; PyObject *res; meth = PyObject_GetAttrString(obj, name); if (meth == NULL) return NULL; va_start(vargs, format); args = Py_VaBuildValue(format, vargs); va_end(vargs); if (args == NULL) { Py_DECREF(meth); return NULL; } res = PyEval_CallObject(meth, args); Py_DECREF(meth); Py_DECREF(args); return res; } PyObject * _PyObject_CallMethodId(PyObject *obj, _Py_Identifier *name, const char *format, ...) { va_list va; PyObject *callable, *retval; if (obj == NULL || name == NULL) { return null_error(); } callable = _PyObject_GetAttrId(obj, name); if (callable == NULL) return NULL; va_start(va, format); retval = callmethod(callable, format, va, 0); va_end(va); Py_DECREF(callable); return retval; } PyObject * _PyObject_CallMethod_SizeT(PyObject *obj, const char *name, const char *format, ...) { va_list va; PyObject *callable, *retval; if (obj == NULL || name == NULL) { return null_error(); } callable = PyObject_GetAttrString(obj, name); if (callable == NULL) return NULL; va_start(va, format); retval = callmethod(callable, format, va, 1); va_end(va); Py_DECREF(callable); return retval; } PyObject * _PyObject_CallMethodId_SizeT(PyObject *obj, _Py_Identifier *name, const char *format, ...) { va_list va; PyObject *callable, *retval; if (obj == NULL || name == NULL) { return null_error(); } callable = _PyObject_GetAttrId(obj, name); if (callable == NULL) { return NULL; } va_start(va, format); retval = callmethod(callable, format, va, 1); va_end(va); Py_DECREF(callable); return retval; } /* --- Call with "..." arguments ---------------------------------- */ static PyObject * object_vacall(PyObject *callable, va_list vargs) { PyObject *small_stack[_PY_FASTCALL_SMALL_STACK]; PyObject **stack; Py_ssize_t nargs; PyObject *result; Py_ssize_t i; va_list countva; if (callable == NULL) { return null_error(); } /* Count the number of arguments */ va_copy(countva, vargs); nargs = 0; while (1) { PyObject *arg = va_arg(countva, PyObject *); if (arg == NULL) { break; } nargs++; } va_end(countva); /* Copy arguments */ if (nargs <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) { stack = small_stack; } else { stack = PyMem_Malloc(nargs * sizeof(stack[0])); if (stack == NULL) { PyErr_NoMemory(); return NULL; } } for (i = 0; i < nargs; ++i) { stack[i] = va_arg(vargs, PyObject *); } /* Call the function */ result = _PyObject_FastCall(callable, stack, nargs); if (stack != small_stack) { PyMem_Free(stack); } return result; } PyObject * PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...) { va_list vargs; PyObject *result; if (callable == NULL || name == NULL) { return null_error(); } callable = PyObject_GetAttr(callable, name); if (callable == NULL) { return NULL; } va_start(vargs, name); result = object_vacall(callable, vargs); va_end(vargs); Py_DECREF(callable); return result; } PyObject * _PyObject_CallMethodIdObjArgs(PyObject *obj, struct _Py_Identifier *name, ...) { va_list vargs; PyObject *callable, *result; if (obj == NULL || name == NULL) { return null_error(); } callable = _PyObject_GetAttrId(obj, name); if (callable == NULL) { return NULL; } va_start(vargs, name); result = object_vacall(callable, vargs); va_end(vargs); Py_DECREF(callable); return result; } PyObject * PyObject_CallFunctionObjArgs(PyObject *callable, ...) { va_list vargs; PyObject *result; va_start(vargs, callable); result = object_vacall(callable, vargs); va_end(vargs); return result; } /* --- PyStack functions ------------------------------------------ */ /* Issue #29234: Inlining _PyStack_AsTuple() into callers increases their stack consumption, Disable inlining to optimize the stack consumption. */ PyObject* dontinline _PyStack_AsTuple(PyObject **stack, Py_ssize_t nargs) { PyObject *args; Py_ssize_t i; args = PyTuple_New(nargs); if (args == NULL) { return NULL; } for (i=0; i < nargs; i++) { PyObject *item = stack[i]; Py_INCREF(item); PyTuple_SET_ITEM(args, i, item); } return args; } PyObject* _PyStack_AsTupleSlice(PyObject **stack, Py_ssize_t nargs, Py_ssize_t start, Py_ssize_t end) { PyObject *args; Py_ssize_t i; assert(0 <= start); assert(end <= nargs); assert(start <= end); args = PyTuple_New(end - start); if (args == NULL) { return NULL; } for (i=start; i < end; i++) { PyObject *item = stack[i]; Py_INCREF(item); PyTuple_SET_ITEM(args, i - start, item); } return args; } PyObject * _PyStack_AsDict(PyObject **values, PyObject *kwnames) { Py_ssize_t nkwargs; PyObject *kwdict; Py_ssize_t i; assert(kwnames != NULL); nkwargs = PyTuple_GET_SIZE(kwnames); kwdict = _PyDict_NewPresized(nkwargs); if (kwdict == NULL) { return NULL; } for (i = 0; i < nkwargs; i++) { PyObject *key = PyTuple_GET_ITEM(kwnames, i); PyObject *value = *values++; /* If key already exists, replace it with the new value */ if (PyDict_SetItem(kwdict, key, value)) { Py_DECREF(kwdict); return NULL; } } return kwdict; } int _PyStack_UnpackDict(PyObject **args, Py_ssize_t nargs, PyObject *kwargs, PyObject ***p_stack, PyObject **p_kwnames) { PyObject **stack, **kwstack; Py_ssize_t nkwargs; Py_ssize_t pos, i; PyObject *key, *value; PyObject *kwnames; assert(nargs >= 0); assert(kwargs == NULL || PyDict_CheckExact(kwargs)); if (kwargs == NULL || (nkwargs = PyDict_GET_SIZE(kwargs)) == 0) { *p_stack = args; *p_kwnames = NULL; return 0; } if ((size_t)nargs > PY_SSIZE_T_MAX / sizeof(stack[0]) - (size_t)nkwargs) { PyErr_NoMemory(); return -1; } stack = PyMem_Malloc((nargs + nkwargs) * sizeof(stack[0])); if (stack == NULL) { PyErr_NoMemory(); return -1; } kwnames = PyTuple_New(nkwargs); if (kwnames == NULL) { PyMem_Free(stack); return -1; } /* Copy position arguments (borrowed references) */ memcpy(stack, args, nargs * sizeof(stack[0])); kwstack = stack + nargs; pos = i = 0; /* This loop doesn't support lookup function mutating the dictionary to change its size. It's a deliberate choice for speed, this function is called in the performance critical hot code. */ while (PyDict_Next(kwargs, &pos, &key, &value)) { Py_INCREF(key); PyTuple_SET_ITEM(kwnames, i, key); /* The stack contains borrowed references */ kwstack[i] = value; i++; } *p_stack = stack; *p_kwnames = kwnames; return 0; }
39,381
1,432
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/listobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/mem/mem.h" #include "libc/mem/gc.internal.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/accu.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/sliceobject.h" /* clang-format off */ /* Ensure ob_item has room for at least newsize elements, and set * ob_size to newsize. If newsize > ob_size on entry, the content * of the new slots at exit is undefined heap trash; it's the caller's * responsibility to overwrite them with sane values. * The number of allocated elements may grow, shrink, or stay the same. * Failure is impossible if newsize <= self.allocated on entry, although * that partly relies on an assumption that the system realloc() never * fails when passed a number of bytes <= the number of bytes last * allocated (the C standard doesn't guarantee this, but it's hard to * imagine a realloc implementation where it wouldn't be true). * Note that self->ob_item may change, and even if newsize is less * than ob_size on entry. */ static int list_resize(PyListObject *self, Py_ssize_t newsize) { PyObject **items; size_t new_allocated; Py_ssize_t allocated = self->allocated; /* Bypass realloc() when a previous overallocation is large enough to accommodate the newsize. If the newsize falls lower than half the allocated size, then proceed with the realloc() to shrink the list. */ if (allocated >= newsize && newsize >= (allocated >> 1)) { assert(self->ob_item != NULL || newsize == 0); Py_SIZE(self) = newsize; return 0; } /* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, but is * enough to give linear-time amortized behavior over a long * sequence of appends() in the presence of a poorly-performing * system realloc(). * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... */ new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); /* check for integer overflow */ if (new_allocated > SIZE_MAX - newsize) { PyErr_NoMemory(); return -1; } else { new_allocated += newsize; } if (newsize == 0) new_allocated = 0; items = self->ob_item; if (new_allocated <= (SIZE_MAX / sizeof(PyObject *))) PyMem_RESIZE(items, PyObject *, new_allocated); else items = NULL; if (items == NULL) { PyErr_NoMemory(); return -1; } self->ob_item = items; Py_SIZE(self) = newsize; self->allocated = new_allocated; return 0; } /* Debug statistic to compare allocations with reuse through the free list */ #undef SHOW_ALLOC_COUNT #ifdef SHOW_ALLOC_COUNT static size_t count_alloc = 0; static size_t count_reuse = 0; static void show_alloc(void) { PyObject *xoptions, *value; _Py_IDENTIFIER(showalloccount); xoptions = PySys_GetXOptions(); if (xoptions == NULL) return; value = _PyDict_GetItemId(xoptions, &PyId_showalloccount); if (value != Py_True) return; fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n", count_alloc); fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T "d\n", count_reuse); fprintf(stderr, "%.2f%% reuse rate\n\n", (100.0*count_reuse/(count_alloc+count_reuse))); } #endif /* Empty list reuse scheme to save calls to malloc and free */ #ifndef PyList_MAXFREELIST #define PyList_MAXFREELIST 80 #endif static PyListObject *free_list[PyList_MAXFREELIST]; static int numfree = 0; int PyList_ClearFreeList(void) { PyListObject *op; int ret = numfree; while (numfree) { op = free_list[--numfree]; assert(PyList_CheckExact(op)); PyObject_GC_Del(op); } return ret; } void PyList_Fini(void) { PyList_ClearFreeList(); } /* Print summary info about the state of the optimized allocator */ void _PyList_DebugMallocStats(FILE *out) { _PyDebugAllocatorStats(out, "free PyListObject", numfree, sizeof(PyListObject)); } PyObject * PyList_New(Py_ssize_t size) { PyListObject *op; #ifdef SHOW_ALLOC_COUNT static int initialized = 0; if (!initialized) { Py_AtExit(show_alloc); initialized = 1; } #endif if (size < 0) { PyErr_BadInternalCall(); return NULL; } if (numfree) { numfree--; op = free_list[numfree]; _Py_NewReference((PyObject *)op); #ifdef SHOW_ALLOC_COUNT count_reuse++; #endif } else { op = PyObject_GC_New(PyListObject, &PyList_Type); if (op == NULL) return NULL; #ifdef SHOW_ALLOC_COUNT count_alloc++; #endif } if (size <= 0) op->ob_item = NULL; else { op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *)); if (op->ob_item == NULL) { Py_DECREF(op); return PyErr_NoMemory(); } } Py_SIZE(op) = size; op->allocated = size; _PyObject_GC_TRACK(op); return (PyObject *) op; } Py_ssize_t PyList_Size(PyObject *op) { if (!PyList_Check(op)) { PyErr_BadInternalCall(); return -1; } else return Py_SIZE(op); } static PyObject *indexerr = NULL; PyObject * PyList_GetItem(PyObject *op, Py_ssize_t i) { if (!PyList_Check(op)) { PyErr_BadInternalCall(); return NULL; } if (i < 0 || i >= Py_SIZE(op)) { if (indexerr == NULL) { indexerr = PyUnicode_FromString( "list index out of range"); if (indexerr == NULL) return NULL; } PyErr_SetObject(PyExc_IndexError, indexerr); return NULL; } return ((PyListObject *)op) -> ob_item[i]; } int PyList_SetItem(PyObject *op, Py_ssize_t i, PyObject *newitem) { PyObject **p; if (!PyList_Check(op)) { Py_XDECREF(newitem); PyErr_BadInternalCall(); return -1; } if (i < 0 || i >= Py_SIZE(op)) { Py_XDECREF(newitem); PyErr_SetString(PyExc_IndexError, "list assignment index out of range"); return -1; } p = ((PyListObject *)op) -> ob_item + i; Py_XSETREF(*p, newitem); return 0; } static int ins1(PyListObject *self, Py_ssize_t where, PyObject *v) { Py_ssize_t i, n = Py_SIZE(self); PyObject **items; if (v == NULL) { PyErr_BadInternalCall(); return -1; } if (n == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "cannot add more objects to list"); return -1; } if (list_resize(self, n+1) < 0) return -1; if (where < 0) { where += n; if (where < 0) where = 0; } if (where > n) where = n; items = self->ob_item; for (i = n; --i >= where; ) items[i+1] = items[i]; Py_INCREF(v); items[where] = v; return 0; } int PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem) { if (!PyList_Check(op)) { PyErr_BadInternalCall(); return -1; } return ins1((PyListObject *)op, where, newitem); } static int app1(PyListObject *self, PyObject *v) { Py_ssize_t n = PyList_GET_SIZE(self); assert (v != NULL); if (n == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "cannot add more objects to list"); return -1; } if (list_resize(self, n+1) < 0) return -1; Py_INCREF(v); PyList_SET_ITEM(self, n, v); return 0; } int PyList_Append(PyObject *op, PyObject *newitem) { if (PyList_Check(op) && (newitem != NULL)) return app1((PyListObject *)op, newitem); PyErr_BadInternalCall(); return -1; } /* Methods */ static void list_dealloc(PyListObject *op) { Py_ssize_t i; PyObject_GC_UnTrack(op); Py_TRASHCAN_SAFE_BEGIN(op) if (op->ob_item != NULL) { /* Do it backwards, for Christian Tismer. There's a simple test case where somehow this reduces thrashing when a *very* large list is created and immediately deleted. */ i = Py_SIZE(op); while (--i >= 0) { Py_XDECREF(op->ob_item[i]); } PyMem_FREE(op->ob_item); } if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op)) free_list[numfree++] = op; else Py_TYPE(op)->tp_free((PyObject *)op); Py_TRASHCAN_SAFE_END(op) } static PyObject * list_repr(PyListObject *v) { Py_ssize_t i; PyObject *s; _PyUnicodeWriter writer; if (Py_SIZE(v) == 0) { return PyUnicode_FromString("[]"); } i = Py_ReprEnter((PyObject*)v); if (i != 0) { return i > 0 ? PyUnicode_FromString("[...]") : NULL; } _PyUnicodeWriter_Init(&writer); writer.overallocate = 1; /* "[" + "1" + ", 2" * (len - 1) + "]" */ writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1; if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0) goto error; /* Do repr() on each element. Note that this may mutate the list, so must refetch the list size on each iteration. */ for (i = 0; i < Py_SIZE(v); ++i) { if (i > 0) { if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) goto error; } s = PyObject_Repr(v->ob_item[i]); if (s == NULL) goto error; if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) { Py_DECREF(s); goto error; } Py_DECREF(s); } writer.overallocate = 0; if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0) goto error; Py_ReprLeave((PyObject *)v); return _PyUnicodeWriter_Finish(&writer); error: _PyUnicodeWriter_Dealloc(&writer); Py_ReprLeave((PyObject *)v); return NULL; } static Py_ssize_t list_length(PyListObject *a) { return Py_SIZE(a); } static int list_contains(PyListObject *a, PyObject *el) { Py_ssize_t i; int cmp; for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i), Py_EQ); return cmp; } static PyObject * list_item(PyListObject *a, Py_ssize_t i) { if (i < 0 || i >= Py_SIZE(a)) { if (indexerr == NULL) { indexerr = PyUnicode_FromString( "list index out of range"); if (indexerr == NULL) return NULL; } PyErr_SetObject(PyExc_IndexError, indexerr); return NULL; } Py_INCREF(a->ob_item[i]); return a->ob_item[i]; } static PyObject * list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { PyListObject *np; PyObject **src, **dest; Py_ssize_t i, len; if (ilow < 0) ilow = 0; else if (ilow > Py_SIZE(a)) ilow = Py_SIZE(a); if (ihigh < ilow) ihigh = ilow; else if (ihigh > Py_SIZE(a)) ihigh = Py_SIZE(a); len = ihigh - ilow; np = (PyListObject *) PyList_New(len); if (np == NULL) return NULL; src = a->ob_item + ilow; dest = np->ob_item; for (i = 0; i < len; i++) { PyObject *v = src[i]; Py_INCREF(v); dest[i] = v; } return (PyObject *)np; } PyObject * PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh) { if (!PyList_Check(a)) { PyErr_BadInternalCall(); return NULL; } return list_slice((PyListObject *)a, ilow, ihigh); } static PyObject * list_concat(PyListObject *a, PyObject *bb) { Py_ssize_t size; Py_ssize_t i; PyObject **src, **dest; PyListObject *np; if (!PyList_Check(bb)) { PyErr_Format(PyExc_TypeError, "can only concatenate list (not \"%.200s\") to list", bb->ob_type->tp_name); return NULL; } #define b ((PyListObject *)bb) if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) return PyErr_NoMemory(); size = Py_SIZE(a) + Py_SIZE(b); np = (PyListObject *) PyList_New(size); if (np == NULL) { return NULL; } src = a->ob_item; dest = np->ob_item; for (i = 0; i < Py_SIZE(a); i++) { PyObject *v = src[i]; Py_INCREF(v); dest[i] = v; } src = b->ob_item; dest = np->ob_item + Py_SIZE(a); for (i = 0; i < Py_SIZE(b); i++) { PyObject *v = src[i]; Py_INCREF(v); dest[i] = v; } return (PyObject *)np; #undef b } static PyObject * list_repeat(PyListObject *a, Py_ssize_t n) { Py_ssize_t i, j; Py_ssize_t size; PyListObject *np; PyObject **p, **items; PyObject *elem; if (n < 0) n = 0; if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) return PyErr_NoMemory(); size = Py_SIZE(a) * n; if (size == 0) return PyList_New(0); np = (PyListObject *) PyList_New(size); if (np == NULL) return NULL; items = np->ob_item; if (Py_SIZE(a) == 1) { elem = a->ob_item[0]; for (i = 0; i < n; i++) { items[i] = elem; Py_INCREF(elem); } return (PyObject *) np; } p = np->ob_item; items = a->ob_item; for (i = 0; i < n; i++) { for (j = 0; j < Py_SIZE(a); j++) { *p = items[j]; Py_INCREF(*p); p++; } } return (PyObject *) np; } static int list_clear(PyListObject *a) { Py_ssize_t i; PyObject **item = a->ob_item; if (item != NULL) { /* Because XDECREF can recursively invoke operations on this list, we make it empty first. */ i = Py_SIZE(a); Py_SIZE(a) = 0; a->ob_item = NULL; a->allocated = 0; while (--i >= 0) { Py_XDECREF(item[i]); } PyMem_FREE(item); } /* Never fails; the return value can be ignored. Note that there is no guarantee that the list is actually empty at this point, because XDECREF may have populated it again! */ return 0; } /* a[ilow:ihigh] = v if v != NULL. * del a[ilow:ihigh] if v == NULL. * * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's * guaranteed the call cannot fail. */ static int list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { /* Because [X]DECREF can recursively invoke list operations on this list, we must postpone all [X]DECREF activity until after the list is back in its canonical shape. Therefore we must allocate an additional array, 'recycle', into which we temporarily copy the items that are deleted from the list. :-( */ PyObject *recycle_on_stack[8]; PyObject **recycle = recycle_on_stack; /* will allocate more if needed */ PyObject **item; PyObject **vitem = NULL; PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */ Py_ssize_t n; /* # of elements in replacement list */ Py_ssize_t norig; /* # of elements in list getting replaced */ Py_ssize_t d; /* Change in size */ Py_ssize_t k; size_t s; int result = -1; /* guilty until proved innocent */ #define b ((PyListObject *)v) if (v == NULL) n = 0; else { if (a == b) { /* Special case "a[i:j] = a" -- copy b first */ v = list_slice(b, 0, Py_SIZE(b)); if (v == NULL) return result; result = list_ass_slice(a, ilow, ihigh, v); Py_DECREF(v); return result; } v_as_SF = PySequence_Fast(v, "can only assign an iterable"); if(v_as_SF == NULL) goto Error; n = PySequence_Fast_GET_SIZE(v_as_SF); vitem = PySequence_Fast_ITEMS(v_as_SF); } if (ilow < 0) ilow = 0; else if (ilow > Py_SIZE(a)) ilow = Py_SIZE(a); if (ihigh < ilow) ihigh = ilow; else if (ihigh > Py_SIZE(a)) ihigh = Py_SIZE(a); norig = ihigh - ilow; assert(norig >= 0); d = n - norig; if (Py_SIZE(a) + d == 0) { Py_XDECREF(v_as_SF); return list_clear(a); } item = a->ob_item; /* recycle the items that we are about to remove */ s = norig * sizeof(PyObject *); /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */ if (s) { if (s > sizeof(recycle_on_stack)) { recycle = (PyObject **)PyMem_MALLOC(s); if (recycle == NULL) { PyErr_NoMemory(); goto Error; } } memcpy(recycle, &item[ilow], s); } if (d < 0) { /* Delete -d items */ Py_ssize_t tail; tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *); memmove(&item[ihigh+d], &item[ihigh], tail); if (list_resize(a, Py_SIZE(a) + d) < 0) { memmove(&item[ihigh], &item[ihigh+d], tail); memcpy(&item[ilow], recycle, s); goto Error; } item = a->ob_item; } else if (d > 0) { /* Insert d items */ k = Py_SIZE(a); if (list_resize(a, k+d) < 0) goto Error; item = a->ob_item; memmove(&item[ihigh+d], &item[ihigh], (k - ihigh)*sizeof(PyObject *)); } for (k = 0; k < n; k++, ilow++) { PyObject *w = vitem[k]; Py_XINCREF(w); item[ilow] = w; } for (k = norig - 1; k >= 0; --k) Py_XDECREF(recycle[k]); result = 0; Error: if (recycle != recycle_on_stack) PyMem_FREE(recycle); Py_XDECREF(v_as_SF); return result; #undef b } int PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { if (!PyList_Check(a)) { PyErr_BadInternalCall(); return -1; } return list_ass_slice((PyListObject *)a, ilow, ihigh, v); } static PyObject * list_inplace_repeat(PyListObject *self, Py_ssize_t n) { PyObject **items; Py_ssize_t size, i, j, p; size = PyList_GET_SIZE(self); if (size == 0 || n == 1) { Py_INCREF(self); return (PyObject *)self; } if (n < 1) { (void)list_clear(self); Py_INCREF(self); return (PyObject *)self; } if (size > PY_SSIZE_T_MAX / n) { return PyErr_NoMemory(); } if (list_resize(self, size*n) < 0) return NULL; p = size; items = self->ob_item; for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */ for (j = 0; j < size; j++) { PyObject *o = items[j]; Py_INCREF(o); items[p++] = o; } } Py_INCREF(self); return (PyObject *)self; } static int list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v) { if (i < 0 || i >= Py_SIZE(a)) { PyErr_SetString(PyExc_IndexError, "list assignment index out of range"); return -1; } if (v == NULL) return list_ass_slice(a, i, i+1, v); Py_INCREF(v); Py_SETREF(a->ob_item[i], v); return 0; } static PyObject * listinsert(PyListObject *self, PyObject **args, Py_ssize_t nargs) { Py_ssize_t i; PyObject *v; if (!_PyArg_ParseStack(args, nargs, "nO:insert", &i, &v)) return NULL; if (ins1(self, i, v) == 0) Py_RETURN_NONE; return NULL; } static PyObject * listclear(PyListObject *self) { list_clear(self); Py_RETURN_NONE; } static PyObject * listcopy(PyListObject *self) { return list_slice(self, 0, Py_SIZE(self)); } static PyObject * listappend(PyListObject *self, PyObject *v) { if (app1(self, v) == 0) Py_RETURN_NONE; return NULL; } static PyObject * listextend(PyListObject *self, PyObject *b) { PyObject *it; /* iter(v) */ Py_ssize_t m; /* size of self */ Py_ssize_t n; /* guess for size of b */ Py_ssize_t mn; /* m + n */ Py_ssize_t i; PyObject *(*iternext)(PyObject *); /* Special cases: 1) lists and tuples which can use PySequence_Fast ops 2) extending self to self requires making a copy first */ if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) { PyObject **src, **dest; b = PySequence_Fast(b, "argument must be iterable"); if (!b) return NULL; n = PySequence_Fast_GET_SIZE(b); if (n == 0) { /* short circuit when b is empty */ Py_DECREF(b); Py_RETURN_NONE; } m = Py_SIZE(self); if (list_resize(self, m + n) < 0) { Py_DECREF(b); return NULL; } /* note that we may still have self == b here for the * situation a.extend(a), but the following code works * in that case too. Just make sure to resize self * before calling PySequence_Fast_ITEMS. */ /* populate the end of self with b's items */ src = PySequence_Fast_ITEMS(b); dest = self->ob_item + m; for (i = 0; i < n; i++) { PyObject *o = src[i]; Py_INCREF(o); dest[i] = o; } Py_DECREF(b); Py_RETURN_NONE; } it = PyObject_GetIter(b); if (it == NULL) return NULL; iternext = *it->ob_type->tp_iternext; /* Guess a result list size. */ n = PyObject_LengthHint(b, 8); if (n < 0) { Py_DECREF(it); return NULL; } m = Py_SIZE(self); if (m > PY_SSIZE_T_MAX - n) { /* m + n overflowed; on the chance that n lied, and there really * is enough room, ignore it. If n was telling the truth, we'll * eventually run out of memory during the loop. */ } else { mn = m + n; /* Make room. */ if (list_resize(self, mn) < 0) goto error; /* Make the list sane again. */ Py_SIZE(self) = m; } /* Run iterator to exhaustion. */ for (;;) { PyObject *item = iternext(it); if (item == NULL) { if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_StopIteration)) PyErr_Clear(); else goto error; } break; } if (Py_SIZE(self) < self->allocated) { /* steals ref */ PyList_SET_ITEM(self, Py_SIZE(self), item); ++Py_SIZE(self); } else { int status = app1(self, item); Py_DECREF(item); /* append creates a new ref */ if (status < 0) goto error; } } /* Cut back result list if initial guess was too large. */ if (Py_SIZE(self) < self->allocated) { if (list_resize(self, Py_SIZE(self)) < 0) goto error; } Py_DECREF(it); Py_RETURN_NONE; error: Py_DECREF(it); return NULL; } PyObject * _PyList_Extend(PyListObject *self, PyObject *b) { return listextend(self, b); } static PyObject * list_inplace_concat(PyListObject *self, PyObject *other) { PyObject *result; result = listextend(self, other); if (result == NULL) return result; Py_DECREF(result); Py_INCREF(self); return (PyObject *)self; } static PyObject * listpop(PyListObject *self, PyObject **args, Py_ssize_t nargs) { Py_ssize_t i = -1; PyObject *v; int status; if (!_PyArg_ParseStack(args, nargs, "|n:pop", &i)) return NULL; if (Py_SIZE(self) == 0) { /* Special-case most common failure cause */ PyErr_SetString(PyExc_IndexError, "pop from empty list"); return NULL; } if (i < 0) i += Py_SIZE(self); if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "pop index out of range"); return NULL; } v = self->ob_item[i]; if (i == Py_SIZE(self) - 1) { status = list_resize(self, Py_SIZE(self) - 1); if (status >= 0) return v; /* and v now owns the reference the list had */ else return NULL; } Py_INCREF(v); status = list_ass_slice(self, i, i+1, (PyObject *)NULL); if (status < 0) { Py_DECREF(v); return NULL; } return v; } /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */ static void reverse_slice(PyObject **lo, PyObject **hi) { assert(lo && hi); --hi; while (lo < hi) { PyObject *t = *lo; *lo = *hi; *hi = t; ++lo; --hi; } } /* Lots of code for an adaptive, stable, natural mergesort. There are many * pieces to this algorithm; read listsort.txt for overviews and details. */ /* A sortslice contains a pointer to an array of keys and a pointer to * an array of corresponding values. In other words, keys[i] * corresponds with values[i]. If values == NULL, then the keys are * also the values. * * Several convenience routines are provided here, so that keys and * values are always moved in sync. */ typedef struct { PyObject **keys; PyObject **values; } sortslice; Py_LOCAL_INLINE(void) sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j) { s1->keys[i] = s2->keys[j]; if (s1->values != NULL) s1->values[i] = s2->values[j]; } Py_LOCAL_INLINE(void) sortslice_copy_incr(sortslice *dst, sortslice *src) { *dst->keys++ = *src->keys++; if (dst->values != NULL) *dst->values++ = *src->values++; } Py_LOCAL_INLINE(void) sortslice_copy_decr(sortslice *dst, sortslice *src) { *dst->keys-- = *src->keys--; if (dst->values != NULL) *dst->values-- = *src->values--; } Py_LOCAL_INLINE(void) sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j, Py_ssize_t n) { memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n); if (s1->values != NULL) memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n); } Py_LOCAL_INLINE(void) sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j, Py_ssize_t n) { memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n); if (s1->values != NULL) memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n); } Py_LOCAL_INLINE(void) sortslice_advance(sortslice *slice, Py_ssize_t n) { slice->keys += n; if (slice->values != NULL) slice->values += n; } /* Comparison function: PyObject_RichCompareBool with Py_LT. * Returns -1 on error, 1 if x < y, 0 if x >= y. */ #define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT)) /* Compare X to Y via "<". Goto "fail" if the comparison raises an error. Else "k" is set to true iff X<Y, and an "if (k)" block is started. It makes more sense in context <wink>. X and Y are PyObject*s. */ #define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \ if (k) /* binarysort is the best method for sorting small arrays: it does few compares, but can do data movement quadratic in the number of elements. [lo, hi) is a contiguous slice of a list, and is sorted via binary insertion. This sort is stable. On entry, must have lo <= start <= hi, and that [lo, start) is already sorted (pass start == lo if you don't know!). If islt() complains return -1, else 0. Even in case of error, the output slice will be some permutation of the input (nothing is lost or duplicated). */ static int binarysort(sortslice lo, PyObject **hi, PyObject **start) { Py_ssize_t k; PyObject **l, **p, **r; PyObject *pivot; assert(lo.keys <= start && start <= hi); /* assert [lo, start) is sorted */ if (lo.keys == start) ++start; for (; start < hi; ++start) { /* set l to where *start belongs */ l = lo.keys; r = start; pivot = *r; /* Invariants: * pivot >= all in [lo, l). * pivot < all in [r, start). * The second is vacuously true at the start. */ assert(l < r); do { p = l + ((r - l) >> 1); IFLT(pivot, *p) r = p; else l = p+1; } while (l < r); assert(l == r); /* The invariants still hold, so pivot >= all in [lo, l) and pivot < all in [l, start), so pivot belongs at l. Note that if there are elements equal to pivot, l points to the first slot after them -- that's why this sort is stable. Slide over to make room. Caution: using memmove is much slower under MSVC 5; we're not usually moving many slots. */ for (p = start; p > l; --p) *p = *(p-1); *l = pivot; if (lo.values != NULL) { Py_ssize_t offset = lo.values - lo.keys; p = start + offset; pivot = *p; l += offset; for (p = start + offset; p > l; --p) *p = *(p-1); *l = pivot; } } return 0; fail: return -1; } /* Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi is required on entry. "A run" is the longest ascending sequence, with lo[0] <= lo[1] <= lo[2] <= ... or the longest descending sequence, with lo[0] > lo[1] > lo[2] > ... Boolean *descending is set to 0 in the former case, or to 1 in the latter. For its intended use in a stable mergesort, the strictness of the defn of "descending" is needed so that the caller can safely reverse a descending sequence without violating stability (strict > ensures there are no equal elements to get out of order). Returns -1 in case of error. */ static Py_ssize_t count_run(PyObject **lo, PyObject **hi, int *descending) { Py_ssize_t k; Py_ssize_t n; assert(lo < hi); *descending = 0; ++lo; if (lo == hi) return 1; n = 2; IFLT(*lo, *(lo-1)) { *descending = 1; for (lo = lo+1; lo < hi; ++lo, ++n) { IFLT(*lo, *(lo-1)) ; else break; } } else { for (lo = lo+1; lo < hi; ++lo, ++n) { IFLT(*lo, *(lo-1)) break; } } return n; fail: return -1; } /* Locate the proper position of key in a sorted vector; if the vector contains an element equal to key, return the position immediately to the left of the leftmost equal element. [gallop_right() does the same except returns the position to the right of the rightmost equal element (if any).] "a" is a sorted vector with n elements, starting at a[0]. n must be > 0. "hint" is an index at which to begin the search, 0 <= hint < n. The closer hint is to the final result, the faster this runs. The return value is the int k in 0..n such that a[k-1] < key <= a[k] pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW, key belongs at index k; or, IOW, the first k elements of a should precede key, and the last n-k should follow key. Returns -1 on error. See listsort.txt for info on the method. */ static Py_ssize_t gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { Py_ssize_t ofs; Py_ssize_t lastofs; Py_ssize_t k; assert(key && a && n > 0 && hint >= 0 && hint < n); a += hint; lastofs = 0; ofs = 1; IFLT(*a, key) { /* a[hint] < key -- gallop right, until * a[hint + lastofs] < key <= a[hint + ofs] */ const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ while (ofs < maxofs) { IFLT(a[ofs], key) { lastofs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) /* int overflow */ ofs = maxofs; } else /* key <= a[hint + ofs] */ break; } if (ofs > maxofs) ofs = maxofs; /* Translate back to offsets relative to &a[0]. */ lastofs += hint; ofs += hint; } else { /* key <= a[hint] -- gallop left, until * a[hint - ofs] < key <= a[hint - lastofs] */ const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ while (ofs < maxofs) { IFLT(*(a-ofs), key) break; /* key <= a[hint - ofs] */ lastofs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) /* int overflow */ ofs = maxofs; } if (ofs > maxofs) ofs = maxofs; /* Translate back to positive offsets relative to &a[0]. */ k = lastofs; lastofs = hint - ofs; ofs = hint - k; } a -= hint; assert(-1 <= lastofs && lastofs < ofs && ofs <= n); /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the * right of lastofs but no farther right than ofs. Do a binary * search, with invariant a[lastofs-1] < key <= a[ofs]. */ ++lastofs; while (lastofs < ofs) { Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); IFLT(a[m], key) lastofs = m+1; /* a[m] < key */ else ofs = m; /* key <= a[m] */ } assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */ return ofs; fail: return -1; } /* Exactly like gallop_left(), except that if key already exists in a[0:n], finds the position immediately to the right of the rightmost equal value. The return value is the int k in 0..n such that a[k-1] <= key < a[k] or -1 if error. The code duplication is massive, but this is enough different given that we're sticking to "<" comparisons that it's much harder to follow if written as one routine with yet another "left or right?" flag. */ static Py_ssize_t gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint) { Py_ssize_t ofs; Py_ssize_t lastofs; Py_ssize_t k; assert(key && a && n > 0 && hint >= 0 && hint < n); a += hint; lastofs = 0; ofs = 1; IFLT(key, *a) { /* key < a[hint] -- gallop left, until * a[hint - ofs] <= key < a[hint - lastofs] */ const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */ while (ofs < maxofs) { IFLT(key, *(a-ofs)) { lastofs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) /* int overflow */ ofs = maxofs; } else /* a[hint - ofs] <= key */ break; } if (ofs > maxofs) ofs = maxofs; /* Translate back to positive offsets relative to &a[0]. */ k = lastofs; lastofs = hint - ofs; ofs = hint - k; } else { /* a[hint] <= key -- gallop right, until * a[hint + lastofs] <= key < a[hint + ofs] */ const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */ while (ofs < maxofs) { IFLT(key, a[ofs]) break; /* a[hint + ofs] <= key */ lastofs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) /* int overflow */ ofs = maxofs; } if (ofs > maxofs) ofs = maxofs; /* Translate back to offsets relative to &a[0]. */ lastofs += hint; ofs += hint; } a -= hint; assert(-1 <= lastofs && lastofs < ofs && ofs <= n); /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the * right of lastofs but no farther right than ofs. Do a binary * search, with invariant a[lastofs-1] <= key < a[ofs]. */ ++lastofs; while (lastofs < ofs) { Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1); IFLT(key, a[m]) ofs = m; /* key < a[m] */ else lastofs = m+1; /* a[m] <= key */ } assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */ return ofs; fail: return -1; } /* The maximum number of entries in a MergeState's pending-runs stack. * This is enough to sort arrays of size up to about * 32 * phi ** MAX_MERGE_PENDING * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array * with 2**64 elements. */ #define MAX_MERGE_PENDING 85 /* When we get into galloping mode, we stay there until both runs win less * often than MIN_GALLOP consecutive times. See listsort.txt for more info. */ #define MIN_GALLOP 7 /* Avoid malloc for small temp arrays. */ #define MERGESTATE_TEMP_SIZE 256 /* One MergeState exists on the stack per invocation of mergesort. It's just * a convenient way to pass state around among the helper functions. */ struct s_slice { sortslice base; Py_ssize_t len; }; typedef struct s_MergeState { /* This controls when we get *into* galloping mode. It's initialized * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for * random data, and lower for highly structured data. */ Py_ssize_t min_gallop; /* 'a' is temp storage to help with merges. It contains room for * alloced entries. */ sortslice a; /* may point to temparray below */ Py_ssize_t alloced; /* A stack of n pending runs yet to be merged. Run #i starts at * address base[i] and extends for len[i] elements. It's always * true (so long as the indices are in bounds) that * * pending[i].base + pending[i].len == pending[i+1].base * * so we could cut the storage for this, but it's a minor amount, * and keeping all the info explicit simplifies the code. */ int n; struct s_slice pending[MAX_MERGE_PENDING]; /* 'a' points to this when possible, rather than muck with malloc. */ PyObject *temparray[MERGESTATE_TEMP_SIZE]; } MergeState; /* Conceptually a MergeState's constructor. */ static void merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc) { assert(ms != NULL); if (has_keyfunc) { /* The temporary space for merging will need at most half the list * size rounded up. Use the minimum possible space so we can use the * rest of temparray for other things. In particular, if there is * enough extra space, listsort() will use it to store the keys. */ ms->alloced = (list_size + 1) / 2; /* ms->alloced describes how many keys will be stored at ms->temparray, but we also need to store the values. Hence, ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */ if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced) ms->alloced = MERGESTATE_TEMP_SIZE / 2; ms->a.values = &ms->temparray[ms->alloced]; } else { ms->alloced = MERGESTATE_TEMP_SIZE; ms->a.values = NULL; } ms->a.keys = ms->temparray; ms->n = 0; ms->min_gallop = MIN_GALLOP; } /* Free all the temp memory owned by the MergeState. This must be called * when you're done with a MergeState, and may be called before then if * you want to free the temp memory early. */ static void merge_freemem(MergeState *ms) { assert(ms != NULL); if (ms->a.keys != ms->temparray) PyMem_Free(ms->a.keys); } /* Ensure enough temp memory for 'need' array slots is available. * Returns 0 on success and -1 if the memory can't be gotten. */ static int merge_getmem(MergeState *ms, Py_ssize_t need) { int multiplier; assert(ms != NULL); if (need <= ms->alloced) return 0; multiplier = ms->a.values != NULL ? 2 : 1; /* Don't realloc! That can cost cycles to copy the old data, but * we don't care what's in the block. */ merge_freemem(ms); if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) { PyErr_NoMemory(); return -1; } ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need * sizeof(PyObject *)); if (ms->a.keys != NULL) { ms->alloced = need; if (ms->a.values != NULL) ms->a.values = &ms->a.keys[need]; return 0; } PyErr_NoMemory(); return -1; } #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \ merge_getmem(MS, NEED)) /* Merge the na elements starting at ssa with the nb elements starting at * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0. * Must also have that ssa.keys[na-1] belongs at the end of the merge, and * should have na <= nb. See listsort.txt for more info. Return 0 if * successful, -1 if error. */ static Py_ssize_t merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na, sortslice ssb, Py_ssize_t nb) { Py_ssize_t k; sortslice dest; int result = -1; /* guilty until proved innocent */ Py_ssize_t min_gallop; assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0); assert(ssa.keys + na == ssb.keys); if (MERGE_GETMEM(ms, na) < 0) return -1; sortslice_memcpy(&ms->a, 0, &ssa, 0, na); dest = ssa; ssa = ms->a; sortslice_copy_incr(&dest, &ssb); --nb; if (nb == 0) goto Succeed; if (na == 1) goto CopyB; min_gallop = ms->min_gallop; for (;;) { Py_ssize_t acount = 0; /* # of times A won in a row */ Py_ssize_t bcount = 0; /* # of times B won in a row */ /* Do the straightforward thing until (if ever) one run * appears to win consistently. */ for (;;) { assert(na > 1 && nb > 0); k = ISLT(ssb.keys[0], ssa.keys[0]); if (k) { if (k < 0) goto Fail; sortslice_copy_incr(&dest, &ssb); ++bcount; acount = 0; --nb; if (nb == 0) goto Succeed; if (bcount >= min_gallop) break; } else { sortslice_copy_incr(&dest, &ssa); ++acount; bcount = 0; --na; if (na == 1) goto CopyB; if (acount >= min_gallop) break; } } /* One run is winning so consistently that galloping may * be a huge win. So try that, and continue galloping until * (if ever) neither run appears to be winning consistently * anymore. */ ++min_gallop; do { assert(na > 1 && nb > 0); min_gallop -= min_gallop > 1; ms->min_gallop = min_gallop; k = gallop_right(ssb.keys[0], ssa.keys, na, 0); acount = k; if (k) { if (k < 0) goto Fail; sortslice_memcpy(&dest, 0, &ssa, 0, k); sortslice_advance(&dest, k); sortslice_advance(&ssa, k); na -= k; if (na == 1) goto CopyB; /* na==0 is impossible now if the comparison * function is consistent, but we can't assume * that it is. */ if (na == 0) goto Succeed; } sortslice_copy_incr(&dest, &ssb); --nb; if (nb == 0) goto Succeed; k = gallop_left(ssa.keys[0], ssb.keys, nb, 0); bcount = k; if (k) { if (k < 0) goto Fail; sortslice_memmove(&dest, 0, &ssb, 0, k); sortslice_advance(&dest, k); sortslice_advance(&ssb, k); nb -= k; if (nb == 0) goto Succeed; } sortslice_copy_incr(&dest, &ssa); --na; if (na == 1) goto CopyB; } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); ++min_gallop; /* penalize it for leaving galloping mode */ ms->min_gallop = min_gallop; } Succeed: result = 0; Fail: if (na) sortslice_memcpy(&dest, 0, &ssa, 0, na); return result; CopyB: assert(na == 1 && nb > 0); /* The last element of ssa belongs at the end of the merge. */ sortslice_memmove(&dest, 0, &ssb, 0, nb); sortslice_copy(&dest, nb, &ssa, 0); return 0; } /* Merge the na elements starting at pa with the nb elements starting at * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0. * Must also have that ssa.keys[na-1] belongs at the end of the merge, and * should have na >= nb. See listsort.txt for more info. Return 0 if * successful, -1 if error. */ static Py_ssize_t merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na, sortslice ssb, Py_ssize_t nb) { Py_ssize_t k; sortslice dest, basea, baseb; int result = -1; /* guilty until proved innocent */ Py_ssize_t min_gallop; assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0); assert(ssa.keys + na == ssb.keys); if (MERGE_GETMEM(ms, nb) < 0) return -1; dest = ssb; sortslice_advance(&dest, nb-1); sortslice_memcpy(&ms->a, 0, &ssb, 0, nb); basea = ssa; baseb = ms->a; ssb.keys = ms->a.keys + nb - 1; if (ssb.values != NULL) ssb.values = ms->a.values + nb - 1; sortslice_advance(&ssa, na - 1); sortslice_copy_decr(&dest, &ssa); --na; if (na == 0) goto Succeed; if (nb == 1) goto CopyA; min_gallop = ms->min_gallop; for (;;) { Py_ssize_t acount = 0; /* # of times A won in a row */ Py_ssize_t bcount = 0; /* # of times B won in a row */ /* Do the straightforward thing until (if ever) one run * appears to win consistently. */ for (;;) { assert(na > 0 && nb > 1); k = ISLT(ssb.keys[0], ssa.keys[0]); if (k) { if (k < 0) goto Fail; sortslice_copy_decr(&dest, &ssa); ++acount; bcount = 0; --na; if (na == 0) goto Succeed; if (acount >= min_gallop) break; } else { sortslice_copy_decr(&dest, &ssb); ++bcount; acount = 0; --nb; if (nb == 1) goto CopyA; if (bcount >= min_gallop) break; } } /* One run is winning so consistently that galloping may * be a huge win. So try that, and continue galloping until * (if ever) neither run appears to be winning consistently * anymore. */ ++min_gallop; do { assert(na > 0 && nb > 1); min_gallop -= min_gallop > 1; ms->min_gallop = min_gallop; k = gallop_right(ssb.keys[0], basea.keys, na, na-1); if (k < 0) goto Fail; k = na - k; acount = k; if (k) { sortslice_advance(&dest, -k); sortslice_advance(&ssa, -k); sortslice_memmove(&dest, 1, &ssa, 1, k); na -= k; if (na == 0) goto Succeed; } sortslice_copy_decr(&dest, &ssb); --nb; if (nb == 1) goto CopyA; k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1); if (k < 0) goto Fail; k = nb - k; bcount = k; if (k) { sortslice_advance(&dest, -k); sortslice_advance(&ssb, -k); sortslice_memcpy(&dest, 1, &ssb, 1, k); nb -= k; if (nb == 1) goto CopyA; /* nb==0 is impossible now if the comparison * function is consistent, but we can't assume * that it is. */ if (nb == 0) goto Succeed; } sortslice_copy_decr(&dest, &ssa); --na; if (na == 0) goto Succeed; } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP); ++min_gallop; /* penalize it for leaving galloping mode */ ms->min_gallop = min_gallop; } Succeed: result = 0; Fail: if (nb) sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb); return result; CopyA: assert(nb == 1 && na > 0); /* The first element of ssb belongs at the front of the merge. */ sortslice_memmove(&dest, 1-na, &ssa, 1-na, na); sortslice_advance(&dest, -na); sortslice_advance(&ssa, -na); sortslice_copy(&dest, 0, &ssb, 0); return 0; } /* Merge the two runs at stack indices i and i+1. * Returns 0 on success, -1 on error. */ static Py_ssize_t merge_at(MergeState *ms, Py_ssize_t i) { sortslice ssa, ssb; Py_ssize_t na, nb; Py_ssize_t k; assert(ms != NULL); assert(ms->n >= 2); assert(i >= 0); assert(i == ms->n - 2 || i == ms->n - 3); ssa = ms->pending[i].base; na = ms->pending[i].len; ssb = ms->pending[i+1].base; nb = ms->pending[i+1].len; assert(na > 0 && nb > 0); assert(ssa.keys + na == ssb.keys); /* Record the length of the combined runs; if i is the 3rd-last * run now, also slide over the last run (which isn't involved * in this merge). The current run i+1 goes away in any case. */ ms->pending[i].len = na + nb; if (i == ms->n - 3) ms->pending[i+1] = ms->pending[i+2]; --ms->n; /* Where does b start in a? Elements in a before that can be * ignored (already in place). */ k = gallop_right(*ssb.keys, ssa.keys, na, 0); if (k < 0) return -1; sortslice_advance(&ssa, k); na -= k; if (na == 0) return 0; /* Where does a end in b? Elements in b after that can be * ignored (already in place). */ nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1); if (nb <= 0) return nb; /* Merge what remains of the runs, using a temp array with * min(na, nb) elements. */ if (na <= nb) return merge_lo(ms, ssa, na, ssb, nb); else return merge_hi(ms, ssa, na, ssb, nb); } /* Examine the stack of runs waiting to be merged, merging adjacent runs * until the stack invariants are re-established: * * 1. len[-3] > len[-2] + len[-1] * 2. len[-2] > len[-1] * * See listsort.txt for more info. * * Returns 0 on success, -1 on error. */ static int merge_collapse(MergeState *ms) { struct s_slice *p = ms->pending; assert(ms); while (ms->n > 1) { Py_ssize_t n = ms->n - 2; if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) || (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) { if (p[n-1].len < p[n+1].len) --n; if (merge_at(ms, n) < 0) return -1; } else if (p[n].len <= p[n+1].len) { if (merge_at(ms, n) < 0) return -1; } else break; } return 0; } /* Regardless of invariants, merge all runs on the stack until only one * remains. This is used at the end of the mergesort. * * Returns 0 on success, -1 on error. */ static int merge_force_collapse(MergeState *ms) { struct s_slice *p = ms->pending; assert(ms); while (ms->n > 1) { Py_ssize_t n = ms->n - 2; if (n > 0 && p[n-1].len < p[n+1].len) --n; if (merge_at(ms, n) < 0) return -1; } return 0; } /* Compute a good value for the minimum run length; natural runs shorter * than this are boosted artificially via binary insertion. * * If n < 64, return n (it's too small to bother with fancy stuff). * Else if n is an exact power of 2, return 32. * Else return an int k, 32 <= k <= 64, such that n/k is close to, but * strictly less than, an exact power of 2. * * See listsort.txt for more info. */ static Py_ssize_t merge_compute_minrun(Py_ssize_t n) { Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */ assert(n >= 0); while (n >= 64) { r |= n & 1; n >>= 1; } return n + r; } static void reverse_sortslice(sortslice *s, Py_ssize_t n) { reverse_slice(s->keys, &s->keys[n]); if (s->values != NULL) reverse_slice(s->values, &s->values[n]); } /* An adaptive, stable, natural mergesort. See listsort.txt. * Returns Py_None on success, NULL on error. Even in case of error, the * list will be some permutation of its input state (nothing is lost or * duplicated). */ static PyObject * listsort(PyListObject *self, PyObject *args, PyObject *kwds) { MergeState *ms; Py_ssize_t nremaining; Py_ssize_t minrun; sortslice lo; Py_ssize_t saved_ob_size, saved_allocated; PyObject **saved_ob_item; PyObject **final_ob_item; PyObject *result = NULL; /* guilty until proved innocent */ int reverse = 0; PyObject *keyfunc = NULL; Py_ssize_t i; static char *kwlist[] = {"key", "reverse", 0}; PyObject **keys; ms = gc(malloc(sizeof(MergeState))); assert(self != NULL); assert (PyList_Check(self)); if (args != NULL) { if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort", kwlist, &keyfunc, &reverse)) return NULL; if (Py_SIZE(args) > 0) { PyErr_SetString(PyExc_TypeError, "must use keyword argument for key function"); return NULL; } } if (keyfunc == Py_None) keyfunc = NULL; /* The list is temporarily made empty, so that mutations performed * by comparison functions can't affect the slice of memory we're * sorting (allowing mutations during sorting is a core-dump * factory, since ob_item may change). */ saved_ob_size = Py_SIZE(self); saved_ob_item = self->ob_item; saved_allocated = self->allocated; Py_SIZE(self) = 0; self->ob_item = NULL; self->allocated = -1; /* any operation will reset it to >= 0 */ if (keyfunc == NULL) { keys = NULL; lo.keys = saved_ob_item; lo.values = NULL; } else { if (saved_ob_size < MERGESTATE_TEMP_SIZE/2) /* Leverage stack space we allocated but won't otherwise use */ keys = &ms->temparray[saved_ob_size+1]; else { keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size); if (keys == NULL) { PyErr_NoMemory(); goto keyfunc_fail; } } for (i = 0; i < saved_ob_size ; i++) { keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i], NULL); if (keys[i] == NULL) { for (i=i-1 ; i>=0 ; i--) Py_DECREF(keys[i]); if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2) PyMem_FREE(keys); goto keyfunc_fail; } } lo.keys = keys; lo.values = saved_ob_item; } merge_init(ms, saved_ob_size, keys != NULL); nremaining = saved_ob_size; if (nremaining < 2) goto succeed; /* Reverse sort stability achieved by initially reversing the list, applying a stable forward sort, then reversing the final result. */ if (reverse) { if (keys != NULL) reverse_slice(&keys[0], &keys[saved_ob_size]); reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]); } /* March over the array once, left to right, finding natural runs, * and extending short natural runs to minrun elements. */ minrun = merge_compute_minrun(nremaining); do { int descending; Py_ssize_t n; /* Identify next run. */ n = count_run(lo.keys, lo.keys + nremaining, &descending); if (n < 0) goto fail; if (descending) reverse_sortslice(&lo, n); /* If short, extend to min(minrun, nremaining). */ if (n < minrun) { const Py_ssize_t force = nremaining <= minrun ? nremaining : minrun; if (binarysort(lo, lo.keys + force, lo.keys + n) < 0) goto fail; n = force; } /* Push run onto pending-runs stack, and maybe merge. */ assert(ms->n < MAX_MERGE_PENDING); ms->pending[ms->n].base = lo; ms->pending[ms->n].len = n; ++ms->n; if (merge_collapse(ms) < 0) goto fail; /* Advance to find next run. */ sortslice_advance(&lo, n); nremaining -= n; } while (nremaining); if (merge_force_collapse(ms) < 0) goto fail; assert(ms->n == 1); assert(keys == NULL ? ms->pending[0].base.keys == saved_ob_item : ms->pending[0].base.keys == &keys[0]); assert(ms->pending[0].len == saved_ob_size); lo = ms->pending[0].base; succeed: result = Py_None; fail: if (keys != NULL) { for (i = 0; i < saved_ob_size; i++) Py_DECREF(keys[i]); if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2) PyMem_FREE(keys); } if (self->allocated != -1 && result != NULL) { /* The user mucked with the list during the sort, * and we don't already have another error to report. */ PyErr_SetString(PyExc_ValueError, "list modified during sort"); result = NULL; } if (reverse && saved_ob_size > 1) reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size); merge_freemem(ms); keyfunc_fail: final_ob_item = self->ob_item; i = Py_SIZE(self); Py_SIZE(self) = saved_ob_size; self->ob_item = saved_ob_item; self->allocated = saved_allocated; if (final_ob_item != NULL) { /* we cannot use list_clear() for this because it does not guarantee that the list is really empty when it returns */ while (--i >= 0) { Py_XDECREF(final_ob_item[i]); } PyMem_FREE(final_ob_item); } Py_XINCREF(result); return result; } #undef IFLT #undef ISLT int PyList_Sort(PyObject *v) { if (v == NULL || !PyList_Check(v)) { PyErr_BadInternalCall(); return -1; } v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL); if (v == NULL) return -1; Py_DECREF(v); return 0; } static PyObject * listreverse(PyListObject *self) { if (Py_SIZE(self) > 1) reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); Py_RETURN_NONE; } int PyList_Reverse(PyObject *v) { PyListObject *self = (PyListObject *)v; if (v == NULL || !PyList_Check(v)) { PyErr_BadInternalCall(); return -1; } if (Py_SIZE(self) > 1) reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self)); return 0; } PyObject * PyList_AsTuple(PyObject *v) { PyObject *w; PyObject **p, **q; Py_ssize_t n; if (v == NULL || !PyList_Check(v)) { PyErr_BadInternalCall(); return NULL; } n = Py_SIZE(v); w = PyTuple_New(n); if (w == NULL) return NULL; p = ((PyTupleObject *)w)->ob_item; q = ((PyListObject *)v)->ob_item; while (--n >= 0) { Py_INCREF(*q); *p = *q; p++; q++; } return w; } static PyObject * listindex(PyListObject *self, PyObject *args) { Py_ssize_t i, start=0, stop=Py_SIZE(self); PyObject *v; if (!PyArg_ParseTuple(args, "O|O&O&:index", &v, _PyEval_SliceIndexNotNone, &start, _PyEval_SliceIndexNotNone, &stop)) return NULL; if (start < 0) { start += Py_SIZE(self); if (start < 0) start = 0; } if (stop < 0) { stop += Py_SIZE(self); if (stop < 0) stop = 0; } for (i = start; i < stop && i < Py_SIZE(self); i++) { int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); if (cmp > 0) return PyLong_FromSsize_t(i); else if (cmp < 0) return NULL; } PyErr_Format(PyExc_ValueError, "%R is not in list", v); return NULL; } static PyObject * listcount(PyListObject *self, PyObject *v) { Py_ssize_t count = 0; Py_ssize_t i; for (i = 0; i < Py_SIZE(self); i++) { int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); if (cmp > 0) count++; else if (cmp < 0) return NULL; } return PyLong_FromSsize_t(count); } static PyObject * listremove(PyListObject *self, PyObject *v) { Py_ssize_t i; for (i = 0; i < Py_SIZE(self); i++) { int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ); if (cmp > 0) { if (list_ass_slice(self, i, i+1, (PyObject *)NULL) == 0) Py_RETURN_NONE; return NULL; } else if (cmp < 0) return NULL; } PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list"); return NULL; } static int list_traverse(PyListObject *o, visitproc visit, void *arg) { Py_ssize_t i; for (i = Py_SIZE(o); --i >= 0; ) Py_VISIT(o->ob_item[i]); return 0; } static PyObject * list_richcompare(PyObject *v, PyObject *w, int op) { PyListObject *vl, *wl; Py_ssize_t i; if (!PyList_Check(v) || !PyList_Check(w)) Py_RETURN_NOTIMPLEMENTED; vl = (PyListObject *)v; wl = (PyListObject *)w; if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) { /* Shortcut: if the lengths differ, the lists differ */ PyObject *res; if (op == Py_EQ) res = Py_False; else res = Py_True; Py_INCREF(res); return res; } /* Search for the first index where items are different */ for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) { int k = PyObject_RichCompareBool(vl->ob_item[i], wl->ob_item[i], Py_EQ); if (k < 0) return NULL; if (!k) break; } if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) { /* No more items to compare -- compare sizes */ Py_ssize_t vs = Py_SIZE(vl); Py_ssize_t ws = Py_SIZE(wl); int cmp; PyObject *res; switch (op) { case Py_LT: cmp = vs < ws; break; case Py_LE: cmp = vs <= ws; break; case Py_EQ: cmp = vs == ws; break; case Py_NE: cmp = vs != ws; break; case Py_GT: cmp = vs > ws; break; case Py_GE: cmp = vs >= ws; break; default: return NULL; /* cannot happen */ } if (cmp) res = Py_True; else res = Py_False; Py_INCREF(res); return res; } /* We have an item that differs -- shortcuts for EQ/NE */ if (op == Py_EQ) { Py_INCREF(Py_False); return Py_False; } if (op == Py_NE) { Py_INCREF(Py_True); return Py_True; } /* Compare the final item again using the proper operator */ return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op); } static int list_init(PyListObject *self, PyObject *args, PyObject *kw) { PyObject *arg = NULL; static char *kwlist[] = {"sequence", 0}; if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg)) return -1; /* Verify list invariants established by PyType_GenericAlloc() */ assert(0 <= Py_SIZE(self)); assert(Py_SIZE(self) <= self->allocated || self->allocated == -1); assert(self->ob_item != NULL || self->allocated == 0 || self->allocated == -1); /* Empty previous contents */ if (self->ob_item != NULL) { (void)list_clear(self); } if (arg != NULL) { PyObject *rv = listextend(self, arg); if (rv == NULL) return -1; Py_DECREF(rv); } return 0; } static PyObject * list_sizeof(PyListObject *self) { Py_ssize_t res; res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*); return PyLong_FromSsize_t(res); } static PyObject *list_iter(PyObject *seq); static PyObject *list_reversed(PyListObject* seq, PyObject* unused); PyDoc_STRVAR(getitem_doc, "x.__getitem__(y) <==> x[y]"); PyDoc_STRVAR(reversed_doc, "L.__reversed__() -- return a reverse iterator over the list"); PyDoc_STRVAR(sizeof_doc, "L.__sizeof__() -- size of L in memory, in bytes"); PyDoc_STRVAR(clear_doc, "L.clear() -> None -- remove all items from L"); PyDoc_STRVAR(copy_doc, "L.copy() -> list -- a shallow copy of L"); PyDoc_STRVAR(append_doc, "L.append(object) -> None -- append object to end"); PyDoc_STRVAR(extend_doc, "L.extend(iterable) -> None -- extend list by appending elements from the iterable"); PyDoc_STRVAR(insert_doc, "L.insert(index, object) -- insert object before index"); PyDoc_STRVAR(pop_doc, "L.pop([index]) -> item -- remove and return item at index (default last).\n" "Raises IndexError if list is empty or index is out of range."); PyDoc_STRVAR(remove_doc, "L.remove(value) -> None -- remove first occurrence of value.\n" "Raises ValueError if the value is not present."); PyDoc_STRVAR(index_doc, "L.index(value, [start, [stop]]) -> integer -- return first index of value.\n" "Raises ValueError if the value is not present."); PyDoc_STRVAR(count_doc, "L.count(value) -> integer -- return number of occurrences of value"); PyDoc_STRVAR(reverse_doc, "L.reverse() -- reverse *IN PLACE*"); PyDoc_STRVAR(sort_doc, "L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*"); static PyObject *list_subscript(PyListObject*, PyObject*); static PyMethodDef list_methods[] = { {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc}, {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc}, {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc}, {"clear", (PyCFunction)listclear, METH_NOARGS, clear_doc}, {"copy", (PyCFunction)listcopy, METH_NOARGS, copy_doc}, {"append", (PyCFunction)listappend, METH_O, append_doc}, {"insert", (PyCFunction)listinsert, METH_FASTCALL, insert_doc}, {"extend", (PyCFunction)listextend, METH_O, extend_doc}, {"pop", (PyCFunction)listpop, METH_FASTCALL, pop_doc}, {"remove", (PyCFunction)listremove, METH_O, remove_doc}, {"index", (PyCFunction)listindex, METH_VARARGS, index_doc}, {"count", (PyCFunction)listcount, METH_O, count_doc}, {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc}, {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc}, {NULL, NULL} /* sentinel */ }; static PySequenceMethods list_as_sequence = { (lenfunc)list_length, /* sq_length */ (binaryfunc)list_concat, /* sq_concat */ (ssizeargfunc)list_repeat, /* sq_repeat */ (ssizeargfunc)list_item, /* sq_item */ 0, /* sq_slice */ (ssizeobjargproc)list_ass_item, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)list_contains, /* sq_contains */ (binaryfunc)list_inplace_concat, /* sq_inplace_concat */ (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */ }; PyDoc_STRVAR(list_doc, "list() -> new empty list\n" "list(iterable) -> new list initialized from iterable's items"); static PyObject * list_subscript(PyListObject* self, PyObject* item) { if (PyIndex_Check(item)) { Py_ssize_t i; i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return NULL; if (i < 0) i += PyList_GET_SIZE(self); return list_item(self, i); } else if (PySlice_Check(item)) { Py_ssize_t start, stop, step, slicelength, cur, i; PyObject* result; PyObject* it; PyObject **src, **dest; if (PySlice_Unpack(item, &start, &stop, &step) < 0) { return NULL; } slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop, step); if (slicelength <= 0) { return PyList_New(0); } else if (step == 1) { return list_slice(self, start, stop); } else { result = PyList_New(slicelength); if (!result) return NULL; src = self->ob_item; dest = ((PyListObject *)result)->ob_item; for (cur = start, i = 0; i < slicelength; cur += (size_t)step, i++) { it = src[cur]; Py_INCREF(it); dest[i] = it; } return result; } } else { PyErr_Format(PyExc_TypeError, "list indices must be integers or slices, not %.200s", item->ob_type->tp_name); return NULL; } } static int list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value) { if (PyIndex_Check(item)) { Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return -1; if (i < 0) i += PyList_GET_SIZE(self); return list_ass_item(self, i, value); } else if (PySlice_Check(item)) { Py_ssize_t start, stop, step, slicelength; if (PySlice_Unpack(item, &start, &stop, &step) < 0) { return -1; } slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop, step); if (step == 1) return list_ass_slice(self, start, stop, value); /* Make sure s[5:2] = [..] inserts at the right place: before 5, not before 2. */ if ((step < 0 && start < stop) || (step > 0 && start > stop)) stop = start; if (value == NULL) { /* delete slice */ PyObject **garbage; size_t cur; Py_ssize_t i; int res; if (slicelength <= 0) return 0; if (step < 0) { stop = start + 1; start = stop + step*(slicelength - 1) - 1; step = -step; } garbage = (PyObject**) PyMem_MALLOC(slicelength*sizeof(PyObject*)); if (!garbage) { PyErr_NoMemory(); return -1; } /* drawing pictures might help understand these for loops. Basically, we memmove the parts of the list that are *not* part of the slice: step-1 items for each item that is part of the slice, and then tail end of the list that was not covered by the slice */ for (cur = start, i = 0; cur < (size_t)stop; cur += step, i++) { Py_ssize_t lim = step - 1; garbage[i] = PyList_GET_ITEM(self, cur); if (cur + step >= (size_t)Py_SIZE(self)) { lim = Py_SIZE(self) - cur - 1; } memmove(self->ob_item + cur - i, self->ob_item + cur + 1, lim * sizeof(PyObject *)); } cur = start + (size_t)slicelength * step; if (cur < (size_t)Py_SIZE(self)) { memmove(self->ob_item + cur - slicelength, self->ob_item + cur, (Py_SIZE(self) - cur) * sizeof(PyObject *)); } Py_SIZE(self) -= slicelength; res = list_resize(self, Py_SIZE(self)); for (i = 0; i < slicelength; i++) { Py_DECREF(garbage[i]); } PyMem_FREE(garbage); return res; } else { /* assign slice */ PyObject *ins, *seq; PyObject **garbage, **seqitems, **selfitems; Py_ssize_t cur, i; /* protect against a[::-1] = a */ if (self == (PyListObject*)value) { seq = list_slice((PyListObject*)value, 0, PyList_GET_SIZE(value)); } else { seq = PySequence_Fast(value, "must assign iterable " "to extended slice"); } if (!seq) return -1; if (PySequence_Fast_GET_SIZE(seq) != slicelength) { PyErr_Format(PyExc_ValueError, "attempt to assign sequence of " "size %zd to extended slice of " "size %zd", PySequence_Fast_GET_SIZE(seq), slicelength); Py_DECREF(seq); return -1; } if (!slicelength) { Py_DECREF(seq); return 0; } garbage = (PyObject**) PyMem_MALLOC(slicelength*sizeof(PyObject*)); if (!garbage) { Py_DECREF(seq); PyErr_NoMemory(); return -1; } selfitems = self->ob_item; seqitems = PySequence_Fast_ITEMS(seq); for (cur = start, i = 0; i < slicelength; cur += (size_t)step, i++) { garbage[i] = selfitems[cur]; ins = seqitems[i]; Py_INCREF(ins); selfitems[cur] = ins; } for (i = 0; i < slicelength; i++) { Py_DECREF(garbage[i]); } PyMem_FREE(garbage); Py_DECREF(seq); return 0; } } else { PyErr_Format(PyExc_TypeError, "list indices must be integers or slices, not %.200s", item->ob_type->tp_name); return -1; } } static PyMappingMethods list_as_mapping = { (lenfunc)list_length, (binaryfunc)list_subscript, (objobjargproc)list_ass_subscript }; PyTypeObject PyList_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "list", sizeof(PyListObject), 0, (destructor)list_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)list_repr, /* tp_repr */ 0, /* tp_as_number */ &list_as_sequence, /* tp_as_sequence */ &list_as_mapping, /* tp_as_mapping */ PyObject_HashNotImplemented, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */ list_doc, /* tp_doc */ (traverseproc)list_traverse, /* tp_traverse */ (inquiry)list_clear, /* tp_clear */ list_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ list_iter, /* tp_iter */ 0, /* tp_iternext */ list_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)list_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; /*********************** List Iterator **************************/ typedef struct { PyObject_HEAD Py_ssize_t it_index; PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ } listiterobject; static PyObject *list_iter(PyObject *); static void listiter_dealloc(listiterobject *); static int listiter_traverse(listiterobject *, visitproc, void *); static PyObject *listiter_next(listiterobject *); static PyObject *listiter_len(listiterobject *); static PyObject *listiter_reduce_general(void *_it, int forward); static PyObject *listiter_reduce(listiterobject *); static PyObject *listiter_setstate(listiterobject *, PyObject *state); PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef listiter_methods[] = { {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyListIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "list_iterator", /* tp_name */ sizeof(listiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)listiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)listiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)listiter_next, /* tp_iternext */ listiter_methods, /* tp_methods */ 0, /* tp_members */ }; static PyObject * list_iter(PyObject *seq) { listiterobject *it; if (!PyList_Check(seq)) { PyErr_BadInternalCall(); return NULL; } it = PyObject_GC_New(listiterobject, &PyListIter_Type); if (it == NULL) return NULL; it->it_index = 0; Py_INCREF(seq); it->it_seq = (PyListObject *)seq; _PyObject_GC_TRACK(it); return (PyObject *)it; } static void listiter_dealloc(listiterobject *it) { _PyObject_GC_UNTRACK(it); Py_XDECREF(it->it_seq); PyObject_GC_Del(it); } static int listiter_traverse(listiterobject *it, visitproc visit, void *arg) { Py_VISIT(it->it_seq); return 0; } static PyObject * listiter_next(listiterobject *it) { PyListObject *seq; PyObject *item; assert(it != NULL); seq = it->it_seq; if (seq == NULL) return NULL; assert(PyList_Check(seq)); if (it->it_index < PyList_GET_SIZE(seq)) { item = PyList_GET_ITEM(seq, it->it_index); ++it->it_index; Py_INCREF(item); return item; } it->it_seq = NULL; Py_DECREF(seq); return NULL; } static PyObject * listiter_len(listiterobject *it) { Py_ssize_t len; if (it->it_seq) { len = PyList_GET_SIZE(it->it_seq) - it->it_index; if (len >= 0) return PyLong_FromSsize_t(len); } return PyLong_FromLong(0); } static PyObject * listiter_reduce(listiterobject *it) { return listiter_reduce_general(it, 1); } static PyObject * listiter_setstate(listiterobject *it, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; if (it->it_seq != NULL) { if (index < 0) index = 0; else if (index > PyList_GET_SIZE(it->it_seq)) index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */ it->it_index = index; } Py_RETURN_NONE; } /*********************** List Reverse Iterator **************************/ typedef struct { PyObject_HEAD Py_ssize_t it_index; PyListObject *it_seq; /* Set to NULL when iterator is exhausted */ } listreviterobject; static PyObject *list_reversed(PyListObject *, PyObject *); static void listreviter_dealloc(listreviterobject *); static int listreviter_traverse(listreviterobject *, visitproc, void *); static PyObject *listreviter_next(listreviterobject *); static PyObject *listreviter_len(listreviterobject *); static PyObject *listreviter_reduce(listreviterobject *); static PyObject *listreviter_setstate(listreviterobject *, PyObject *); static PyMethodDef listreviter_methods[] = { {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyListRevIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "list_reverseiterator", /* tp_name */ sizeof(listreviterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)listreviter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)listreviter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)listreviter_next, /* tp_iternext */ listreviter_methods, /* tp_methods */ 0, }; static PyObject * list_reversed(PyListObject *seq, PyObject *unused) { listreviterobject *it; it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type); if (it == NULL) return NULL; assert(PyList_Check(seq)); it->it_index = PyList_GET_SIZE(seq) - 1; Py_INCREF(seq); it->it_seq = seq; PyObject_GC_Track(it); return (PyObject *)it; } static void listreviter_dealloc(listreviterobject *it) { PyObject_GC_UnTrack(it); Py_XDECREF(it->it_seq); PyObject_GC_Del(it); } static int listreviter_traverse(listreviterobject *it, visitproc visit, void *arg) { Py_VISIT(it->it_seq); return 0; } static PyObject * listreviter_next(listreviterobject *it) { PyObject *item; Py_ssize_t index; PyListObject *seq; assert(it != NULL); seq = it->it_seq; if (seq == NULL) { return NULL; } assert(PyList_Check(seq)); index = it->it_index; if (index>=0 && index < PyList_GET_SIZE(seq)) { item = PyList_GET_ITEM(seq, index); it->it_index--; Py_INCREF(item); return item; } it->it_index = -1; it->it_seq = NULL; Py_DECREF(seq); return NULL; } static PyObject * listreviter_len(listreviterobject *it) { Py_ssize_t len = it->it_index + 1; if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len) len = 0; return PyLong_FromSsize_t(len); } static PyObject * listreviter_reduce(listreviterobject *it) { return listiter_reduce_general(it, 0); } static PyObject * listreviter_setstate(listreviterobject *it, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; if (it->it_seq != NULL) { if (index < -1) index = -1; else if (index > PyList_GET_SIZE(it->it_seq) - 1) index = PyList_GET_SIZE(it->it_seq) - 1; it->it_index = index; } Py_RETURN_NONE; } /* common pickling support */ static PyObject * listiter_reduce_general(void *_it, int forward) { PyObject *list; /* the objects are not the same, index is of different types! */ if (forward) { listiterobject *it = (listiterobject *)_it; if (it->it_seq) return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"), it->it_seq, it->it_index); } else { listreviterobject *it = (listreviterobject *)_it; if (it->it_seq) return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"), it->it_seq, it->it_index); } /* empty iterator, create an empty list */ list = PyList_New(0); if (list == NULL) return NULL; return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list); }
89,586
3,005
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/complexobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/math.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyfpe.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymath.h" #include "third_party/python/Include/pystrtod.h" #include "third_party/python/Include/structmember.h" /* clang-format off */ /* Borrows heavily from floatobject.c */ /* Submitted by Jim Hugunin */ /* elementary operations on complex numbers */ static Py_complex c_1 = {1., 0.}; Py_complex _Py_c_sum(Py_complex a, Py_complex b) { Py_complex r; r.real = a.real + b.real; r.imag = a.imag + b.imag; return r; } Py_complex _Py_c_diff(Py_complex a, Py_complex b) { Py_complex r; r.real = a.real - b.real; r.imag = a.imag - b.imag; return r; } Py_complex _Py_c_neg(Py_complex a) { Py_complex r; r.real = -a.real; r.imag = -a.imag; return r; } Py_complex _Py_c_prod(Py_complex a, Py_complex b) { Py_complex r; r.real = a.real*b.real - a.imag*b.imag; r.imag = a.real*b.imag + a.imag*b.real; return r; } Py_complex _Py_c_quot(Py_complex a, Py_complex b) { /****************************************************************** This was the original algorithm. It's grossly prone to spurious overflow and underflow errors. It also merrily divides by 0 despite checking for that(!). The code still serves a doc purpose here, as the algorithm following is a simple by-cases transformation of this one: Py_complex r; double d = b.real*b.real + b.imag*b.imag; if (d == 0.) errno = EDOM; r.real = (a.real*b.real + a.imag*b.imag)/d; r.imag = (a.imag*b.real - a.real*b.imag)/d; return r; ******************************************************************/ /* This algorithm is better, and is pretty obvious: first divide the * numerators and denominator by whichever of {b.real, b.imag} has * larger magnitude. The earliest reference I found was to CACM * Algorithm 116 (Complex Division, Robert L. Smith, Stanford * University). As usual, though, we're still ignoring all IEEE * endcases. */ Py_complex r; /* the result */ const double abs_breal = b.real < 0 ? -b.real : b.real; const double abs_bimag = b.imag < 0 ? -b.imag : b.imag; if (abs_breal >= abs_bimag) { /* divide tops and bottom by b.real */ if (abs_breal == 0.0) { errno = EDOM; r.real = r.imag = 0.0; } else { const double ratio = b.imag / b.real; const double denom = b.real + b.imag * ratio; r.real = (a.real + a.imag * ratio) / denom; r.imag = (a.imag - a.real * ratio) / denom; } } else if (abs_bimag >= abs_breal) { /* divide tops and bottom by b.imag */ const double ratio = b.real / b.imag; const double denom = b.real * ratio + b.imag; assert(b.imag != 0.0); r.real = (a.real * ratio + a.imag) / denom; r.imag = (a.imag * ratio - a.real) / denom; } else { /* At least one of b.real or b.imag is a NaN */ r.real = r.imag = Py_NAN; } return r; } Py_complex _Py_c_pow(Py_complex a, Py_complex b) { Py_complex r; double vabs,len,at,phase; if (b.real == 0. && b.imag == 0.) { r.real = 1.; r.imag = 0.; } else if (a.real == 0. && a.imag == 0.) { if (b.imag != 0. || b.real < 0.) errno = EDOM; r.real = 0.; r.imag = 0.; } else { vabs = hypot(a.real,a.imag); len = pow(vabs,b.real); at = atan2(a.imag, a.real); phase = at*b.real; if (b.imag != 0.0) { len /= exp(at*b.imag); phase += b.imag*log(vabs); } r.real = len*cos(phase); r.imag = len*sin(phase); } return r; } static Py_complex c_powu(Py_complex x, long n) { Py_complex r, p; long mask = 1; r = c_1; p = x; while (mask > 0 && n >= mask) { if (n & mask) r = _Py_c_prod(r,p); mask <<= 1; p = _Py_c_prod(p,p); } return r; } static Py_complex c_powi(Py_complex x, long n) { Py_complex cn; if (n > 100 || n < -100) { cn.real = (double) n; cn.imag = 0.; return _Py_c_pow(x,cn); } else if (n > 0) return c_powu(x,n); else return _Py_c_quot(c_1, c_powu(x,-n)); } double _Py_c_abs(Py_complex z) { /* sets errno = ERANGE on overflow; otherwise errno = 0 */ double result; if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) { /* C99 rules: if either the real or the imaginary part is an infinity, return infinity, even if the other part is a NaN. */ if (Py_IS_INFINITY(z.real)) { result = fabs(z.real); errno = 0; return result; } if (Py_IS_INFINITY(z.imag)) { result = fabs(z.imag); errno = 0; return result; } /* either the real or imaginary part is a NaN, and neither is infinite. Result should be NaN. */ return Py_NAN; } result = hypot(z.real, z.imag); if (!Py_IS_FINITE(result)) errno = ERANGE; else errno = 0; return result; } static PyObject * complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) { PyObject *op; op = type->tp_alloc(type, 0); if (op != NULL) ((PyComplexObject *)op)->cval = cval; return op; } PyObject * PyComplex_FromCComplex(Py_complex cval) { PyComplexObject *op; /* Inline PyObject_New */ op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject)); if (op == NULL) return PyErr_NoMemory(); (void)PyObject_INIT(op, &PyComplex_Type); op->cval = cval; return (PyObject *) op; } static PyObject * complex_subtype_from_doubles(PyTypeObject *type, double real, double imag) { Py_complex c; c.real = real; c.imag = imag; return complex_subtype_from_c_complex(type, c); } PyObject * PyComplex_FromDoubles(double real, double imag) { Py_complex c; c.real = real; c.imag = imag; return PyComplex_FromCComplex(c); } double PyComplex_RealAsDouble(PyObject *op) { if (PyComplex_Check(op)) { return ((PyComplexObject *)op)->cval.real; } else { return PyFloat_AsDouble(op); } } double PyComplex_ImagAsDouble(PyObject *op) { if (PyComplex_Check(op)) { return ((PyComplexObject *)op)->cval.imag; } else { return 0.0; } } static PyObject * try_complex_special_method(PyObject *op) { PyObject *f; _Py_IDENTIFIER(__complex__); f = _PyObject_LookupSpecial(op, &PyId___complex__); if (f) { PyObject *res = PyObject_CallFunctionObjArgs(f, NULL); Py_DECREF(f); if (res != NULL && !PyComplex_Check(res)) { PyErr_SetString(PyExc_TypeError, "__complex__ should return a complex object"); Py_DECREF(res); return NULL; } return res; } return NULL; } Py_complex PyComplex_AsCComplex(PyObject *op) { Py_complex cv; PyObject *newop = NULL; assert(op); /* If op is already of type PyComplex_Type, return its value */ if (PyComplex_Check(op)) { return ((PyComplexObject *)op)->cval; } /* If not, use op's __complex__ method, if it exists */ /* return -1 on failure */ cv.real = -1.; cv.imag = 0.; newop = try_complex_special_method(op); if (newop) { cv = ((PyComplexObject *)newop)->cval; Py_DECREF(newop); return cv; } else if (PyErr_Occurred()) { return cv; } /* If neither of the above works, interpret op as a float giving the real part of the result, and fill in the imaginary part as 0. */ else { /* PyFloat_AsDouble will return -1 on failure */ cv.real = PyFloat_AsDouble(op); return cv; } } static void complex_dealloc(PyObject *op) { op->ob_type->tp_free(op); } static PyObject * complex_repr(PyComplexObject *v) { int precision = 0; char format_code = 'r'; PyObject *result = NULL; /* If these are non-NULL, they'll need to be freed. */ char *pre = NULL; char *im = NULL; /* These do not need to be freed. re is either an alias for pre or a pointer to a constant. lead and tail are pointers to constants. */ char *re = NULL; char *lead = ""; char *tail = ""; if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) { /* Real part is +0: just output the imaginary part and do not include parens. */ re = ""; im = PyOS_double_to_string(v->cval.imag, format_code, precision, 0, NULL); if (!im) { PyErr_NoMemory(); goto done; } } else { /* Format imaginary part with sign, real part without. Include parens in the result. */ pre = PyOS_double_to_string(v->cval.real, format_code, precision, 0, NULL); if (!pre) { PyErr_NoMemory(); goto done; } re = pre; im = PyOS_double_to_string(v->cval.imag, format_code, precision, Py_DTSF_SIGN, NULL); if (!im) { PyErr_NoMemory(); goto done; } lead = "("; tail = ")"; } result = PyUnicode_FromFormat("%s%s%sj%s", lead, re, im, tail); done: PyMem_Free(im); PyMem_Free(pre); return result; } static Py_hash_t complex_hash(PyComplexObject *v) { Py_uhash_t hashreal, hashimag, combined; hashreal = (Py_uhash_t)_Py_HashDouble(v->cval.real); if (hashreal == (Py_uhash_t)-1) return -1; hashimag = (Py_uhash_t)_Py_HashDouble(v->cval.imag); if (hashimag == (Py_uhash_t)-1) return -1; /* Note: if the imaginary part is 0, hashimag is 0 now, * so the following returns hashreal unchanged. This is * important because numbers of different types that * compare equal must have the same hash value, so that * hash(x + 0*j) must equal hash(x). */ combined = hashreal + _PyHASH_IMAG * hashimag; if (combined == (Py_uhash_t)-1) combined = (Py_uhash_t)-2; return (Py_hash_t)combined; } /* This macro may return! */ #define TO_COMPLEX(obj, c) \ if (PyComplex_Check(obj)) \ c = ((PyComplexObject *)(obj))->cval; \ else if (to_complex(&(obj), &(c)) < 0) \ return (obj) static int to_complex(PyObject **pobj, Py_complex *pc) { PyObject *obj = *pobj; pc->real = pc->imag = 0.0; if (PyLong_Check(obj)) { pc->real = PyLong_AsDouble(obj); if (pc->real == -1.0 && PyErr_Occurred()) { *pobj = NULL; return -1; } return 0; } if (PyFloat_Check(obj)) { pc->real = PyFloat_AsDouble(obj); return 0; } Py_INCREF(Py_NotImplemented); *pobj = Py_NotImplemented; return -1; } static PyObject * complex_add(PyObject *v, PyObject *w) { Py_complex result; Py_complex a, b; TO_COMPLEX(v, a); TO_COMPLEX(w, b); PyFPE_START_PROTECT("complex_add", return 0) result = _Py_c_sum(a, b); PyFPE_END_PROTECT(result) return PyComplex_FromCComplex(result); } static PyObject * complex_sub(PyObject *v, PyObject *w) { Py_complex result; Py_complex a, b; TO_COMPLEX(v, a); TO_COMPLEX(w, b); PyFPE_START_PROTECT("complex_sub", return 0) result = _Py_c_diff(a, b); PyFPE_END_PROTECT(result) return PyComplex_FromCComplex(result); } static PyObject * complex_mul(PyObject *v, PyObject *w) { Py_complex result; Py_complex a, b; TO_COMPLEX(v, a); TO_COMPLEX(w, b); PyFPE_START_PROTECT("complex_mul", return 0) result = _Py_c_prod(a, b); PyFPE_END_PROTECT(result) return PyComplex_FromCComplex(result); } static PyObject * complex_div(PyObject *v, PyObject *w) { Py_complex quot; Py_complex a, b; TO_COMPLEX(v, a); TO_COMPLEX(w, b); PyFPE_START_PROTECT("complex_div", return 0) errno = 0; quot = _Py_c_quot(a, b); PyFPE_END_PROTECT(quot) if (errno == EDOM) { PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero"); return NULL; } return PyComplex_FromCComplex(quot); } static PyObject * complex_remainder(PyObject *v, PyObject *w) { PyErr_SetString(PyExc_TypeError, "can't mod complex numbers."); return NULL; } static PyObject * complex_divmod(PyObject *v, PyObject *w) { PyErr_SetString(PyExc_TypeError, "can't take floor or mod of complex number."); return NULL; } static PyObject * complex_pow(PyObject *v, PyObject *w, PyObject *z) { Py_complex p; Py_complex exponent; long int_exponent; Py_complex a, b; TO_COMPLEX(v, a); TO_COMPLEX(w, b); if (z != Py_None) { PyErr_SetString(PyExc_ValueError, "complex modulo"); return NULL; } PyFPE_START_PROTECT("complex_pow", return 0) errno = 0; exponent = b; int_exponent = (long)exponent.real; if (exponent.imag == 0. && exponent.real == int_exponent) p = c_powi(a, int_exponent); else p = _Py_c_pow(a, exponent); PyFPE_END_PROTECT(p) Py_ADJUST_ERANGE2(p.real, p.imag); if (errno == EDOM) { PyErr_SetString(PyExc_ZeroDivisionError, "0.0 to a negative or complex power"); return NULL; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "complex exponentiation"); return NULL; } return PyComplex_FromCComplex(p); } static PyObject * complex_int_div(PyObject *v, PyObject *w) { PyErr_SetString(PyExc_TypeError, "can't take floor of complex number."); return NULL; } static PyObject * complex_neg(PyComplexObject *v) { Py_complex neg; neg.real = -v->cval.real; neg.imag = -v->cval.imag; return PyComplex_FromCComplex(neg); } static PyObject * complex_pos(PyComplexObject *v) { if (PyComplex_CheckExact(v)) { Py_INCREF(v); return (PyObject *)v; } else return PyComplex_FromCComplex(v->cval); } static PyObject * complex_abs(PyComplexObject *v) { double result; PyFPE_START_PROTECT("complex_abs", return 0) result = _Py_c_abs(v->cval); PyFPE_END_PROTECT(result) if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "absolute value too large"); return NULL; } return PyFloat_FromDouble(result); } static int complex_bool(PyComplexObject *v) { return v->cval.real != 0.0 || v->cval.imag != 0.0; } static PyObject * complex_richcompare(PyObject *v, PyObject *w, int op) { PyObject *res; Py_complex i; int equal; if (op != Py_EQ && op != Py_NE) { goto Unimplemented; } assert(PyComplex_Check(v)); TO_COMPLEX(v, i); if (PyLong_Check(w)) { /* Check for 0.0 imaginary part first to avoid the rich * comparison when possible. */ if (i.imag == 0.0) { PyObject *j, *sub_res; j = PyFloat_FromDouble(i.real); if (j == NULL) return NULL; sub_res = PyObject_RichCompare(j, w, op); Py_DECREF(j); return sub_res; } else { equal = 0; } } else if (PyFloat_Check(w)) { equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0); } else if (PyComplex_Check(w)) { Py_complex j; TO_COMPLEX(w, j); equal = (i.real == j.real && i.imag == j.imag); } else { goto Unimplemented; } if (equal == (op == Py_EQ)) res = Py_True; else res = Py_False; Py_INCREF(res); return res; Unimplemented: Py_RETURN_NOTIMPLEMENTED; } static PyObject * complex_int(PyObject *v) { PyErr_SetString(PyExc_TypeError, "can't convert complex to int"); return NULL; } static PyObject * complex_float(PyObject *v) { PyErr_SetString(PyExc_TypeError, "can't convert complex to float"); return NULL; } static PyObject * complex_conjugate(PyObject *self) { Py_complex c; c = ((PyComplexObject *)self)->cval; c.imag = -c.imag; return PyComplex_FromCComplex(c); } PyDoc_STRVAR(complex_conjugate_doc, "complex.conjugate() -> complex\n" "\n" "Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j."); static PyObject * complex_getnewargs(PyComplexObject *v) { Py_complex c = v->cval; return Py_BuildValue("(dd)", c.real, c.imag); } PyDoc_STRVAR(complex__format__doc, "complex.__format__() -> str\n" "\n" "Convert to a string according to format_spec."); static PyObject * complex__format__(PyObject* self, PyObject* args) { PyObject *format_spec; _PyUnicodeWriter writer; int ret; if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) return NULL; _PyUnicodeWriter_Init(&writer); ret = _PyComplex_FormatAdvancedWriter( &writer, self, format_spec, 0, PyUnicode_GET_LENGTH(format_spec)); if (ret == -1) { _PyUnicodeWriter_Dealloc(&writer); return NULL; } return _PyUnicodeWriter_Finish(&writer); } #if 0 static PyObject * complex_is_finite(PyObject *self) { Py_complex c; c = ((PyComplexObject *)self)->cval; return PyBool_FromLong((long)(Py_IS_FINITE(c.real) && Py_IS_FINITE(c.imag))); } PyDoc_STRVAR(complex_is_finite_doc, "complex.is_finite() -> bool\n" "\n" "Returns True if the real and the imaginary part is finite."); #endif static PyMethodDef complex_methods[] = { {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS, complex_conjugate_doc}, #if 0 {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS, complex_is_finite_doc}, #endif {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS}, {"__format__", (PyCFunction)complex__format__, METH_VARARGS, complex__format__doc}, {NULL, NULL} /* sentinel */ }; static PyMemberDef complex_members[] = { {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY, "the real part of a complex number"}, {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY, "the imaginary part of a complex number"}, {0}, }; static PyObject * complex_from_string_inner(const char *s, Py_ssize_t len, void *type) { double x=0.0, y=0.0, z; int got_bracket=0; const char *start; char *end; /* position on first nonblank */ start = s; while (Py_ISSPACE(*s)) s++; if (*s == '(') { /* Skip over possible bracket from repr(). */ got_bracket = 1; s++; while (Py_ISSPACE(*s)) s++; } /* a valid complex string usually takes one of the three forms: <float> - real part only <float>j - imaginary part only <float><signed-float>j - real and imaginary parts where <float> represents any numeric string that's accepted by the float constructor (including 'nan', 'inf', 'infinity', etc.), and <signed-float> is any string of the form <float> whose first character is '+' or '-'. For backwards compatibility, the extra forms <float><sign>j <sign>j j are also accepted, though support for these forms may be removed from a future version of Python. */ /* first look for forms starting with <float> */ z = PyOS_string_to_double(s, &end, NULL); if (z == -1.0 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_ValueError)) PyErr_Clear(); else return NULL; } if (end != s) { /* all 4 forms starting with <float> land here */ s = end; if (*s == '+' || *s == '-') { /* <float><signed-float>j | <float><sign>j */ x = z; y = PyOS_string_to_double(s, &end, NULL); if (y == -1.0 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_ValueError)) PyErr_Clear(); else return NULL; } if (end != s) /* <float><signed-float>j */ s = end; else { /* <float><sign>j */ y = *s == '+' ? 1.0 : -1.0; s++; } if (!(*s == 'j' || *s == 'J')) goto parse_error; s++; } else if (*s == 'j' || *s == 'J') { /* <float>j */ s++; y = z; } else /* <float> */ x = z; } else { /* not starting with <float>; must be <sign>j or j */ if (*s == '+' || *s == '-') { /* <sign>j */ y = *s == '+' ? 1.0 : -1.0; s++; } else /* j */ y = 1.0; if (!(*s == 'j' || *s == 'J')) goto parse_error; s++; } /* trailing whitespace and closing bracket */ while (Py_ISSPACE(*s)) s++; if (got_bracket) { /* if there was an opening parenthesis, then the corresponding closing parenthesis should be right here */ if (*s != ')') goto parse_error; s++; while (Py_ISSPACE(*s)) s++; } /* we should now be at the end of the string */ if (s-start != len) goto parse_error; return complex_subtype_from_doubles((PyTypeObject *)type, x, y); parse_error: PyErr_SetString(PyExc_ValueError, "complex() arg is a malformed string"); return NULL; } static PyObject * complex_subtype_from_string(PyTypeObject *type, PyObject *v) { const char *s; PyObject *s_buffer = NULL, *result = NULL; Py_ssize_t len; if (PyUnicode_Check(v)) { s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v); if (s_buffer == NULL) { return NULL; } s = PyUnicode_AsUTF8AndSize(s_buffer, &len); if (s == NULL) { goto exit; } } else { PyErr_Format(PyExc_TypeError, "complex() argument must be a string or a number, not '%.200s'", Py_TYPE(v)->tp_name); return NULL; } result = _Py_string_to_number_with_underscores(s, len, "complex", v, type, complex_from_string_inner); exit: Py_DECREF(s_buffer); return result; } static PyObject * complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *r, *i, *tmp; PyNumberMethods *nbr, *nbi = NULL; Py_complex cr, ci; int own_r = 0; int cr_is_complex = 0; int ci_is_complex = 0; static char *kwlist[] = {"real", "imag", 0}; r = Py_False; i = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist, &r, &i)) return NULL; /* Special-case for a single argument when type(arg) is complex. */ if (PyComplex_CheckExact(r) && i == NULL && type == &PyComplex_Type) { /* Note that we can't know whether it's safe to return a complex *subclass* instance as-is, hence the restriction to exact complexes here. If either the input or the output is a complex subclass, it will be handled below as a non-orthogonal vector. */ Py_INCREF(r); return r; } if (PyUnicode_Check(r)) { if (i != NULL) { PyErr_SetString(PyExc_TypeError, "complex() can't take second arg" " if first is a string"); return NULL; } return complex_subtype_from_string(type, r); } if (i != NULL && PyUnicode_Check(i)) { PyErr_SetString(PyExc_TypeError, "complex() second arg can't be a string"); return NULL; } tmp = try_complex_special_method(r); if (tmp) { r = tmp; own_r = 1; } else if (PyErr_Occurred()) { return NULL; } nbr = r->ob_type->tp_as_number; if (nbr == NULL || nbr->nb_float == NULL) { PyErr_Format(PyExc_TypeError, "complex() first argument must be a string or a number, " "not '%.200s'", Py_TYPE(r)->tp_name); if (own_r) { Py_DECREF(r); } return NULL; } if (i != NULL) { nbi = i->ob_type->tp_as_number; if (nbi == NULL || nbi->nb_float == NULL) { PyErr_Format(PyExc_TypeError, "complex() second argument must be a number, " "not '%.200s'", Py_TYPE(i)->tp_name); if (own_r) { Py_DECREF(r); } return NULL; } } /* If we get this far, then the "real" and "imag" parts should both be treated as numbers, and the constructor should return a complex number equal to (real + imag*1j). Note that we do NOT assume the input to already be in canonical form; the "real" and "imag" parts might themselves be complex numbers, which slightly complicates the code below. */ if (PyComplex_Check(r)) { /* Note that if r is of a complex subtype, we're only retaining its real & imag parts here, and the return value is (properly) of the builtin complex type. */ cr = ((PyComplexObject*)r)->cval; cr_is_complex = 1; if (own_r) { Py_DECREF(r); } } else { /* The "real" part really is entirely real, and contributes nothing in the imaginary direction. Just treat it as a double. */ tmp = PyNumber_Float(r); if (own_r) { /* r was a newly created complex number, rather than the original "real" argument. */ Py_DECREF(r); } if (tmp == NULL) return NULL; if (!PyFloat_Check(tmp)) { PyErr_SetString(PyExc_TypeError, "float(r) didn't return a float"); Py_DECREF(tmp); return NULL; } cr.real = PyFloat_AsDouble(tmp); cr.imag = 0.0; Py_DECREF(tmp); } if (i == NULL) { ci.real = cr.imag; } else if (PyComplex_Check(i)) { ci = ((PyComplexObject*)i)->cval; ci_is_complex = 1; } else { /* The "imag" part really is entirely imaginary, and contributes nothing in the real direction. Just treat it as a double. */ tmp = (*nbi->nb_float)(i); if (tmp == NULL) return NULL; ci.real = PyFloat_AsDouble(tmp); Py_DECREF(tmp); } /* If the input was in canonical form, then the "real" and "imag" parts are real numbers, so that ci.imag and cr.imag are zero. We need this correction in case they were not real numbers. */ if (ci_is_complex) { cr.real -= ci.imag; } if (cr_is_complex && i != NULL) { ci.real += cr.imag; } return complex_subtype_from_doubles(type, cr.real, ci.real); } PyDoc_STRVAR(complex_doc, "complex(real[, imag]) -> complex number\n" "\n" "Create a complex number from a real part and an optional imaginary part.\n" "This is equivalent to (real + imag*1j) where imag defaults to 0."); static PyNumberMethods complex_as_number = { (binaryfunc)complex_add, /* nb_add */ (binaryfunc)complex_sub, /* nb_subtract */ (binaryfunc)complex_mul, /* nb_multiply */ (binaryfunc)complex_remainder, /* nb_remainder */ (binaryfunc)complex_divmod, /* nb_divmod */ (ternaryfunc)complex_pow, /* nb_power */ (unaryfunc)complex_neg, /* nb_negative */ (unaryfunc)complex_pos, /* nb_positive */ (unaryfunc)complex_abs, /* nb_absolute */ (inquiry)complex_bool, /* nb_bool */ 0, /* nb_invert */ 0, /* nb_lshift */ 0, /* nb_rshift */ 0, /* nb_and */ 0, /* nb_xor */ 0, /* nb_or */ complex_int, /* nb_int */ 0, /* nb_reserved */ complex_float, /* nb_float */ 0, /* nb_inplace_add */ 0, /* nb_inplace_subtract */ 0, /* nb_inplace_multiply*/ 0, /* nb_inplace_remainder */ 0, /* nb_inplace_power */ 0, /* nb_inplace_lshift */ 0, /* nb_inplace_rshift */ 0, /* nb_inplace_and */ 0, /* nb_inplace_xor */ 0, /* nb_inplace_or */ (binaryfunc)complex_int_div, /* nb_floor_divide */ (binaryfunc)complex_div, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ }; PyTypeObject PyComplex_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "complex", sizeof(PyComplexObject), 0, complex_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)complex_repr, /* tp_repr */ &complex_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)complex_hash, /* tp_hash */ 0, /* tp_call */ (reprfunc)complex_repr, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ complex_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ complex_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ complex_methods, /* tp_methods */ complex_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ complex_new, /* tp_new */ PyObject_Del, /* tp_free */ };
33,944
1,160
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/floatobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/math.h" #include "libc/runtime/fenv.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dtoa.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyfpe.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymath.h" #include "third_party/python/Include/pystrtod.h" #include "third_party/python/Include/structseq.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ /* XXX There should be overflow checks here, but it's hard to check for any kind of float exception without losing portability. */ /* Special free list free_list is a singly-linked list of available PyFloatObjects, linked via abuse of their ob_type members. */ #ifndef PyFloat_MAXFREELIST #define PyFloat_MAXFREELIST 100 #endif static int numfree = 0; static PyFloatObject *free_list = NULL; double PyFloat_GetMax(void) { return DBL_MAX; } double PyFloat_GetMin(void) { return DBL_MIN; } static PyTypeObject FloatInfoType; PyDoc_STRVAR(floatinfo__doc__, "sys.float_info\n\ \n\ A structseq holding information about the float type. It contains low level\n\ information about the precision and internal representation. Please study\n\ your system's :file:`float.h` for more information."); static PyStructSequence_Field floatinfo_fields[] = { {"max", PyDoc_STR("DBL_MAX -- maximum representable finite float")}, {"max_exp", PyDoc_STR("DBL_MAX_EXP -- maximum int e such that radix**(e-1) is representable")}, {"max_10_exp", PyDoc_STR("DBL_MAX_10_EXP -- maximum int e such that 10**e is representable")}, {"min", PyDoc_STR("DBL_MIN -- Minimum positive normalized float")}, {"min_exp", PyDoc_STR("DBL_MIN_EXP -- minimum int e such that radix**(e-1) is a normalized float")}, {"min_10_exp", PyDoc_STR("DBL_MIN_10_EXP -- minimum int e such that 10**e is a normalized")}, {"dig", PyDoc_STR("DBL_DIG -- digits")}, {"mant_dig", PyDoc_STR("DBL_MANT_DIG -- mantissa digits")}, {"epsilon", PyDoc_STR("DBL_EPSILON -- Difference between 1 and the next representable float")}, {"radix", PyDoc_STR("FLT_RADIX -- radix of exponent")}, {"rounds", PyDoc_STR("FLT_ROUNDS -- rounding mode")}, {0} }; static PyStructSequence_Desc floatinfo_desc = { "sys.float_info", /* name */ floatinfo__doc__, /* doc */ floatinfo_fields, /* fields */ 11 }; PyObject * PyFloat_GetInfo(void) { PyObject* floatinfo; int pos = 0; floatinfo = PyStructSequence_New(&FloatInfoType); if (floatinfo == NULL) { return NULL; } #define SetIntFlag(flag) \ PyStructSequence_SET_ITEM(floatinfo, pos++, PyLong_FromLong(flag)) #define SetDblFlag(flag) \ PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag)) SetDblFlag(DBL_MAX); SetIntFlag(DBL_MAX_EXP); SetIntFlag(DBL_MAX_10_EXP); SetDblFlag(DBL_MIN); SetIntFlag(DBL_MIN_EXP); SetIntFlag(DBL_MIN_10_EXP); SetIntFlag(DBL_DIG); SetIntFlag(DBL_MANT_DIG); SetDblFlag(DBL_EPSILON); SetIntFlag(FLT_RADIX); SetIntFlag(FLT_ROUNDS); #undef SetIntFlag #undef SetDblFlag if (PyErr_Occurred()) { Py_CLEAR(floatinfo); return NULL; } return floatinfo; } PyObject * PyFloat_FromDouble(double fval) { PyFloatObject *op = free_list; if (op != NULL) { free_list = (PyFloatObject *) Py_TYPE(op); numfree--; } else { op = (PyFloatObject*) PyObject_MALLOC(sizeof(PyFloatObject)); if (!op) return PyErr_NoMemory(); } /* Inline PyObject_New */ (void)PyObject_INIT(op, &PyFloat_Type); op->ob_fval = fval; return (PyObject *) op; } static PyObject * float_from_string_inner(const char *s, Py_ssize_t len, void *obj) { double x; const char *end; const char *last = s + len; /* strip space */ while (s < last && Py_ISSPACE(*s)) { s++; } while (s < last - 1 && Py_ISSPACE(last[-1])) { last--; } /* We don't care about overflow or underflow. If the platform * supports them, infinities and signed zeroes (on underflow) are * fine. */ x = PyOS_string_to_double(s, (char **)&end, NULL); if (end != last) { PyErr_Format(PyExc_ValueError, "could not convert string to float: " "%R", obj); return NULL; } else if (x == -1.0 && PyErr_Occurred()) { return NULL; } else { return PyFloat_FromDouble(x); } } PyObject * PyFloat_FromString(PyObject *v) { const char *s; PyObject *s_buffer = NULL; Py_ssize_t len; Py_buffer view = {NULL, NULL}; PyObject *result = NULL; if (PyUnicode_Check(v)) { s_buffer = _PyUnicode_TransformDecimalAndSpaceToASCII(v); if (s_buffer == NULL) return NULL; s = PyUnicode_AsUTF8AndSize(s_buffer, &len); if (s == NULL) { Py_DECREF(s_buffer); return NULL; } } else if (PyBytes_Check(v)) { s = PyBytes_AS_STRING(v); len = PyBytes_GET_SIZE(v); } else if (PyByteArray_Check(v)) { s = PyByteArray_AS_STRING(v); len = PyByteArray_GET_SIZE(v); } else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) { s = (const char *)view.buf; len = view.len; /* Copy to NUL-terminated buffer. */ s_buffer = PyBytes_FromStringAndSize(s, len); if (s_buffer == NULL) { PyBuffer_Release(&view); return NULL; } s = PyBytes_AS_STRING(s_buffer); } else { PyErr_Format(PyExc_TypeError, "float() argument must be a string or a number, not '%.200s'", Py_TYPE(v)->tp_name); return NULL; } result = _Py_string_to_number_with_underscores(s, len, "float", v, v, float_from_string_inner); PyBuffer_Release(&view); Py_XDECREF(s_buffer); return result; } static void float_dealloc(PyFloatObject *op) { if (PyFloat_CheckExact(op)) { if (numfree >= PyFloat_MAXFREELIST) { PyObject_FREE(op); return; } numfree++; Py_TYPE(op) = (struct _typeobject *)free_list; free_list = op; } else Py_TYPE(op)->tp_free((PyObject *)op); } double PyFloat_AsDouble(PyObject *op) { PyNumberMethods *nb; PyObject *res; double val; if (op == NULL) { PyErr_BadArgument(); return -1; } if (PyFloat_Check(op)) { return PyFloat_AS_DOUBLE(op); } nb = Py_TYPE(op)->tp_as_number; if (nb == NULL || nb->nb_float == NULL) { PyErr_Format(PyExc_TypeError, "must be real number, not %.50s", op->ob_type->tp_name); return -1; } res = (*nb->nb_float) (op); if (res == NULL) { return -1; } if (!PyFloat_CheckExact(res)) { if (!PyFloat_Check(res)) { PyErr_Format(PyExc_TypeError, "%.50s.__float__ returned non-float (type %.50s)", op->ob_type->tp_name, res->ob_type->tp_name); Py_DECREF(res); return -1; } if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "%.50s.__float__ returned non-float (type %.50s). " "The ability to return an instance of a strict subclass of float " "is deprecated, and may be removed in a future version of Python.", op->ob_type->tp_name, res->ob_type->tp_name)) { Py_DECREF(res); return -1; } } val = PyFloat_AS_DOUBLE(res); Py_DECREF(res); return val; } /* Macro and helper that convert PyObject obj to a C double and store the value in dbl. If conversion to double raises an exception, obj is set to NULL, and the function invoking this macro returns NULL. If obj is not of float or int type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro. */ #define CONVERT_TO_DOUBLE(obj, dbl) \ if (PyFloat_Check(obj)) \ dbl = PyFloat_AS_DOUBLE(obj); \ else if (convert_to_double(&(obj), &(dbl)) < 0) \ return obj; /* Methods */ static int convert_to_double(PyObject **v, double *dbl) { PyObject *obj = *v; if (PyLong_Check(obj)) { *dbl = PyLong_AsDouble(obj); if (*dbl == -1.0 && PyErr_Occurred()) { *v = NULL; return -1; } } else { Py_INCREF(Py_NotImplemented); *v = Py_NotImplemented; return -1; } return 0; } static PyObject * float_repr(PyFloatObject *v) { PyObject *result; char *buf; buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), 'r', 0, Py_DTSF_ADD_DOT_0, NULL); if (!buf) return PyErr_NoMemory(); result = _PyUnicode_FromASCII(buf, strlen(buf)); PyMem_Free(buf); return result; } /* Comparison is pretty much a nightmare. When comparing float to float, * we do it as straightforwardly (and long-windedly) as conceivable, so * that, e.g., Python x == y delivers the same result as the platform * C x == y when x and/or y is a NaN. * When mixing float with an integer type, there's no good *uniform* approach. * Converting the double to an integer obviously doesn't work, since we * may lose info from fractional bits. Converting the integer to a double * also has two failure modes: (1) an int may trigger overflow (too * large to fit in the dynamic range of a C double); (2) even a C long may have * more bits than fit in a C double (e.g., on a 64-bit box long may have * 63 bits of precision, but a C double probably has only 53), and then * we can falsely claim equality when low-order integer bits are lost by * coercion to double. So this part is painful too. */ static PyObject* float_richcompare(PyObject *v, PyObject *w, int op) { double i, j; int r = 0; assert(PyFloat_Check(v)); i = PyFloat_AS_DOUBLE(v); /* Switch on the type of w. Set i and j to doubles to be compared, * and op to the richcomp to use. */ if (PyFloat_Check(w)) j = PyFloat_AS_DOUBLE(w); else if (!Py_IS_FINITE(i)) { if (PyLong_Check(w)) /* If i is an infinity, its magnitude exceeds any * finite integer, so it doesn't matter which int we * compare i with. If i is a NaN, similarly. */ j = 0.0; else goto Unimplemented; } else if (PyLong_Check(w)) { int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1; int wsign = _PyLong_Sign(w); size_t nbits; int exponent; if (vsign != wsign) { /* Magnitudes are irrelevant -- the signs alone * determine the outcome. */ i = (double)vsign; j = (double)wsign; goto Compare; } /* The signs are the same. */ /* Convert w to a double if it fits. In particular, 0 fits. */ nbits = _PyLong_NumBits(w); if (nbits == (size_t)-1 && PyErr_Occurred()) { /* This long is so large that size_t isn't big enough * to hold the # of bits. Replace with little doubles * that give the same outcome -- w is so large that * its magnitude must exceed the magnitude of any * finite float. */ PyErr_Clear(); i = (double)vsign; assert(wsign != 0); j = wsign * 2.0; goto Compare; } if (nbits <= 48) { j = PyLong_AsDouble(w); /* It's impossible that <= 48 bits overflowed. */ assert(j != -1.0 || ! PyErr_Occurred()); goto Compare; } assert(wsign != 0); /* else nbits was 0 */ assert(vsign != 0); /* if vsign were 0, then since wsign is * not 0, we would have taken the * vsign != wsign branch at the start */ /* We want to work with non-negative numbers. */ if (vsign < 0) { /* "Multiply both sides" by -1; this also swaps the * comparator. */ i = -i; op = _Py_SwappedOp[op]; } assert(i > 0.0); (void) frexp(i, &exponent); /* exponent is the # of bits in v before the radix point; * we know that nbits (the # of bits in w) > 48 at this point */ if (exponent < 0 || (size_t)exponent < nbits) { i = 1.0; j = 2.0; goto Compare; } if ((size_t)exponent > nbits) { i = 2.0; j = 1.0; goto Compare; } /* v and w have the same number of bits before the radix * point. Construct two ints that have the same comparison * outcome. */ { double fracpart; double intpart; PyObject *result = NULL; PyObject *one = NULL; PyObject *vv = NULL; PyObject *ww = w; if (wsign < 0) { ww = PyNumber_Negative(w); if (ww == NULL) goto Error; } else Py_INCREF(ww); fracpart = modf(i, &intpart); vv = PyLong_FromDouble(intpart); if (vv == NULL) goto Error; if (fracpart != 0.0) { /* Shift left, and or a 1 bit into vv * to represent the lost fraction. */ PyObject *temp; one = PyLong_FromLong(1); if (one == NULL) goto Error; temp = PyNumber_Lshift(ww, one); if (temp == NULL) goto Error; Py_DECREF(ww); ww = temp; temp = PyNumber_Lshift(vv, one); if (temp == NULL) goto Error; Py_DECREF(vv); vv = temp; temp = PyNumber_Or(vv, one); if (temp == NULL) goto Error; Py_DECREF(vv); vv = temp; } r = PyObject_RichCompareBool(vv, ww, op); if (r < 0) goto Error; result = PyBool_FromLong(r); Error: Py_XDECREF(vv); Py_XDECREF(ww); Py_XDECREF(one); return result; } } /* else if (PyLong_Check(w)) */ else /* w isn't float or int */ goto Unimplemented; Compare: PyFPE_START_PROTECT("richcompare", return NULL) switch (op) { case Py_EQ: r = i == j; break; case Py_NE: r = i != j; break; case Py_LE: r = i <= j; break; case Py_GE: r = i >= j; break; case Py_LT: r = i < j; break; case Py_GT: r = i > j; break; } PyFPE_END_PROTECT(r) return PyBool_FromLong(r); Unimplemented: Py_RETURN_NOTIMPLEMENTED; } static Py_hash_t float_hash(PyFloatObject *v) { return _Py_HashDouble(v->ob_fval); } static PyObject * float_add(PyObject *v, PyObject *w) { double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); PyFPE_START_PROTECT("add", return 0) a = a + b; PyFPE_END_PROTECT(a) return PyFloat_FromDouble(a); } static PyObject * float_sub(PyObject *v, PyObject *w) { double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); PyFPE_START_PROTECT("subtract", return 0) a = a - b; PyFPE_END_PROTECT(a) return PyFloat_FromDouble(a); } static PyObject * float_mul(PyObject *v, PyObject *w) { double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); PyFPE_START_PROTECT("multiply", return 0) a = a * b; PyFPE_END_PROTECT(a) return PyFloat_FromDouble(a); } static PyObject * float_div(PyObject *v, PyObject *w) { double a,b; CONVERT_TO_DOUBLE(v, a); CONVERT_TO_DOUBLE(w, b); if (b == 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "float division by zero"); return NULL; } PyFPE_START_PROTECT("divide", return 0) a = a / b; PyFPE_END_PROTECT(a) return PyFloat_FromDouble(a); } static PyObject * float_rem(PyObject *v, PyObject *w) { double vx, wx; double mod; CONVERT_TO_DOUBLE(v, vx); CONVERT_TO_DOUBLE(w, wx); if (wx == 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "float modulo"); return NULL; } PyFPE_START_PROTECT("modulo", return 0) mod = fmod(vx, wx); if (mod) { /* ensure the remainder has the same sign as the denominator */ if ((wx < 0) != (mod < 0)) { mod += wx; } } else { /* the remainder is zero, and in the presence of signed zeroes fmod returns different results across platforms; ensure it has the same sign as the denominator. */ mod = copysign(0.0, wx); } PyFPE_END_PROTECT(mod) return PyFloat_FromDouble(mod); } static PyObject * float_divmod(PyObject *v, PyObject *w) { double vx, wx; double div, mod, floordiv; CONVERT_TO_DOUBLE(v, vx); CONVERT_TO_DOUBLE(w, wx); if (wx == 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()"); return NULL; } PyFPE_START_PROTECT("divmod", return 0) mod = fmod(vx, wx); /* fmod is typically exact, so vx-mod is *mathematically* an exact multiple of wx. But this is fp arithmetic, and fp vx - mod is an approximation; the result is that div may not be an exact integral value after the division, although it will always be very close to one. */ div = (vx - mod) / wx; if (mod) { /* ensure the remainder has the same sign as the denominator */ if ((wx < 0) != (mod < 0)) { mod += wx; div -= 1.0; } } else { /* the remainder is zero, and in the presence of signed zeroes fmod returns different results across platforms; ensure it has the same sign as the denominator. */ mod = copysign(0.0, wx); } /* snap quotient to nearest integral value */ if (div) { floordiv = floor(div); if (div - floordiv > 0.5) floordiv += 1.0; } else { /* div is zero - get the same sign as the true quotient */ floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */ } PyFPE_END_PROTECT(floordiv) return Py_BuildValue("(dd)", floordiv, mod); } static PyObject * float_floor_div(PyObject *v, PyObject *w) { PyObject *t, *r; t = float_divmod(v, w); if (t == NULL || t == Py_NotImplemented) return t; assert(PyTuple_CheckExact(t)); r = PyTuple_GET_ITEM(t, 0); Py_INCREF(r); Py_DECREF(t); return r; } /* determine whether x is an odd integer or not; assumes that x is not an infinity or nan. */ #define DOUBLE_IS_ODD_INTEGER(x) (fmod(fabs(x), 2.0) == 1.0) static PyObject * float_pow(PyObject *v, PyObject *w, PyObject *z) { double iv, iw, ix; int negate_result = 0; if ((PyObject *)z != Py_None) { PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not " "allowed unless all arguments are integers"); return NULL; } CONVERT_TO_DOUBLE(v, iv); CONVERT_TO_DOUBLE(w, iw); /* Sort out special cases here instead of relying on pow() */ if (iw == 0) { /* v**0 is 1, even 0**0 */ return PyFloat_FromDouble(1.0); } if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */ return PyFloat_FromDouble(iv); } if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */ return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw); } if (Py_IS_INFINITY(iw)) { /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if * abs(v) > 1 (including case where v infinite) * * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if * abs(v) > 1 (including case where v infinite) */ iv = fabs(iv); if (iv == 1.0) return PyFloat_FromDouble(1.0); else if ((iw > 0.0) == (iv > 1.0)) return PyFloat_FromDouble(fabs(iw)); /* return inf */ else return PyFloat_FromDouble(0.0); } if (Py_IS_INFINITY(iv)) { /* (+-inf)**w is: inf for w positive, 0 for w negative; in * both cases, we need to add the appropriate sign if w is * an odd integer. */ int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); if (iw > 0.0) return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv)); else return PyFloat_FromDouble(iw_is_odd ? copysign(0.0, iv) : 0.0); } if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero (already dealt with above), and an error if w is negative. */ int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw); if (iw < 0.0) { PyErr_SetString(PyExc_ZeroDivisionError, "0.0 cannot be raised to a " "negative power"); return NULL; } /* use correct sign if iw is odd */ return PyFloat_FromDouble(iw_is_odd ? iv : 0.0); } if (iv < 0.0) { /* Whether this is an error is a mess, and bumps into libm * bugs so we have to figure it out ourselves. */ if (iw != floor(iw)) { /* Negative numbers raised to fractional powers * become complex. */ return PyComplex_Type.tp_as_number->nb_power(v, w, z); } /* iw is an exact integer, albeit perhaps a very large * one. Replace iv by its absolute value and remember * to negate the pow result if iw is odd. */ iv = -iv; negate_result = DOUBLE_IS_ODD_INTEGER(iw); } if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */ /* (-1) ** large_integer also ends up here. Here's an * extract from the comments for the previous * implementation explaining why this special case is * necessary: * * -1 raised to an exact integer should never be exceptional. * Alas, some libms (chiefly glibc as of early 2003) return * NaN and set EDOM on pow(-1, large_int) if the int doesn't * happen to be representable in a *C* integer. That's a * bug. */ return PyFloat_FromDouble(negate_result ? -1.0 : 1.0); } /* Now iv and iw are finite, iw is nonzero, and iv is * positive and not equal to 1.0. We finally allow * the platform pow to step in and do the rest. */ errno = 0; PyFPE_START_PROTECT("pow", return NULL) ix = pow(iv, iw); PyFPE_END_PROTECT(ix) Py_ADJUST_ERANGE1(ix); if (negate_result) ix = -ix; if (errno != 0) { /* We don't expect any errno value other than ERANGE, but * the range of libm bugs appears unbounded. */ PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : PyExc_ValueError); return NULL; } return PyFloat_FromDouble(ix); } #undef DOUBLE_IS_ODD_INTEGER static PyObject * float_neg(PyFloatObject *v) { return PyFloat_FromDouble(-v->ob_fval); } static PyObject * float_abs(PyFloatObject *v) { return PyFloat_FromDouble(fabs(v->ob_fval)); } static int float_bool(PyFloatObject *v) { return v->ob_fval != 0.0; } static PyObject * float_is_integer(PyObject *v) { double x = PyFloat_AsDouble(v); PyObject *o; if (x == -1.0 && PyErr_Occurred()) return NULL; if (!Py_IS_FINITE(x)) Py_RETURN_FALSE; errno = 0; PyFPE_START_PROTECT("is_integer", return NULL) o = (floor(x) == x) ? Py_True : Py_False; PyFPE_END_PROTECT(x) if (errno != 0) { PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError : PyExc_ValueError); return NULL; } Py_INCREF(o); return o; } #if 0 static PyObject * float_is_inf(PyObject *v) { double x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) return NULL; return PyBool_FromLong((long)Py_IS_INFINITY(x)); } static PyObject * float_is_nan(PyObject *v) { double x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) return NULL; return PyBool_FromLong((long)Py_IS_NAN(x)); } static PyObject * float_is_finite(PyObject *v) { double x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) return NULL; return PyBool_FromLong((long)Py_IS_FINITE(x)); } #endif static PyObject * float_trunc(PyObject *v) { double x = PyFloat_AsDouble(v); double wholepart; /* integral portion of x, rounded toward 0 */ (void)modf(x, &wholepart); /* Try to get out cheap if this fits in a Python int. The attempt * to cast to long must be protected, as C doesn't define what * happens if the double is too big to fit in a long. Some rare * systems raise an exception then (RISCOS was mentioned as one, * and someone using a non-default option on Sun also bumped into * that). Note that checking for >= and <= LONG_{MIN,MAX} would * still be vulnerable: if a long has more bits of precision than * a double, casting MIN/MAX to double may yield an approximation, * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would * yield true from the C expression wholepart<=LONG_MAX, despite * that wholepart is actually greater than LONG_MAX. */ if (LONG_MIN < wholepart && wholepart < LONG_MAX) { const long aslong = (long)wholepart; return PyLong_FromLong(aslong); } return PyLong_FromDouble(wholepart); } /* double_round: rounds a finite double to the closest multiple of 10**-ndigits; here ndigits is within reasonable bounds (typically, -308 <= ndigits <= 323). Returns a Python float, or sets a Python error and returns NULL on failure (OverflowError and memory errors are possible). */ #ifndef PY_NO_SHORT_FLOAT_REPR /* version of double_round that uses the correctly-rounded string<->double conversions from Python/dtoa.c */ static PyObject * double_round(double x, int ndigits) { double rounded; Py_ssize_t buflen, mybuflen=100; char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf; int decpt, sign; PyObject *result = NULL; _Py_SET_53BIT_PRECISION_HEADER; /* round to a decimal string */ _Py_SET_53BIT_PRECISION_START; buf = _Py_dg_dtoa(x, 3, ndigits, &decpt, &sign, &buf_end); _Py_SET_53BIT_PRECISION_END; if (buf == NULL) { PyErr_NoMemory(); return NULL; } /* Get new buffer if shortbuf is too small. Space needed <= buf_end - buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */ buflen = buf_end - buf; if (buflen + 8 > mybuflen) { mybuflen = buflen+8; mybuf = (char *)PyMem_Malloc(mybuflen); if (mybuf == NULL) { PyErr_NoMemory(); goto exit; } } /* copy buf to mybuf, adding exponent, sign and leading 0 */ PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""), buf, decpt - (int)buflen); /* and convert the resulting string back to a double */ errno = 0; _Py_SET_53BIT_PRECISION_START; rounded = _Py_dg_strtod(mybuf, NULL); _Py_SET_53BIT_PRECISION_END; if (errno == ERANGE && fabs(rounded) >= 1.) PyErr_SetString(PyExc_OverflowError, "rounded value too large to represent"); else result = PyFloat_FromDouble(rounded); /* done computing value; now clean up */ if (mybuf != shortbuf) PyMem_Free(mybuf); exit: _Py_dg_freedtoa(buf); return result; } #else /* PY_NO_SHORT_FLOAT_REPR */ /* fallback version, to be used when correctly rounded binary<->decimal conversions aren't available */ static PyObject * double_round(double x, int ndigits) { double pow1, pow2, y, z; if (ndigits >= 0) { if (ndigits > 22) { /* pow1 and pow2 are each safe from overflow, but pow1*pow2 ~= pow(10.0, ndigits) might overflow */ pow1 = pow(10.0, (double)(ndigits-22)); pow2 = 1e22; } else { pow1 = pow(10.0, (double)ndigits); pow2 = 1.0; } y = (x*pow1)*pow2; /* if y overflows, then rounded value is exactly x */ if (!Py_IS_FINITE(y)) return PyFloat_FromDouble(x); } else { pow1 = pow(10.0, (double)-ndigits); pow2 = 1.0; /* unused; silences a gcc compiler warning */ y = x / pow1; } z = round(y); if (fabs(y-z) == 0.5) /* halfway between two integers; use round-half-even */ z = 2.0*round(y/2.0); if (ndigits >= 0) z = (z / pow2) / pow1; else z *= pow1; /* if computation resulted in overflow, raise OverflowError */ if (!Py_IS_FINITE(z)) { PyErr_SetString(PyExc_OverflowError, "overflow occurred during round"); return NULL; } return PyFloat_FromDouble(z); } #endif /* PY_NO_SHORT_FLOAT_REPR */ /* round a Python float v to the closest multiple of 10**-ndigits */ static PyObject * float_round(PyObject *v, PyObject **args, Py_ssize_t nargs) { double x, rounded; PyObject *o_ndigits = NULL; Py_ssize_t ndigits; x = PyFloat_AsDouble(v); if (!_PyArg_UnpackStack(args, nargs, "__round__", 0, 1, &o_ndigits)) return NULL; if (o_ndigits == NULL || o_ndigits == Py_None) { /* single-argument round or with None ndigits: * round to nearest integer */ rounded = round(x); if (fabs(x-rounded) == 0.5) /* halfway case: round to even */ rounded = 2.0*round(x/2.0); return PyLong_FromDouble(rounded); } /* interpret second argument as a Py_ssize_t; clips on overflow */ ndigits = PyNumber_AsSsize_t(o_ndigits, NULL); if (ndigits == -1 && PyErr_Occurred()) return NULL; /* nans and infinities round to themselves */ if (!Py_IS_FINITE(x)) return PyFloat_FromDouble(x); /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x always rounds to itself. For ndigits < NDIGITS_MIN, x always rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */ #define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103)) #define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103)) if (ndigits > NDIGITS_MAX) /* return x */ return PyFloat_FromDouble(x); else if (ndigits < NDIGITS_MIN) /* return 0.0, but with sign of x */ return PyFloat_FromDouble(0.0*x); else /* finite x, and ndigits is not unreasonably large */ return double_round(x, (int)ndigits); #undef NDIGITS_MAX #undef NDIGITS_MIN } static PyObject * float_float(PyObject *v) { if (PyFloat_CheckExact(v)) Py_INCREF(v); else v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval); return v; } /* turn ASCII hex characters into integer values and vice versa */ static char char_from_hex(int x) { assert(0 <= x && x < 16); return Py_hexdigits[x]; } static int hex_from_char(char c) { int x; switch(c) { case '0': x = 0; break; case '1': x = 1; break; case '2': x = 2; break; case '3': x = 3; break; case '4': x = 4; break; case '5': x = 5; break; case '6': x = 6; break; case '7': x = 7; break; case '8': x = 8; break; case '9': x = 9; break; case 'a': case 'A': x = 10; break; case 'b': case 'B': x = 11; break; case 'c': case 'C': x = 12; break; case 'd': case 'D': x = 13; break; case 'e': case 'E': x = 14; break; case 'f': case 'F': x = 15; break; default: x = -1; break; } return x; } /* convert a float to a hexadecimal string */ /* TOHEX_NBITS is DBL_MANT_DIG rounded up to the next integer of the form 4k+1. */ #define TOHEX_NBITS DBL_MANT_DIG + 3 - (DBL_MANT_DIG+2)%4 static PyObject * float_hex(PyObject *v) { double x, m; int e, shift, i, si, esign; /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the trailing NUL byte. */ char s[(TOHEX_NBITS-1)/4+3]; CONVERT_TO_DOUBLE(v, x); if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) return float_repr((PyFloatObject *)v); if (x == 0.0) { if (copysign(1.0, x) == -1.0) return PyUnicode_FromString("-0x0.0p+0"); else return PyUnicode_FromString("0x0.0p+0"); } m = frexp(fabs(x), &e); shift = 1 - Py_MAX(DBL_MIN_EXP - e, 0); m = ldexp(m, shift); e -= shift; si = 0; s[si] = char_from_hex((int)m); si++; m -= (int)m; s[si] = '.'; si++; for (i=0; i < (TOHEX_NBITS-1)/4; i++) { m *= 16.0; s[si] = char_from_hex((int)m); si++; m -= (int)m; } s[si] = '\0'; if (e < 0) { esign = (int)'-'; e = -e; } else esign = (int)'+'; if (x < 0.0) return PyUnicode_FromFormat("-0x%sp%c%d", s, esign, e); else return PyUnicode_FromFormat("0x%sp%c%d", s, esign, e); } PyDoc_STRVAR(float_hex_doc, "float.hex() -> string\n\ \n\ Return a hexadecimal representation of a floating-point number.\n\ >>> (-0.1).hex()\n\ '-0x1.999999999999ap-4'\n\ >>> 3.14159.hex()\n\ '0x1.921f9f01b866ep+1'"); /* Convert a hexadecimal string to a float. */ static PyObject * float_fromhex(PyObject *cls, PyObject *arg) { PyObject *result; double x; long exp, top_exp, lsb, key_digit; char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end; int half_eps, digit, round_up, negate=0; Py_ssize_t length, ndigits, fdigits, i; /* * For the sake of simplicity and correctness, we impose an artificial * limit on ndigits, the total number of hex digits in the coefficient * The limit is chosen to ensure that, writing exp for the exponent, * * (1) if exp > LONG_MAX/2 then the value of the hex string is * guaranteed to overflow (provided it's nonzero) * * (2) if exp < LONG_MIN/2 then the value of the hex string is * guaranteed to underflow to 0. * * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of * overflow in the calculation of exp and top_exp below. * * More specifically, ndigits is assumed to satisfy the following * inequalities: * * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2 * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP * * If either of these inequalities is not satisfied, a ValueError is * raised. Otherwise, write x for the value of the hex string, and * assume x is nonzero. Then * * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits). * * Now if exp > LONG_MAX/2 then: * * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP) * = DBL_MAX_EXP * * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C * double, so overflows. If exp < LONG_MIN/2, then * * exp + 4*ndigits <= LONG_MIN/2 - 1 + ( * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2) * = DBL_MIN_EXP - DBL_MANT_DIG - 1 * * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0 * when converted to a C double. * * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both * exp+4*ndigits and exp-4*ndigits are within the range of a long. */ s = PyUnicode_AsUTF8AndSize(arg, &length); if (s == NULL) return NULL; s_end = s + length; /******************** * Parse the string * ********************/ /* leading whitespace */ while (Py_ISSPACE(*s)) s++; /* infinities and nans */ x = _Py_parse_inf_or_nan(s, &coeff_end); if (coeff_end != s) { s = coeff_end; goto finished; } /* optional sign */ if (*s == '-') { s++; negate = 1; } else if (*s == '+') s++; /* [0x] */ s_store = s; if (*s == '0') { s++; if (*s == 'x' || *s == 'X') s++; else s = s_store; } /* coefficient: <integer> [. <fraction>] */ coeff_start = s; while (hex_from_char(*s) >= 0) s++; s_store = s; if (*s == '.') { s++; while (hex_from_char(*s) >= 0) s++; coeff_end = s-1; } else coeff_end = s; /* ndigits = total # of hex digits; fdigits = # after point */ ndigits = coeff_end - coeff_start; fdigits = coeff_end - s_store; if (ndigits == 0) goto parse_error; if (ndigits > Py_MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2, LONG_MAX/2 + 1 - DBL_MAX_EXP)/4) goto insane_length_error; /* [p <exponent>] */ if (*s == 'p' || *s == 'P') { s++; exp_start = s; if (*s == '-' || *s == '+') s++; if (!('0' <= *s && *s <= '9')) goto parse_error; s++; while ('0' <= *s && *s <= '9') s++; exp = strtol(exp_start, NULL, 10); } else exp = 0; /* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */ #define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \ coeff_end-(j) : \ coeff_end-1-(j))) /******************************************* * Compute rounded value of the hex string * *******************************************/ /* Discard leading zeros, and catch extreme overflow and underflow */ while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0) ndigits--; if (ndigits == 0 || exp < LONG_MIN/2) { x = 0.0; goto finished; } if (exp > LONG_MAX/2) goto overflow_error; /* Adjust exponent for fractional part. */ exp = exp - 4*((long)fdigits); /* top_exp = 1 more than exponent of most sig. bit of coefficient */ top_exp = exp + 4*((long)ndigits - 1); for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2) top_exp++; /* catch almost all nonextreme cases of overflow and underflow here */ if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) { x = 0.0; goto finished; } if (top_exp > DBL_MAX_EXP) goto overflow_error; /* lsb = exponent of least significant bit of the *rounded* value. This is top_exp - DBL_MANT_DIG unless result is subnormal. */ lsb = Py_MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG; x = 0.0; if (exp >= lsb) { /* no rounding required */ for (i = ndigits-1; i >= 0; i--) x = 16.0*x + HEX_DIGIT(i); x = ldexp(x, (int)(exp)); goto finished; } /* rounding required. key_digit is the index of the hex digit containing the first bit to be rounded away. */ half_eps = 1 << (int)((lsb - exp - 1) % 4); key_digit = (lsb - exp - 1) / 4; for (i = ndigits-1; i > key_digit; i--) x = 16.0*x + HEX_DIGIT(i); digit = HEX_DIGIT(key_digit); x = 16.0*x + (double)(digit & (16-2*half_eps)); /* round-half-even: round up if bit lsb-1 is 1 and at least one of bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */ if ((digit & half_eps) != 0) { round_up = 0; if ((digit & (3*half_eps-1)) != 0 || (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0)) round_up = 1; else for (i = key_digit-1; i >= 0; i--) if (HEX_DIGIT(i) != 0) { round_up = 1; break; } if (round_up) { x += 2*half_eps; if (top_exp == DBL_MAX_EXP && x == ldexp((double)(2*half_eps), DBL_MANT_DIG)) /* overflow corner case: pre-rounded value < 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */ goto overflow_error; } } x = ldexp(x, (int)(exp+4*key_digit)); finished: /* optional trailing whitespace leading to the end of the string */ while (Py_ISSPACE(*s)) s++; if (s != s_end) goto parse_error; result = PyFloat_FromDouble(negate ? -x : x); if (cls != (PyObject *)&PyFloat_Type && result != NULL) { Py_SETREF(result, PyObject_CallFunctionObjArgs(cls, result, NULL)); } return result; overflow_error: PyErr_SetString(PyExc_OverflowError, "hexadecimal value too large to represent as a float"); return NULL; parse_error: PyErr_SetString(PyExc_ValueError, "invalid hexadecimal floating-point string"); return NULL; insane_length_error: PyErr_SetString(PyExc_ValueError, "hexadecimal string too long to convert"); return NULL; } PyDoc_STRVAR(float_fromhex_doc, "float.fromhex(string) -> float\n\ \n\ Create a floating-point number from a hexadecimal string.\n\ >>> float.fromhex('0x1.ffffp10')\n\ 2047.984375\n\ >>> float.fromhex('-0x1p-1074')\n\ -5e-324"); static PyObject * float_as_integer_ratio(PyObject *v, PyObject *unused) { double self; double float_part; int exponent; int i; PyObject *py_exponent = NULL; PyObject *numerator = NULL; PyObject *denominator = NULL; PyObject *result_pair = NULL; PyNumberMethods *long_methods = PyLong_Type.tp_as_number; CONVERT_TO_DOUBLE(v, self); if (Py_IS_INFINITY(self)) { PyErr_SetString(PyExc_OverflowError, "cannot convert Infinity to integer ratio"); return NULL; } if (Py_IS_NAN(self)) { PyErr_SetString(PyExc_ValueError, "cannot convert NaN to integer ratio"); return NULL; } PyFPE_START_PROTECT("as_integer_ratio", goto error); float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */ PyFPE_END_PROTECT(float_part); for (i=0; i<300 && float_part != floor(float_part) ; i++) { float_part *= 2.0; exponent--; } /* self == float_part * 2**exponent exactly and float_part is integral. If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part to be truncated by PyLong_FromDouble(). */ numerator = PyLong_FromDouble(float_part); if (numerator == NULL) goto error; denominator = PyLong_FromLong(1); if (denominator == NULL) goto error; py_exponent = PyLong_FromLong(Py_ABS(exponent)); if (py_exponent == NULL) goto error; /* fold in 2**exponent */ if (exponent > 0) { Py_SETREF(numerator, long_methods->nb_lshift(numerator, py_exponent)); if (numerator == NULL) goto error; } else { Py_SETREF(denominator, long_methods->nb_lshift(denominator, py_exponent)); if (denominator == NULL) goto error; } result_pair = PyTuple_Pack(2, numerator, denominator); error: Py_XDECREF(py_exponent); Py_XDECREF(denominator); Py_XDECREF(numerator); return result_pair; } PyDoc_STRVAR(float_as_integer_ratio_doc, "float.as_integer_ratio() -> (int, int)\n" "\n" "Return a pair of integers, whose ratio is exactly equal to the original\n" "float and with a positive denominator.\n" "Raise OverflowError on infinities and a ValueError on NaNs.\n" "\n" ">>> (10.0).as_integer_ratio()\n" "(10, 1)\n" ">>> (0.0).as_integer_ratio()\n" "(0, 1)\n" ">>> (-.25).as_integer_ratio()\n" "(-1, 4)"); static PyObject * float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject * float_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *x = Py_False; /* Integer zero */ static char *kwlist[] = {"x", 0}; if (type != &PyFloat_Type) return float_subtype_new(type, args, kwds); /* Wimp out */ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x)) return NULL; /* If it's a string, but not a string subclass, use PyFloat_FromString. */ if (PyUnicode_CheckExact(x)) return PyFloat_FromString(x); return PyNumber_Float(x); } /* Wimpy, slow approach to tp_new calls for subtypes of float: first create a regular float from whatever arguments we got, then allocate a subtype instance and initialize its ob_fval from the regular float. The regular float is then thrown away. */ static PyObject * float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *tmp, *newobj; assert(PyType_IsSubtype(type, &PyFloat_Type)); tmp = float_new(&PyFloat_Type, args, kwds); if (tmp == NULL) return NULL; assert(PyFloat_Check(tmp)); newobj = type->tp_alloc(type, 0); if (newobj == NULL) { Py_DECREF(tmp); return NULL; } ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval; Py_DECREF(tmp); return newobj; } static PyObject * float_getnewargs(PyFloatObject *v) { return Py_BuildValue("(d)", v->ob_fval); } /* this is for the benefit of the pack/unpack routines below */ typedef enum { unknown_format, ieee_big_endian_format, ieee_little_endian_format } float_format_type; static float_format_type double_format, float_format; static float_format_type detected_double_format, detected_float_format; static PyObject * float_getformat(PyTypeObject *v, PyObject* arg) { char* s; float_format_type r; if (!PyUnicode_Check(arg)) { PyErr_Format(PyExc_TypeError, "__getformat__() argument must be string, not %.500s", Py_TYPE(arg)->tp_name); return NULL; } s = PyUnicode_AsUTF8(arg); if (s == NULL) return NULL; if (strcmp(s, "double") == 0) { r = double_format; } else if (strcmp(s, "float") == 0) { r = float_format; } else { PyErr_SetString(PyExc_ValueError, "__getformat__() argument 1 must be " "'double' or 'float'"); return NULL; } switch (r) { case unknown_format: return PyUnicode_FromString("unknown"); case ieee_little_endian_format: return PyUnicode_FromString("IEEE, little-endian"); case ieee_big_endian_format: return PyUnicode_FromString("IEEE, big-endian"); default: Py_FatalError("insane float_format or double_format"); return NULL; } } PyDoc_STRVAR(float_getformat_doc, "float.__getformat__(typestr) -> string\n" "\n" "You probably don't want to use this function. It exists mainly to be\n" "used in Python's test suite.\n" "\n" "typestr must be 'double' or 'float'. This function returns whichever of\n" "'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n" "format of floating point numbers used by the C type named by typestr."); static PyObject * float_setformat(PyTypeObject *v, PyObject* args) { char* typestr; char* format; float_format_type f; float_format_type detected; float_format_type *p; if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format)) return NULL; if (strcmp(typestr, "double") == 0) { p = &double_format; detected = detected_double_format; } else if (strcmp(typestr, "float") == 0) { p = &float_format; detected = detected_float_format; } else { PyErr_SetString(PyExc_ValueError, "__setformat__() argument 1 must " "be 'double' or 'float'"); return NULL; } if (strcmp(format, "unknown") == 0) { f = unknown_format; } else if (strcmp(format, "IEEE, little-endian") == 0) { f = ieee_little_endian_format; } else if (strcmp(format, "IEEE, big-endian") == 0) { f = ieee_big_endian_format; } else { PyErr_SetString(PyExc_ValueError, "__setformat__() argument 2 must be " "'unknown', 'IEEE, little-endian' or " "'IEEE, big-endian'"); return NULL; } if (f != unknown_format && f != detected) { PyErr_Format(PyExc_ValueError, "can only set %s format to 'unknown' or the " "detected platform value", typestr); return NULL; } *p = f; Py_RETURN_NONE; } PyDoc_STRVAR(float_setformat_doc, "float.__setformat__(typestr, fmt) -> None\n" "\n" "You probably don't want to use this function. It exists mainly to be\n" "used in Python's test suite.\n" "\n" "typestr must be 'double' or 'float'. fmt must be one of 'unknown',\n" "'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n" "one of the latter two if it appears to match the underlying C reality.\n" "\n" "Override the automatic determination of C-level floating point type.\n" "This affects how floats are converted to and from binary strings."); static PyObject * float_getzero(PyObject *v, void *closure) { return PyFloat_FromDouble(0.0); } static PyObject * float__format__(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *format_spec; _PyUnicodeWriter writer; int ret; if (!_PyArg_ParseStack(args, nargs, "U:__format__", &format_spec)) return NULL; _PyUnicodeWriter_Init(&writer); ret = _PyFloat_FormatAdvancedWriter( &writer, self, format_spec, 0, PyUnicode_GET_LENGTH(format_spec)); if (ret == -1) { _PyUnicodeWriter_Dealloc(&writer); return NULL; } return _PyUnicodeWriter_Finish(&writer); } PyDoc_STRVAR(float__format__doc, "float.__format__(format_spec) -> string\n" "\n" "Formats the float according to format_spec."); static PyMethodDef float_methods[] = { {"conjugate", (PyCFunction)float_float, METH_NOARGS, "Return self, the complex conjugate of any float."}, {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS, "Return the Integral closest to x between 0 and x."}, {"__round__", (PyCFunction)float_round, METH_FASTCALL, "Return the Integral closest to x, rounding half toward even.\n" "When an argument is passed, work like built-in round(x, ndigits)."}, {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS, float_as_integer_ratio_doc}, {"fromhex", (PyCFunction)float_fromhex, METH_O|METH_CLASS, float_fromhex_doc}, {"hex", (PyCFunction)float_hex, METH_NOARGS, float_hex_doc}, {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS, "Return True if the float is an integer."}, #if 0 {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS, "Return True if the float is positive or negative infinite."}, {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS, "Return True if the float is finite, neither infinite nor NaN."}, {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS, "Return True if the float is not a number (NaN)."}, #endif {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS}, {"__getformat__", (PyCFunction)float_getformat, METH_O|METH_CLASS, float_getformat_doc}, {"__setformat__", (PyCFunction)float_setformat, METH_VARARGS|METH_CLASS, float_setformat_doc}, {"__format__", (PyCFunction)float__format__, METH_FASTCALL, float__format__doc}, {NULL, NULL} /* sentinel */ }; static PyGetSetDef float_getset[] = { {"real", (getter)float_float, (setter)NULL, "the real part of a complex number", NULL}, {"imag", (getter)float_getzero, (setter)NULL, "the imaginary part of a complex number", NULL}, {NULL} /* Sentinel */ }; PyDoc_STRVAR(float_doc, "float(x) -> floating point number\n\ \n\ Convert a string or number to a floating point number, if possible."); static PyNumberMethods float_as_number = { float_add, /*nb_add*/ float_sub, /*nb_subtract*/ float_mul, /*nb_multiply*/ float_rem, /*nb_remainder*/ float_divmod, /*nb_divmod*/ float_pow, /*nb_power*/ (unaryfunc)float_neg, /*nb_negative*/ (unaryfunc)float_float, /*nb_positive*/ (unaryfunc)float_abs, /*nb_absolute*/ (inquiry)float_bool, /*nb_bool*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ float_trunc, /*nb_int*/ 0, /*nb_reserved*/ float_float, /*nb_float*/ 0, /* nb_inplace_add */ 0, /* nb_inplace_subtract */ 0, /* nb_inplace_multiply */ 0, /* nb_inplace_remainder */ 0, /* nb_inplace_power */ 0, /* nb_inplace_lshift */ 0, /* nb_inplace_rshift */ 0, /* nb_inplace_and */ 0, /* nb_inplace_xor */ 0, /* nb_inplace_or */ float_floor_div, /* nb_floor_divide */ float_div, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ }; PyTypeObject PyFloat_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "float", sizeof(PyFloatObject), 0, (destructor)float_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)float_repr, /* tp_repr */ &float_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)float_hash, /* tp_hash */ 0, /* tp_call */ (reprfunc)float_repr, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ float_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ float_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ float_methods, /* tp_methods */ 0, /* tp_members */ float_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ float_new, /* tp_new */ }; int _PyFloat_Init(void) { /* We attempt to determine if this machine is using IEEE floating point formats by peering at the bits of some carefully chosen values. If it looks like we are on an IEEE platform, the float packing/unpacking routines can just copy bits, if not they resort to arithmetic & shifts and masks. The shifts & masks approach works on all finite values, but what happens to infinities, NaNs and signed zeroes on packing is an accident, and attempting to unpack a NaN or an infinity will raise an exception. Note that if we're on some whacked-out platform which uses IEEE formats but isn't strictly little-endian or big- endian, we will fall back to the portable shifts & masks method. */ #if SIZEOF_DOUBLE == 8 { double x = 9006104071832581.0; if (bcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0) detected_double_format = ieee_big_endian_format; else if (bcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0) detected_double_format = ieee_little_endian_format; else detected_double_format = unknown_format; } #else detected_double_format = unknown_format; #endif #if SIZEOF_FLOAT == 4 { float y = 16711938.0; if (bcmp(&y, "\x4b\x7f\x01\x02", 4) == 0) detected_float_format = ieee_big_endian_format; else if (bcmp(&y, "\x02\x01\x7f\x4b", 4) == 0) detected_float_format = ieee_little_endian_format; else detected_float_format = unknown_format; } #else detected_float_format = unknown_format; #endif double_format = detected_double_format; float_format = detected_float_format; /* Init float info */ if (FloatInfoType.tp_name == NULL) { if (PyStructSequence_InitType2(&FloatInfoType, &floatinfo_desc) < 0) return 0; } return 1; } int PyFloat_ClearFreeList(void) { PyFloatObject *f = free_list, *next; int i = numfree; while (f) { next = (PyFloatObject*) Py_TYPE(f); PyObject_FREE(f); f = next; } free_list = NULL; numfree = 0; return i; } void PyFloat_Fini(void) { (void)PyFloat_ClearFreeList(); } /* Print summary info about the state of the optimized allocator */ void _PyFloat_DebugMallocStats(FILE *out) { _PyDebugAllocatorStats(out, "free PyFloatObject", numfree, sizeof(PyFloatObject)); } /*---------------------------------------------------------------------------- * _PyFloat_{Pack,Unpack}{2,4,8}. See floatobject.h. * To match the NPY_HALF_ROUND_TIES_TO_EVEN behavior in: * https://github.com/numpy/numpy/blob/master/numpy/core/src/npymath/halffloat.c * We use: * bits = (unsigned short)f; Note the truncation * if ((f - bits > 0.5) || (f - bits == 0.5 && bits % 2)) { * bits++; * } */ int _PyFloat_Pack2(double x, unsigned char *p, int le) { unsigned char sign; int e; double f; unsigned short bits; int incr = 1; if (x == 0.0) { sign = (copysign(1.0, x) == -1.0); e = 0; bits = 0; } else if (Py_IS_INFINITY(x)) { sign = (x < 0.0); e = 0x1f; bits = 0; } else if (Py_IS_NAN(x)) { /* There are 2046 distinct half-precision NaNs (1022 signaling and 1024 quiet), but there are only two quiet NaNs that don't arise by quieting a signaling NaN; we get those by setting the topmost bit of the fraction field and clearing all other fraction bits. We choose the one with the appropriate sign. */ sign = (copysign(1.0, x) == -1.0); e = 0x1f; bits = 512; } else { sign = (x < 0.0); if (sign) { x = -x; } f = frexp(x, &e); if (f < 0.5 || f >= 1.0) { PyErr_SetString(PyExc_SystemError, "frexp() result out of range"); return -1; } /* Normalize f to be in the range [1.0, 2.0) */ f *= 2.0; e--; if (e >= 16) { goto Overflow; } else if (e < -25) { /* |x| < 2**-25. Underflow to zero. */ f = 0.0; e = 0; } else if (e < -14) { /* |x| < 2**-14. Gradual underflow */ f = ldexp(f, 14 + e); e = 0; } else /* if (!(e == 0 && f == 0.0)) */ { e += 15; f -= 1.0; /* Get rid of leading 1 */ } f *= 1024.0; /* 2**10 */ /* Round to even */ bits = (unsigned short)f; /* Note the truncation */ assert(bits < 1024); assert(e < 31); if ((f - bits > 0.5) || ((f - bits == 0.5) && (bits % 2 == 1))) { ++bits; if (bits == 1024) { /* The carry propagated out of a string of 10 1 bits. */ bits = 0; ++e; if (e == 31) goto Overflow; } } } bits |= (e << 10) | (sign << 15); /* Write out result. */ if (le) { p += 1; incr = -1; } /* First byte */ *p = (unsigned char)((bits >> 8) & 0xFF); p += incr; /* Second byte */ *p = (unsigned char)(bits & 0xFF); return 0; Overflow: PyErr_SetString(PyExc_OverflowError, "float too large to pack with e format"); return -1; } int _PyFloat_Pack4(double x, unsigned char *p, int le) { if (float_format == unknown_format) { unsigned char sign; int e; double f; unsigned int fbits; int incr = 1; if (le) { p += 3; incr = -1; } if (x < 0) { sign = 1; x = -x; } else sign = 0; f = frexp(x, &e); /* Normalize f to be in the range [1.0, 2.0) */ if (0.5 <= f && f < 1.0) { f *= 2.0; e--; } else if (f == 0.0) e = 0; else { PyErr_SetString(PyExc_SystemError, "frexp() result out of range"); return -1; } if (e >= 128) goto Overflow; else if (e < -126) { /* Gradual underflow */ f = ldexp(f, 126 + e); e = 0; } else if (!(e == 0 && f == 0.0)) { e += 127; f -= 1.0; /* Get rid of leading 1 */ } f *= 8388608.0; /* 2**23 */ fbits = (unsigned int)(f + 0.5); /* Round */ assert(fbits <= 8388608); if (fbits >> 23) { /* The carry propagated out of a string of 23 1 bits. */ fbits = 0; ++e; if (e >= 255) goto Overflow; } /* First byte */ *p = (sign << 7) | (e >> 1); p += incr; /* Second byte */ *p = (char) (((e & 1) << 7) | (fbits >> 16)); p += incr; /* Third byte */ *p = (fbits >> 8) & 0xFF; p += incr; /* Fourth byte */ *p = fbits & 0xFF; /* Done */ return 0; } else { float y = (float)x; int i, incr = 1; if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x)) goto Overflow; unsigned char s[sizeof(float)]; memcpy(s, &y, sizeof(float)); if ((float_format == ieee_little_endian_format && !le) || (float_format == ieee_big_endian_format && le)) { p += 3; incr = -1; } for (i = 0; i < 4; i++) { *p = s[i]; p += incr; } return 0; } Overflow: PyErr_SetString(PyExc_OverflowError, "float too large to pack with f format"); return -1; } int _PyFloat_Pack8(double x, unsigned char *p, int le) { if (double_format == unknown_format) { unsigned char sign; int e; double f; unsigned int fhi, flo; int incr = 1; if (le) { p += 7; incr = -1; } if (x < 0) { sign = 1; x = -x; } else sign = 0; f = frexp(x, &e); /* Normalize f to be in the range [1.0, 2.0) */ if (0.5 <= f && f < 1.0) { f *= 2.0; e--; } else if (f == 0.0) e = 0; else { PyErr_SetString(PyExc_SystemError, "frexp() result out of range"); return -1; } if (e >= 1024) goto Overflow; else if (e < -1022) { /* Gradual underflow */ f = ldexp(f, 1022 + e); e = 0; } else if (!(e == 0 && f == 0.0)) { e += 1023; f -= 1.0; /* Get rid of leading 1 */ } /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */ f *= 268435456.0; /* 2**28 */ fhi = (unsigned int)f; /* Truncate */ assert(fhi < 268435456); f -= (double)fhi; f *= 16777216.0; /* 2**24 */ flo = (unsigned int)(f + 0.5); /* Round */ assert(flo <= 16777216); if (flo >> 24) { /* The carry propagated out of a string of 24 1 bits. */ flo = 0; ++fhi; if (fhi >> 28) { /* And it also progagated out of the next 28 bits. */ fhi = 0; ++e; if (e >= 2047) goto Overflow; } } /* First byte */ *p = (sign << 7) | (e >> 4); p += incr; /* Second byte */ *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24)); p += incr; /* Third byte */ *p = (fhi >> 16) & 0xFF; p += incr; /* Fourth byte */ *p = (fhi >> 8) & 0xFF; p += incr; /* Fifth byte */ *p = fhi & 0xFF; p += incr; /* Sixth byte */ *p = (flo >> 16) & 0xFF; p += incr; /* Seventh byte */ *p = (flo >> 8) & 0xFF; p += incr; /* Eighth byte */ *p = flo & 0xFF; /* p += incr; */ /* Done */ return 0; Overflow: PyErr_SetString(PyExc_OverflowError, "float too large to pack with d format"); return -1; } else { const unsigned char *s = (unsigned char*)&x; int i, incr = 1; if ((double_format == ieee_little_endian_format && !le) || (double_format == ieee_big_endian_format && le)) { p += 7; incr = -1; } for (i = 0; i < 8; i++) { *p = *s++; p += incr; } return 0; } } double _PyFloat_Unpack2(const unsigned char *p, int le) { unsigned char sign; int e; unsigned int f; double x; int incr = 1; if (le) { p += 1; incr = -1; } /* First byte */ sign = (*p >> 7) & 1; e = (*p & 0x7C) >> 2; f = (*p & 0x03) << 8; p += incr; /* Second byte */ f |= *p; if (e == 0x1f) { #ifdef PY_NO_SHORT_FLOAT_REPR if (f == 0) { /* Infinity */ return sign ? -Py_HUGE_VAL : Py_HUGE_VAL; } else { /* NaN */ #ifdef Py_NAN return sign ? -Py_NAN : Py_NAN; #else PyErr_SetString( PyExc_ValueError, "can't unpack IEEE 754 NaN " "on platform that does not support NaNs"); return -1; #endif /* #ifdef Py_NAN */ } #else if (f == 0) { /* Infinity */ return _Py_dg_infinity(sign); } else { /* NaN */ return _Py_dg_stdnan(sign); } #endif /* #ifdef PY_NO_SHORT_FLOAT_REPR */ } x = (double)f / 1024.0; if (e == 0) { e = -14; } else { x += 1.0; e -= 15; } x = ldexp(x, e); if (sign) x = -x; return x; } double _PyFloat_Unpack4(const unsigned char *p, int le) { if (float_format == unknown_format) { unsigned char sign; int e; unsigned int f; double x; int incr = 1; if (le) { p += 3; incr = -1; } /* First byte */ sign = (*p >> 7) & 1; e = (*p & 0x7F) << 1; p += incr; /* Second byte */ e |= (*p >> 7) & 1; f = (*p & 0x7F) << 16; p += incr; if (e == 255) { PyErr_SetString( PyExc_ValueError, "can't unpack IEEE 754 special value " "on non-IEEE platform"); return -1; } /* Third byte */ f |= *p << 8; p += incr; /* Fourth byte */ f |= *p; x = (double)f / 8388608.0; /* XXX This sadly ignores Inf/NaN issues */ if (e == 0) e = -126; else { x += 1.0; e -= 127; } x = ldexp(x, e); if (sign) x = -x; return x; } else { float x; if ((float_format == ieee_little_endian_format && !le) || (float_format == ieee_big_endian_format && le)) { char buf[4]; char *d = &buf[3]; int i; for (i = 0; i < 4; i++) { *d-- = *p++; } memcpy(&x, buf, 4); } else { memcpy(&x, p, 4); } return x; } } double _PyFloat_Unpack8(const unsigned char *p, int le) { if (double_format == unknown_format) { unsigned char sign; int e; unsigned int fhi, flo; double x; int incr = 1; if (le) { p += 7; incr = -1; } /* First byte */ sign = (*p >> 7) & 1; e = (*p & 0x7F) << 4; p += incr; /* Second byte */ e |= (*p >> 4) & 0xF; fhi = (*p & 0xF) << 24; p += incr; if (e == 2047) { PyErr_SetString( PyExc_ValueError, "can't unpack IEEE 754 special value " "on non-IEEE platform"); return -1.0; } /* Third byte */ fhi |= *p << 16; p += incr; /* Fourth byte */ fhi |= *p << 8; p += incr; /* Fifth byte */ fhi |= *p; p += incr; /* Sixth byte */ flo = *p << 16; p += incr; /* Seventh byte */ flo |= *p << 8; p += incr; /* Eighth byte */ flo |= *p; x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */ x /= 268435456.0; /* 2**28 */ if (e == 0) e = -1022; else { x += 1.0; e -= 1023; } x = ldexp(x, e); if (sign) x = -x; return x; } else { double x; if ((double_format == ieee_little_endian_format && !le) || (double_format == ieee_big_endian_format && le)) { char buf[8]; char *d = &buf[7]; int i; for (i = 0; i < 8; i++) { *d-- = *p++; } memcpy(&x, buf, 8); } else { memcpy(&x, p, 8); } return x; } }
74,329
2,603
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/bytearrayobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytes_methods.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pystrhex.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ /*[clinic input] class bytearray "PyByteArrayObject *" "&PyByteArray_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=5535b77c37a119e0]*/ char _PyByteArray_empty_string[] = ""; void PyByteArray_Fini(void) { } int PyByteArray_Init(void) { return 1; } /* end nullbytes support */ /* Helpers */ static int _getbytevalue(PyObject* arg, int *value) { long face_value; if (PyLong_Check(arg)) { face_value = PyLong_AsLong(arg); } else { PyObject *index = PyNumber_Index(arg); if (index == NULL) { *value = -1; return 0; } face_value = PyLong_AsLong(index); Py_DECREF(index); } if (face_value < 0 || face_value >= 256) { /* this includes the OverflowError in case the long is too large */ PyErr_SetString(PyExc_ValueError, "byte must be in range(0, 256)"); *value = -1; return 0; } *value = face_value; return 1; } static int bytearray_getbuffer(PyByteArrayObject *obj, Py_buffer *view, int flags) { void *ptr; if (view == NULL) { PyErr_SetString(PyExc_BufferError, "bytearray_getbuffer: view==NULL argument is obsolete"); return -1; } ptr = (void *) PyByteArray_AS_STRING(obj); /* cannot fail if view != NULL and readonly == 0 */ (void)PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags); obj->ob_exports++; return 0; } static void bytearray_releasebuffer(PyByteArrayObject *obj, Py_buffer *view) { obj->ob_exports--; } static int _canresize(PyByteArrayObject *self) { if (self->ob_exports > 0) { PyErr_SetString(PyExc_BufferError, "Existing exports of data: object cannot be re-sized"); return 0; } return 1; } #include "third_party/python/Objects/clinic/bytearrayobject.inc" /* Direct API functions */ PyObject * PyByteArray_FromObject(PyObject *input) { return PyObject_CallFunctionObjArgs((PyObject *)&PyByteArray_Type, input, NULL); } static PyObject * _PyByteArray_FromBufferObject(PyObject *obj) { PyObject *result; Py_buffer view; if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) { return NULL; } result = PyByteArray_FromStringAndSize(NULL, view.len); if (result != NULL && PyBuffer_ToContiguous(PyByteArray_AS_STRING(result), &view, view.len, 'C') < 0) { Py_CLEAR(result); } PyBuffer_Release(&view); return result; } PyObject * PyByteArray_FromStringAndSize(const char *bytes, Py_ssize_t size) { PyByteArrayObject *new; Py_ssize_t alloc; if (size < 0) { PyErr_SetString(PyExc_SystemError, "Negative size passed to PyByteArray_FromStringAndSize"); return NULL; } /* Prevent buffer overflow when setting alloc to size+1. */ if (size == PY_SSIZE_T_MAX) { return PyErr_NoMemory(); } new = PyObject_New(PyByteArrayObject, &PyByteArray_Type); if (new == NULL) return NULL; if (size == 0) { new->ob_bytes = NULL; alloc = 0; } else { alloc = size + 1; new->ob_bytes = PyObject_Malloc(alloc); if (new->ob_bytes == NULL) { Py_DECREF(new); return PyErr_NoMemory(); } if (bytes != NULL && size > 0) memcpy(new->ob_bytes, bytes, size); new->ob_bytes[size] = '\0'; /* Trailing null byte */ } Py_SIZE(new) = size; new->ob_alloc = alloc; new->ob_start = new->ob_bytes; new->ob_exports = 0; return (PyObject *)new; } Py_ssize_t PyByteArray_Size(PyObject *self) { assert(self != NULL); assert(PyByteArray_Check(self)); return PyByteArray_GET_SIZE(self); } char * PyByteArray_AsString(PyObject *self) { assert(self != NULL); assert(PyByteArray_Check(self)); return PyByteArray_AS_STRING(self); } int PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size) { void *sval; PyByteArrayObject *obj = ((PyByteArrayObject *)self); /* All computations are done unsigned to avoid integer overflows (see issue #22335). */ size_t alloc = (size_t) obj->ob_alloc; size_t logical_offset = (size_t) (obj->ob_start - obj->ob_bytes); size_t size = (size_t) requested_size; assert(self != NULL); assert(PyByteArray_Check(self)); assert(logical_offset <= alloc); assert(requested_size >= 0); if (requested_size == Py_SIZE(self)) { return 0; } if (!_canresize(obj)) { return -1; } if (size + logical_offset + 1 <= alloc) { /* Current buffer is large enough to host the requested size, decide on a strategy. */ if (size < alloc / 2) { /* Major downsize; resize down to exact size */ alloc = size + 1; } else { /* Minor downsize; quick exit */ Py_SIZE(self) = size; PyByteArray_AS_STRING(self)[size] = '\0'; /* Trailing null */ return 0; } } else { /* Need growing, decide on a strategy */ if (size <= alloc * 1.125) { /* Moderate upsize; overallocate similar to list_resize() */ alloc = size + (size >> 3) + (size < 9 ? 3 : 6); } else { /* Major upsize; resize up to exact size */ alloc = size + 1; } } if (alloc > PY_SSIZE_T_MAX) { PyErr_NoMemory(); return -1; } if (logical_offset > 0) { sval = PyObject_Malloc(alloc); if (sval == NULL) { PyErr_NoMemory(); return -1; } memcpy(sval, PyByteArray_AS_STRING(self), Py_MIN((size_t)requested_size, (size_t)Py_SIZE(self))); PyObject_Free(obj->ob_bytes); } else { sval = PyObject_Realloc(obj->ob_bytes, alloc); if (sval == NULL) { PyErr_NoMemory(); return -1; } } obj->ob_bytes = obj->ob_start = sval; Py_SIZE(self) = size; obj->ob_alloc = alloc; obj->ob_bytes[size] = '\0'; /* Trailing null byte */ return 0; } PyObject * PyByteArray_Concat(PyObject *a, PyObject *b) { Py_buffer va, vb; PyByteArrayObject *result = NULL; va.len = -1; vb.len = -1; if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 || PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name); goto done; } if (va.len > PY_SSIZE_T_MAX - vb.len) { PyErr_NoMemory(); goto done; } result = (PyByteArrayObject *) \ PyByteArray_FromStringAndSize(NULL, va.len + vb.len); if (result != NULL) { memcpy(result->ob_bytes, va.buf, va.len); memcpy(result->ob_bytes + va.len, vb.buf, vb.len); } done: if (va.len != -1) PyBuffer_Release(&va); if (vb.len != -1) PyBuffer_Release(&vb); return (PyObject *)result; } /* Functions stuffed into the type object */ static Py_ssize_t bytearray_length(PyByteArrayObject *self) { return Py_SIZE(self); } static PyObject * bytearray_iconcat(PyByteArrayObject *self, PyObject *other) { Py_ssize_t size; Py_buffer vo; if (PyObject_GetBuffer(other, &vo, PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", Py_TYPE(other)->tp_name, Py_TYPE(self)->tp_name); return NULL; } size = Py_SIZE(self); if (size > PY_SSIZE_T_MAX - vo.len) { PyBuffer_Release(&vo); return PyErr_NoMemory(); } if (PyByteArray_Resize((PyObject *)self, size + vo.len) < 0) { PyBuffer_Release(&vo); return NULL; } memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len); PyBuffer_Release(&vo); Py_INCREF(self); return (PyObject *)self; } static PyObject * bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count) { PyByteArrayObject *result; Py_ssize_t mysize; Py_ssize_t size; if (count < 0) count = 0; mysize = Py_SIZE(self); if (count > 0 && mysize > PY_SSIZE_T_MAX / count) return PyErr_NoMemory(); size = mysize * count; result = (PyByteArrayObject *)PyByteArray_FromStringAndSize(NULL, size); if (result != NULL && size != 0) { if (mysize == 1) memset(result->ob_bytes, self->ob_bytes[0], size); else { Py_ssize_t i; for (i = 0; i < count; i++) memcpy(result->ob_bytes + i*mysize, self->ob_bytes, mysize); } } return (PyObject *)result; } static PyObject * bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count) { Py_ssize_t mysize; Py_ssize_t size; char *buf; if (count < 0) count = 0; mysize = Py_SIZE(self); if (count > 0 && mysize > PY_SSIZE_T_MAX / count) return PyErr_NoMemory(); size = mysize * count; if (PyByteArray_Resize((PyObject *)self, size) < 0) return NULL; buf = PyByteArray_AS_STRING(self); if (mysize == 1) memset(buf, buf[0], size); else { Py_ssize_t i; for (i = 1; i < count; i++) memcpy(buf + i*mysize, buf, mysize); } Py_INCREF(self); return (PyObject *)self; } static PyObject * bytearray_getitem(PyByteArrayObject *self, Py_ssize_t i) { if (i < 0) i += Py_SIZE(self); if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); return NULL; } return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i])); } static PyObject * bytearray_subscript(PyByteArrayObject *self, PyObject *index) { if (PyIndex_Check(index)) { Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return NULL; if (i < 0) i += PyByteArray_GET_SIZE(self); if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); return NULL; } return PyLong_FromLong((unsigned char)(PyByteArray_AS_STRING(self)[i])); } else if (PySlice_Check(index)) { Py_ssize_t start, stop, step, slicelength, cur, i; if (PySlice_Unpack(index, &start, &stop, &step) < 0) { return NULL; } slicelength = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start, &stop, step); if (slicelength <= 0) return PyByteArray_FromStringAndSize("", 0); else if (step == 1) { return PyByteArray_FromStringAndSize( PyByteArray_AS_STRING(self) + start, slicelength); } else { char *source_buf = PyByteArray_AS_STRING(self); char *result_buf; PyObject *result; result = PyByteArray_FromStringAndSize(NULL, slicelength); if (result == NULL) return NULL; result_buf = PyByteArray_AS_STRING(result); for (cur = start, i = 0; i < slicelength; cur += step, i++) { result_buf[i] = source_buf[cur]; } return result; } } else { PyErr_Format(PyExc_TypeError, "bytearray indices must be integers or slices, not %.200s", Py_TYPE(index)->tp_name); return NULL; } } static int bytearray_setslice_linear(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi, char *bytes, Py_ssize_t bytes_len) { Py_ssize_t avail = hi - lo; char *buf = PyByteArray_AS_STRING(self); Py_ssize_t growth = bytes_len - avail; int res = 0; assert(avail >= 0); if (growth < 0) { if (!_canresize(self)) return -1; if (lo == 0) { /* Shrink the buffer by advancing its logical start */ self->ob_start -= growth; /* 0 lo hi old_size | |<----avail----->|<-----tail------>| | |<-bytes_len->|<-----tail------>| 0 new_lo new_hi new_size */ } else { /* 0 lo hi old_size | |<----avail----->|<-----tomove------>| | |<-bytes_len->|<-----tomove------>| 0 lo new_hi new_size */ memmove(buf + lo + bytes_len, buf + hi, Py_SIZE(self) - hi); } if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self) + growth) < 0) { /* Issue #19578: Handling the memory allocation failure here is tricky here because the bytearray object has already been modified. Depending on growth and lo, the behaviour is different. If growth < 0 and lo != 0, the operation is completed, but a MemoryError is still raised and the memory block is not shrunk. Otherwise, the bytearray is restored in its previous state and a MemoryError is raised. */ if (lo == 0) { self->ob_start += growth; return -1; } /* memmove() removed bytes, the bytearray object cannot be restored in its previous state. */ Py_SIZE(self) += growth; res = -1; } buf = PyByteArray_AS_STRING(self); } else if (growth > 0) { if (Py_SIZE(self) > (Py_ssize_t)PY_SSIZE_T_MAX - growth) { PyErr_NoMemory(); return -1; } if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self) + growth) < 0) { return -1; } buf = PyByteArray_AS_STRING(self); /* Make the place for the additional bytes */ /* 0 lo hi old_size | |<-avail->|<-----tomove------>| | |<---bytes_len-->|<-----tomove------>| 0 lo new_hi new_size */ memmove(buf + lo + bytes_len, buf + hi, Py_SIZE(self) - lo - bytes_len); } if (bytes_len > 0) memcpy(buf + lo, bytes, bytes_len); return res; } static int bytearray_setslice(PyByteArrayObject *self, Py_ssize_t lo, Py_ssize_t hi, PyObject *values) { Py_ssize_t needed; void *bytes; Py_buffer vbytes; int res = 0; vbytes.len = -1; if (values == (PyObject *)self) { /* Make a copy and call this function recursively */ int err; values = PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(values), PyByteArray_GET_SIZE(values)); if (values == NULL) return -1; err = bytearray_setslice(self, lo, hi, values); Py_DECREF(values); return err; } if (values == NULL) { /* del b[lo:hi] */ bytes = NULL; needed = 0; } else { if (PyObject_GetBuffer(values, &vbytes, PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "can't set bytearray slice from %.100s", Py_TYPE(values)->tp_name); return -1; } needed = vbytes.len; bytes = vbytes.buf; } if (lo < 0) lo = 0; if (hi < lo) hi = lo; if (hi > Py_SIZE(self)) hi = Py_SIZE(self); res = bytearray_setslice_linear(self, lo, hi, bytes, needed); if (vbytes.len != -1) PyBuffer_Release(&vbytes); return res; } static int bytearray_setitem(PyByteArrayObject *self, Py_ssize_t i, PyObject *value) { int ival; if (i < 0) i += Py_SIZE(self); if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); return -1; } if (value == NULL) return bytearray_setslice(self, i, i+1, NULL); if (!_getbytevalue(value, &ival)) return -1; PyByteArray_AS_STRING(self)[i] = ival; return 0; } static int bytearray_ass_subscript(PyByteArrayObject *self, PyObject *index, PyObject *values) { Py_ssize_t start, stop, step, slicelen, needed; char *buf, *bytes; buf = PyByteArray_AS_STRING(self); if (PyIndex_Check(index)) { Py_ssize_t i = PyNumber_AsSsize_t(index, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return -1; if (i < 0) i += PyByteArray_GET_SIZE(self); if (i < 0 || i >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "bytearray index out of range"); return -1; } if (values == NULL) { /* Fall through to slice assignment */ start = i; stop = i + 1; step = 1; slicelen = 1; } else { int ival; if (!_getbytevalue(values, &ival)) return -1; buf[i] = (char)ival; return 0; } } else if (PySlice_Check(index)) { if (PySlice_Unpack(index, &start, &stop, &step) < 0) { return -1; } slicelen = PySlice_AdjustIndices(PyByteArray_GET_SIZE(self), &start, &stop, step); } else { PyErr_Format(PyExc_TypeError, "bytearray indices must be integers or slices, not %.200s", Py_TYPE(index)->tp_name); return -1; } if (values == NULL) { bytes = NULL; needed = 0; } else if (values == (PyObject *)self || !PyByteArray_Check(values)) { int err; if (PyNumber_Check(values) || PyUnicode_Check(values)) { PyErr_SetString(PyExc_TypeError, "can assign only bytes, buffers, or iterables " "of ints in range(0, 256)"); return -1; } /* Make a copy and call this function recursively */ values = PyByteArray_FromObject(values); if (values == NULL) return -1; err = bytearray_ass_subscript(self, index, values); Py_DECREF(values); return err; } else { assert(PyByteArray_Check(values)); bytes = PyByteArray_AS_STRING(values); needed = Py_SIZE(values); } /* Make sure b[5:2] = ... inserts before 5, not before 2. */ if ((step < 0 && start < stop) || (step > 0 && start > stop)) stop = start; if (step == 1) { return bytearray_setslice_linear(self, start, stop, bytes, needed); } else { if (needed == 0) { /* Delete slice */ size_t cur; Py_ssize_t i; if (!_canresize(self)) return -1; if (slicelen == 0) /* Nothing to do here. */ return 0; if (step < 0) { stop = start + 1; start = stop + step * (slicelen - 1) - 1; step = -step; } for (cur = start, i = 0; i < slicelen; cur += step, i++) { Py_ssize_t lim = step - 1; if (cur + step >= (size_t)PyByteArray_GET_SIZE(self)) lim = PyByteArray_GET_SIZE(self) - cur - 1; memmove(buf + cur - i, buf + cur + 1, lim); } /* Move the tail of the bytes, in one chunk */ cur = start + (size_t)slicelen*step; if (cur < (size_t)PyByteArray_GET_SIZE(self)) { memmove(buf + cur - slicelen, buf + cur, PyByteArray_GET_SIZE(self) - cur); } if (PyByteArray_Resize((PyObject *)self, PyByteArray_GET_SIZE(self) - slicelen) < 0) return -1; return 0; } else { /* Assign slice */ Py_ssize_t i; size_t cur; if (needed != slicelen) { PyErr_Format(PyExc_ValueError, "attempt to assign bytes of size %zd " "to extended slice of size %zd", needed, slicelen); return -1; } for (cur = start, i = 0; i < slicelen; cur += step, i++) buf[cur] = bytes[i]; return 0; } } } static int bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"source", "encoding", "errors", 0}; PyObject *arg = NULL; const char *encoding = NULL; const char *errors = NULL; Py_ssize_t count; PyObject *it; PyObject *(*iternext)(PyObject *); if (Py_SIZE(self) != 0) { /* Empty previous contents (yes, do this first of all!) */ if (PyByteArray_Resize((PyObject *)self, 0) < 0) return -1; } /* Parse arguments */ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytearray", kwlist, &arg, &encoding, &errors)) return -1; /* Make a quick exit if no first argument */ if (arg == NULL) { if (encoding != NULL || errors != NULL) { PyErr_SetString(PyExc_TypeError, "encoding or errors without sequence argument"); return -1; } return 0; } if (PyUnicode_Check(arg)) { /* Encode via the codec registry */ PyObject *encoded, *new; if (encoding == NULL) { PyErr_SetString(PyExc_TypeError, "string argument without an encoding"); return -1; } encoded = PyUnicode_AsEncodedString(arg, encoding, errors); if (encoded == NULL) return -1; assert(PyBytes_Check(encoded)); new = bytearray_iconcat(self, encoded); Py_DECREF(encoded); if (new == NULL) return -1; Py_DECREF(new); return 0; } /* If it's not unicode, there can't be encoding or errors */ if (encoding != NULL || errors != NULL) { PyErr_SetString(PyExc_TypeError, "encoding or errors without a string argument"); return -1; } /* Is it an int? */ if (PyIndex_Check(arg)) { count = PyNumber_AsSsize_t(arg, PyExc_OverflowError); if (count == -1 && PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_TypeError)) return -1; PyErr_Clear(); /* fall through */ } else { if (count < 0) { PyErr_SetString(PyExc_ValueError, "negative count"); return -1; } if (count > 0) { if (PyByteArray_Resize((PyObject *)self, count)) return -1; bzero(PyByteArray_AS_STRING(self), count); } return 0; } } /* Use the buffer API */ if (PyObject_CheckBuffer(arg)) { Py_ssize_t size; Py_buffer view; if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0) return -1; size = view.len; if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail; if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self), &view, size, 'C') < 0) goto fail; PyBuffer_Release(&view); return 0; fail: PyBuffer_Release(&view); return -1; } /* XXX Optimize this if the arguments is a list, tuple */ /* Get the iterator */ it = PyObject_GetIter(arg); if (it == NULL) return -1; iternext = *Py_TYPE(it)->tp_iternext; /* Run the iterator to exhaustion */ for (;;) { PyObject *item; int rc, value; /* Get the next item */ item = iternext(it); if (item == NULL) { if (PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_StopIteration)) goto error; PyErr_Clear(); } break; } /* Interpret it as an int (__index__) */ rc = _getbytevalue(item, &value); Py_DECREF(item); if (!rc) goto error; /* Append the byte */ if (Py_SIZE(self) + 1 < self->ob_alloc) { Py_SIZE(self)++; PyByteArray_AS_STRING(self)[Py_SIZE(self)] = '\0'; } else if (PyByteArray_Resize((PyObject *)self, Py_SIZE(self)+1) < 0) goto error; PyByteArray_AS_STRING(self)[Py_SIZE(self)-1] = value; } /* Clean up and return success */ Py_DECREF(it); return 0; error: /* Error handling when it != NULL */ Py_DECREF(it); return -1; } /* Mostly copied from string_repr, but without the "smart quote" functionality. */ static PyObject * bytearray_repr(PyByteArrayObject *self) { const char *quote_prefix = "bytearray(b"; const char *quote_postfix = ")"; Py_ssize_t length = Py_SIZE(self); /* 15 == strlen(quote_prefix) + 2 + strlen(quote_postfix) + 1 */ size_t newsize; PyObject *v; Py_ssize_t i; char *bytes; char c; char *p; int quote; char *test, *start; char *buffer; if (length > (PY_SSIZE_T_MAX - 15) / 4) { PyErr_SetString(PyExc_OverflowError, "bytearray object is too large to make repr"); return NULL; } newsize = 15 + length * 4; buffer = PyObject_Malloc(newsize); if (buffer == NULL) { PyErr_NoMemory(); return NULL; } /* Figure out which quote to use; single is preferred */ quote = '\''; start = PyByteArray_AS_STRING(self); for (test = start; test < start+length; ++test) { if (*test == '"') { quote = '\''; /* back to single */ break; } else if (*test == '\'') quote = '"'; } p = buffer; while (*quote_prefix) *p++ = *quote_prefix++; *p++ = quote; bytes = PyByteArray_AS_STRING(self); for (i = 0; i < length; i++) { /* There's at least enough room for a hex escape and a closing quote. */ assert(newsize - (p - buffer) >= 5); c = bytes[i]; if (c == '\'' || c == '\\') *p++ = '\\', *p++ = c; else if (c == '\t') *p++ = '\\', *p++ = 't'; else if (c == '\n') *p++ = '\\', *p++ = 'n'; else if (c == '\r') *p++ = '\\', *p++ = 'r'; else if (c == 0) *p++ = '\\', *p++ = 'x', *p++ = '0', *p++ = '0'; else if (c < ' ' || c >= 0x7f) { *p++ = '\\'; *p++ = 'x'; *p++ = Py_hexdigits[(c & 0xf0) >> 4]; *p++ = Py_hexdigits[c & 0xf]; } else *p++ = c; } assert(newsize - (p - buffer) >= 1); *p++ = quote; while (*quote_postfix) { *p++ = *quote_postfix++; } v = PyUnicode_DecodeASCII(buffer, p - buffer, NULL); PyObject_Free(buffer); return v; } static PyObject * bytearray_str(PyObject *op) { if (Py_BytesWarningFlag) { if (PyErr_WarnEx(PyExc_BytesWarning, "str() on a bytearray instance", 1)) return NULL; } return bytearray_repr((PyByteArrayObject*)op); } static PyObject * bytearray_richcompare(PyObject *self, PyObject *other, int op) { Py_ssize_t self_size, other_size; Py_buffer self_bytes, other_bytes; PyObject *res; Py_ssize_t minsize; int cmp, rc; /* Bytes can be compared to anything that supports the (binary) buffer API. Except that a comparison with Unicode is always an error, even if the comparison is for equality. */ rc = PyObject_IsInstance(self, (PyObject*)&PyUnicode_Type); if (!rc) rc = PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type); if (rc < 0) return NULL; if (rc) { if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) { if (PyErr_WarnEx(PyExc_BytesWarning, "Comparison between bytearray and string", 1)) return NULL; } Py_RETURN_NOTIMPLEMENTED; } if (PyObject_GetBuffer(self, &self_bytes, PyBUF_SIMPLE) != 0) { PyErr_Clear(); Py_RETURN_NOTIMPLEMENTED; } self_size = self_bytes.len; if (PyObject_GetBuffer(other, &other_bytes, PyBUF_SIMPLE) != 0) { PyErr_Clear(); PyBuffer_Release(&self_bytes); Py_RETURN_NOTIMPLEMENTED; } other_size = other_bytes.len; if (self_size != other_size && (op == Py_EQ || op == Py_NE)) { /* Shortcut: if the lengths differ, the objects differ */ cmp = (op == Py_NE); } else { minsize = self_size; if (other_size < minsize) minsize = other_size; cmp = memcmp(self_bytes.buf, other_bytes.buf, minsize); /* In ISO C, memcmp() guarantees to use unsigned bytes! */ if (cmp == 0) { if (self_size < other_size) cmp = -1; else if (self_size > other_size) cmp = 1; } switch (op) { case Py_LT: cmp = cmp < 0; break; case Py_LE: cmp = cmp <= 0; break; case Py_EQ: cmp = cmp == 0; break; case Py_NE: cmp = cmp != 0; break; case Py_GT: cmp = cmp > 0; break; case Py_GE: cmp = cmp >= 0; break; } } res = cmp ? Py_True : Py_False; PyBuffer_Release(&self_bytes); PyBuffer_Release(&other_bytes); Py_INCREF(res); return res; } static void bytearray_dealloc(PyByteArrayObject *self) { if (self->ob_exports > 0) { PyErr_SetString(PyExc_SystemError, "deallocated bytearray object has exported buffers"); PyErr_Print(); } if (self->ob_bytes != 0) { PyObject_Free(self->ob_bytes); } Py_TYPE(self)->tp_free((PyObject *)self); } /* -------------------------------------------------------------------- */ /* Methods */ #define FASTSEARCH fastsearch #define STRINGLIB(F) stringlib_##F #define STRINGLIB_CHAR char #define STRINGLIB_SIZEOF_CHAR 1 #define STRINGLIB_LEN PyByteArray_GET_SIZE #define STRINGLIB_STR PyByteArray_AS_STRING #define STRINGLIB_NEW PyByteArray_FromStringAndSize #define STRINGLIB_ISSPACE Py_ISSPACE #define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r')) #define STRINGLIB_CHECK_EXACT PyByteArray_CheckExact #define STRINGLIB_MUTABLE 1 #include "third_party/python/Objects/stringlib/fastsearch.inc" #include "third_party/python/Objects/stringlib/count.inc" #include "third_party/python/Objects/stringlib/find.inc" #include "third_party/python/Objects/stringlib/join.inc" #include "third_party/python/Objects/stringlib/partition.inc" #include "third_party/python/Objects/stringlib/split.inc" #include "third_party/python/Objects/stringlib/ctype.inc" #include "third_party/python/Objects/stringlib/transmogrify.inc" static PyObject * bytearray_find(PyByteArrayObject *self, PyObject *args) { return _Py_bytes_find(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args); } static PyObject * bytearray_count(PyByteArrayObject *self, PyObject *args) { return _Py_bytes_count(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args); } /*[clinic input] bytearray.clear Remove all items from the bytearray. [clinic start generated code]*/ static PyObject * bytearray_clear_impl(PyByteArrayObject *self) /*[clinic end generated code: output=85c2fe6aede0956c input=ed6edae9de447ac4]*/ { if (PyByteArray_Resize((PyObject *)self, 0) < 0) return NULL; Py_RETURN_NONE; } /*[clinic input] bytearray.copy Return a copy of B. [clinic start generated code]*/ static PyObject * bytearray_copy_impl(PyByteArrayObject *self) /*[clinic end generated code: output=68cfbcfed484c132 input=6597b0c01bccaa9e]*/ { return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING((PyObject *)self), PyByteArray_GET_SIZE(self)); } static PyObject * bytearray_index(PyByteArrayObject *self, PyObject *args) { return _Py_bytes_index(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args); } static PyObject * bytearray_rfind(PyByteArrayObject *self, PyObject *args) { return _Py_bytes_rfind(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args); } static PyObject * bytearray_rindex(PyByteArrayObject *self, PyObject *args) { return _Py_bytes_rindex(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args); } static int bytearray_contains(PyObject *self, PyObject *arg) { return _Py_bytes_contains(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), arg); } static PyObject * bytearray_startswith(PyByteArrayObject *self, PyObject *args) { return _Py_bytes_startswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args); } static PyObject * bytearray_endswith(PyByteArrayObject *self, PyObject *args) { return _Py_bytes_endswith(PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), args); } /*[clinic input] bytearray.translate table: object Translation table, which must be a bytes object of length 256. / delete as deletechars: object(c_default="NULL") = b'' Return a copy with each character mapped by the given translation table. All characters occurring in the optional argument delete are removed. The remaining characters are mapped through the given translation table. [clinic start generated code]*/ static PyObject * bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, PyObject *deletechars) /*[clinic end generated code: output=b6a8f01c2a74e446 input=cfff956d4d127a9b]*/ { char *input, *output; const char *table_chars; Py_ssize_t i, c; PyObject *input_obj = (PyObject*)self; const char *output_start; Py_ssize_t inlen; PyObject *result = NULL; int trans_table[256]; Py_buffer vtable, vdel; if (table == Py_None) { table_chars = NULL; table = NULL; } else if (PyObject_GetBuffer(table, &vtable, PyBUF_SIMPLE) != 0) { return NULL; } else { if (vtable.len != 256) { PyErr_SetString(PyExc_ValueError, "translation table must be 256 characters long"); PyBuffer_Release(&vtable); return NULL; } table_chars = (const char*)vtable.buf; } if (deletechars != NULL) { if (PyObject_GetBuffer(deletechars, &vdel, PyBUF_SIMPLE) != 0) { if (table != NULL) PyBuffer_Release(&vtable); return NULL; } } else { vdel.buf = NULL; vdel.len = 0; } inlen = PyByteArray_GET_SIZE(input_obj); result = PyByteArray_FromStringAndSize((char *)NULL, inlen); if (result == NULL) goto done; output_start = output = PyByteArray_AS_STRING(result); input = PyByteArray_AS_STRING(input_obj); if (vdel.len == 0 && table_chars != NULL) { /* If no deletions are required, use faster code */ for (i = inlen; --i >= 0; ) { c = Py_CHARMASK(*input++); *output++ = table_chars[c]; } goto done; } if (table_chars == NULL) { for (i = 0; i < 256; i++) trans_table[i] = Py_CHARMASK(i); } else { for (i = 0; i < 256; i++) trans_table[i] = Py_CHARMASK(table_chars[i]); } for (i = 0; i < vdel.len; i++) trans_table[(int) Py_CHARMASK( ((unsigned char*)vdel.buf)[i] )] = -1; for (i = inlen; --i >= 0; ) { c = Py_CHARMASK(*input++); if (trans_table[c] != -1) *output++ = (char)trans_table[c]; } /* Fix the size of the resulting string */ if (inlen > 0) if (PyByteArray_Resize(result, output - output_start) < 0) { Py_CLEAR(result); goto done; } done: if (table != NULL) PyBuffer_Release(&vtable); if (deletechars != NULL) PyBuffer_Release(&vdel); return result; } /*[clinic input] @staticmethod bytearray.maketrans frm: Py_buffer to: Py_buffer / Return a translation table useable for the bytes or bytearray translate method. The returned table will be one where each byte in frm is mapped to the byte at the same position in to. The bytes objects frm and to must be of the same length. [clinic start generated code]*/ static PyObject * bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to) /*[clinic end generated code: output=1df267d99f56b15e input=5925a81d2fbbf151]*/ { return _Py_bytes_maketrans(frm, to); } /*[clinic input] bytearray.replace old: Py_buffer new: Py_buffer count: Py_ssize_t = -1 Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences. / Return a copy with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. [clinic start generated code]*/ static PyObject * bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count) /*[clinic end generated code: output=d39884c4dc59412a input=aa379d988637c7fb]*/ { return stringlib_replace((PyObject *)self, (const char *)old->buf, old->len, (const char *)new->buf, new->len, count); } /*[clinic input] bytearray.split sep: object = None The delimiter according which to split the bytearray. None (the default value) means split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). maxsplit: Py_ssize_t = -1 Maximum number of splits to do. -1 (the default value) means no limit. Return a list of the sections in the bytearray, using sep as the delimiter. [clinic start generated code]*/ static PyObject * bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit) /*[clinic end generated code: output=833e2cf385d9a04d input=24f82669f41bf523]*/ { Py_ssize_t len = PyByteArray_GET_SIZE(self), n; const char *s = PyByteArray_AS_STRING(self), *sub; PyObject *list; Py_buffer vsub; if (maxsplit < 0) maxsplit = PY_SSIZE_T_MAX; if (sep == Py_None) return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit); if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) return NULL; sub = vsub.buf; n = vsub.len; list = stringlib_split( (PyObject*) self, s, len, sub, n, maxsplit ); PyBuffer_Release(&vsub); return list; } /*[clinic input] bytearray.partition sep: object / Partition the bytearray into three parts using the given separator. This will search for the separator sep in the bytearray. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it as new bytearray objects. If the separator is not found, returns a 3-tuple containing the copy of the original bytearray object and two empty bytearray objects. [clinic start generated code]*/ static PyObject * bytearray_partition(PyByteArrayObject *self, PyObject *sep) /*[clinic end generated code: output=45d2525ddd35f957 input=8f644749ee4fc83a]*/ { PyObject *bytesep, *result; bytesep = _PyByteArray_FromBufferObject(sep); if (! bytesep) return NULL; result = stringlib_partition( (PyObject*) self, PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), bytesep, PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep) ); Py_DECREF(bytesep); return result; } /*[clinic input] bytearray.rpartition sep: object / Partition the bytearray into three parts using the given separator. This will search for the separator sep in the bytearray, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it as new bytearray objects. If the separator is not found, returns a 3-tuple containing two empty bytearray objects and the copy of the original bytearray object. [clinic start generated code]*/ static PyObject * bytearray_rpartition(PyByteArrayObject *self, PyObject *sep) /*[clinic end generated code: output=440de3c9426115e8 input=7e3df3e6cb8fa0ac]*/ { PyObject *bytesep, *result; bytesep = _PyByteArray_FromBufferObject(sep); if (! bytesep) return NULL; result = stringlib_rpartition( (PyObject*) self, PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), bytesep, PyByteArray_AS_STRING(bytesep), PyByteArray_GET_SIZE(bytesep) ); Py_DECREF(bytesep); return result; } /*[clinic input] bytearray.rsplit = bytearray.split Return a list of the sections in the bytearray, using sep as the delimiter. Splitting is done starting at the end of the bytearray and working to the front. [clinic start generated code]*/ static PyObject * bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit) /*[clinic end generated code: output=a55e0b5a03cb6190 input=a68286e4dd692ffe]*/ { Py_ssize_t len = PyByteArray_GET_SIZE(self), n; const char *s = PyByteArray_AS_STRING(self), *sub; PyObject *list; Py_buffer vsub; if (maxsplit < 0) maxsplit = PY_SSIZE_T_MAX; if (sep == Py_None) return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit); if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) return NULL; sub = vsub.buf; n = vsub.len; list = stringlib_rsplit( (PyObject*) self, s, len, sub, n, maxsplit ); PyBuffer_Release(&vsub); return list; } /*[clinic input] bytearray.reverse Reverse the order of the values in B in place. [clinic start generated code]*/ static PyObject * bytearray_reverse_impl(PyByteArrayObject *self) /*[clinic end generated code: output=9f7616f29ab309d3 input=543356319fc78557]*/ { char swap, *head, *tail; Py_ssize_t i, j, n = Py_SIZE(self); j = n / 2; head = PyByteArray_AS_STRING(self); tail = head + n - 1; for (i = 0; i < j; i++) { swap = *head; *head++ = *tail; *tail-- = swap; } Py_RETURN_NONE; } /*[python input] class bytesvalue_converter(CConverter): type = 'int' converter = '_getbytevalue' [python start generated code]*/ /*[python end generated code: output=da39a3ee5e6b4b0d input=29c2e7c26c212812]*/ /*[clinic input] bytearray.insert index: Py_ssize_t The index where the value is to be inserted. item: bytesvalue The item to be inserted. / Insert a single item into the bytearray before the given index. [clinic start generated code]*/ static PyObject * bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item) /*[clinic end generated code: output=76c775a70e7b07b7 input=b2b5d07e9de6c070]*/ { Py_ssize_t n = Py_SIZE(self); char *buf; if (n == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "cannot add more objects to bytearray"); return NULL; } if (PyByteArray_Resize((PyObject *)self, n + 1) < 0) return NULL; buf = PyByteArray_AS_STRING(self); if (index < 0) { index += n; if (index < 0) index = 0; } if (index > n) index = n; memmove(buf + index + 1, buf + index, n - index); buf[index] = item; Py_RETURN_NONE; } /*[clinic input] bytearray.append item: bytesvalue The item to be appended. / Append a single item to the end of the bytearray. [clinic start generated code]*/ static PyObject * bytearray_append_impl(PyByteArrayObject *self, int item) /*[clinic end generated code: output=a154e19ed1886cb6 input=20d6bec3d1340593]*/ { Py_ssize_t n = Py_SIZE(self); if (n == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "cannot add more objects to bytearray"); return NULL; } if (PyByteArray_Resize((PyObject *)self, n + 1) < 0) return NULL; PyByteArray_AS_STRING(self)[n] = item; Py_RETURN_NONE; } /*[clinic input] bytearray.extend iterable_of_ints: object The iterable of items to append. / Append all the items from the iterator or sequence to the end of the bytearray. [clinic start generated code]*/ static PyObject * bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints) /*[clinic end generated code: output=98155dbe249170b1 input=c617b3a93249ba28]*/ { PyObject *it, *item, *bytearray_obj; Py_ssize_t buf_size = 0, len = 0; int value; char *buf; /* bytearray_setslice code only accepts something supporting PEP 3118. */ if (PyObject_CheckBuffer(iterable_of_ints)) { if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), iterable_of_ints) == -1) return NULL; Py_RETURN_NONE; } it = PyObject_GetIter(iterable_of_ints); if (it == NULL) return NULL; /* Try to determine the length of the argument. 32 is arbitrary. */ buf_size = PyObject_LengthHint(iterable_of_ints, 32); if (buf_size == -1) { Py_DECREF(it); return NULL; } bytearray_obj = PyByteArray_FromStringAndSize(NULL, buf_size); if (bytearray_obj == NULL) { Py_DECREF(it); return NULL; } buf = PyByteArray_AS_STRING(bytearray_obj); while ((item = PyIter_Next(it)) != NULL) { if (! _getbytevalue(item, &value)) { Py_DECREF(item); Py_DECREF(it); Py_DECREF(bytearray_obj); return NULL; } buf[len++] = value; Py_DECREF(item); if (len >= buf_size) { Py_ssize_t addition; if (len == PY_SSIZE_T_MAX) { Py_DECREF(it); Py_DECREF(bytearray_obj); return PyErr_NoMemory(); } addition = len >> 1; if (addition > PY_SSIZE_T_MAX - len - 1) buf_size = PY_SSIZE_T_MAX; else buf_size = len + addition + 1; if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) { Py_DECREF(it); Py_DECREF(bytearray_obj); return NULL; } /* Recompute the `buf' pointer, since the resizing operation may have invalidated it. */ buf = PyByteArray_AS_STRING(bytearray_obj); } } Py_DECREF(it); /* Resize down to exact size. */ if (PyByteArray_Resize((PyObject *)bytearray_obj, len) < 0) { Py_DECREF(bytearray_obj); return NULL; } if (bytearray_setslice(self, Py_SIZE(self), Py_SIZE(self), bytearray_obj) == -1) { Py_DECREF(bytearray_obj); return NULL; } Py_DECREF(bytearray_obj); Py_RETURN_NONE; } /*[clinic input] bytearray.pop index: Py_ssize_t = -1 The index from where to remove the item. -1 (the default value) means remove the last item. / Remove and return a single item from B. If no index argument is given, will pop the last item. [clinic start generated code]*/ static PyObject * bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index) /*[clinic end generated code: output=e0ccd401f8021da8 input=3591df2d06c0d237]*/ { int value; Py_ssize_t n = Py_SIZE(self); char *buf; if (n == 0) { PyErr_SetString(PyExc_IndexError, "pop from empty bytearray"); return NULL; } if (index < 0) index += Py_SIZE(self); if (index < 0 || index >= Py_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "pop index out of range"); return NULL; } if (!_canresize(self)) return NULL; buf = PyByteArray_AS_STRING(self); value = buf[index]; memmove(buf + index, buf + index + 1, n - index); if (PyByteArray_Resize((PyObject *)self, n - 1) < 0) return NULL; return PyLong_FromLong((unsigned char)value); } /*[clinic input] bytearray.remove value: bytesvalue The value to remove. / Remove the first occurrence of a value in the bytearray. [clinic start generated code]*/ static PyObject * bytearray_remove_impl(PyByteArrayObject *self, int value) /*[clinic end generated code: output=d659e37866709c13 input=121831240cd51ddf]*/ { Py_ssize_t where, n = Py_SIZE(self); char *buf = PyByteArray_AS_STRING(self); where = stringlib_find_char(buf, n, value); if (where < 0) { PyErr_SetString(PyExc_ValueError, "value not found in bytearray"); return NULL; } if (!_canresize(self)) return NULL; memmove(buf + where, buf + where + 1, n - where); if (PyByteArray_Resize((PyObject *)self, n - 1) < 0) return NULL; Py_RETURN_NONE; } /* XXX These two helpers could be optimized if argsize == 1 */ static Py_ssize_t lstrip_helper(const char *myptr, Py_ssize_t mysize, const void *argptr, Py_ssize_t argsize) { Py_ssize_t i = 0; while (i < mysize && memchr(argptr, (unsigned char) myptr[i], argsize)) i++; return i; } static Py_ssize_t rstrip_helper(const char *myptr, Py_ssize_t mysize, const void *argptr, Py_ssize_t argsize) { Py_ssize_t i = mysize - 1; while (i >= 0 && memchr(argptr, (unsigned char) myptr[i], argsize)) i--; return i + 1; } /*[clinic input] bytearray.strip bytes: object = None / Strip leading and trailing bytes contained in the argument. If the argument is omitted or None, strip leading and trailing ASCII whitespace. [clinic start generated code]*/ static PyObject * bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes) /*[clinic end generated code: output=760412661a34ad5a input=ef7bb59b09c21d62]*/ { Py_ssize_t left, right, mysize, byteslen; char *myptr, *bytesptr; Py_buffer vbytes; if (bytes == Py_None) { bytesptr = "\t\n\r\f\v "; byteslen = 6; } else { if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0) return NULL; bytesptr = (char *) vbytes.buf; byteslen = vbytes.len; } myptr = PyByteArray_AS_STRING(self); mysize = Py_SIZE(self); left = lstrip_helper(myptr, mysize, bytesptr, byteslen); if (left == mysize) right = left; else right = rstrip_helper(myptr, mysize, bytesptr, byteslen); if (bytes != Py_None) PyBuffer_Release(&vbytes); return PyByteArray_FromStringAndSize(myptr + left, right - left); } /*[clinic input] bytearray.lstrip bytes: object = None / Strip leading bytes contained in the argument. If the argument is omitted or None, strip leading ASCII whitespace. [clinic start generated code]*/ static PyObject * bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes) /*[clinic end generated code: output=d005c9d0ab909e66 input=80843f975dd7c480]*/ { Py_ssize_t left, right, mysize, byteslen; char *myptr, *bytesptr; Py_buffer vbytes; if (bytes == Py_None) { bytesptr = "\t\n\r\f\v "; byteslen = 6; } else { if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0) return NULL; bytesptr = (char *) vbytes.buf; byteslen = vbytes.len; } myptr = PyByteArray_AS_STRING(self); mysize = Py_SIZE(self); left = lstrip_helper(myptr, mysize, bytesptr, byteslen); right = mysize; if (bytes != Py_None) PyBuffer_Release(&vbytes); return PyByteArray_FromStringAndSize(myptr + left, right - left); } /*[clinic input] bytearray.rstrip bytes: object = None / Strip trailing bytes contained in the argument. If the argument is omitted or None, strip trailing ASCII whitespace. [clinic start generated code]*/ static PyObject * bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes) /*[clinic end generated code: output=030e2fbd2f7276bd input=e728b994954cfd91]*/ { Py_ssize_t right, mysize, byteslen; char *myptr, *bytesptr; Py_buffer vbytes; if (bytes == Py_None) { bytesptr = "\t\n\r\f\v "; byteslen = 6; } else { if (PyObject_GetBuffer(bytes, &vbytes, PyBUF_SIMPLE) != 0) return NULL; bytesptr = (char *) vbytes.buf; byteslen = vbytes.len; } myptr = PyByteArray_AS_STRING(self); mysize = Py_SIZE(self); right = rstrip_helper(myptr, mysize, bytesptr, byteslen); if (bytes != Py_None) PyBuffer_Release(&vbytes); return PyByteArray_FromStringAndSize(myptr, right); } /*[clinic input] bytearray.decode encoding: str(c_default="NULL") = 'utf-8' The encoding with which to decode the bytearray. errors: str(c_default="NULL") = 'strict' The error handling scheme to use for the handling of decoding errors. The default is 'strict' meaning that decoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that can handle UnicodeDecodeErrors. Decode the bytearray using the codec registered for encoding. [clinic start generated code]*/ static PyObject * bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors) /*[clinic end generated code: output=f57d43f4a00b42c5 input=f28d8f903020257b]*/ { if (encoding == NULL) encoding = PyUnicode_GetDefaultEncoding(); return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors); } PyDoc_STRVAR(alloc_doc, "B.__alloc__() -> int\n\ \n\ Return the number of bytes actually allocated."); static PyObject * bytearray_alloc(PyByteArrayObject *self) { return PyLong_FromSsize_t(self->ob_alloc); } /*[clinic input] bytearray.join iterable_of_bytes: object / Concatenate any number of bytes/bytearray objects. The bytearray whose method is called is inserted in between each pair. The result is returned as a new bytearray object. [clinic start generated code]*/ static PyObject * bytearray_join(PyByteArrayObject *self, PyObject *iterable_of_bytes) /*[clinic end generated code: output=a8516370bf68ae08 input=aba6b1f9b30fcb8e]*/ { return stringlib_bytes_join((PyObject*)self, iterable_of_bytes); } /*[clinic input] bytearray.splitlines keepends: int(c_default="0") = False Return a list of the lines in the bytearray, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. [clinic start generated code]*/ static PyObject * bytearray_splitlines_impl(PyByteArrayObject *self, int keepends) /*[clinic end generated code: output=4223c94b895f6ad9 input=8ccade941e5ea0bd]*/ { return stringlib_splitlines( (PyObject*) self, PyByteArray_AS_STRING(self), PyByteArray_GET_SIZE(self), keepends ); } /*[clinic input] @classmethod bytearray.fromhex string: unicode / Create a bytearray object from a string of hexadecimal numbers. Spaces between two numbers are accepted. Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef') [clinic start generated code]*/ static PyObject * bytearray_fromhex_impl(PyTypeObject *type, PyObject *string) /*[clinic end generated code: output=8f0f0b6d30fb3ba0 input=f033a16d1fb21f48]*/ { PyObject *result = _PyBytes_FromHex(string, type == &PyByteArray_Type); if (type != &PyByteArray_Type && result != NULL) { Py_SETREF(result, PyObject_CallFunctionObjArgs((PyObject *)type, result, NULL)); } return result; } PyDoc_STRVAR(hex__doc__, "B.hex() -> string\n\ \n\ Create a string of hexadecimal numbers from a bytearray object.\n\ Example: bytearray([0xb9, 0x01, 0xef]).hex() -> 'b901ef'."); static PyObject * bytearray_hex(PyBytesObject *self) { char* argbuf = PyByteArray_AS_STRING(self); Py_ssize_t arglen = PyByteArray_GET_SIZE(self); return _Py_strhex(argbuf, arglen); } static PyObject * _common_reduce(PyByteArrayObject *self, int proto) { PyObject *dict; _Py_IDENTIFIER(__dict__); char *buf; dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__); if (dict == NULL) { PyErr_Clear(); dict = Py_None; Py_INCREF(dict); } buf = PyByteArray_AS_STRING(self); if (proto < 3) { /* use str based reduction for backwards compatibility with Python 2.x */ PyObject *latin1; if (Py_SIZE(self)) latin1 = PyUnicode_DecodeLatin1(buf, Py_SIZE(self), NULL); else latin1 = PyUnicode_FromString(""); return Py_BuildValue("(O(Ns)N)", Py_TYPE(self), latin1, "latin-1", dict); } else { /* use more efficient byte based reduction */ if (Py_SIZE(self)) { return Py_BuildValue("(O(y#)N)", Py_TYPE(self), buf, Py_SIZE(self), dict); } else { return Py_BuildValue("(O()N)", Py_TYPE(self), dict); } } } /*[clinic input] bytearray.__reduce__ as bytearray_reduce Return state information for pickling. [clinic start generated code]*/ static PyObject * bytearray_reduce_impl(PyByteArrayObject *self) /*[clinic end generated code: output=52bf304086464cab input=44b5737ada62dd3f]*/ { return _common_reduce(self, 2); } /*[clinic input] bytearray.__reduce_ex__ as bytearray_reduce_ex proto: int = 0 / Return state information for pickling. [clinic start generated code]*/ static PyObject * bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto) /*[clinic end generated code: output=52eac33377197520 input=f129bc1a1aa151ee]*/ { return _common_reduce(self, proto); } /*[clinic input] bytearray.__sizeof__ as bytearray_sizeof Returns the size of the bytearray object in memory, in bytes. [clinic start generated code]*/ static PyObject * bytearray_sizeof_impl(PyByteArrayObject *self) /*[clinic end generated code: output=738abdd17951c427 input=e27320fd98a4bc5a]*/ { Py_ssize_t res; res = _PyObject_SIZE(Py_TYPE(self)) + self->ob_alloc * sizeof(char); return PyLong_FromSsize_t(res); } static PySequenceMethods bytearray_as_sequence = { (lenfunc)bytearray_length, /* sq_length */ (binaryfunc)PyByteArray_Concat, /* sq_concat */ (ssizeargfunc)bytearray_repeat, /* sq_repeat */ (ssizeargfunc)bytearray_getitem, /* sq_item */ 0, /* sq_slice */ (ssizeobjargproc)bytearray_setitem, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)bytearray_contains, /* sq_contains */ (binaryfunc)bytearray_iconcat, /* sq_inplace_concat */ (ssizeargfunc)bytearray_irepeat, /* sq_inplace_repeat */ }; static PyMappingMethods bytearray_as_mapping = { (lenfunc)bytearray_length, (binaryfunc)bytearray_subscript, (objobjargproc)bytearray_ass_subscript, }; static PyBufferProcs bytearray_as_buffer = { (getbufferproc)bytearray_getbuffer, (releasebufferproc)bytearray_releasebuffer, }; static PyMethodDef bytearray_methods[] = { {"__alloc__", (PyCFunction)bytearray_alloc, METH_NOARGS, alloc_doc}, BYTEARRAY_REDUCE_METHODDEF BYTEARRAY_REDUCE_EX_METHODDEF BYTEARRAY_SIZEOF_METHODDEF BYTEARRAY_APPEND_METHODDEF {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS, _Py_capitalize__doc__}, {"center", (PyCFunction)stringlib_center, METH_VARARGS, _Py_center__doc__}, BYTEARRAY_CLEAR_METHODDEF BYTEARRAY_COPY_METHODDEF {"count", (PyCFunction)bytearray_count, METH_VARARGS, _Py_count__doc__}, BYTEARRAY_DECODE_METHODDEF {"endswith", (PyCFunction)bytearray_endswith, METH_VARARGS, _Py_endswith__doc__}, {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS, _Py_expandtabs__doc__}, BYTEARRAY_EXTEND_METHODDEF {"find", (PyCFunction)bytearray_find, METH_VARARGS, _Py_find__doc__}, BYTEARRAY_FROMHEX_METHODDEF {"hex", (PyCFunction)bytearray_hex, METH_NOARGS, hex__doc__}, {"index", (PyCFunction)bytearray_index, METH_VARARGS, _Py_index__doc__}, BYTEARRAY_INSERT_METHODDEF {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS, _Py_isalnum__doc__}, {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS, _Py_isalpha__doc__}, {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS, _Py_isdigit__doc__}, {"islower", (PyCFunction)stringlib_islower, METH_NOARGS, _Py_islower__doc__}, {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS, _Py_isspace__doc__}, {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS, _Py_istitle__doc__}, {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS, _Py_isupper__doc__}, BYTEARRAY_JOIN_METHODDEF {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, _Py_ljust__doc__}, {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, BYTEARRAY_LSTRIP_METHODDEF BYTEARRAY_MAKETRANS_METHODDEF BYTEARRAY_PARTITION_METHODDEF BYTEARRAY_POP_METHODDEF BYTEARRAY_REMOVE_METHODDEF BYTEARRAY_REPLACE_METHODDEF BYTEARRAY_REVERSE_METHODDEF {"rfind", (PyCFunction)bytearray_rfind, METH_VARARGS, _Py_rfind__doc__}, {"rindex", (PyCFunction)bytearray_rindex, METH_VARARGS, _Py_rindex__doc__}, {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, _Py_rjust__doc__}, BYTEARRAY_RPARTITION_METHODDEF BYTEARRAY_RSPLIT_METHODDEF BYTEARRAY_RSTRIP_METHODDEF BYTEARRAY_SPLIT_METHODDEF BYTEARRAY_SPLITLINES_METHODDEF {"startswith", (PyCFunction)bytearray_startswith, METH_VARARGS , _Py_startswith__doc__}, BYTEARRAY_STRIP_METHODDEF {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, _Py_swapcase__doc__}, {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, BYTEARRAY_TRANSLATE_METHODDEF {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, _Py_zfill__doc__}, {NULL} }; static PyObject * bytearray_mod(PyObject *v, PyObject *w) { if (!PyByteArray_Check(v)) Py_RETURN_NOTIMPLEMENTED; return _PyBytes_FormatEx(PyByteArray_AS_STRING(v), PyByteArray_GET_SIZE(v), w, 1); } static PyNumberMethods bytearray_as_number = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ bytearray_mod, /*nb_remainder*/ }; PyDoc_STRVAR(bytearray_doc, "bytearray(iterable_of_ints) -> bytearray\n\ bytearray(string, encoding[, errors]) -> bytearray\n\ bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer\n\ bytearray(int) -> bytes array of size given by the parameter initialized with null bytes\n\ bytearray() -> empty bytes array\n\ \n\ Construct a mutable bytearray object from:\n\ - an iterable yielding integers in range(256)\n\ - a text string encoded using the specified encoding\n\ - a bytes or a buffer object\n\ - any object implementing the buffer API.\n\ - an integer"); static PyObject *bytearray_iter(PyObject *seq); PyTypeObject PyByteArray_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "bytearray", sizeof(PyByteArrayObject), 0, (destructor)bytearray_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)bytearray_repr, /* tp_repr */ &bytearray_as_number, /* tp_as_number */ &bytearray_as_sequence, /* tp_as_sequence */ &bytearray_as_mapping, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ bytearray_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &bytearray_as_buffer, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ bytearray_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)bytearray_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ bytearray_iter, /* tp_iter */ 0, /* tp_iternext */ bytearray_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)bytearray_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_Del, /* tp_free */ }; /*********************** Bytes Iterator ****************************/ typedef struct { PyObject_HEAD Py_ssize_t it_index; PyByteArrayObject *it_seq; /* Set to NULL when iterator is exhausted */ } bytesiterobject; static void bytearrayiter_dealloc(bytesiterobject *it) { _PyObject_GC_UNTRACK(it); Py_XDECREF(it->it_seq); PyObject_GC_Del(it); } static int bytearrayiter_traverse(bytesiterobject *it, visitproc visit, void *arg) { Py_VISIT(it->it_seq); return 0; } static PyObject * bytearrayiter_next(bytesiterobject *it) { PyByteArrayObject *seq; PyObject *item; assert(it != NULL); seq = it->it_seq; if (seq == NULL) return NULL; assert(PyByteArray_Check(seq)); if (it->it_index < PyByteArray_GET_SIZE(seq)) { item = PyLong_FromLong( (unsigned char)PyByteArray_AS_STRING(seq)[it->it_index]); if (item != NULL) ++it->it_index; return item; } it->it_seq = NULL; Py_DECREF(seq); return NULL; } static PyObject * bytearrayiter_length_hint(bytesiterobject *it) { Py_ssize_t len = 0; if (it->it_seq) { len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index; if (len < 0) { len = 0; } } return PyLong_FromSsize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * bytearrayiter_reduce(bytesiterobject *it) { if (it->it_seq != NULL) { return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"), it->it_seq, it->it_index); } else { PyObject *u = PyUnicode_FromUnicode(NULL, 0); if (u == NULL) return NULL; return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u); } } static PyObject * bytearrayiter_setstate(bytesiterobject *it, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; if (it->it_seq != NULL) { if (index < 0) index = 0; else if (index > PyByteArray_GET_SIZE(it->it_seq)) index = PyByteArray_GET_SIZE(it->it_seq); /* iterator exhausted */ it->it_index = index; } Py_RETURN_NONE; } PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef bytearrayiter_methods[] = { {"__length_hint__", (PyCFunction)bytearrayiter_length_hint, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)bytearrayiter_reduce, METH_NOARGS, bytearray_reduce__doc__}, {"__setstate__", (PyCFunction)bytearrayiter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyByteArrayIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "bytearray_iterator", /* tp_name */ sizeof(bytesiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)bytearrayiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)bytearrayiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)bytearrayiter_next, /* tp_iternext */ bytearrayiter_methods, /* tp_methods */ 0, }; static PyObject * bytearray_iter(PyObject *seq) { bytesiterobject *it; if (!PyByteArray_Check(seq)) { PyErr_BadInternalCall(); return NULL; } it = PyObject_GC_New(bytesiterobject, &PyByteArrayIter_Type); if (it == NULL) return NULL; it->it_index = 0; Py_INCREF(seq); it->it_seq = (PyByteArrayObject *)seq; _PyObject_GC_TRACK(it); return (PyObject *)it; }
72,854
2,457
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/methodobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/structmember.h" /* clang-format off */ /* Free list for method objects to safe malloc/free overhead * The m_self element is used to chain the objects. */ static PyCFunctionObject *free_list = NULL; static int numfree = 0; #ifndef PyCFunction_MAXFREELIST #define PyCFunction_MAXFREELIST 256 #endif /* undefine macro trampoline to PyCFunction_NewEx */ #undef PyCFunction_New PyObject * PyCFunction_New(PyMethodDef *ml, PyObject *self) { return PyCFunction_NewEx(ml, self, NULL); } PyObject * PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module) { PyCFunctionObject *op; op = free_list; if (op != NULL) { free_list = (PyCFunctionObject *)(op->m_self); (void)PyObject_INIT(op, &PyCFunction_Type); numfree--; } else { op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type); if (op == NULL) return NULL; } op->m_weakreflist = NULL; op->m_ml = ml; Py_XINCREF(self); op->m_self = self; Py_XINCREF(module); op->m_module = module; _PyObject_GC_TRACK(op); return (PyObject *)op; } PyCFunction PyCFunction_GetFunction(PyObject *op) { if (!PyCFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return PyCFunction_GET_FUNCTION(op); } PyObject * PyCFunction_GetSelf(PyObject *op) { if (!PyCFunction_Check(op)) { PyErr_BadInternalCall(); return NULL; } return PyCFunction_GET_SELF(op); } int PyCFunction_GetFlags(PyObject *op) { if (!PyCFunction_Check(op)) { PyErr_BadInternalCall(); return -1; } return PyCFunction_GET_FLAGS(op); } /* Methods (the standard built-in methods, that is) */ static void meth_dealloc(PyCFunctionObject *m) { _PyObject_GC_UNTRACK(m); if (m->m_weakreflist != NULL) { PyObject_ClearWeakRefs((PyObject*) m); } Py_XDECREF(m->m_self); Py_XDECREF(m->m_module); if (numfree < PyCFunction_MAXFREELIST) { m->m_self = (PyObject *)free_list; free_list = m; numfree++; } else { PyObject_GC_Del(m); } } static PyObject * meth_reduce(PyCFunctionObject *m) { PyObject *builtins; PyObject *getattr; _Py_IDENTIFIER(getattr); if (m->m_self == NULL || PyModule_Check(m->m_self)) return PyUnicode_FromString(m->m_ml->ml_name); builtins = PyEval_GetBuiltins(); getattr = _PyDict_GetItemId(builtins, &PyId_getattr); return Py_BuildValue("O(Os)", getattr, m->m_self, m->m_ml->ml_name); } static PyMethodDef meth_methods[] = { {"__reduce__", (PyCFunction)meth_reduce, METH_NOARGS, NULL}, {NULL, NULL} }; static PyObject * meth_get__text_signature__(PyCFunctionObject *m, void *closure) { return _PyType_GetTextSignatureFromInternalDoc(m->m_ml->ml_name, m->m_ml->ml_doc); } static PyObject * meth_get__doc__(PyCFunctionObject *m, void *closure) { return _PyType_GetDocFromInternalDoc(m->m_ml->ml_name, m->m_ml->ml_doc); } static PyObject * meth_get__name__(PyCFunctionObject *m, void *closure) { return PyUnicode_FromString(m->m_ml->ml_name); } static PyObject * meth_get__qualname__(PyCFunctionObject *m, void *closure) { /* If __self__ is a module or NULL, return m.__name__ (e.g. len.__qualname__ == 'len') If __self__ is a type, return m.__self__.__qualname__ + '.' + m.__name__ (e.g. dict.fromkeys.__qualname__ == 'dict.fromkeys') Otherwise return type(m.__self__).__qualname__ + '.' + m.__name__ (e.g. [].append.__qualname__ == 'list.append') */ PyObject *type, *type_qualname, *res; _Py_IDENTIFIER(__qualname__); if (m->m_self == NULL || PyModule_Check(m->m_self)) return PyUnicode_FromString(m->m_ml->ml_name); type = PyType_Check(m->m_self) ? m->m_self : (PyObject*)Py_TYPE(m->m_self); type_qualname = _PyObject_GetAttrId(type, &PyId___qualname__); if (type_qualname == NULL) return NULL; if (!PyUnicode_Check(type_qualname)) { PyErr_SetString(PyExc_TypeError, "<method>.__class__." "__qualname__ is not a unicode object"); Py_XDECREF(type_qualname); return NULL; } res = PyUnicode_FromFormat("%S.%s", type_qualname, m->m_ml->ml_name); Py_DECREF(type_qualname); return res; } static int meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg) { Py_VISIT(m->m_self); Py_VISIT(m->m_module); return 0; } static PyObject * meth_get__self__(PyCFunctionObject *m, void *closure) { PyObject *self; self = PyCFunction_GET_SELF(m); if (self == NULL) self = Py_None; Py_INCREF(self); return self; } static PyGetSetDef meth_getsets [] = { {"__doc__", (getter)meth_get__doc__, NULL, NULL}, {"__name__", (getter)meth_get__name__, NULL, NULL}, {"__qualname__", (getter)meth_get__qualname__, NULL, NULL}, {"__self__", (getter)meth_get__self__, NULL, NULL}, {"__text_signature__", (getter)meth_get__text_signature__, NULL, NULL}, {0} }; #define OFF(x) offsetof(PyCFunctionObject, x) static PyMemberDef meth_members[] = { {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED}, {NULL} }; static PyObject * meth_repr(PyCFunctionObject *m) { if (m->m_self == NULL || PyModule_Check(m->m_self)) return PyUnicode_FromFormat("<built-in function %s>", m->m_ml->ml_name); return PyUnicode_FromFormat("<built-in method %s of %s object at %p>", m->m_ml->ml_name, m->m_self->ob_type->tp_name, m->m_self); } static PyObject * meth_richcompare(PyObject *self, PyObject *other, int op) { PyCFunctionObject *a, *b; PyObject *res; int eq; if ((op != Py_EQ && op != Py_NE) || !PyCFunction_Check(self) || !PyCFunction_Check(other)) { Py_RETURN_NOTIMPLEMENTED; } a = (PyCFunctionObject *)self; b = (PyCFunctionObject *)other; eq = a->m_self == b->m_self; if (eq) eq = a->m_ml->ml_meth == b->m_ml->ml_meth; if (op == Py_EQ) res = eq ? Py_True : Py_False; else res = eq ? Py_False : Py_True; Py_INCREF(res); return res; } static Py_hash_t meth_hash(PyCFunctionObject *a) { Py_hash_t x, y; if (a->m_self == NULL) x = 0; else { x = PyObject_Hash(a->m_self); if (x == -1) return -1; } y = _Py_HashPointer((void*)(a->m_ml->ml_meth)); if (y == -1) return -1; x ^= y; if (x == -1) x = -2; return x; } PyTypeObject PyCFunction_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "builtin_function_or_method", sizeof(PyCFunctionObject), 0, (destructor)meth_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)meth_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)meth_hash, /* tp_hash */ PyCFunction_Call, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)meth_traverse, /* tp_traverse */ 0, /* tp_clear */ meth_richcompare, /* tp_richcompare */ offsetof(PyCFunctionObject, m_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ meth_methods, /* tp_methods */ meth_members, /* tp_members */ meth_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ }; /* Clear out the free list */ int PyCFunction_ClearFreeList(void) { int freelist_size = numfree; while (free_list) { PyCFunctionObject *v = free_list; free_list = (PyCFunctionObject *)(v->m_self); PyObject_GC_Del(v); numfree--; } assert(numfree == 0); return freelist_size; } void PyCFunction_Fini(void) { (void)PyCFunction_ClearFreeList(); } /* Print summary info about the state of the optimized allocator */ void _PyCFunction_DebugMallocStats(FILE *out) { _PyDebugAllocatorStats(out, "free PyCFunctionObject", numfree, sizeof(PyCFunctionObject)); }
10,616
348
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/moduleobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ static Py_ssize_t max_module_number; typedef struct { PyObject_HEAD PyObject *md_dict; struct PyModuleDef *md_def; void *md_state; PyObject *md_weaklist; PyObject *md_name; /* for logging purposes after md_dict is cleared */ } PyModuleObject; static PyMemberDef module_members[] = { {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, {0} }; /* Helper for sanity check for traverse not handling m_state == NULL * Issue #32374 */ #ifdef Py_DEBUG static int bad_traverse_test(PyObject *self, void *arg) { assert(self != NULL); return 0; } #endif PyTypeObject PyModuleDef_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "moduledef", /* tp_name */ sizeof(struct PyModuleDef), /* tp_basicsize */ 0, /* tp_itemsize */ }; PyObject* PyModuleDef_Init(struct PyModuleDef* def) { if (PyType_Ready(&PyModuleDef_Type) < 0) return NULL; if (def->m_base.m_index == 0) { max_module_number++; Py_REFCNT(def) = 1; Py_TYPE(def) = &PyModuleDef_Type; def->m_base.m_index = max_module_number; } return (PyObject*)def; } static int module_init_dict(PyModuleObject *mod, PyObject *md_dict, PyObject *name, PyObject *doc) { _Py_IDENTIFIER(__name__); _Py_IDENTIFIER(__doc__); _Py_IDENTIFIER(__package__); _Py_IDENTIFIER(__loader__); _Py_IDENTIFIER(__spec__); if (md_dict == NULL) return -1; if (doc == NULL) doc = Py_None; if (_PyDict_SetItemId(md_dict, &PyId___name__, name) != 0) return -1; if (_PyDict_SetItemId(md_dict, &PyId___doc__, doc) != 0) return -1; if (_PyDict_SetItemId(md_dict, &PyId___package__, Py_None) != 0) return -1; if (_PyDict_SetItemId(md_dict, &PyId___loader__, Py_None) != 0) return -1; if (_PyDict_SetItemId(md_dict, &PyId___spec__, Py_None) != 0) return -1; if (PyUnicode_CheckExact(name)) { Py_INCREF(name); Py_XSETREF(mod->md_name, name); } return 0; } PyObject * PyModule_NewObject(PyObject *name) { PyModuleObject *m; m = PyObject_GC_New(PyModuleObject, &PyModule_Type); if (m == NULL) return NULL; m->md_def = NULL; m->md_state = NULL; m->md_weaklist = NULL; m->md_name = NULL; m->md_dict = PyDict_New(); if (module_init_dict(m, m->md_dict, name, NULL) != 0) goto fail; PyObject_GC_Track(m); return (PyObject *)m; fail: Py_DECREF(m); return NULL; } PyObject * PyModule_New(const char *name) { PyObject *nameobj, *module; nameobj = PyUnicode_FromString(name); if (nameobj == NULL) return NULL; module = PyModule_NewObject(nameobj); Py_DECREF(nameobj); return module; } /* Check API/ABI version * Issues a warning on mismatch, which is usually not fatal. * Returns 0 if an exception is raised. */ static int check_api_version(const char *name, int module_api_version) { if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) { int err; err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "Python C API version mismatch for module %.100s: " "This Python has API version %d, module %.100s has version %d.", name, PYTHON_API_VERSION, name, module_api_version); if (err) return 0; } return 1; } static int _add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions) { PyObject *func; PyMethodDef *fdef; for (fdef = functions; fdef->ml_name != NULL; fdef++) { if ((fdef->ml_flags & METH_CLASS) || (fdef->ml_flags & METH_STATIC)) { PyErr_SetString(PyExc_ValueError, "module functions cannot set" " METH_CLASS or METH_STATIC"); return -1; } func = PyCFunction_NewEx(fdef, (PyObject*)module, name); if (func == NULL) { return -1; } if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) { Py_DECREF(func); return -1; } Py_DECREF(func); } return 0; } PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { const char* name; PyModuleObject *m; PyInterpreterState *interp = PyThreadState_Get()->interp; if (interp->modules == NULL) Py_FatalError("Python import machinery not initialized"); if (!PyModuleDef_Init(module)) return NULL; name = module->m_name; if (!check_api_version(name, module_api_version)) { return NULL; } if (module->m_slots) { PyErr_Format( PyExc_SystemError, "module %s: PyModule_Create is incompatible with m_slots", name); return NULL; } /* Make sure name is fully qualified. This is a bit of a hack: when the shared library is loaded, the module name is "package.module", but the module calls PyModule_Create*() with just "module" for the name. The shared library loader squirrels away the true name of the module in _Py_PackageContext, and PyModule_Create*() will substitute this (if the name actually matches). */ if (_Py_PackageContext != NULL) { char *p = strrchr(_Py_PackageContext, '.'); if (p != NULL && strcmp(module->m_name, p+1) == 0) { name = _Py_PackageContext; _Py_PackageContext = NULL; } } if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) return NULL; if (module->m_size > 0) { m->md_state = PyMem_MALLOC(module->m_size); if (!m->md_state) { PyErr_NoMemory(); Py_DECREF(m); return NULL; } bzero(m->md_state, module->m_size); } if (module->m_methods != NULL) { if (PyModule_AddFunctions((PyObject *) m, module->m_methods) != 0) { Py_DECREF(m); return NULL; } } if (module->m_doc != NULL) { if (PyModule_SetDocString((PyObject *) m, module->m_doc) != 0) { Py_DECREF(m); return NULL; } } m->md_def = module; return (PyObject*)m; } PyObject * PyModule_FromDefAndSpec2(struct PyModuleDef* def, PyObject *spec, int module_api_version) { PyModuleDef_Slot* cur_slot; PyObject *(*create)(PyObject *, PyModuleDef*) = NULL; PyObject *nameobj; PyObject *m = NULL; int has_execution_slots = 0; char *name; int ret; PyModuleDef_Init(def); nameobj = PyObject_GetAttrString(spec, "name"); if (nameobj == NULL) { return NULL; } name = PyUnicode_AsUTF8(nameobj); if (name == NULL) { goto error; } if (!check_api_version(name, module_api_version)) { goto error; } if (def->m_size < 0) { PyErr_Format( PyExc_SystemError, "module %s: m_size may not be negative for multi-phase initialization", name); goto error; } for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) { if (cur_slot->slot == Py_mod_create) { if (create) { PyErr_Format( PyExc_SystemError, "module %s has multiple create slots", name); goto error; } create = cur_slot->value; } else if (cur_slot->slot < 0 || cur_slot->slot > _Py_mod_LAST_SLOT) { PyErr_Format( PyExc_SystemError, "module %s uses unknown slot ID %i", name, cur_slot->slot); goto error; } else { has_execution_slots = 1; } } if (create) { m = create(spec, def); if (m == NULL) { if (!PyErr_Occurred()) { PyErr_Format( PyExc_SystemError, "creation of module %s failed without setting an exception", name); } goto error; } else { if (PyErr_Occurred()) { PyErr_Format(PyExc_SystemError, "creation of module %s raised unreported exception", name); goto error; } } } else { m = PyModule_NewObject(nameobj); if (m == NULL) { goto error; } } if (PyModule_Check(m)) { ((PyModuleObject*)m)->md_state = NULL; ((PyModuleObject*)m)->md_def = def; } else { if (def->m_size > 0 || def->m_traverse || def->m_clear || def->m_free) { PyErr_Format( PyExc_SystemError, "module %s is not a module object, but requests module state", name); goto error; } if (has_execution_slots) { PyErr_Format( PyExc_SystemError, "module %s specifies execution slots, but did not create " "a ModuleType instance", name); goto error; } } if (def->m_methods != NULL) { ret = _add_methods_to_object(m, nameobj, def->m_methods); if (ret != 0) { goto error; } } if (def->m_doc != NULL) { ret = PyModule_SetDocString(m, def->m_doc); if (ret != 0) { goto error; } } /* Sanity check for traverse not handling m_state == NULL * This doesn't catch all possible cases, but in many cases it should * make many cases of invalid code crash or raise Valgrind issues * sooner than they would otherwise. * Issue #32374 */ #ifdef Py_DEBUG if (def->m_traverse != NULL) { def->m_traverse(m, bad_traverse_test, NULL); } #endif Py_DECREF(nameobj); return m; error: Py_DECREF(nameobj); Py_XDECREF(m); return NULL; } int PyModule_ExecDef(PyObject *module, PyModuleDef *def) { PyModuleDef_Slot *cur_slot; const char *name; int ret; name = PyModule_GetName(module); if (name == NULL) { return -1; } if (def->m_size >= 0) { PyModuleObject *md = (PyModuleObject*)module; if (md->md_state == NULL) { /* Always set a state pointer; this serves as a marker to skip * multiple initialization (importlib.reload() is no-op) */ md->md_state = PyMem_MALLOC(def->m_size); if (!md->md_state) { PyErr_NoMemory(); return -1; } bzero(md->md_state, def->m_size); } } if (def->m_slots == NULL) { return 0; } for (cur_slot = def->m_slots; cur_slot && cur_slot->slot; cur_slot++) { switch (cur_slot->slot) { case Py_mod_create: /* handled in PyModule_FromDefAndSpec2 */ break; case Py_mod_exec: ret = ((int (*)(PyObject *))cur_slot->value)(module); if (ret != 0) { if (!PyErr_Occurred()) { PyErr_Format( PyExc_SystemError, "execution of module %s failed without setting an exception", name); } return -1; } if (PyErr_Occurred()) { PyErr_Format( PyExc_SystemError, "execution of module %s raised unreported exception", name); return -1; } break; default: PyErr_Format( PyExc_SystemError, "module %s initialized with unknown slot %i", name, cur_slot->slot); return -1; } } return 0; } int PyModule_AddFunctions(PyObject *m, PyMethodDef *functions) { int res; PyObject *name = PyModule_GetNameObject(m); if (name == NULL) { return -1; } res = _add_methods_to_object(m, name, functions); Py_DECREF(name); return res; } int PyModule_SetDocString(PyObject *m, const char *doc) { PyObject *v; _Py_IDENTIFIER(__doc__); v = PyUnicode_FromString(doc); if (v == NULL || _PyObject_SetAttrId(m, &PyId___doc__, v) != 0) { Py_XDECREF(v); return -1; } Py_DECREF(v); return 0; } PyObject * PyModule_GetDict(PyObject *m) { PyObject *d; if (!PyModule_Check(m)) { PyErr_BadInternalCall(); return NULL; } d = ((PyModuleObject *)m) -> md_dict; assert(d != NULL); return d; } PyObject* PyModule_GetNameObject(PyObject *m) { _Py_IDENTIFIER(__name__); PyObject *d; PyObject *name; if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } d = ((PyModuleObject *)m)->md_dict; if (d == NULL || (name = _PyDict_GetItemId(d, &PyId___name__)) == NULL || !PyUnicode_Check(name)) { PyErr_SetString(PyExc_SystemError, "nameless module"); return NULL; } Py_INCREF(name); return name; } const char * PyModule_GetName(PyObject *m) { PyObject *name = PyModule_GetNameObject(m); if (name == NULL) return NULL; Py_DECREF(name); /* module dict has still a reference */ return PyUnicode_AsUTF8(name); } PyObject* PyModule_GetFilenameObject(PyObject *m) { _Py_IDENTIFIER(__file__); PyObject *d; PyObject *fileobj; if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } d = ((PyModuleObject *)m)->md_dict; if (d == NULL || (fileobj = _PyDict_GetItemId(d, &PyId___file__)) == NULL || !PyUnicode_Check(fileobj)) { PyErr_SetString(PyExc_SystemError, "module filename missing"); return NULL; } Py_INCREF(fileobj); return fileobj; } const char * PyModule_GetFilename(PyObject *m) { PyObject *fileobj; char *utf8; fileobj = PyModule_GetFilenameObject(m); if (fileobj == NULL) return NULL; utf8 = PyUnicode_AsUTF8(fileobj); Py_DECREF(fileobj); /* module dict has still a reference */ return utf8; } PyModuleDef* PyModule_GetDef(PyObject* m) { if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } return ((PyModuleObject *)m)->md_def; } void* PyModule_GetState(PyObject* m) { if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } return ((PyModuleObject *)m)->md_state; } void _PyModule_Clear(PyObject *m) { PyObject *d = ((PyModuleObject *)m)->md_dict; if (d != NULL) _PyModule_ClearDict(d); } void _PyModule_ClearDict(PyObject *d) { /* To make the execution order of destructors for global objects a bit more predictable, we first zap all objects whose name starts with a single underscore, before we clear the entire dictionary. We zap them by replacing them with None, rather than deleting them from the dictionary, to avoid rehashing the dictionary (to some extent). */ Py_ssize_t pos; PyObject *key, *value; /* First, clear only names starting with a single underscore */ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { if (PyUnicode_READ_CHAR(key, 0) == '_' && PyUnicode_READ_CHAR(key, 1) != '_') { if (Py_VerboseFlag > 1) { const char *s = PyUnicode_AsUTF8(key); if (s != NULL) PySys_WriteStderr("# clear[1] %s\n", s); else PyErr_Clear(); } if (PyDict_SetItem(d, key, Py_None) != 0) PyErr_Clear(); } } } /* Next, clear all names except for __builtins__ */ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyUnicode_Check(key)) { if (PyUnicode_READ_CHAR(key, 0) != '_' || !_PyUnicode_EqualToASCIIString(key, "__builtins__")) { if (Py_VerboseFlag > 1) { const char *s = PyUnicode_AsUTF8(key); if (s != NULL) PySys_WriteStderr("# clear[2] %s\n", s); else PyErr_Clear(); } if (PyDict_SetItem(d, key, Py_None) != 0) PyErr_Clear(); } } } /* Note: we leave __builtins__ in place, so that destructors of non-global objects defined in this module can still use builtins, in particularly 'None'. */ } /* Methods */ static int module_init(PyModuleObject *m, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"name", "doc", NULL}; PyObject *dict, *name = Py_None, *doc = Py_None; if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__", kwlist, &name, &doc)) return -1; dict = m->md_dict; if (dict == NULL) { dict = PyDict_New(); if (dict == NULL) return -1; m->md_dict = dict; } if (module_init_dict(m, dict, name, doc) < 0) return -1; return 0; } static void module_dealloc(PyModuleObject *m) { PyObject_GC_UnTrack(m); if (Py_VerboseFlag && m->md_name) { PySys_FormatStderr("# destroy %S\n", m->md_name); } if (m->md_weaklist != NULL) PyObject_ClearWeakRefs((PyObject *) m); if (m->md_def && m->md_def->m_free) m->md_def->m_free(m); Py_XDECREF(m->md_dict); Py_XDECREF(m->md_name); if (m->md_state != NULL) PyMem_FREE(m->md_state); Py_TYPE(m)->tp_free((PyObject *)m); } static PyObject * module_repr(PyModuleObject *m) { PyThreadState *tstate = PyThreadState_GET(); PyInterpreterState *interp = tstate->interp; return PyObject_CallMethod(interp->importlib, "_module_repr", "O", m); } static PyObject* module_getattro(PyModuleObject *m, PyObject *name) { PyObject *attr, *mod_name; attr = PyObject_GenericGetAttr((PyObject *)m, name); if (attr || !PyErr_ExceptionMatches(PyExc_AttributeError)) return attr; PyErr_Clear(); if (m->md_dict) { _Py_IDENTIFIER(__name__); mod_name = _PyDict_GetItemId(m->md_dict, &PyId___name__); if (mod_name && PyUnicode_Check(mod_name)) { PyErr_Format(PyExc_AttributeError, "module '%U' has no attribute '%U'", mod_name, name); return NULL; } } PyErr_Format(PyExc_AttributeError, "module has no attribute '%U'", name); return NULL; } static int module_traverse(PyModuleObject *m, visitproc visit, void *arg) { if (m->md_def && m->md_def->m_traverse) { int res = m->md_def->m_traverse((PyObject*)m, visit, arg); if (res) return res; } Py_VISIT(m->md_dict); return 0; } static int module_clear(PyModuleObject *m) { if (m->md_def && m->md_def->m_clear) { int res = m->md_def->m_clear((PyObject*)m); if (res) return res; } Py_CLEAR(m->md_dict); return 0; } static PyObject * module_dir(PyObject *self, PyObject *args) { _Py_IDENTIFIER(__dict__); PyObject *result = NULL; PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__); if (dict != NULL) { if (PyDict_Check(dict)) result = PyDict_Keys(dict); else { const char *name = PyModule_GetName(self); if (name) PyErr_Format(PyExc_TypeError, "%.200s.__dict__ is not a dictionary", name); } } Py_XDECREF(dict); return result; } static PyMethodDef module_methods[] = { {"__dir__", module_dir, METH_NOARGS, PyDoc_STR("__dir__() -> list\nspecialized dir() implementation")}, {0} }; PyDoc_STRVAR(module_doc, "module(name[, doc])\n\ \n\ Create a module object.\n\ The name must be a string; the optional doc argument can have any type."); PyTypeObject PyModule_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "module", /* tp_name */ sizeof(PyModuleObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)module_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)module_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ (getattrofunc)module_getattro, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ module_doc, /* tp_doc */ (traverseproc)module_traverse, /* tp_traverse */ (inquiry)module_clear, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyModuleObject, md_weaklist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ module_methods, /* tp_methods */ module_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ (initproc)module_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ };
24,584
819
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/classobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/classobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/structmember.h" /* clang-format off */ /* Class object implementation (dead now except for methods) */ #define TP_DESCR_GET(t) ((t)->tp_descr_get) /* Free list for method objects to safe malloc/free overhead * The im_self element is used to chain the elements. */ static PyMethodObject *free_list; static int numfree = 0; #ifndef PyMethod_MAXFREELIST #define PyMethod_MAXFREELIST 256 #endif _Py_IDENTIFIER(__name__); _Py_IDENTIFIER(__qualname__); PyObject * PyMethod_Function(PyObject *im) { if (!PyMethod_Check(im)) { PyErr_BadInternalCall(); return NULL; } return ((PyMethodObject *)im)->im_func; } PyObject * PyMethod_Self(PyObject *im) { if (!PyMethod_Check(im)) { PyErr_BadInternalCall(); return NULL; } return ((PyMethodObject *)im)->im_self; } /* Method objects are used for bound instance methods returned by instancename.methodname. ClassName.methodname returns an ordinary function. */ PyObject * PyMethod_New(PyObject *func, PyObject *self) { PyMethodObject *im; if (self == NULL) { PyErr_BadInternalCall(); return NULL; } im = free_list; if (im != NULL) { free_list = (PyMethodObject *)(im->im_self); (void)PyObject_INIT(im, &PyMethod_Type); numfree--; } else { im = PyObject_GC_New(PyMethodObject, &PyMethod_Type); if (im == NULL) return NULL; } im->im_weakreflist = NULL; Py_INCREF(func); im->im_func = func; Py_XINCREF(self); im->im_self = self; _PyObject_GC_TRACK(im); return (PyObject *)im; } static PyObject * method_reduce(PyMethodObject *im) { PyObject *self = PyMethod_GET_SELF(im); PyObject *func = PyMethod_GET_FUNCTION(im); PyObject *funcname; _Py_IDENTIFIER(getattr); funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { return NULL; } return Py_BuildValue("N(ON)", _PyEval_GetBuiltinId(&PyId_getattr), self, funcname); } static PyMethodDef method_methods[] = { {"__reduce__", (PyCFunction)method_reduce, METH_NOARGS, NULL}, {NULL, NULL} }; /* Descriptors for PyMethod attributes */ /* im_func and im_self are stored in the PyMethod object */ #define MO_OFF(x) offsetof(PyMethodObject, x) static PyMemberDef method_memberlist[] = { {"__func__", T_OBJECT, MO_OFF(im_func), READONLY|RESTRICTED, "the function (or other callable) implementing a method"}, {"__self__", T_OBJECT, MO_OFF(im_self), READONLY|RESTRICTED, "the instance to which a method is bound"}, {NULL} /* Sentinel */ }; /* Christian Tismer argued convincingly that method attributes should (nearly) always override function attributes. The one exception is __doc__; there's a default __doc__ which should only be used for the class, not for instances */ static PyObject * method_get_doc(PyMethodObject *im, void *context) { static PyObject *docstr; if (docstr == NULL) { docstr= PyUnicode_InternFromString("__doc__"); if (docstr == NULL) return NULL; } return PyObject_GetAttr(im->im_func, docstr); } static PyGetSetDef method_getset[] = { {"__doc__", (getter)method_get_doc, NULL, NULL}, {0} }; static PyObject * method_getattro(PyObject *obj, PyObject *name) { PyMethodObject *im = (PyMethodObject *)obj; PyTypeObject *tp = obj->ob_type; PyObject *descr = NULL; { if (tp->tp_dict == NULL) { if (PyType_Ready(tp) < 0) return NULL; } descr = _PyType_Lookup(tp, name); } if (descr != NULL) { descrgetfunc f = TP_DESCR_GET(descr->ob_type); if (f != NULL) return f(descr, obj, (PyObject *)obj->ob_type); else { Py_INCREF(descr); return descr; } } return PyObject_GetAttr(im->im_func, name); } PyDoc_STRVAR(method_doc, "method(function, instance)\n\ \n\ Create a bound instance method object."); static PyObject * method_new(PyTypeObject* type, PyObject* args, PyObject *kw) { PyObject *func; PyObject *self; if (!_PyArg_NoKeywords("method", kw)) return NULL; if (!PyArg_UnpackTuple(args, "method", 2, 2, &func, &self)) return NULL; if (!PyCallable_Check(func)) { PyErr_SetString(PyExc_TypeError, "first argument must be callable"); return NULL; } if (self == NULL || self == Py_None) { PyErr_SetString(PyExc_TypeError, "self must not be None"); return NULL; } return PyMethod_New(func, self); } static void method_dealloc(PyMethodObject *im) { _PyObject_GC_UNTRACK(im); if (im->im_weakreflist != NULL) PyObject_ClearWeakRefs((PyObject *)im); Py_DECREF(im->im_func); Py_XDECREF(im->im_self); if (numfree < PyMethod_MAXFREELIST) { im->im_self = (PyObject *)free_list; free_list = im; numfree++; } else { PyObject_GC_Del(im); } } static PyObject * method_richcompare(PyObject *self, PyObject *other, int op) { PyMethodObject *a, *b; PyObject *res; int eq; if ((op != Py_EQ && op != Py_NE) || !PyMethod_Check(self) || !PyMethod_Check(other)) { Py_RETURN_NOTIMPLEMENTED; } a = (PyMethodObject *)self; b = (PyMethodObject *)other; eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ); if (eq == 1) { if (a->im_self == NULL || b->im_self == NULL) eq = a->im_self == b->im_self; else eq = PyObject_RichCompareBool(a->im_self, b->im_self, Py_EQ); } if (eq < 0) return NULL; if (op == Py_EQ) res = eq ? Py_True : Py_False; else res = eq ? Py_False : Py_True; Py_INCREF(res); return res; } static PyObject * method_repr(PyMethodObject *a) { PyObject *self = a->im_self; PyObject *func = a->im_func; PyObject *funcname = NULL, *result = NULL; const char *defname = "?"; funcname = _PyObject_GetAttrId(func, &PyId___qualname__); if (funcname == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); } } if (funcname != NULL && !PyUnicode_Check(funcname)) { Py_DECREF(funcname); funcname = NULL; } /* XXX Shouldn't use repr()/%R here! */ result = PyUnicode_FromFormat("<bound method %V of %R>", funcname, defname, self); Py_XDECREF(funcname); return result; } static Py_hash_t method_hash(PyMethodObject *a) { Py_hash_t x, y; if (a->im_self == NULL) x = PyObject_Hash(Py_None); else x = PyObject_Hash(a->im_self); if (x == -1) return -1; y = PyObject_Hash(a->im_func); if (y == -1) return -1; x = x ^ y; if (x == -1) x = -2; return x; } static int method_traverse(PyMethodObject *im, visitproc visit, void *arg) { Py_VISIT(im->im_func); Py_VISIT(im->im_self); return 0; } static PyObject * method_call(PyObject *method, PyObject *args, PyObject *kwargs) { PyObject *self, *func; self = PyMethod_GET_SELF(method); if (self == NULL) { PyErr_BadInternalCall(); return NULL; } func = PyMethod_GET_FUNCTION(method); return _PyObject_Call_Prepend(func, self, args, kwargs); } static PyObject * method_descr_get(PyObject *meth, PyObject *obj, PyObject *cls) { /* Don't rebind an already bound method of a class that's not a base class of cls. */ if (PyMethod_GET_SELF(meth) != NULL) { /* Already bound */ Py_INCREF(meth); return meth; } /* Bind it to obj */ return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj); } PyTypeObject PyMethod_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "method", sizeof(PyMethodObject), 0, (destructor)method_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)method_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)method_hash, /* tp_hash */ method_call, /* tp_call */ 0, /* tp_str */ method_getattro, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ method_doc, /* tp_doc */ (traverseproc)method_traverse, /* tp_traverse */ 0, /* tp_clear */ method_richcompare, /* tp_richcompare */ offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ method_methods, /* tp_methods */ method_memberlist, /* tp_members */ method_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ method_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ method_new, /* tp_new */ }; /* Clear out the free list */ int PyMethod_ClearFreeList(void) { int freelist_size = numfree; while (free_list) { PyMethodObject *im = free_list; free_list = (PyMethodObject *)(im->im_self); PyObject_GC_Del(im); numfree--; } assert(numfree == 0); return freelist_size; } void PyMethod_Fini(void) { (void)PyMethod_ClearFreeList(); } /* Print summary info about the state of the optimized allocator */ void _PyMethod_DebugMallocStats(FILE *out) { _PyDebugAllocatorStats(out, "free PyMethodObject", numfree, sizeof(PyMethodObject)); } /* ------------------------------------------------------------------------ * instance method */ PyObject * PyInstanceMethod_New(PyObject *func) { PyInstanceMethodObject *method; method = PyObject_GC_New(PyInstanceMethodObject, &PyInstanceMethod_Type); if (method == NULL) return NULL; Py_INCREF(func); method->func = func; _PyObject_GC_TRACK(method); return (PyObject *)method; } PyObject * PyInstanceMethod_Function(PyObject *im) { if (!PyInstanceMethod_Check(im)) { PyErr_BadInternalCall(); return NULL; } return PyInstanceMethod_GET_FUNCTION(im); } #define IMO_OFF(x) offsetof(PyInstanceMethodObject, x) static PyMemberDef instancemethod_memberlist[] = { {"__func__", T_OBJECT, IMO_OFF(func), READONLY|RESTRICTED, "the function (or other callable) implementing a method"}, {NULL} /* Sentinel */ }; static PyObject * instancemethod_get_doc(PyObject *self, void *context) { static PyObject *docstr; if (docstr == NULL) { docstr = PyUnicode_InternFromString("__doc__"); if (docstr == NULL) return NULL; } return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), docstr); } static PyGetSetDef instancemethod_getset[] = { {"__doc__", (getter)instancemethod_get_doc, NULL, NULL}, {0} }; static PyObject * instancemethod_getattro(PyObject *self, PyObject *name) { PyTypeObject *tp = self->ob_type; PyObject *descr = NULL; if (tp->tp_dict == NULL) { if (PyType_Ready(tp) < 0) return NULL; } descr = _PyType_Lookup(tp, name); if (descr != NULL) { descrgetfunc f = TP_DESCR_GET(descr->ob_type); if (f != NULL) return f(descr, self, (PyObject *)self->ob_type); else { Py_INCREF(descr); return descr; } } return PyObject_GetAttr(PyInstanceMethod_GET_FUNCTION(self), name); } static void instancemethod_dealloc(PyObject *self) { _PyObject_GC_UNTRACK(self); Py_DECREF(PyInstanceMethod_GET_FUNCTION(self)); PyObject_GC_Del(self); } static int instancemethod_traverse(PyObject *self, visitproc visit, void *arg) { Py_VISIT(PyInstanceMethod_GET_FUNCTION(self)); return 0; } static PyObject * instancemethod_call(PyObject *self, PyObject *arg, PyObject *kw) { return PyObject_Call(PyMethod_GET_FUNCTION(self), arg, kw); } static PyObject * instancemethod_descr_get(PyObject *descr, PyObject *obj, PyObject *type) { PyObject *func = PyInstanceMethod_GET_FUNCTION(descr); if (obj == NULL) { Py_INCREF(func); return func; } else return PyMethod_New(func, obj); } static PyObject * instancemethod_richcompare(PyObject *self, PyObject *other, int op) { PyInstanceMethodObject *a, *b; PyObject *res; int eq; if ((op != Py_EQ && op != Py_NE) || !PyInstanceMethod_Check(self) || !PyInstanceMethod_Check(other)) { Py_RETURN_NOTIMPLEMENTED; } a = (PyInstanceMethodObject *)self; b = (PyInstanceMethodObject *)other; eq = PyObject_RichCompareBool(a->func, b->func, Py_EQ); if (eq < 0) return NULL; if (op == Py_EQ) res = eq ? Py_True : Py_False; else res = eq ? Py_False : Py_True; Py_INCREF(res); return res; } static PyObject * instancemethod_repr(PyObject *self) { PyObject *func = PyInstanceMethod_Function(self); PyObject *funcname = NULL , *result = NULL; char *defname = "?"; if (func == NULL) { PyErr_BadInternalCall(); return NULL; } funcname = _PyObject_GetAttrId(func, &PyId___name__); if (funcname == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) return NULL; PyErr_Clear(); } else if (!PyUnicode_Check(funcname)) { Py_DECREF(funcname); funcname = NULL; } result = PyUnicode_FromFormat("<instancemethod %V at %p>", funcname, defname, self); Py_XDECREF(funcname); return result; } /* static long instancemethod_hash(PyObject *self) { long x, y; x = (long)self; y = PyObject_Hash(PyInstanceMethod_GET_FUNCTION(self)); if (y == -1) return -1; x = x ^ y; if (x == -1) x = -2; return x; } */ PyDoc_STRVAR(instancemethod_doc, "instancemethod(function)\n\ \n\ Bind a function to a class."); static PyObject * instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw) { PyObject *func; if (!_PyArg_NoKeywords("instancemethod", kw)) return NULL; if (!PyArg_UnpackTuple(args, "instancemethod", 1, 1, &func)) return NULL; if (!PyCallable_Check(func)) { PyErr_SetString(PyExc_TypeError, "first argument must be callable"); return NULL; } return PyInstanceMethod_New(func); } PyTypeObject PyInstanceMethod_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "instancemethod", /* tp_name */ sizeof(PyInstanceMethodObject), /* tp_basicsize */ 0, /* tp_itemsize */ instancemethod_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)instancemethod_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /*(hashfunc)instancemethod_hash, tp_hash */ instancemethod_call, /* tp_call */ 0, /* tp_str */ instancemethod_getattro, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ instancemethod_doc, /* tp_doc */ instancemethod_traverse, /* tp_traverse */ 0, /* tp_clear */ instancemethod_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ instancemethod_memberlist, /* tp_members */ instancemethod_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ instancemethod_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ instancemethod_new, /* tp_new */ };
19,931
663
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/genobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/genobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/opcode.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ static PyObject *gen_close(PyGenObject *, PyObject *); static PyObject *async_gen_asend_new(PyAsyncGenObject *, PyObject *); static PyObject *async_gen_athrow_new(PyAsyncGenObject *, PyObject *); static char *NON_INIT_CORO_MSG = "can't send non-None value to a " "just-started coroutine"; static char *ASYNC_GEN_IGNORED_EXIT_MSG = "async generator ignored GeneratorExit"; static int gen_traverse(PyGenObject *gen, visitproc visit, void *arg) { Py_VISIT((PyObject *)gen->gi_frame); Py_VISIT(gen->gi_code); Py_VISIT(gen->gi_name); Py_VISIT(gen->gi_qualname); return 0; } void _PyGen_Finalize(PyObject *self) { PyGenObject *gen = (PyGenObject *)self; PyObject *res = NULL; PyObject *error_type, *error_value, *error_traceback; if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL) /* Generator isn't paused, so no need to close */ return; if (PyAsyncGen_CheckExact(self)) { PyAsyncGenObject *agen = (PyAsyncGenObject*)self; PyObject *finalizer = agen->ag_finalizer; if (finalizer && !agen->ag_closed) { /* Save the current exception, if any. */ PyErr_Fetch(&error_type, &error_value, &error_traceback); res = PyObject_CallFunctionObjArgs(finalizer, self, NULL); if (res == NULL) { PyErr_WriteUnraisable(self); } else { Py_DECREF(res); } /* Restore the saved exception. */ PyErr_Restore(error_type, error_value, error_traceback); return; } } /* Save the current exception, if any. */ PyErr_Fetch(&error_type, &error_value, &error_traceback); /* If `gen` is a coroutine, and if it was never awaited on, issue a RuntimeWarning. */ if (gen->gi_code != NULL && ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE && gen->gi_frame->f_lasti == -1) { if (!error_value) { PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname); } } else { res = gen_close(gen, NULL); } if (res == NULL) { if (PyErr_Occurred()) PyErr_WriteUnraisable(self); } else { Py_DECREF(res); } /* Restore the saved exception. */ PyErr_Restore(error_type, error_value, error_traceback); } static void gen_dealloc(PyGenObject *gen) { PyObject *self = (PyObject *) gen; _PyObject_GC_UNTRACK(gen); if (gen->gi_weakreflist != NULL) PyObject_ClearWeakRefs(self); _PyObject_GC_TRACK(self); if (PyObject_CallFinalizerFromDealloc(self)) return; /* resurrected. :( */ _PyObject_GC_UNTRACK(self); if (PyAsyncGen_CheckExact(gen)) { /* We have to handle this case for asynchronous generators right here, because this code has to be between UNTRACK and GC_Del. */ Py_CLEAR(((PyAsyncGenObject*)gen)->ag_finalizer); } if (gen->gi_frame != NULL) { gen->gi_frame->f_gen = NULL; Py_CLEAR(gen->gi_frame); } Py_CLEAR(gen->gi_code); Py_CLEAR(gen->gi_name); Py_CLEAR(gen->gi_qualname); PyObject_GC_Del(gen); } static PyObject * gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing) { PyThreadState *tstate = PyThreadState_GET(); PyFrameObject *f = gen->gi_frame; PyObject *result; if (gen->gi_running) { char *msg = "generator already executing"; if (PyCoro_CheckExact(gen)) { msg = "coroutine already executing"; } else if (PyAsyncGen_CheckExact(gen)) { msg = "async generator already executing"; } PyErr_SetString(PyExc_ValueError, msg); return NULL; } if (f == NULL || f->f_stacktop == NULL) { if (PyCoro_CheckExact(gen) && !closing) { /* `gen` is an exhausted coroutine: raise an error, except when called from gen_close(), which should always be a silent method. */ PyErr_SetString( PyExc_RuntimeError, "cannot reuse already awaited coroutine"); } else if (arg && !exc) { /* `gen` is an exhausted generator: only set exception if called from send(). */ if (PyAsyncGen_CheckExact(gen)) { PyErr_SetNone(PyExc_StopAsyncIteration); } else { PyErr_SetNone(PyExc_StopIteration); } } return NULL; } if (f->f_lasti == -1) { if (arg && arg != Py_None) { char *msg = "can't send non-None value to a " "just-started generator"; if (PyCoro_CheckExact(gen)) { msg = NON_INIT_CORO_MSG; } else if (PyAsyncGen_CheckExact(gen)) { msg = "can't send non-None value to a " "just-started async generator"; } PyErr_SetString(PyExc_TypeError, msg); return NULL; } } else { /* Push arg onto the frame's value stack */ result = arg ? arg : Py_None; Py_INCREF(result); *(f->f_stacktop++) = result; } /* Generators always return to their most recent caller, not * necessarily their creator. */ Py_XINCREF(tstate->frame); assert(f->f_back == NULL); f->f_back = tstate->frame; gen->gi_running = 1; result = PyEval_EvalFrameEx(f, exc); gen->gi_running = 0; /* Don't keep the reference to f_back any longer than necessary. It * may keep a chain of frames alive or it could create a reference * cycle. */ assert(f->f_back == tstate->frame); Py_CLEAR(f->f_back); /* If the generator just returned (as opposed to yielding), signal * that the generator is exhausted. */ if (result && f->f_stacktop == NULL) { if (result == Py_None) { /* Delay exception instantiation if we can */ if (PyAsyncGen_CheckExact(gen)) { PyErr_SetNone(PyExc_StopAsyncIteration); } else { PyErr_SetNone(PyExc_StopIteration); } } else { /* Async generators cannot return anything but None */ assert(!PyAsyncGen_CheckExact(gen)); _PyGen_SetStopIterationValue(result); } Py_CLEAR(result); } else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) { /* Check for __future__ generator_stop and conditionally turn * a leaking StopIteration into RuntimeError (with its cause * set appropriately). */ const int check_stop_iter_error_flags = CO_FUTURE_GENERATOR_STOP | CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR; if (gen->gi_code != NULL && ((PyCodeObject *)gen->gi_code)->co_flags & check_stop_iter_error_flags) { /* `gen` is either: * a generator with CO_FUTURE_GENERATOR_STOP flag; * a coroutine; * a generator with CO_ITERABLE_COROUTINE flag (decorated with types.coroutine decorator); * an async generator. */ const char *msg = "generator raised StopIteration"; if (PyCoro_CheckExact(gen)) { msg = "coroutine raised StopIteration"; } else if PyAsyncGen_CheckExact(gen) { msg = "async generator raised StopIteration"; } _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg); } else { /* `gen` is an ordinary generator without CO_FUTURE_GENERATOR_STOP flag. */ PyObject *exc, *val, *tb; /* Pop the exception before issuing a warning. */ PyErr_Fetch(&exc, &val, &tb); if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "generator '%.50S' raised StopIteration", gen->gi_qualname)) { /* Warning was converted to an error. */ Py_XDECREF(exc); Py_XDECREF(val); Py_XDECREF(tb); } else { PyErr_Restore(exc, val, tb); } } } else if (PyAsyncGen_CheckExact(gen) && !result && PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) { /* code in `gen` raised a StopAsyncIteration error: raise a RuntimeError. */ const char *msg = "async generator raised StopAsyncIteration"; _PyErr_FormatFromCause(PyExc_RuntimeError, "%s", msg); } if (!result || f->f_stacktop == NULL) { /* generator can't be rerun, so release the frame */ /* first clean reference cycle through stored exception traceback */ PyObject *t, *v, *tb; t = f->f_exc_type; v = f->f_exc_value; tb = f->f_exc_traceback; f->f_exc_type = NULL; f->f_exc_value = NULL; f->f_exc_traceback = NULL; Py_XDECREF(t); Py_XDECREF(v); Py_XDECREF(tb); gen->gi_frame->f_gen = NULL; gen->gi_frame = NULL; Py_DECREF(f); } return result; } PyDoc_STRVAR(send_doc, "send(arg) -> send 'arg' into generator,\n\ return next yielded value or raise StopIteration."); PyObject * _PyGen_Send(PyGenObject *gen, PyObject *arg) { return gen_send_ex(gen, arg, 0, 0); } PyDoc_STRVAR(close_doc, "close() -> raise GeneratorExit inside generator."); /* * This helper function is used by gen_close and gen_throw to * close a subiterator being delegated to by yield-from. */ static int gen_close_iter(PyObject *yf) { PyObject *retval = NULL; _Py_IDENTIFIER(close); if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) { retval = gen_close((PyGenObject *)yf, NULL); if (retval == NULL) return -1; } else { PyObject *meth = _PyObject_GetAttrId(yf, &PyId_close); if (meth == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_WriteUnraisable(yf); PyErr_Clear(); } else { retval = _PyObject_CallNoArg(meth); Py_DECREF(meth); if (retval == NULL) return -1; } } Py_XDECREF(retval); return 0; } PyObject * _PyGen_yf(PyGenObject *gen) { PyObject *yf = NULL; PyFrameObject *f = gen->gi_frame; if (f && f->f_stacktop) { PyObject *bytecode = f->f_code->co_code; unsigned char *code = (unsigned char *)PyBytes_AS_STRING(bytecode); if (f->f_lasti < 0) { /* Return immediately if the frame didn't start yet. YIELD_FROM always come after LOAD_CONST: a code object should not start with YIELD_FROM */ assert(code[0] != YIELD_FROM); return NULL; } if (code[f->f_lasti + sizeof(_Py_CODEUNIT)] != YIELD_FROM) return NULL; yf = f->f_stacktop[-1]; Py_INCREF(yf); } return yf; } static PyObject * gen_close(PyGenObject *gen, PyObject *args) { PyObject *retval; PyObject *yf = _PyGen_yf(gen); int err = 0; if (yf) { gen->gi_running = 1; err = gen_close_iter(yf); gen->gi_running = 0; Py_DECREF(yf); } if (err == 0) PyErr_SetNone(PyExc_GeneratorExit); retval = gen_send_ex(gen, Py_None, 1, 1); if (retval) { char *msg = "generator ignored GeneratorExit"; if (PyCoro_CheckExact(gen)) { msg = "coroutine ignored GeneratorExit"; } else if (PyAsyncGen_CheckExact(gen)) { msg = ASYNC_GEN_IGNORED_EXIT_MSG; } Py_DECREF(retval); PyErr_SetString(PyExc_RuntimeError, msg); return NULL; } if (PyErr_ExceptionMatches(PyExc_StopIteration) || PyErr_ExceptionMatches(PyExc_GeneratorExit)) { PyErr_Clear(); /* ignore these errors */ Py_INCREF(Py_None); return Py_None; } return NULL; } PyDoc_STRVAR(throw_doc, "throw(typ[,val[,tb]]) -> raise exception in generator,\n\ return next yielded value or raise StopIteration."); static PyObject * _gen_throw(PyGenObject *gen, int close_on_genexit, PyObject *typ, PyObject *val, PyObject *tb) { PyObject *yf = _PyGen_yf(gen); _Py_IDENTIFIER(throw); if (yf) { PyObject *ret; int err; if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit ) { /* Asynchronous generators *should not* be closed right away. We have to allow some awaits to work it through, hence the `close_on_genexit` parameter here. */ gen->gi_running = 1; err = gen_close_iter(yf); gen->gi_running = 0; Py_DECREF(yf); if (err < 0) return gen_send_ex(gen, Py_None, 1, 0); goto throw_here; } if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) { /* `yf` is a generator or a coroutine. */ gen->gi_running = 1; /* Close the generator that we are currently iterating with 'yield from' or awaiting on with 'await'. */ ret = _gen_throw((PyGenObject *)yf, close_on_genexit, typ, val, tb); gen->gi_running = 0; } else { /* `yf` is an iterator or a coroutine-like object. */ PyObject *meth = _PyObject_GetAttrId(yf, &PyId_throw); if (meth == NULL) { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { Py_DECREF(yf); return NULL; } PyErr_Clear(); Py_DECREF(yf); goto throw_here; } gen->gi_running = 1; ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL); gen->gi_running = 0; Py_DECREF(meth); } Py_DECREF(yf); if (!ret) { PyObject *val; /* Pop subiterator from stack */ ret = *(--gen->gi_frame->f_stacktop); assert(ret == yf); Py_DECREF(ret); /* Termination repetition of YIELD_FROM */ assert(gen->gi_frame->f_lasti >= 0); gen->gi_frame->f_lasti += sizeof(_Py_CODEUNIT); if (_PyGen_FetchStopIterationValue(&val) == 0) { ret = gen_send_ex(gen, val, 0, 0); Py_DECREF(val); } else { ret = gen_send_ex(gen, Py_None, 1, 0); } } return ret; } throw_here: /* First, check the traceback argument, replacing None with NULL. */ if (tb == Py_None) { tb = NULL; } else if (tb != NULL && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "throw() third argument must be a traceback object"); return NULL; } Py_INCREF(typ); Py_XINCREF(val); Py_XINCREF(tb); if (PyExceptionClass_Check(typ)) PyErr_NormalizeException(&typ, &val, &tb); else if (PyExceptionInstance_Check(typ)) { /* Raising an instance. The value should be a dummy. */ if (val && val != Py_None) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto failed_throw; } else { /* Normalize to raise <class>, <instance> */ Py_XDECREF(val); val = typ; typ = PyExceptionInstance_Class(typ); Py_INCREF(typ); if (tb == NULL) /* Returns NULL if there's no traceback */ tb = PyException_GetTraceback(val); } } else { /* Not something you can raise. throw() fails. */ PyErr_Format(PyExc_TypeError, "exceptions must be classes or instances " "deriving from BaseException, not %s", Py_TYPE(typ)->tp_name); goto failed_throw; } PyErr_Restore(typ, val, tb); return gen_send_ex(gen, Py_None, 1, 0); failed_throw: /* Didn't use our arguments, so restore their original refcounts */ Py_DECREF(typ); Py_XDECREF(val); Py_XDECREF(tb); return NULL; } static PyObject * gen_throw(PyGenObject *gen, PyObject *args) { PyObject *typ; PyObject *tb = NULL; PyObject *val = NULL; if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb)) { return NULL; } return _gen_throw(gen, 1, typ, val, tb); } static PyObject * gen_iternext(PyGenObject *gen) { return gen_send_ex(gen, NULL, 0, 0); } /* * Set StopIteration with specified value. Value can be arbitrary object * or NULL. * * Returns 0 if StopIteration is set and -1 if any other exception is set. */ int _PyGen_SetStopIterationValue(PyObject *value) { PyObject *e; if (value == NULL || (!PyTuple_Check(value) && !PyExceptionInstance_Check(value))) { /* Delay exception instantiation if we can */ PyErr_SetObject(PyExc_StopIteration, value); return 0; } /* Construct an exception instance manually with * PyObject_CallFunctionObjArgs and pass it to PyErr_SetObject. * * We do this to handle a situation when "value" is a tuple, in which * case PyErr_SetObject would set the value of StopIteration to * the first element of the tuple. * * (See PyErr_SetObject/_PyErr_CreateException code for details.) */ e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, value, NULL); if (e == NULL) { return -1; } PyErr_SetObject(PyExc_StopIteration, e); Py_DECREF(e); return 0; } /* * If StopIteration exception is set, fetches its 'value' * attribute if any, otherwise sets pvalue to None. * * Returns 0 if no exception or StopIteration is set. * If any other exception is set, returns -1 and leaves * pvalue unchanged. */ int _PyGen_FetchStopIterationValue(PyObject **pvalue) { PyObject *et, *ev, *tb; PyObject *value = NULL; if (PyErr_ExceptionMatches(PyExc_StopIteration)) { PyErr_Fetch(&et, &ev, &tb); if (ev) { /* exception will usually be normalised already */ if (PyObject_TypeCheck(ev, (PyTypeObject *) et)) { value = ((PyStopIterationObject *)ev)->value; Py_INCREF(value); Py_DECREF(ev); } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) { /* Avoid normalisation and take ev as value. * * Normalization is required if the value is a tuple, in * that case the value of StopIteration would be set to * the first element of the tuple. * * (See _PyErr_CreateException code for details.) */ value = ev; } else { /* normalisation required */ PyErr_NormalizeException(&et, &ev, &tb); if (!PyObject_TypeCheck(ev, (PyTypeObject *)PyExc_StopIteration)) { PyErr_Restore(et, ev, tb); return -1; } value = ((PyStopIterationObject *)ev)->value; Py_INCREF(value); Py_DECREF(ev); } } Py_XDECREF(et); Py_XDECREF(tb); } else if (PyErr_Occurred()) { return -1; } if (value == NULL) { value = Py_None; Py_INCREF(value); } *pvalue = value; return 0; } static PyObject * gen_repr(PyGenObject *gen) { return PyUnicode_FromFormat("<generator object %S at %p>", gen->gi_qualname, gen); } static PyObject * gen_get_name(PyGenObject *op, void *Py_UNUSED(ignored)) { Py_INCREF(op->gi_name); return op->gi_name; } static int gen_set_name(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored)) { /* Not legal to del gen.gi_name or to set it to anything * other than a string object. */ if (value == NULL || !PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } Py_INCREF(value); Py_XSETREF(op->gi_name, value); return 0; } static PyObject * gen_get_qualname(PyGenObject *op, void *Py_UNUSED(ignored)) { Py_INCREF(op->gi_qualname); return op->gi_qualname; } static int gen_set_qualname(PyGenObject *op, PyObject *value, void *Py_UNUSED(ignored)) { /* Not legal to del gen.__qualname__ or to set it to anything * other than a string object. */ if (value == NULL || !PyUnicode_Check(value)) { PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } Py_INCREF(value); Py_XSETREF(op->gi_qualname, value); return 0; } static PyObject * gen_getyieldfrom(PyGenObject *gen, void *Py_UNUSED(ignored)) { PyObject *yf = _PyGen_yf(gen); if (yf == NULL) Py_RETURN_NONE; return yf; } static PyGetSetDef gen_getsetlist[] = { {"__name__", (getter)gen_get_name, (setter)gen_set_name, PyDoc_STR("name of the generator")}, {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname, PyDoc_STR("qualified name of the generator")}, {"gi_yieldfrom", (getter)gen_getyieldfrom, NULL, PyDoc_STR("object being iterated by yield from, or None")}, {NULL} /* Sentinel */ }; static PyMemberDef gen_memberlist[] = { {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), READONLY}, {"gi_running", T_BOOL, offsetof(PyGenObject, gi_running), READONLY}, {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), READONLY}, {NULL} /* Sentinel */ }; static PyMethodDef gen_methods[] = { {"send",(PyCFunction)_PyGen_Send, METH_O, send_doc}, {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc}, {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc}, {NULL, NULL} /* Sentinel */ }; PyTypeObject PyGen_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "generator", /* tp_name */ sizeof(PyGenObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)gen_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ (reprfunc)gen_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gen_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)gen_iternext, /* tp_iternext */ gen_methods, /* tp_methods */ gen_memberlist, /* tp_members */ gen_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ _PyGen_Finalize, /* tp_finalize */ }; static PyObject * gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f, PyObject *name, PyObject *qualname) { PyGenObject *gen = PyObject_GC_New(PyGenObject, type); if (gen == NULL) { Py_DECREF(f); return NULL; } gen->gi_frame = f; f->f_gen = (PyObject *) gen; Py_INCREF(f->f_code); gen->gi_code = (PyObject *)(f->f_code); gen->gi_running = 0; gen->gi_weakreflist = NULL; if (name != NULL) gen->gi_name = name; else gen->gi_name = ((PyCodeObject *)gen->gi_code)->co_name; Py_INCREF(gen->gi_name); if (qualname != NULL) gen->gi_qualname = qualname; else gen->gi_qualname = gen->gi_name; Py_INCREF(gen->gi_qualname); _PyObject_GC_TRACK(gen); return (PyObject *)gen; } PyObject * PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname) { return gen_new_with_qualname(&PyGen_Type, f, name, qualname); } PyObject * PyGen_New(PyFrameObject *f) { return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL); } int PyGen_NeedsFinalizing(PyGenObject *gen) { int i; PyFrameObject *f = gen->gi_frame; if (f == NULL || f->f_stacktop == NULL) return 0; /* no frame or empty blockstack == no finalization */ /* Any block type besides a loop requires cleanup. */ for (i = 0; i < f->f_iblock; i++) if (f->f_blockstack[i].b_type != SETUP_LOOP) return 1; /* No blocks except loops, it's safe to skip finalization. */ return 0; } /* Coroutine Object */ typedef struct { PyObject_HEAD PyCoroObject *cw_coroutine; } PyCoroWrapper; static int gen_is_coroutine(PyObject *o) { if (PyGen_CheckExact(o)) { PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code; if (code->co_flags & CO_ITERABLE_COROUTINE) { return 1; } } return 0; } /* * This helper function returns an awaitable for `o`: * - `o` if `o` is a coroutine-object; * - `type(o)->tp_as_async->am_await(o)` * * Raises a TypeError if it's not possible to return * an awaitable and returns NULL. */ PyObject * _PyCoro_GetAwaitableIter(PyObject *o) { unaryfunc getter = NULL; PyTypeObject *ot; if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) { /* 'o' is a coroutine. */ Py_INCREF(o); return o; } ot = Py_TYPE(o); if (ot->tp_as_async != NULL) { getter = ot->tp_as_async->am_await; } if (getter != NULL) { PyObject *res = (*getter)(o); if (res != NULL) { if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) { /* __await__ must return an *iterator*, not a coroutine or another awaitable (see PEP 492) */ PyErr_SetString(PyExc_TypeError, "__await__() returned a coroutine"); Py_CLEAR(res); } else if (!PyIter_Check(res)) { PyErr_Format(PyExc_TypeError, "__await__() returned non-iterator " "of type '%.100s'", Py_TYPE(res)->tp_name); Py_CLEAR(res); } } return res; } PyErr_Format(PyExc_TypeError, "object %.100s can't be used in 'await' expression", ot->tp_name); return NULL; } static PyObject * coro_repr(PyCoroObject *coro) { return PyUnicode_FromFormat("<coroutine object %S at %p>", coro->cr_qualname, coro); } static PyObject * coro_await(PyCoroObject *coro) { PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type); if (cw == NULL) { return NULL; } Py_INCREF(coro); cw->cw_coroutine = coro; _PyObject_GC_TRACK(cw); return (PyObject *)cw; } static PyObject * coro_get_cr_await(PyCoroObject *coro, void *Py_UNUSED(ignored)) { PyObject *yf = _PyGen_yf((PyGenObject *) coro); if (yf == NULL) Py_RETURN_NONE; return yf; } static PyGetSetDef coro_getsetlist[] = { {"__name__", (getter)gen_get_name, (setter)gen_set_name, PyDoc_STR("name of the coroutine")}, {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname, PyDoc_STR("qualified name of the coroutine")}, {"cr_await", (getter)coro_get_cr_await, NULL, PyDoc_STR("object being awaited on, or None")}, {NULL} /* Sentinel */ }; static PyMemberDef coro_memberlist[] = { {"cr_frame", T_OBJECT, offsetof(PyCoroObject, cr_frame), READONLY}, {"cr_running", T_BOOL, offsetof(PyCoroObject, cr_running), READONLY}, {"cr_code", T_OBJECT, offsetof(PyCoroObject, cr_code), READONLY}, {NULL} /* Sentinel */ }; PyDoc_STRVAR(coro_send_doc, "send(arg) -> send 'arg' into coroutine,\n\ return next iterated value or raise StopIteration."); PyDoc_STRVAR(coro_throw_doc, "throw(typ[,val[,tb]]) -> raise exception in coroutine,\n\ return next iterated value or raise StopIteration."); PyDoc_STRVAR(coro_close_doc, "close() -> raise GeneratorExit inside coroutine."); static PyMethodDef coro_methods[] = { {"send",(PyCFunction)_PyGen_Send, METH_O, coro_send_doc}, {"throw",(PyCFunction)gen_throw, METH_VARARGS, coro_throw_doc}, {"close",(PyCFunction)gen_close, METH_NOARGS, coro_close_doc}, {NULL, NULL} /* Sentinel */ }; static PyAsyncMethods coro_as_async = { (unaryfunc)coro_await, /* am_await */ 0, /* am_aiter */ 0 /* am_anext */ }; PyTypeObject PyCoro_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "coroutine", /* tp_name */ sizeof(PyCoroObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)gen_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ &coro_as_async, /* tp_as_async */ (reprfunc)coro_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */ 0, /* tp_doc */ (traverseproc)gen_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyCoroObject, cr_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ coro_methods, /* tp_methods */ coro_memberlist, /* tp_members */ coro_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ _PyGen_Finalize, /* tp_finalize */ }; static void coro_wrapper_dealloc(PyCoroWrapper *cw) { _PyObject_GC_UNTRACK((PyObject *)cw); Py_CLEAR(cw->cw_coroutine); PyObject_GC_Del(cw); } static PyObject * coro_wrapper_iternext(PyCoroWrapper *cw) { return gen_send_ex((PyGenObject *)cw->cw_coroutine, NULL, 0, 0); } static PyObject * coro_wrapper_send(PyCoroWrapper *cw, PyObject *arg) { return gen_send_ex((PyGenObject *)cw->cw_coroutine, arg, 0, 0); } static PyObject * coro_wrapper_throw(PyCoroWrapper *cw, PyObject *args) { return gen_throw((PyGenObject *)cw->cw_coroutine, args); } static PyObject * coro_wrapper_close(PyCoroWrapper *cw, PyObject *args) { return gen_close((PyGenObject *)cw->cw_coroutine, args); } static int coro_wrapper_traverse(PyCoroWrapper *cw, visitproc visit, void *arg) { Py_VISIT((PyObject *)cw->cw_coroutine); return 0; } static PyMethodDef coro_wrapper_methods[] = { {"send",(PyCFunction)coro_wrapper_send, METH_O, coro_send_doc}, {"throw",(PyCFunction)coro_wrapper_throw, METH_VARARGS, coro_throw_doc}, {"close",(PyCFunction)coro_wrapper_close, METH_NOARGS, coro_close_doc}, {NULL, NULL} /* Sentinel */ }; PyTypeObject _PyCoroWrapper_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "coroutine_wrapper", sizeof(PyCoroWrapper), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)coro_wrapper_dealloc, /* destructor tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ "A wrapper object implementing __await__ for coroutines.", (traverseproc)coro_wrapper_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)coro_wrapper_iternext, /* tp_iternext */ coro_wrapper_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ }; PyObject * PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname) { return gen_new_with_qualname(&PyCoro_Type, f, name, qualname); } /* __aiter__ wrapper; see http://bugs.python.org/issue27243 for details. */ typedef struct { PyObject_HEAD PyObject *ags_aiter; } PyAIterWrapper; static PyObject * aiter_wrapper_iternext(PyAIterWrapper *aw) { _PyGen_SetStopIterationValue(aw->ags_aiter); return NULL; } static int aiter_wrapper_traverse(PyAIterWrapper *aw, visitproc visit, void *arg) { Py_VISIT((PyObject *)aw->ags_aiter); return 0; } static void aiter_wrapper_dealloc(PyAIterWrapper *aw) { _PyObject_GC_UNTRACK((PyObject *)aw); Py_CLEAR(aw->ags_aiter); PyObject_GC_Del(aw); } static PyAsyncMethods aiter_wrapper_as_async = { PyObject_SelfIter, /* am_await */ 0, /* am_aiter */ 0 /* am_anext */ }; PyTypeObject _PyAIterWrapper_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "aiter_wrapper", sizeof(PyAIterWrapper), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)aiter_wrapper_dealloc, /* destructor tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ &aiter_wrapper_as_async, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ "A wrapper object for __aiter__ bakwards compatibility.", (traverseproc)aiter_wrapper_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)aiter_wrapper_iternext, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ }; PyObject * _PyAIterWrapper_New(PyObject *aiter) { PyAIterWrapper *aw = PyObject_GC_New(PyAIterWrapper, &_PyAIterWrapper_Type); if (aw == NULL) { return NULL; } Py_INCREF(aiter); aw->ags_aiter = aiter; _PyObject_GC_TRACK(aw); return (PyObject *)aw; } /* ========= Asynchronous Generators ========= */ typedef enum { AWAITABLE_STATE_INIT, /* new awaitable, has not yet been iterated */ AWAITABLE_STATE_ITER, /* being iterated */ AWAITABLE_STATE_CLOSED, /* closed */ } AwaitableState; typedef struct { PyObject_HEAD PyAsyncGenObject *ags_gen; /* Can be NULL, when in the __anext__() mode (equivalent of "asend(None)") */ PyObject *ags_sendval; AwaitableState ags_state; } PyAsyncGenASend; typedef struct { PyObject_HEAD PyAsyncGenObject *agt_gen; /* Can be NULL, when in the "aclose()" mode (equivalent of "athrow(GeneratorExit)") */ PyObject *agt_args; AwaitableState agt_state; } PyAsyncGenAThrow; typedef struct { PyObject_HEAD PyObject *agw_val; } _PyAsyncGenWrappedValue; #ifndef _PyAsyncGen_MAXFREELIST #define _PyAsyncGen_MAXFREELIST 80 #endif /* Freelists boost performance 6-10%; they also reduce memory fragmentation, as _PyAsyncGenWrappedValue and PyAsyncGenASend are short-living objects that are instantiated for every __anext__ call. */ static _PyAsyncGenWrappedValue *ag_value_freelist[_PyAsyncGen_MAXFREELIST]; static int ag_value_freelist_free = 0; static PyAsyncGenASend *ag_asend_freelist[_PyAsyncGen_MAXFREELIST]; static int ag_asend_freelist_free = 0; #define _PyAsyncGenWrappedValue_CheckExact(o) \ (Py_TYPE(o) == &_PyAsyncGenWrappedValue_Type) #define PyAsyncGenASend_CheckExact(o) \ (Py_TYPE(o) == &_PyAsyncGenASend_Type) static int async_gen_traverse(PyAsyncGenObject *gen, visitproc visit, void *arg) { Py_VISIT(gen->ag_finalizer); return gen_traverse((PyGenObject*)gen, visit, arg); } static PyObject * async_gen_repr(PyAsyncGenObject *o) { return PyUnicode_FromFormat("<async_generator object %S at %p>", o->ag_qualname, o); } static int async_gen_init_hooks(PyAsyncGenObject *o) { PyThreadState *tstate; PyObject *finalizer; PyObject *firstiter; if (o->ag_hooks_inited) { return 0; } o->ag_hooks_inited = 1; tstate = PyThreadState_GET(); finalizer = tstate->async_gen_finalizer; if (finalizer) { Py_INCREF(finalizer); o->ag_finalizer = finalizer; } firstiter = tstate->async_gen_firstiter; if (firstiter) { PyObject *res; Py_INCREF(firstiter); res = PyObject_CallFunction(firstiter, "O", o); Py_DECREF(firstiter); if (res == NULL) { return 1; } Py_DECREF(res); } return 0; } static PyObject * async_gen_anext(PyAsyncGenObject *o) { if (async_gen_init_hooks(o)) { return NULL; } return async_gen_asend_new(o, NULL); } static PyObject * async_gen_asend(PyAsyncGenObject *o, PyObject *arg) { if (async_gen_init_hooks(o)) { return NULL; } return async_gen_asend_new(o, arg); } static PyObject * async_gen_aclose(PyAsyncGenObject *o, PyObject *arg) { if (async_gen_init_hooks(o)) { return NULL; } return async_gen_athrow_new(o, NULL); } static PyObject * async_gen_athrow(PyAsyncGenObject *o, PyObject *args) { if (async_gen_init_hooks(o)) { return NULL; } return async_gen_athrow_new(o, args); } static PyGetSetDef async_gen_getsetlist[] = { {"__name__", (getter)gen_get_name, (setter)gen_set_name, PyDoc_STR("name of the async generator")}, {"__qualname__", (getter)gen_get_qualname, (setter)gen_set_qualname, PyDoc_STR("qualified name of the async generator")}, {"ag_await", (getter)coro_get_cr_await, NULL, PyDoc_STR("object being awaited on, or None")}, {NULL} /* Sentinel */ }; static PyMemberDef async_gen_memberlist[] = { {"ag_frame", T_OBJECT, offsetof(PyAsyncGenObject, ag_frame), READONLY}, {"ag_running", T_BOOL, offsetof(PyAsyncGenObject, ag_running), READONLY}, {"ag_code", T_OBJECT, offsetof(PyAsyncGenObject, ag_code), READONLY}, {NULL} /* Sentinel */ }; PyDoc_STRVAR(async_aclose_doc, "aclose() -> raise GeneratorExit inside generator."); PyDoc_STRVAR(async_asend_doc, "asend(v) -> send 'v' in generator."); PyDoc_STRVAR(async_athrow_doc, "athrow(typ[,val[,tb]]) -> raise exception in generator."); static PyMethodDef async_gen_methods[] = { {"asend", (PyCFunction)async_gen_asend, METH_O, async_asend_doc}, {"athrow",(PyCFunction)async_gen_athrow, METH_VARARGS, async_athrow_doc}, {"aclose", (PyCFunction)async_gen_aclose, METH_NOARGS, async_aclose_doc}, {NULL, NULL} /* Sentinel */ }; static PyAsyncMethods async_gen_as_async = { 0, /* am_await */ PyObject_SelfIter, /* am_aiter */ (unaryfunc)async_gen_anext /* am_anext */ }; PyTypeObject PyAsyncGen_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "async_generator", /* tp_name */ sizeof(PyAsyncGenObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)gen_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ &async_gen_as_async, /* tp_as_async */ (reprfunc)async_gen_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */ 0, /* tp_doc */ (traverseproc)async_gen_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ async_gen_methods, /* tp_methods */ async_gen_memberlist, /* tp_members */ async_gen_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0, /* tp_version_tag */ _PyGen_Finalize, /* tp_finalize */ }; PyObject * PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname) { PyAsyncGenObject *o; o = (PyAsyncGenObject *)gen_new_with_qualname( &PyAsyncGen_Type, f, name, qualname); if (o == NULL) { return NULL; } o->ag_finalizer = NULL; o->ag_closed = 0; o->ag_hooks_inited = 0; return (PyObject*)o; } int PyAsyncGen_ClearFreeLists(void) { int ret = ag_value_freelist_free + ag_asend_freelist_free; while (ag_value_freelist_free) { _PyAsyncGenWrappedValue *o; o = ag_value_freelist[--ag_value_freelist_free]; assert(_PyAsyncGenWrappedValue_CheckExact(o)); PyObject_GC_Del(o); } while (ag_asend_freelist_free) { PyAsyncGenASend *o; o = ag_asend_freelist[--ag_asend_freelist_free]; assert(Py_TYPE(o) == &_PyAsyncGenASend_Type); PyObject_GC_Del(o); } return ret; } void PyAsyncGen_Fini(void) { PyAsyncGen_ClearFreeLists(); } static PyObject * async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result) { if (result == NULL) { if (!PyErr_Occurred()) { PyErr_SetNone(PyExc_StopAsyncIteration); } if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) || PyErr_ExceptionMatches(PyExc_GeneratorExit) ) { gen->ag_closed = 1; } return NULL; } if (_PyAsyncGenWrappedValue_CheckExact(result)) { /* async yield */ _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val); Py_DECREF(result); return NULL; } return result; } /* ---------- Async Generator ASend Awaitable ------------ */ static void async_gen_asend_dealloc(PyAsyncGenASend *o) { _PyObject_GC_UNTRACK((PyObject *)o); Py_CLEAR(o->ags_gen); Py_CLEAR(o->ags_sendval); if (ag_asend_freelist_free < _PyAsyncGen_MAXFREELIST) { assert(PyAsyncGenASend_CheckExact(o)); ag_asend_freelist[ag_asend_freelist_free++] = o; } else { PyObject_GC_Del(o); } } static int async_gen_asend_traverse(PyAsyncGenASend *o, visitproc visit, void *arg) { Py_VISIT(o->ags_gen); Py_VISIT(o->ags_sendval); return 0; } static PyObject * async_gen_asend_send(PyAsyncGenASend *o, PyObject *arg) { PyObject *result; if (o->ags_state == AWAITABLE_STATE_CLOSED) { PyErr_SetNone(PyExc_StopIteration); return NULL; } if (o->ags_state == AWAITABLE_STATE_INIT) { if (arg == NULL || arg == Py_None) { arg = o->ags_sendval; } o->ags_state = AWAITABLE_STATE_ITER; } result = gen_send_ex((PyGenObject*)o->ags_gen, arg, 0, 0); result = async_gen_unwrap_value(o->ags_gen, result); if (result == NULL) { o->ags_state = AWAITABLE_STATE_CLOSED; } return result; } static PyObject * async_gen_asend_iternext(PyAsyncGenASend *o) { return async_gen_asend_send(o, NULL); } static PyObject * async_gen_asend_throw(PyAsyncGenASend *o, PyObject *args) { PyObject *result; if (o->ags_state == AWAITABLE_STATE_CLOSED) { PyErr_SetNone(PyExc_StopIteration); return NULL; } result = gen_throw((PyGenObject*)o->ags_gen, args); result = async_gen_unwrap_value(o->ags_gen, result); if (result == NULL) { o->ags_state = AWAITABLE_STATE_CLOSED; } return result; } static PyObject * async_gen_asend_close(PyAsyncGenASend *o, PyObject *args) { o->ags_state = AWAITABLE_STATE_CLOSED; Py_RETURN_NONE; } static PyMethodDef async_gen_asend_methods[] = { {"send", (PyCFunction)async_gen_asend_send, METH_O, send_doc}, {"throw", (PyCFunction)async_gen_asend_throw, METH_VARARGS, throw_doc}, {"close", (PyCFunction)async_gen_asend_close, METH_NOARGS, close_doc}, {NULL, NULL} /* Sentinel */ }; static PyAsyncMethods async_gen_asend_as_async = { PyObject_SelfIter, /* am_await */ 0, /* am_aiter */ 0 /* am_anext */ }; PyTypeObject _PyAsyncGenASend_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "async_generator_asend", /* tp_name */ sizeof(PyAsyncGenASend), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)async_gen_asend_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ &async_gen_asend_as_async, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)async_gen_asend_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)async_gen_asend_iternext, /* tp_iternext */ async_gen_asend_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static PyObject * async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval) { PyAsyncGenASend *o; if (ag_asend_freelist_free) { ag_asend_freelist_free--; o = ag_asend_freelist[ag_asend_freelist_free]; _Py_NewReference((PyObject *)o); } else { o = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type); if (o == NULL) { return NULL; } } Py_INCREF(gen); o->ags_gen = gen; Py_XINCREF(sendval); o->ags_sendval = sendval; o->ags_state = AWAITABLE_STATE_INIT; _PyObject_GC_TRACK((PyObject*)o); return (PyObject*)o; } /* ---------- Async Generator Value Wrapper ------------ */ static void async_gen_wrapped_val_dealloc(_PyAsyncGenWrappedValue *o) { _PyObject_GC_UNTRACK((PyObject *)o); Py_CLEAR(o->agw_val); if (ag_value_freelist_free < _PyAsyncGen_MAXFREELIST) { assert(_PyAsyncGenWrappedValue_CheckExact(o)); ag_value_freelist[ag_value_freelist_free++] = o; } else { PyObject_GC_Del(o); } } static int async_gen_wrapped_val_traverse(_PyAsyncGenWrappedValue *o, visitproc visit, void *arg) { Py_VISIT(o->agw_val); return 0; } PyTypeObject _PyAsyncGenWrappedValue_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "async_generator_wrapped_value", /* tp_name */ sizeof(_PyAsyncGenWrappedValue), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)async_gen_wrapped_val_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)async_gen_wrapped_val_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; PyObject * _PyAsyncGenValueWrapperNew(PyObject *val) { _PyAsyncGenWrappedValue *o; assert(val); if (ag_value_freelist_free) { ag_value_freelist_free--; o = ag_value_freelist[ag_value_freelist_free]; assert(_PyAsyncGenWrappedValue_CheckExact(o)); _Py_NewReference((PyObject*)o); } else { o = PyObject_GC_New(_PyAsyncGenWrappedValue, &_PyAsyncGenWrappedValue_Type); if (o == NULL) { return NULL; } } o->agw_val = val; Py_INCREF(val); _PyObject_GC_TRACK((PyObject*)o); return (PyObject*)o; } /* ---------- Async Generator AThrow awaitable ------------ */ static void async_gen_athrow_dealloc(PyAsyncGenAThrow *o) { _PyObject_GC_UNTRACK((PyObject *)o); Py_CLEAR(o->agt_gen); Py_CLEAR(o->agt_args); PyObject_GC_Del(o); } static int async_gen_athrow_traverse(PyAsyncGenAThrow *o, visitproc visit, void *arg) { Py_VISIT(o->agt_gen); Py_VISIT(o->agt_args); return 0; } static PyObject * async_gen_athrow_send(PyAsyncGenAThrow *o, PyObject *arg) { PyGenObject *gen = (PyGenObject*)o->agt_gen; PyFrameObject *f = gen->gi_frame; PyObject *retval; if (f == NULL || f->f_stacktop == NULL || o->agt_state == AWAITABLE_STATE_CLOSED) { PyErr_SetNone(PyExc_StopIteration); return NULL; } if (o->agt_state == AWAITABLE_STATE_INIT) { if (o->agt_gen->ag_closed) { PyErr_SetNone(PyExc_StopIteration); return NULL; } if (arg != Py_None) { PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG); return NULL; } o->agt_state = AWAITABLE_STATE_ITER; if (o->agt_args == NULL) { /* aclose() mode */ o->agt_gen->ag_closed = 1; retval = _gen_throw((PyGenObject *)gen, 0, /* Do not close generator when PyExc_GeneratorExit is passed */ PyExc_GeneratorExit, NULL, NULL); if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) { Py_DECREF(retval); goto yield_close; } } else { PyObject *typ; PyObject *tb = NULL; PyObject *val = NULL; if (!PyArg_UnpackTuple(o->agt_args, "athrow", 1, 3, &typ, &val, &tb)) { return NULL; } retval = _gen_throw((PyGenObject *)gen, 0, /* Do not close generator when PyExc_GeneratorExit is passed */ typ, val, tb); retval = async_gen_unwrap_value(o->agt_gen, retval); } if (retval == NULL) { goto check_error; } return retval; } assert(o->agt_state == AWAITABLE_STATE_ITER); retval = gen_send_ex((PyGenObject *)gen, arg, 0, 0); if (o->agt_args) { return async_gen_unwrap_value(o->agt_gen, retval); } else { /* aclose() mode */ if (retval) { if (_PyAsyncGenWrappedValue_CheckExact(retval)) { Py_DECREF(retval); goto yield_close; } else { return retval; } } else { goto check_error; } } yield_close: PyErr_SetString( PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG); return NULL; check_error: if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) || PyErr_ExceptionMatches(PyExc_GeneratorExit)) { o->agt_state = AWAITABLE_STATE_CLOSED; if (o->agt_args == NULL) { /* when aclose() is called we don't want to propagate StopAsyncIteration or GeneratorExit; just raise StopIteration, signalling that this 'aclose()' await is done. */ PyErr_Clear(); PyErr_SetNone(PyExc_StopIteration); } } return NULL; } static PyObject * async_gen_athrow_throw(PyAsyncGenAThrow *o, PyObject *args) { PyObject *retval; if (o->agt_state == AWAITABLE_STATE_INIT) { PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG); return NULL; } if (o->agt_state == AWAITABLE_STATE_CLOSED) { PyErr_SetNone(PyExc_StopIteration); return NULL; } retval = gen_throw((PyGenObject*)o->agt_gen, args); if (o->agt_args) { return async_gen_unwrap_value(o->agt_gen, retval); } else { /* aclose() mode */ if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) { Py_DECREF(retval); PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG); return NULL; } return retval; } } static PyObject * async_gen_athrow_iternext(PyAsyncGenAThrow *o) { return async_gen_athrow_send(o, Py_None); } static PyObject * async_gen_athrow_close(PyAsyncGenAThrow *o, PyObject *args) { o->agt_state = AWAITABLE_STATE_CLOSED; Py_RETURN_NONE; } static PyMethodDef async_gen_athrow_methods[] = { {"send", (PyCFunction)async_gen_athrow_send, METH_O, send_doc}, {"throw", (PyCFunction)async_gen_athrow_throw, METH_VARARGS, throw_doc}, {"close", (PyCFunction)async_gen_athrow_close, METH_NOARGS, close_doc}, {NULL, NULL} /* Sentinel */ }; static PyAsyncMethods async_gen_athrow_as_async = { PyObject_SelfIter, /* am_await */ 0, /* am_aiter */ 0 /* am_anext */ }; PyTypeObject _PyAsyncGenAThrow_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "async_generator_athrow", /* tp_name */ sizeof(PyAsyncGenAThrow), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)async_gen_athrow_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ &async_gen_athrow_as_async, /* tp_as_async */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)async_gen_athrow_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)async_gen_athrow_iternext, /* tp_iternext */ async_gen_athrow_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static PyObject * async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args) { PyAsyncGenAThrow *o; o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type); if (o == NULL) { return NULL; } o->agt_gen = gen; o->agt_args = args; o->agt_state = AWAITABLE_STATE_INIT; Py_INCREF(gen); Py_XINCREF(args); _PyObject_GC_TRACK((PyObject*)o); return (PyObject*)o; }
70,888
2,094
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/iterobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/iterobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" /* clang-format off */ typedef struct { PyObject_HEAD Py_ssize_t it_index; PyObject *it_seq; /* Set to NULL when iterator is exhausted */ } seqiterobject; PyObject * PySeqIter_New(PyObject *seq) { seqiterobject *it; if (!PySequence_Check(seq)) { PyErr_BadInternalCall(); return NULL; } it = PyObject_GC_New(seqiterobject, &PySeqIter_Type); if (it == NULL) return NULL; it->it_index = 0; Py_INCREF(seq); it->it_seq = seq; _PyObject_GC_TRACK(it); return (PyObject *)it; } static void iter_dealloc(seqiterobject *it) { _PyObject_GC_UNTRACK(it); Py_XDECREF(it->it_seq); PyObject_GC_Del(it); } static int iter_traverse(seqiterobject *it, visitproc visit, void *arg) { Py_VISIT(it->it_seq); return 0; } static PyObject * iter_iternext(PyObject *iterator) { seqiterobject *it; PyObject *seq; PyObject *result; assert(PySeqIter_Check(iterator)); it = (seqiterobject *)iterator; seq = it->it_seq; if (seq == NULL) return NULL; if (it->it_index == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "iter index too large"); return NULL; } result = PySequence_GetItem(seq, it->it_index); if (result != NULL) { it->it_index++; return result; } if (PyErr_ExceptionMatches(PyExc_IndexError) || PyErr_ExceptionMatches(PyExc_StopIteration)) { PyErr_Clear(); it->it_seq = NULL; Py_DECREF(seq); } return NULL; } static PyObject * iter_len(seqiterobject *it) { Py_ssize_t seqsize, len; if (it->it_seq) { if (_PyObject_HasLen(it->it_seq)) { seqsize = PySequence_Size(it->it_seq); if (seqsize == -1) return NULL; } else { Py_RETURN_NOTIMPLEMENTED; } len = seqsize - it->it_index; if (len >= 0) return PyLong_FromSsize_t(len); } return PyLong_FromLong(0); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * iter_reduce(seqiterobject *it) { if (it->it_seq != NULL) return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"), it->it_seq, it->it_index); else return Py_BuildValue("N(())", _PyObject_GetBuiltin("iter")); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyObject * iter_setstate(seqiterobject *it, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; if (it->it_seq != NULL) { if (index < 0) index = 0; it->it_index = index; } Py_RETURN_NONE; } PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef seqiter_methods[] = { {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)iter_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)iter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PySeqIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "iterator", /* tp_name */ sizeof(seqiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)iter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)iter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ iter_iternext, /* tp_iternext */ seqiter_methods, /* tp_methods */ 0, /* tp_members */ }; /* -------------------------------------- */ typedef struct { PyObject_HEAD PyObject *it_callable; /* Set to NULL when iterator is exhausted */ PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */ } calliterobject; PyObject * PyCallIter_New(PyObject *callable, PyObject *sentinel) { calliterobject *it; it = PyObject_GC_New(calliterobject, &PyCallIter_Type); if (it == NULL) return NULL; Py_INCREF(callable); it->it_callable = callable; Py_INCREF(sentinel); it->it_sentinel = sentinel; _PyObject_GC_TRACK(it); return (PyObject *)it; } static void calliter_dealloc(calliterobject *it) { _PyObject_GC_UNTRACK(it); Py_XDECREF(it->it_callable); Py_XDECREF(it->it_sentinel); PyObject_GC_Del(it); } static int calliter_traverse(calliterobject *it, visitproc visit, void *arg) { Py_VISIT(it->it_callable); Py_VISIT(it->it_sentinel); return 0; } static PyObject * calliter_iternext(calliterobject *it) { PyObject *result; if (it->it_callable == NULL) { return NULL; } result = _PyObject_CallNoArg(it->it_callable); if (result != NULL) { int ok; ok = PyObject_RichCompareBool(it->it_sentinel, result, Py_EQ); if (ok == 0) { return result; /* Common case, fast path */ } Py_DECREF(result); if (ok > 0) { Py_CLEAR(it->it_callable); Py_CLEAR(it->it_sentinel); } } else if (PyErr_ExceptionMatches(PyExc_StopIteration)) { PyErr_Clear(); Py_CLEAR(it->it_callable); Py_CLEAR(it->it_sentinel); } return NULL; } static PyObject * calliter_reduce(calliterobject *it) { if (it->it_callable != NULL && it->it_sentinel != NULL) return Py_BuildValue("N(OO)", _PyObject_GetBuiltin("iter"), it->it_callable, it->it_sentinel); else return Py_BuildValue("N(())", _PyObject_GetBuiltin("iter")); } static PyMethodDef calliter_methods[] = { {"__reduce__", (PyCFunction)calliter_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyCallIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "callable_iterator", /* tp_name */ sizeof(calliterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)calliter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)calliter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)calliter_iternext, /* tp_iternext */ calliter_methods, /* tp_methods */ };
10,326
300
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/object.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/log/countbranch.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/cellobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/classobject.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/enumobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/genobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/iterobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/memoryobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/namespaceobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/odictobject.h" #include "third_party/python/Include/pycapsule.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/rangeobject.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/weakrefobject.h" /* clang-format off */ _Py_IDENTIFIER(Py_Repr); _Py_IDENTIFIER(__bytes__); _Py_IDENTIFIER(__dir__); _Py_IDENTIFIER(__isabstractmethod__); _Py_IDENTIFIER(builtins); #ifdef Py_REF_DEBUG Py_ssize_t _Py_RefTotal; Py_ssize_t _Py_GetRefTotal(void) { PyObject *o; Py_ssize_t total = _Py_RefTotal; o = _PySet_Dummy; if (o != NULL) total -= o->ob_refcnt; return total; } void _PyDebug_PrintTotalRefs(void) { PyObject *xoptions, *value; _Py_IDENTIFIER(showrefcount); xoptions = PySys_GetXOptions(); if (xoptions == NULL) return; value = _PyDict_GetItemId(xoptions, &PyId_showrefcount); if (value == Py_True) fprintf(stderr, "[%" PY_FORMAT_SIZE_T "d refs, " "%" PY_FORMAT_SIZE_T "d blocks]\n", _Py_GetRefTotal(), _Py_GetAllocatedBlocks()); } #endif /* Py_REF_DEBUG */ /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros. These are used by the individual routines for object creation. Do not call them otherwise, they do not initialize the object! */ #ifdef Py_TRACE_REFS /* Head of circular doubly-linked list of all objects. These are linked * together via the _ob_prev and _ob_next members of a PyObject, which * exist only in a Py_TRACE_REFS build. */ static PyObject refchain = {&refchain, &refchain}; /* Insert op at the front of the list of all objects. If force is true, * op is added even if _ob_prev and _ob_next are non-NULL already. If * force is false amd _ob_prev or _ob_next are non-NULL, do nothing. * force should be true if and only if op points to freshly allocated, * uninitialized memory, or you've unlinked op from the list and are * relinking it into the front. * Note that objects are normally added to the list via _Py_NewReference, * which is called by PyObject_Init. Not all objects are initialized that * way, though; exceptions include statically allocated type objects, and * statically allocated singletons (like Py_True and Py_None). */ void _Py_AddToAllObjects(PyObject *op, int force) { #ifdef Py_DEBUG if (!force) { /* If it's initialized memory, op must be in or out of * the list unambiguously. */ assert((op->_ob_prev == NULL) == (op->_ob_next == NULL)); } #endif if (force || op->_ob_prev == NULL) { op->_ob_next = refchain._ob_next; op->_ob_prev = &refchain; refchain._ob_next->_ob_prev = op; refchain._ob_next = op; } } #endif /* Py_TRACE_REFS */ #ifdef COUNT_ALLOCS static PyTypeObject *type_list; /* All types are added to type_list, at least when they get one object created. That makes them immortal, which unfortunately contributes to garbage itself. If unlist_types_without_objects is set, they will be removed from the type_list once the last object is deallocated. */ static int unlist_types_without_objects; extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs; extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs; extern Py_ssize_t null_strings, one_strings; void dump_counts(FILE* f) { PyTypeObject *tp; PyObject *xoptions, *value; _Py_IDENTIFIER(showalloccount); xoptions = PySys_GetXOptions(); if (xoptions == NULL) return; value = _PyDict_GetItemId(xoptions, &PyId_showalloccount); if (value != Py_True) return; for (tp = type_list; tp; tp = tp->tp_next) fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, " "freed: %" PY_FORMAT_SIZE_T "d, " "max in use: %" PY_FORMAT_SIZE_T "d\n", tp->tp_name, tp->tp_allocs, tp->tp_frees, tp->tp_maxalloc); fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, " "empty: %" PY_FORMAT_SIZE_T "d\n", fast_tuple_allocs, tuple_zero_allocs); fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, " "neg: %" PY_FORMAT_SIZE_T "d\n", quick_int_allocs, quick_neg_int_allocs); fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, " "1-strings: %" PY_FORMAT_SIZE_T "d\n", null_strings, one_strings); } PyObject * get_counts(void) { PyTypeObject *tp; PyObject *result; PyObject *v; result = PyList_New(0); if (result == NULL) return NULL; for (tp = type_list; tp; tp = tp->tp_next) { v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs, tp->tp_frees, tp->tp_maxalloc); if (v == NULL) { Py_DECREF(result); return NULL; } if (PyList_Append(result, v) < 0) { Py_DECREF(v); Py_DECREF(result); return NULL; } Py_DECREF(v); } return result; } void inc_count(PyTypeObject *tp) { if (tp->tp_next == NULL && tp->tp_prev == NULL) { /* first time; insert in linked list */ if (tp->tp_next != NULL) /* sanity check */ Py_FatalError("XXX inc_count sanity check"); if (type_list) type_list->tp_prev = tp; tp->tp_next = type_list; /* Note that as of Python 2.2, heap-allocated type objects * can go away, but this code requires that they stay alive * until program exit. That's why we're careful with * refcounts here. type_list gets a new reference to tp, * while ownership of the reference type_list used to hold * (if any) was transferred to tp->tp_next in the line above. * tp is thus effectively immortal after this. */ Py_INCREF(tp); type_list = tp; #ifdef Py_TRACE_REFS /* Also insert in the doubly-linked list of all objects, * if not already there. */ _Py_AddToAllObjects((PyObject *)tp, 0); #endif } tp->tp_allocs++; if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc) tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees; } void dec_count(PyTypeObject *tp) { tp->tp_frees++; if (unlist_types_without_objects && tp->tp_allocs == tp->tp_frees) { /* unlink the type from type_list */ if (tp->tp_prev) tp->tp_prev->tp_next = tp->tp_next; else type_list = tp->tp_next; if (tp->tp_next) tp->tp_next->tp_prev = tp->tp_prev; tp->tp_next = tp->tp_prev = NULL; Py_DECREF(tp); } } #endif #ifdef Py_REF_DEBUG /* Log a fatal error; doesn't return. */ void _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op) { char buf[300]; PyOS_snprintf(buf, sizeof(buf), "%s:%i object at %p has negative ref count " "%" PY_FORMAT_SIZE_T "d", fname, lineno, op, op->ob_refcnt); Py_FatalError(buf); } #endif /* Py_REF_DEBUG */ void Py_IncRef(PyObject *o) { Py_XINCREF(o); } void Py_DecRef(PyObject *o) { Py_XDECREF(o); } PyObject * PyObject_Init(PyObject *op, PyTypeObject *tp) { if (op == NULL) return PyErr_NoMemory(); /* Any changes should be reflected in PyObject_INIT (objimpl.h) */ Py_TYPE(op) = tp; _Py_NewReference(op); return op; } PyVarObject * PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size) { if (op == NULL) return (PyVarObject *) PyErr_NoMemory(); /* Any changes should be reflected in PyObject_INIT_VAR */ op->ob_size = size; Py_TYPE(op) = tp; _Py_NewReference((PyObject *)op); return op; } PyObject * _PyObject_New(PyTypeObject *tp) { PyObject *op; op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); if (op == NULL) return PyErr_NoMemory(); return PyObject_INIT(op, tp); } PyVarObject * _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems) { PyVarObject *op; const size_t size = _PyObject_VAR_SIZE(tp, nitems); op = (PyVarObject *) PyObject_MALLOC(size); if (op == NULL) return (PyVarObject *)PyErr_NoMemory(); return PyObject_INIT_VAR(op, tp, nitems); } void PyObject_CallFinalizer(PyObject *self) { PyTypeObject *tp = Py_TYPE(self); /* The former could happen on heaptypes created from the C API, e.g. PyType_FromSpec(). */ if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) || tp->tp_finalize == NULL) return; /* tp_finalize should only be called once. */ if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self)) return; tp->tp_finalize(self); if (PyType_IS_GC(tp)) _PyGC_SET_FINALIZED(self, 1); } int PyObject_CallFinalizerFromDealloc(PyObject *self) { Py_ssize_t refcnt; /* Temporarily resurrect the object. */ if (self->ob_refcnt != 0) { Py_FatalError("PyObject_CallFinalizerFromDealloc called on " "object with a non-zero refcount"); } self->ob_refcnt = 1; PyObject_CallFinalizer(self); /* Undo the temporary resurrection; can't use DECREF here, it would * cause a recursive call. */ assert(self->ob_refcnt > 0); if (--self->ob_refcnt == 0) return 0; /* this is the normal path out */ /* tp_finalize resurrected it! Make it look like the original Py_DECREF * never happened. */ refcnt = self->ob_refcnt; _Py_NewReference(self); self->ob_refcnt = refcnt; if (PyType_IS_GC(Py_TYPE(self))) { assert(_PyGC_REFS(self) != _PyGC_REFS_UNTRACKED); } /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so * we need to undo that. */ _Py_DEC_REFTOTAL; /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object * chain, so no more to do there. * If COUNT_ALLOCS, the original decref bumped tp_frees, and * _Py_NewReference bumped tp_allocs: both of those need to be * undone. */ #ifdef COUNT_ALLOCS --Py_TYPE(self)->tp_frees; --Py_TYPE(self)->tp_allocs; #endif return -1; } int PyObject_Print(PyObject *op, FILE *fp, int flags) { int ret = 0; if (PyErr_CheckSignals()) return -1; #ifdef USE_STACKCHECK if (PyOS_CheckStack()) { PyErr_SetString(PyExc_MemoryError, "stack overflow"); return -1; } #endif clearerr(fp); /* Clear any previous error condition */ if (op == NULL) { Py_BEGIN_ALLOW_THREADS fprintf(fp, "<nil>"); Py_END_ALLOW_THREADS } else { if (op->ob_refcnt <= 0) /* XXX(twouters) cast refcount to long until %zd is universally available */ Py_BEGIN_ALLOW_THREADS fprintf(fp, "<refcnt %ld at %p>", (long)op->ob_refcnt, op); Py_END_ALLOW_THREADS else { PyObject *s; if (flags & Py_PRINT_RAW) s = PyObject_Str(op); else s = PyObject_Repr(op); if (s == NULL) ret = -1; else if (PyBytes_Check(s)) { fwrite(PyBytes_AS_STRING(s), 1, PyBytes_GET_SIZE(s), fp); } else if (PyUnicode_Check(s)) { PyObject *t; t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace"); if (t == NULL) { ret = -1; } else { fwrite(PyBytes_AS_STRING(t), 1, PyBytes_GET_SIZE(t), fp); Py_DECREF(t); } } else { PyErr_Format(PyExc_TypeError, "str() or repr() returned '%.100s'", s->ob_type->tp_name); ret = -1; } Py_XDECREF(s); } } if (ret == 0) { if (ferror(fp)) { PyErr_SetFromErrno(PyExc_IOError); clearerr(fp); ret = -1; } } return ret; } /* For debugging convenience. Set a breakpoint here and call it from your DLL */ void _Py_BreakPoint(void) { } /* Heuristic checking if the object memory has been deallocated. Rely on the debug hooks on Python memory allocators which fills the memory with DEADBYTE (0xDB) when memory is deallocated. The function can be used to prevent segmentation fault on dereferencing pointers like 0xdbdbdbdbdbdbdbdb. Such pointer is very unlikely to be mapped in memory. */ int _PyObject_IsFreed(PyObject *op) { uintptr_t ptr = (uintptr_t)op; if (_PyMem_IsFreed(&ptr, sizeof(ptr))) { return 1; } int freed = _PyMem_IsFreed(&op->ob_type, sizeof(op->ob_type)); /* ignore op->ob_ref: the value can have be modified by Py_INCREF() and Py_DECREF(). */ #ifdef Py_TRACE_REFS freed &= _PyMem_IsFreed(&op->_ob_next, sizeof(op->_ob_next)); freed &= _PyMem_IsFreed(&op->_ob_prev, sizeof(op->_ob_prev)); #endif return freed; } /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */ void _PyObject_Dump(PyObject* op) { if (op == NULL) { fprintf(stderr, "<NULL object>\n"); fflush(stderr); return; } if (_PyObject_IsFreed(op)) { /* It seems like the object memory has been freed: don't access it to prevent a segmentation fault. */ fprintf(stderr, "<freed object>\n"); return; } // PyGILState_STATE gil; PyObject *error_type, *error_value, *error_traceback; fprintf(stderr, "object : "); fflush(stderr); // gil = PyGILState_Ensure(); PyErr_Fetch(&error_type, &error_value, &error_traceback); (void)PyObject_Print(op, stderr, 0); fflush(stderr); PyErr_Restore(error_type, error_value, error_traceback); // PyGILState_Release(gil); /* XXX(twouters) cast refcount to long until %zd is universally available */ fprintf(stderr, "\n" "type : %s\n" "refcount: %ld\n" "address : %p\n", Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, (long)op->ob_refcnt, op); fflush(stderr); } PyObject * PyObject_Repr(PyObject *v) { PyObject *res; if (PyErr_CheckSignals()) return NULL; #ifdef USE_STACKCHECK if (PyOS_CheckStack()) { PyErr_SetString(PyExc_MemoryError, "stack overflow"); return NULL; } #endif if (v == NULL) return PyUnicode_FromString("<NULL>"); if (Py_TYPE(v)->tp_repr == NULL) return PyUnicode_FromFormat("<%s object at %p>", v->ob_type->tp_name, v); #ifdef Py_DEBUG /* PyObject_Repr() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); #endif /* It is possible for a type to have a tp_repr representation that loops infinitely. */ if (Py_EnterRecursiveCall(" while getting the repr of an object")) return NULL; res = (*v->ob_type->tp_repr)(v); Py_LeaveRecursiveCall(); if (res == NULL) return NULL; if (!PyUnicode_Check(res)) { PyErr_Format(PyExc_TypeError, "__repr__ returned non-string (type %.200s)", res->ob_type->tp_name); Py_DECREF(res); return NULL; } #ifndef Py_DEBUG if (PyUnicode_READY(res) < 0) return NULL; #endif return res; } PyObject * PyObject_Str(PyObject *v) { PyObject *res; if (PyErr_CheckSignals()) return NULL; #ifdef USE_STACKCHECK if (PyOS_CheckStack()) { PyErr_SetString(PyExc_MemoryError, "stack overflow"); return NULL; } #endif if (v == NULL) return PyUnicode_FromString("<NULL>"); if (PyUnicode_CheckExact(v)) { #ifndef Py_DEBUG if (PyUnicode_READY(v) < 0) return NULL; #endif Py_INCREF(v); return v; } if (Py_TYPE(v)->tp_str == NULL) return PyObject_Repr(v); #ifdef Py_DEBUG /* PyObject_Str() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); #endif /* It is possible for a type to have a tp_str representation that loops infinitely. */ if (Py_EnterRecursiveCall(" while getting the str of an object")) return NULL; res = (*Py_TYPE(v)->tp_str)(v); Py_LeaveRecursiveCall(); if (res == NULL) return NULL; if (!PyUnicode_Check(res)) { PyErr_Format(PyExc_TypeError, "__str__ returned non-string (type %.200s)", Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } #ifndef Py_DEBUG if (PyUnicode_READY(res) < 0) return NULL; #endif assert(_PyUnicode_CheckConsistency(res, 1)); return res; } PyObject * PyObject_ASCII(PyObject *v) { PyObject *repr, *ascii, *res; repr = PyObject_Repr(v); if (repr == NULL) return NULL; if (PyUnicode_IS_ASCII(repr)) return repr; /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace"); Py_DECREF(repr); if (ascii == NULL) return NULL; res = PyUnicode_DecodeASCII( PyBytes_AS_STRING(ascii), PyBytes_GET_SIZE(ascii), NULL); Py_DECREF(ascii); return res; } PyObject * PyObject_Bytes(PyObject *v) { PyObject *result, *func; if (v == NULL) return PyBytes_FromString("<NULL>"); if (PyBytes_CheckExact(v)) { Py_INCREF(v); return v; } func = _PyObject_LookupSpecial(v, &PyId___bytes__); if (func != NULL) { result = PyObject_CallFunctionObjArgs(func, NULL); Py_DECREF(func); if (result == NULL) return NULL; if (!PyBytes_Check(result)) { PyErr_Format(PyExc_TypeError, "__bytes__ returned non-bytes (type %.200s)", Py_TYPE(result)->tp_name); Py_DECREF(result); return NULL; } return result; } else if (PyErr_Occurred()) return NULL; return PyBytes_FromObject(v); } /* For Python 3.0.1 and later, the old three-way comparison has been completely removed in favour of rich comparisons. PyObject_Compare() and PyObject_Cmp() are gone, and the builtin cmp function no longer exists. The old tp_compare slot has been renamed to tp_reserved, and should no longer be used. Use tp_richcompare instead. See (*) below for practical amendments. tp_richcompare gets called with a first argument of the appropriate type and a second object of an arbitrary type. We never do any kind of coercion. The tp_richcompare slot should return an object, as follows: NULL if an exception occurred NotImplemented if the requested comparison is not implemented any other false value if the requested comparison is false any other true value if the requested comparison is true The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get NotImplemented. (*) Practical amendments: - If rich comparison returns NotImplemented, == and != are decided by comparing the object pointer (i.e. falling back to the base object implementation). */ /* Map rich comparison operators to their swapped version, e.g. LT <--> GT */ int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE}; static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="}; /* Perform a rich comparison, raising TypeError when the requested comparison operator is not supported. */ static PyObject * do_richcompare(PyObject *v, PyObject *w, int op) { richcmpfunc f; PyObject *res; int checked_reverse_op = 0; if (v->ob_type != w->ob_type && PyType_IsSubtype(w->ob_type, v->ob_type) && (f = w->ob_type->tp_richcompare) != NULL) { checked_reverse_op = 1; res = (*f)(w, v, _Py_SwappedOp[op]); if (res != Py_NotImplemented) return res; Py_DECREF(res); } if ((f = v->ob_type->tp_richcompare) != NULL) { res = (*f)(v, w, op); if (res != Py_NotImplemented) return res; Py_DECREF(res); } if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) { res = (*f)(w, v, _Py_SwappedOp[op]); if (res != Py_NotImplemented) return res; Py_DECREF(res); } /* If neither object implements it, provide a sensible default for == and !=, but raise an exception for ordering. */ switch (op) { case Py_EQ: res = (v == w) ? Py_True : Py_False; break; case Py_NE: res = (v != w) ? Py_True : Py_False; break; default: PyErr_Format(PyExc_TypeError, "'%s' not supported between instances of '%.100s' and '%.100s'", opstrings[op], v->ob_type->tp_name, w->ob_type->tp_name); return NULL; } Py_INCREF(res); return res; } /* Perform a rich comparison with object result. This wraps do_richcompare() with a check for NULL arguments and a recursion check. */ PyObject * PyObject_RichCompare(PyObject *v, PyObject *w, int op) { PyObject *res; assert(Py_LT <= op && op <= Py_GE); if (v == NULL || w == NULL) { if (!PyErr_Occurred()) PyErr_BadInternalCall(); return NULL; } if (Py_EnterRecursiveCall(" in comparison")) return NULL; res = do_richcompare(v, w, op); Py_LeaveRecursiveCall(); return res; } /* Perform a rich comparison with integer result. This wraps PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */ int PyObject_RichCompareBool(PyObject *v, PyObject *w, int op) { PyObject *res; int ok; /* Quick result when objects are the same. Guarantees that identity implies equality. */ if (v == w) { if (op == Py_EQ) return 1; else if (op == Py_NE) return 0; } res = PyObject_RichCompare(v, w, op); if (res == NULL) return -1; if (PyBool_Check(res)) ok = (res == Py_True); else ok = PyObject_IsTrue(res); Py_DECREF(res); return ok; } Py_hash_t PyObject_HashNotImplemented(PyObject *v) { PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", Py_TYPE(v)->tp_name); return -1; } Py_hash_t PyObject_Hash(PyObject *v) { PyTypeObject *tp = Py_TYPE(v); if (tp->tp_hash != NULL) return (*tp->tp_hash)(v); /* To keep to the general practice that inheriting * solely from object in C code should work without * an explicit call to PyType_Ready, we implicitly call * PyType_Ready here and then check the tp_hash slot again */ if (tp->tp_dict == NULL) { if (PyType_Ready(tp) < 0) return -1; if (tp->tp_hash != NULL) return (*tp->tp_hash)(v); } /* Otherwise, the object can't be hashed */ return PyObject_HashNotImplemented(v); } PyObject * PyObject_GetAttrString(PyObject *v, const char *name) { PyObject *w, *res; if (Py_TYPE(v)->tp_getattr != NULL) return (*Py_TYPE(v)->tp_getattr)(v, (char*)name); w = PyUnicode_InternFromString(name); if (w == NULL) return NULL; res = PyObject_GetAttr(v, w); Py_DECREF(w); return res; } int PyObject_HasAttrString(PyObject *v, const char *name) { PyObject *res = PyObject_GetAttrString(v, name); if (res != NULL) { Py_DECREF(res); return 1; } PyErr_Clear(); return 0; } int PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w) { PyObject *s; int res; if (Py_TYPE(v)->tp_setattr != NULL) return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w); s = PyUnicode_InternFromString(name); if (s == NULL) return -1; res = PyObject_SetAttr(v, s, w); Py_XDECREF(s); return res; } int _PyObject_IsAbstract(PyObject *obj) { int res; PyObject* isabstract; if (obj == NULL) return 0; isabstract = _PyObject_GetAttrId(obj, &PyId___isabstractmethod__); if (isabstract == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); return 0; } return -1; } res = PyObject_IsTrue(isabstract); Py_DECREF(isabstract); return res; } PyObject * _PyObject_GetAttrId(PyObject *v, _Py_Identifier *name) { PyObject *result; PyObject *oname = _PyUnicode_FromId(name); /* borrowed */ if (!oname) return NULL; result = PyObject_GetAttr(v, oname); return result; } int _PyObject_HasAttrId(PyObject *v, _Py_Identifier *name) { int result; PyObject *oname = _PyUnicode_FromId(name); /* borrowed */ if (!oname) return -1; result = PyObject_HasAttr(v, oname); return result; } int _PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w) { int result; PyObject *oname = _PyUnicode_FromId(name); /* borrowed */ if (!oname) return -1; result = PyObject_SetAttr(v, oname, w); return result; } PyObject * PyObject_GetAttr(PyObject *v, PyObject *name) { PyTypeObject *tp = Py_TYPE(v); if (!PyUnicode_Check(name)) { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return NULL; } if (tp->tp_getattro != NULL) return (*tp->tp_getattro)(v, name); if (tp->tp_getattr != NULL) { char *name_str = PyUnicode_AsUTF8(name); if (name_str == NULL) return NULL; return (*tp->tp_getattr)(v, name_str); } PyErr_Format(PyExc_AttributeError, "'%.50s' object has no attribute '%U'", tp->tp_name, name); return NULL; } int PyObject_HasAttr(PyObject *v, PyObject *name) { PyObject *res = PyObject_GetAttr(v, name); if (res != NULL) { Py_DECREF(res); return 1; } PyErr_Clear(); return 0; } int PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value) { PyTypeObject *tp = Py_TYPE(v); int err; if (!PyUnicode_Check(name)) { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return -1; } Py_INCREF(name); PyUnicode_InternInPlace(&name); if (tp->tp_setattro != NULL) { err = (*tp->tp_setattro)(v, name, value); Py_DECREF(name); return err; } if (tp->tp_setattr != NULL) { char *name_str = PyUnicode_AsUTF8(name); if (name_str == NULL) return -1; err = (*tp->tp_setattr)(v, name_str, value); Py_DECREF(name); return err; } Py_DECREF(name); assert(name->ob_refcnt >= 1); if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) PyErr_Format(PyExc_TypeError, "'%.100s' object has no attributes " "(%s .%U)", tp->tp_name, value==NULL ? "del" : "assign to", name); else PyErr_Format(PyExc_TypeError, "'%.100s' object has only read-only attributes " "(%s .%U)", tp->tp_name, value==NULL ? "del" : "assign to", name); return -1; } /* Helper to get a pointer to an object's __dict__ slot, if any */ PyObject ** _PyObject_GetDictPtr(PyObject *obj) { Py_ssize_t dictoffset; PyTypeObject *tp = Py_TYPE(obj); dictoffset = tp->tp_dictoffset; if (dictoffset == 0) return NULL; if (dictoffset < 0) { Py_ssize_t tsize; size_t size; tsize = ((PyVarObject *)obj)->ob_size; if (tsize < 0) tsize = -tsize; size = _PyObject_VAR_SIZE(tp, tsize); dictoffset += (long)size; assert(dictoffset > 0); assert(dictoffset % SIZEOF_VOID_P == 0); } return (PyObject **) ((char *)obj + dictoffset); } PyObject * PyObject_SelfIter(PyObject *obj) { Py_INCREF(obj); return obj; } /* Convenience function to get a builtin from its name */ PyObject * _PyObject_GetBuiltin(const char *name) { PyObject *mod_name, *mod, *attr; mod_name = _PyUnicode_FromId(&PyId_builtins); /* borrowed */ if (mod_name == NULL) return NULL; mod = PyImport_Import(mod_name); if (mod == NULL) return NULL; attr = PyObject_GetAttrString(mod, name); Py_DECREF(mod); return attr; } /* Helper used when the __next__ method is removed from a type: tp_iternext is never NULL and can be safely called without checking on every iteration. */ PyObject * _PyObject_NextNotImplemented(PyObject *self) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not iterable", Py_TYPE(self)->tp_name); return NULL; } /* Specialized version of _PyObject_GenericGetAttrWithDict specifically for the LOAD_METHOD opcode. Return 1 if a method is found, 0 if it's a regular attribute from __dict__ or something returned by using a descriptor protocol. `method` will point to the resolved attribute or NULL. In the latter case, an error will be set. */ int _PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { PyTypeObject *tp = Py_TYPE(obj); PyObject *descr; descrgetfunc f = NULL; PyObject **dictptr, *dict; PyObject *attr; int meth_found = 0; assert(*method == NULL); if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr || !PyUnicode_Check(name)) { *method = PyObject_GetAttr(obj, name); return 0; } if (tp->tp_dict == NULL && PyType_Ready(tp) < 0) return 0; descr = _PyType_Lookup(tp, name); if (descr != NULL) { Py_INCREF(descr); if (PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type)) { meth_found = 1; } else { f = descr->ob_type->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { *method = f(descr, obj, (PyObject *)obj->ob_type); Py_DECREF(descr); return 0; } } } dictptr = _PyObject_GetDictPtr(obj); if (dictptr != NULL && (dict = *dictptr) != NULL) { Py_INCREF(dict); attr = PyDict_GetItem(dict, name); if (attr != NULL) { Py_INCREF(attr); *method = attr; Py_DECREF(dict); Py_XDECREF(descr); return 0; } Py_DECREF(dict); } if (meth_found) { *method = descr; return 1; } if (f != NULL) { *method = f(descr, obj, (PyObject *)Py_TYPE(obj)); Py_DECREF(descr); return 0; } if (descr != NULL) { *method = descr; return 0; } PyErr_Format(PyExc_AttributeError, "'%.50s' object has no attribute '%U'", tp->tp_name, name); return 0; } /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */ PyObject * _PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict) { PyTypeObject *tp = Py_TYPE(obj); PyObject *descr = NULL; PyObject *res = NULL; descrgetfunc f; Py_ssize_t dictoffset; PyObject **dictptr; if (UNLIKELY(!PyUnicode_Check(name))){ PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return NULL; } Py_INCREF(name); if (UNLIKELY(tp->tp_dict == NULL)) { if (PyType_Ready(tp) < 0) goto done; } descr = _PyType_Lookup(tp, name); f = NULL; if (descr != NULL) { Py_INCREF(descr); f = descr->ob_type->tp_descr_get; if (f != NULL && PyDescr_IsData(descr)) { res = f(descr, obj, (PyObject *)obj->ob_type); goto done; } } if (LIKELY(dict == NULL)) { /* Inline _PyObject_GetDictPtr */ dictoffset = tp->tp_dictoffset; if (dictoffset != 0) { if (dictoffset < 0) { Py_ssize_t tsize; size_t size; tsize = ((PyVarObject *)obj)->ob_size; if (tsize < 0) tsize = -tsize; size = _PyObject_VAR_SIZE(tp, tsize); assert(size <= PY_SSIZE_T_MAX); dictoffset += (Py_ssize_t)size; assert(dictoffset > 0); assert(dictoffset % SIZEOF_VOID_P == 0); } dictptr = (PyObject **) ((char *)obj + dictoffset); dict = *dictptr; } } if (dict != NULL) { Py_INCREF(dict); res = PyDict_GetItem(dict, name); if (res != NULL) { Py_INCREF(res); Py_DECREF(dict); goto done; } Py_DECREF(dict); } if (f != NULL) { res = f(descr, obj, (PyObject *)Py_TYPE(obj)); goto done; } if (descr != NULL) { res = descr; descr = NULL; goto done; } PyErr_Format(PyExc_AttributeError, "'%.50s' object has no attribute '%U'", tp->tp_name, name); done: Py_XDECREF(descr); Py_DECREF(name); return res; } PyObject * PyObject_GenericGetAttr(PyObject *obj, PyObject *name) { return _PyObject_GenericGetAttrWithDict(obj, name, NULL); } int _PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name, PyObject *value, PyObject *dict) { PyTypeObject *tp = Py_TYPE(obj); PyObject *descr; descrsetfunc f; PyObject **dictptr; int res = -1; if (!PyUnicode_Check(name)){ PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); return -1; } if (tp->tp_dict == NULL && PyType_Ready(tp) < 0) return -1; Py_INCREF(name); descr = _PyType_Lookup(tp, name); if (descr != NULL) { Py_INCREF(descr); f = descr->ob_type->tp_descr_set; if (f != NULL) { res = f(descr, obj, value); goto done; } } if (dict == NULL) { dictptr = _PyObject_GetDictPtr(obj); if (dictptr == NULL) { if (descr == NULL) { PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%U'", tp->tp_name, name); } else { PyErr_Format(PyExc_AttributeError, "'%.50s' object attribute '%U' is read-only", tp->tp_name, name); } goto done; } res = _PyObjectDict_SetItem(tp, dictptr, name, value); } else { Py_INCREF(dict); if (value == NULL) res = PyDict_DelItem(dict, name); else res = PyDict_SetItem(dict, name, value); Py_DECREF(dict); } if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) PyErr_SetObject(PyExc_AttributeError, name); done: Py_XDECREF(descr); Py_DECREF(name); return res; } int PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value) { return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL); } int PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context) { PyObject **dictptr = _PyObject_GetDictPtr(obj); if (dictptr == NULL) { PyErr_SetString(PyExc_AttributeError, "This object has no __dict__"); return -1; } if (value == NULL) { PyErr_SetString(PyExc_TypeError, "cannot delete __dict__"); return -1; } if (!PyDict_Check(value)) { PyErr_Format(PyExc_TypeError, "__dict__ must be set to a dictionary, " "not a '%.200s'", Py_TYPE(value)->tp_name); return -1; } Py_INCREF(value); Py_XSETREF(*dictptr, value); return 0; } /* Test a value used as condition, e.g., in a for or if statement. Return -1 if an error occurred */ int PyObject_IsTrue(PyObject *v) { Py_ssize_t res; if (v == Py_True) return 1; if (v == Py_False) return 0; if (v == Py_None) return 0; else if (v->ob_type->tp_as_number != NULL && v->ob_type->tp_as_number->nb_bool != NULL) res = (*v->ob_type->tp_as_number->nb_bool)(v); else if (v->ob_type->tp_as_mapping != NULL && v->ob_type->tp_as_mapping->mp_length != NULL) res = (*v->ob_type->tp_as_mapping->mp_length)(v); else if (v->ob_type->tp_as_sequence != NULL && v->ob_type->tp_as_sequence->sq_length != NULL) res = (*v->ob_type->tp_as_sequence->sq_length)(v); else return 1; /* if it is negative, it should be either -1 or -2 */ return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); } /* equivalent of 'not v' Return -1 if an error occurred */ int PyObject_Not(PyObject *v) { int res; res = PyObject_IsTrue(v); if (res < 0) return res; return res == 0; } /* Test whether an object can be called */ int PyCallable_Check(PyObject *x) { if (x == NULL) return 0; return x->ob_type->tp_call != NULL; } /* Helper for PyObject_Dir without arguments: returns the local scope. */ static PyObject * _dir_locals(void) { PyObject *names; PyObject *locals; locals = PyEval_GetLocals(); if (locals == NULL) return NULL; names = PyMapping_Keys(locals); if (!names) return NULL; if (!PyList_Check(names)) { PyErr_Format(PyExc_TypeError, "dir(): expected keys() of locals to be a list, " "not '%.200s'", Py_TYPE(names)->tp_name); Py_DECREF(names); return NULL; } if (PyList_Sort(names)) { Py_DECREF(names); return NULL; } /* the locals don't need to be DECREF'd */ return names; } /* Helper for PyObject_Dir: object introspection. */ static PyObject * _dir_object(PyObject *obj) { PyObject *result, *sorted; PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__); assert(obj); if (dirfunc == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "object does not provide __dir__"); return NULL; } /* use __dir__ */ result = PyObject_CallFunctionObjArgs(dirfunc, NULL); Py_DECREF(dirfunc); if (result == NULL) return NULL; /* return sorted(result) */ sorted = PySequence_List(result); Py_DECREF(result); if (sorted == NULL) return NULL; if (PyList_Sort(sorted)) { Py_DECREF(sorted); return NULL; } return sorted; } /* Implementation of dir() -- if obj is NULL, returns the names in the current (local) scope. Otherwise, performs introspection of the object: returns a sorted list of attribute names (supposedly) accessible from the object */ PyObject * PyObject_Dir(PyObject *obj) { return (obj == NULL) ? _dir_locals() : _dir_object(obj); } /* None is a non-NULL undefined value. There is (and should be!) no way to create other objects of this type, so there is exactly one (which is indestructible, by the way). */ /* ARGSUSED */ static PyObject * none_repr(PyObject *op) { return PyUnicode_FromString("None"); } /* ARGUSED */ static void none_dealloc(PyObject* ignore) { /* This should never get called, but we also don't want to SEGV if * we accidentally decref None out of existence. */ Py_FatalError("deallocating None"); } static PyObject * none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) { PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments"); return NULL; } Py_RETURN_NONE; } static int none_bool(PyObject *v) { return 0; } static PyNumberMethods none_as_number = { 0, /* nb_add */ 0, /* nb_subtract */ 0, /* nb_multiply */ 0, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ (inquiry)none_bool, /* nb_bool */ 0, /* nb_invert */ 0, /* nb_lshift */ 0, /* nb_rshift */ 0, /* nb_and */ 0, /* nb_xor */ 0, /* nb_or */ 0, /* nb_int */ 0, /* nb_reserved */ 0, /* nb_float */ 0, /* nb_inplace_add */ 0, /* nb_inplace_subtract */ 0, /* nb_inplace_multiply */ 0, /* nb_inplace_remainder */ 0, /* nb_inplace_power */ 0, /* nb_inplace_lshift */ 0, /* nb_inplace_rshift */ 0, /* nb_inplace_and */ 0, /* nb_inplace_xor */ 0, /* nb_inplace_or */ 0, /* nb_floor_divide */ 0, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ 0, /* nb_index */ }; PyTypeObject _PyNone_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "NoneType", 0, 0, none_dealloc, /*tp_dealloc*/ /*never called*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ none_repr, /*tp_repr*/ &none_as_number, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call */ 0, /*tp_str */ 0, /*tp_getattro */ 0, /*tp_setattro */ 0, /*tp_as_buffer */ Py_TPFLAGS_DEFAULT, /*tp_flags */ 0, /*tp_doc */ 0, /*tp_traverse */ 0, /*tp_clear */ 0, /*tp_richcompare */ 0, /*tp_weaklistoffset */ 0, /*tp_iter */ 0, /*tp_iternext */ 0, /*tp_methods */ 0, /*tp_members */ 0, /*tp_getset */ 0, /*tp_base */ 0, /*tp_dict */ 0, /*tp_descr_get */ 0, /*tp_descr_set */ 0, /*tp_dictoffset */ 0, /*tp_init */ 0, /*tp_alloc */ none_new, /*tp_new */ }; PyObject _Py_NoneStruct = { _PyObject_EXTRA_INIT 1, &_PyNone_Type }; /* NotImplemented is an object that can be used to signal that an operation is not implemented for the given type combination. */ static PyObject * NotImplemented_repr(PyObject *op) { return PyUnicode_FromString("NotImplemented"); } static PyObject * NotImplemented_reduce(PyObject *op) { return PyUnicode_FromString("NotImplemented"); } static PyMethodDef notimplemented_methods[] = { {"__reduce__", (PyCFunction)NotImplemented_reduce, METH_NOARGS, NULL}, {NULL, NULL} }; static PyObject * notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) { PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments"); return NULL; } Py_RETURN_NOTIMPLEMENTED; } static void notimplemented_dealloc(PyObject* ignore) { /* This should never get called, but we also don't want to SEGV if * we accidentally decref NotImplemented out of existence. */ Py_FatalError("deallocating NotImplemented"); } PyTypeObject _PyNotImplemented_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "NotImplementedType", 0, 0, notimplemented_dealloc, /*tp_dealloc*/ /*never called*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ NotImplemented_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call */ 0, /*tp_str */ 0, /*tp_getattro */ 0, /*tp_setattro */ 0, /*tp_as_buffer */ Py_TPFLAGS_DEFAULT, /*tp_flags */ 0, /*tp_doc */ 0, /*tp_traverse */ 0, /*tp_clear */ 0, /*tp_richcompare */ 0, /*tp_weaklistoffset */ 0, /*tp_iter */ 0, /*tp_iternext */ notimplemented_methods, /*tp_methods */ 0, /*tp_members */ 0, /*tp_getset */ 0, /*tp_base */ 0, /*tp_dict */ 0, /*tp_descr_get */ 0, /*tp_descr_set */ 0, /*tp_dictoffset */ 0, /*tp_init */ 0, /*tp_alloc */ notimplemented_new, /*tp_new */ }; PyObject _Py_NotImplementedStruct = { _PyObject_EXTRA_INIT 1, &_PyNotImplemented_Type }; void _Py_ReadyTypes(void) { if (PyType_Ready(&PyBaseObject_Type) < 0) Py_FatalError("Can't initialize object type"); if (PyType_Ready(&PyType_Type) < 0) Py_FatalError("Can't initialize type type"); if (PyType_Ready(&_PyWeakref_RefType) < 0) Py_FatalError("Can't initialize weakref type"); if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) Py_FatalError("Can't initialize callable weakref proxy type"); if (PyType_Ready(&_PyWeakref_ProxyType) < 0) Py_FatalError("Can't initialize weakref proxy type"); if (PyType_Ready(&PyLong_Type) < 0) Py_FatalError("Can't initialize int type"); if (PyType_Ready(&PyBool_Type) < 0) Py_FatalError("Can't initialize bool type"); if (PyType_Ready(&PyByteArray_Type) < 0) Py_FatalError("Can't initialize bytearray type"); if (PyType_Ready(&PyBytes_Type) < 0) Py_FatalError("Can't initialize 'str'"); if (PyType_Ready(&PyList_Type) < 0) Py_FatalError("Can't initialize list type"); if (PyType_Ready(&_PyNone_Type) < 0) Py_FatalError("Can't initialize None type"); if (PyType_Ready(&_PyNotImplemented_Type) < 0) Py_FatalError("Can't initialize NotImplemented type"); if (PyType_Ready(&PyTraceBack_Type) < 0) Py_FatalError("Can't initialize traceback type"); if (PyType_Ready(&PySuper_Type) < 0) Py_FatalError("Can't initialize super type"); if (PyType_Ready(&PyRange_Type) < 0) Py_FatalError("Can't initialize range type"); if (PyType_Ready(&PyDict_Type) < 0) Py_FatalError("Can't initialize dict type"); if (PyType_Ready(&PyDictKeys_Type) < 0) Py_FatalError("Can't initialize dict keys type"); if (PyType_Ready(&PyDictValues_Type) < 0) Py_FatalError("Can't initialize dict values type"); if (PyType_Ready(&PyDictItems_Type) < 0) Py_FatalError("Can't initialize dict items type"); if (PyType_Ready(&PyODict_Type) < 0) Py_FatalError("Can't initialize OrderedDict type"); if (PyType_Ready(&PyODictKeys_Type) < 0) Py_FatalError("Can't initialize odict_keys type"); if (PyType_Ready(&PyODictItems_Type) < 0) Py_FatalError("Can't initialize odict_items type"); if (PyType_Ready(&PyODictValues_Type) < 0) Py_FatalError("Can't initialize odict_values type"); if (PyType_Ready(&PyODictIter_Type) < 0) Py_FatalError("Can't initialize odict_keyiterator type"); if (PyType_Ready(&PySet_Type) < 0) Py_FatalError("Can't initialize set type"); if (PyType_Ready(&PyUnicode_Type) < 0) Py_FatalError("Can't initialize str type"); if (PyType_Ready(&PySlice_Type) < 0) Py_FatalError("Can't initialize slice type"); if (PyType_Ready(&PyStaticMethod_Type) < 0) Py_FatalError("Can't initialize static method type"); if (PyType_Ready(&PyComplex_Type) < 0) Py_FatalError("Can't initialize complex type"); if (PyType_Ready(&PyFloat_Type) < 0) Py_FatalError("Can't initialize float type"); if (PyType_Ready(&PyFrozenSet_Type) < 0) Py_FatalError("Can't initialize frozenset type"); if (PyType_Ready(&PyProperty_Type) < 0) Py_FatalError("Can't initialize property type"); if (PyType_Ready(&_PyManagedBuffer_Type) < 0) Py_FatalError("Can't initialize managed buffer type"); if (PyType_Ready(&PyMemoryView_Type) < 0) Py_FatalError("Can't initialize memoryview type"); if (PyType_Ready(&PyTuple_Type) < 0) Py_FatalError("Can't initialize tuple type"); if (PyType_Ready(&PyEnum_Type) < 0) Py_FatalError("Can't initialize enumerate type"); if (PyType_Ready(&PyReversed_Type) < 0) Py_FatalError("Can't initialize reversed type"); if (PyType_Ready(&PyStdPrinter_Type) < 0) Py_FatalError("Can't initialize StdPrinter"); if (PyType_Ready(&PyCode_Type) < 0) Py_FatalError("Can't initialize code type"); if (PyType_Ready(&PyFrame_Type) < 0) Py_FatalError("Can't initialize frame type"); if (PyType_Ready(&PyCFunction_Type) < 0) Py_FatalError("Can't initialize builtin function type"); if (PyType_Ready(&PyMethod_Type) < 0) Py_FatalError("Can't initialize method type"); if (PyType_Ready(&PyFunction_Type) < 0) Py_FatalError("Can't initialize function type"); if (PyType_Ready(&PyDictProxy_Type) < 0) Py_FatalError("Can't initialize dict proxy type"); if (PyType_Ready(&PyGen_Type) < 0) Py_FatalError("Can't initialize generator type"); if (PyType_Ready(&PyGetSetDescr_Type) < 0) Py_FatalError("Can't initialize get-set descriptor type"); if (PyType_Ready(&PyWrapperDescr_Type) < 0) Py_FatalError("Can't initialize wrapper type"); if (PyType_Ready(&_PyMethodWrapper_Type) < 0) Py_FatalError("Can't initialize method wrapper type"); if (PyType_Ready(&PyEllipsis_Type) < 0) Py_FatalError("Can't initialize ellipsis type"); if (PyType_Ready(&PyMemberDescr_Type) < 0) Py_FatalError("Can't initialize member descriptor type"); if (PyType_Ready(&_PyNamespace_Type) < 0) Py_FatalError("Can't initialize namespace type"); if (PyType_Ready(&PyCapsule_Type) < 0) Py_FatalError("Can't initialize capsule type"); if (PyType_Ready(&PyLongRangeIter_Type) < 0) Py_FatalError("Can't initialize long range iterator type"); if (PyType_Ready(&PyCell_Type) < 0) Py_FatalError("Can't initialize cell type"); if (PyType_Ready(&PyInstanceMethod_Type) < 0) Py_FatalError("Can't initialize instance method type"); if (PyType_Ready(&PyClassMethodDescr_Type) < 0) Py_FatalError("Can't initialize class method descr type"); if (PyType_Ready(&PyMethodDescr_Type) < 0) Py_FatalError("Can't initialize method descr type"); if (PyType_Ready(&PyCallIter_Type) < 0) Py_FatalError("Can't initialize call iter type"); if (PyType_Ready(&PySeqIter_Type) < 0) Py_FatalError("Can't initialize sequence iterator type"); if (PyType_Ready(&PyCoro_Type) < 0) Py_FatalError("Can't initialize coroutine type"); if (PyType_Ready(&_PyCoroWrapper_Type) < 0) Py_FatalError("Can't initialize coroutine wrapper type"); } #ifdef Py_TRACE_REFS void _Py_NewReference(PyObject *op) { _Py_INC_REFTOTAL; op->ob_refcnt = 1; _Py_AddToAllObjects(op, 1); _Py_INC_TPALLOCS(op); } noasan void _Py_ForgetReference(PyObject *op) { #ifdef SLOW_UNREF_CHECK PyObject *p; #endif if (op->ob_refcnt < 0) Py_FatalError("UNREF negative refcnt"); if (op == &refchain || op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) { fprintf(stderr, "* ob\n"); _PyObject_Dump(op); fprintf(stderr, "* op->_ob_prev->_ob_next\n"); _PyObject_Dump(op->_ob_prev->_ob_next); fprintf(stderr, "* op->_ob_next->_ob_prev\n"); _PyObject_Dump(op->_ob_next->_ob_prev); Py_FatalError("UNREF invalid object"); } #ifdef SLOW_UNREF_CHECK for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { if (p == op) break; } if (p == &refchain) /* Not found */ Py_FatalError("UNREF unknown object"); #endif op->_ob_next->_ob_prev = op->_ob_prev; op->_ob_prev->_ob_next = op->_ob_next; op->_ob_next = op->_ob_prev = NULL; _Py_INC_TPFREES(op); } void _Py_Dealloc(PyObject *op) { destructor dealloc = Py_TYPE(op)->tp_dealloc; _Py_ForgetReference(op); (*dealloc)(op); } /* Print all live objects. Because PyObject_Print is called, the * interpreter must be in a healthy state. */ void _Py_PrintReferences(FILE *fp) { PyObject *op; fprintf(fp, "Remaining objects:\n"); for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); if (PyObject_Print(op, fp, 0) != 0) PyErr_Clear(); putc('\n', fp); } } /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this * doesn't make any calls to the Python C API, so is always safe to call. */ void _Py_PrintReferenceAddresses(FILE *fp) { PyObject *op; fprintf(fp, "Remaining object addresses:\n"); for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, op->ob_refcnt, Py_TYPE(op)->tp_name); } PyObject * _Py_GetObjects(PyObject *self, PyObject *args) { int i, n; PyObject *t = NULL; PyObject *res, *op; if (!PyArg_ParseTuple(args, "i|O", &n, &t)) return NULL; op = refchain._ob_next; res = PyList_New(0); if (res == NULL) return NULL; for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { while (op == self || op == args || op == res || op == t || (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { op = op->_ob_next; if (op == &refchain) return res; } if (PyList_Append(res, op) < 0) { Py_DECREF(res); return NULL; } op = op->_ob_next; } return res; } #endif /* Hack to force loading of abstract.o */ Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size; void _PyObject_DebugTypeStats(FILE *out) { _PyCFunction_DebugMallocStats(out); _PyDict_DebugMallocStats(out); _PyFloat_DebugMallocStats(out); _PyFrame_DebugMallocStats(out); _PyList_DebugMallocStats(out); _PyMethod_DebugMallocStats(out); _PyTuple_DebugMallocStats(out); } /* These methods are used to control infinite recursion in repr, str, print, etc. Container objects that may recursively contain themselves, e.g. builtin dictionaries and lists, should use Py_ReprEnter() and Py_ReprLeave() to avoid infinite recursion. Py_ReprEnter() returns 0 the first time it is called for a particular object and 1 every time thereafter. It returns -1 if an exception occurred. Py_ReprLeave() has no return value. See dictobject.c and listobject.c for examples of use. */ int Py_ReprEnter(PyObject *obj) { PyObject *dict; PyObject *list; Py_ssize_t i; dict = PyThreadState_GetDict(); /* Ignore a missing thread-state, so that this function can be called early on startup. */ if (dict == NULL) return 0; list = _PyDict_GetItemId(dict, &PyId_Py_Repr); if (list == NULL) { list = PyList_New(0); if (list == NULL) return -1; if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0) return -1; Py_DECREF(list); } i = PyList_GET_SIZE(list); while (--i >= 0) { if (PyList_GET_ITEM(list, i) == obj) return 1; } if (PyList_Append(list, obj) < 0) return -1; return 0; } void Py_ReprLeave(PyObject *obj) { PyObject *dict; PyObject *list; Py_ssize_t i; PyObject *error_type, *error_value, *error_traceback; PyErr_Fetch(&error_type, &error_value, &error_traceback); dict = PyThreadState_GetDict(); if (dict == NULL) goto finally; list = _PyDict_GetItemId(dict, &PyId_Py_Repr); if (list == NULL || !PyList_Check(list)) goto finally; i = PyList_GET_SIZE(list); /* Count backwards because we always expect obj to be list[-1] */ while (--i >= 0) { if (PyList_GET_ITEM(list, i) == obj) { PyList_SetSlice(list, i, i + 1, NULL); break; } } finally: /* ignore exceptions because there is no way to report them. */ PyErr_Restore(error_type, error_value, error_traceback); } /* Trashcan support. */ /* Current call-stack depth of tp_dealloc calls. */ int _PyTrash_delete_nesting = 0; /* List of objects that still need to be cleaned up, singly linked via their * gc headers' gc_prev pointers. */ PyObject *_PyTrash_delete_later = NULL; /* Add op to the _PyTrash_delete_later list. Called when the current * call-stack depth gets large. op must be a currently untracked gc'ed * object, with refcount 0. Py_DECREF must already have been called on it. */ void _PyTrash_deposit_object(PyObject *op) { assert(PyObject_IS_GC(op)); assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED); assert(op->ob_refcnt == 0); _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; _PyTrash_delete_later = op; } /* The equivalent API, using per-thread state recursion info */ void _PyTrash_thread_deposit_object(PyObject *op) { PyThreadState *tstate = PyThreadState_GET(); assert(PyObject_IS_GC(op)); assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED); assert(op->ob_refcnt == 0); _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *) tstate->trash_delete_later; tstate->trash_delete_later = op; } /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when * the call-stack unwinds again. */ void _PyTrash_destroy_chain(void) { while (_PyTrash_delete_later) { PyObject *op = _PyTrash_delete_later; destructor dealloc = Py_TYPE(op)->tp_dealloc; _PyTrash_delete_later = (PyObject*) _Py_AS_GC(op)->gc.gc_prev; /* Call the deallocator directly. This used to try to * fool Py_DECREF into calling it indirectly, but * Py_DECREF was already called on this object, and in * assorted non-release builds calling Py_DECREF again ends * up distorting allocation statistics. */ assert(op->ob_refcnt == 0); ++_PyTrash_delete_nesting; (*dealloc)(op); --_PyTrash_delete_nesting; } } /* The equivalent API, using per-thread state recursion info */ void _PyTrash_thread_destroy_chain(void) { PyThreadState *tstate = PyThreadState_GET(); while (tstate->trash_delete_later) { PyObject *op = tstate->trash_delete_later; destructor dealloc = Py_TYPE(op)->tp_dealloc; tstate->trash_delete_later = (PyObject*) _Py_AS_GC(op)->gc.gc_prev; /* Call the deallocator directly. This used to try to * fool Py_DECREF into calling it indirectly, but * Py_DECREF was already called on this object, and in * assorted non-release builds calling Py_DECREF again ends * up distorting allocation statistics. */ assert(op->ob_refcnt == 0); ++tstate->trash_delete_nesting; (*dealloc)(op); --tstate->trash_delete_nesting; } } #ifndef Py_TRACE_REFS /* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc. Define this here, so we can undefine the macro. */ #undef _Py_Dealloc void _Py_Dealloc(PyObject *); void _Py_Dealloc(PyObject *op) { _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA (*Py_TYPE(op)->tp_dealloc)(op); } #endif
63,810
2,191
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/accu.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/accu.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ static PyObject * join_list_unicode(PyObject *lst) { /* return ''.join(lst) */ PyObject *sep, *ret; sep = PyUnicode_FromStringAndSize("", 0); ret = PyUnicode_Join(sep, lst); Py_DECREF(sep); return ret; } int _PyAccu_Init(_PyAccu *acc) { /* Lazily allocated */ acc->large = NULL; acc->small = PyList_New(0); if (acc->small == NULL) return -1; return 0; } static int flush_accumulator(_PyAccu *acc) { Py_ssize_t nsmall = PyList_GET_SIZE(acc->small); if (nsmall) { int ret; PyObject *joined; if (acc->large == NULL) { acc->large = PyList_New(0); if (acc->large == NULL) return -1; } joined = join_list_unicode(acc->small); if (joined == NULL) return -1; if (PyList_SetSlice(acc->small, 0, nsmall, NULL)) { Py_DECREF(joined); return -1; } ret = PyList_Append(acc->large, joined); Py_DECREF(joined); return ret; } return 0; } int _PyAccu_Accumulate(_PyAccu *acc, PyObject *unicode) { Py_ssize_t nsmall; assert(PyUnicode_Check(unicode)); if (PyList_Append(acc->small, unicode)) return -1; nsmall = PyList_GET_SIZE(acc->small); /* Each item in a list of unicode objects has an overhead (in 64-bit * builds) of: * - 8 bytes for the list slot * - 56 bytes for the header of the unicode object * that is, 64 bytes. 100000 such objects waste more than 6MB * compared to a single concatenated string. */ if (nsmall < 100000) return 0; return flush_accumulator(acc); } PyObject * _PyAccu_FinishAsList(_PyAccu *acc) { int ret; PyObject *res; ret = flush_accumulator(acc); Py_CLEAR(acc->small); if (ret) { Py_CLEAR(acc->large); return NULL; } res = acc->large; acc->large = NULL; return res; } PyObject * _PyAccu_Finish(_PyAccu *acc) { PyObject *list, *res; if (acc->large == NULL) { list = acc->small; acc->small = NULL; } else { list = _PyAccu_FinishAsList(acc); if (!list) return NULL; } res = join_list_unicode(list); Py_DECREF(list); return res; } void _PyAccu_Destroy(_PyAccu *acc) { Py_CLEAR(acc->small); Py_CLEAR(acc->large); }
3,391
123
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/bytesobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "libc/assert.h" #include "libc/fmt/fmt.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytes_methods.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/pystrhex.h" #include "third_party/python/Include/pystrtod.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ /*[clinic input] class bytes "PyBytesObject *" "&PyBytes_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7a238f965d64892b]*/ #include "third_party/python/Objects/clinic/bytesobject.inc" #ifdef COUNT_ALLOCS Py_ssize_t null_strings, one_strings; #endif static PyBytesObject *characters[UCHAR_MAX + 1]; static PyBytesObject *nullstring; /* PyBytesObject_SIZE gives the basic size of a string; any memory allocation for a string of length n should request PyBytesObject_SIZE + n bytes. Using PyBytesObject_SIZE instead of sizeof(PyBytesObject) saves 3 bytes per string allocation on a typical system. */ #define PyBytesObject_SIZE (offsetof(PyBytesObject, ob_sval) + 1) /* Forward declaration */ Py_LOCAL_INLINE(Py_ssize_t) _PyBytesWriter_GetSize(_PyBytesWriter *writer, char *str); /* For PyBytes_FromString(), the parameter `str' points to a null-terminated string containing exactly `size' bytes. For PyBytes_FromStringAndSize(), the parameter `str' is either NULL or else points to a string containing at least `size' bytes. For PyBytes_FromStringAndSize(), the string in the `str' parameter does not have to be null-terminated. (Therefore it is safe to construct a substring by calling `PyBytes_FromStringAndSize(origstring, substrlen)'.) If `str' is NULL then PyBytes_FromStringAndSize() will allocate `size+1' bytes (setting the last byte to the null terminating character) and you can fill in the data yourself. If `str' is non-NULL then the resulting PyBytes object must be treated as immutable and you must not fill in nor alter the data yourself, since the strings may be shared. The PyObject member `op->ob_size', which denotes the number of "extra items" in a variable-size object, will contain the number of bytes allocated for string data, not counting the null terminating character. It is therefore equal to the `size' parameter (for PyBytes_FromStringAndSize()) or the length of the string in the `str' parameter (for PyBytes_FromString()). */ static PyObject * _PyBytes_FromSize(Py_ssize_t size, int use_calloc) { PyBytesObject *op; assert(size >= 0); if (size == 0 && (op = nullstring) != NULL) { #ifdef COUNT_ALLOCS null_strings++; #endif Py_INCREF(op); return (PyObject *)op; } if ((size_t)size > (size_t)PY_SSIZE_T_MAX - PyBytesObject_SIZE) { PyErr_SetString(PyExc_OverflowError, "byte string is too large"); return NULL; } /* Inline PyObject_NewVar */ if (use_calloc) op = (PyBytesObject *)PyObject_Calloc(1, PyBytesObject_SIZE + size); else op = (PyBytesObject *)PyObject_Malloc(PyBytesObject_SIZE + size); if (op == NULL) return PyErr_NoMemory(); (void)PyObject_INIT_VAR(op, &PyBytes_Type, size); op->ob_shash = -1; if (!use_calloc) op->ob_sval[size] = '\0'; /* empty byte string singleton */ if (size == 0) { nullstring = op; Py_INCREF(op); } return (PyObject *) op; } PyObject * PyBytes_FromStringAndSize(const char *str, Py_ssize_t size) { PyBytesObject *op; if (size < 0) { PyErr_SetString(PyExc_SystemError, "Negative size passed to PyBytes_FromStringAndSize"); return NULL; } if (size == 1 && str != NULL && (op = characters[*str & UCHAR_MAX]) != NULL) { #ifdef COUNT_ALLOCS one_strings++; #endif Py_INCREF(op); return (PyObject *)op; } op = (PyBytesObject *)_PyBytes_FromSize(size, 0); if (op == NULL) return NULL; if (str == NULL) return (PyObject *) op; memcpy(op->ob_sval, str, size); /* share short strings */ if (size == 1) { characters[*str & UCHAR_MAX] = op; Py_INCREF(op); } return (PyObject *) op; } PyObject * PyBytes_FromString(const char *str) { size_t size; PyBytesObject *op; assert(str != NULL); size = strlen(str); if (size > PY_SSIZE_T_MAX - PyBytesObject_SIZE) { PyErr_SetString(PyExc_OverflowError, "byte string is too long"); return NULL; } if (size == 0 && (op = nullstring) != NULL) { #ifdef COUNT_ALLOCS null_strings++; #endif Py_INCREF(op); return (PyObject *)op; } if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) { #ifdef COUNT_ALLOCS one_strings++; #endif Py_INCREF(op); return (PyObject *)op; } /* Inline PyObject_NewVar */ op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + size); if (op == NULL) return PyErr_NoMemory(); (void)PyObject_INIT_VAR(op, &PyBytes_Type, size); op->ob_shash = -1; memcpy(op->ob_sval, str, size+1); /* share short strings */ if (size == 0) { nullstring = op; Py_INCREF(op); } else if (size == 1) { characters[*str & UCHAR_MAX] = op; Py_INCREF(op); } return (PyObject *) op; } PyObject * PyBytes_FromFormatV(const char *format, va_list vargs) { char *s; const char *f; const char *p; Py_ssize_t prec; int longflag; int size_tflag; /* Longest 64-bit formatted numbers: - "18446744073709551615\0" (21 bytes) - "-9223372036854775808\0" (21 bytes) Decimal takes the most space (it isn't enough for octal.) Longest 64-bit pointer representation: "0xffffffffffffffff\0" (19 bytes). */ char buffer[21]; _PyBytesWriter writer; _PyBytesWriter_Init(&writer); s = _PyBytesWriter_Alloc(&writer, strlen(format)); if (s == NULL) return NULL; writer.overallocate = 1; #define WRITE_BYTES(str) \ do { \ s = _PyBytesWriter_WriteBytes(&writer, s, (str), strlen(str)); \ if (s == NULL) \ goto error; \ } while (0) for (f = format; *f; f++) { if (*f != '%') { *s++ = *f; continue; } p = f++; /* ignore the width (ex: 10 in "%10s") */ while (Py_ISDIGIT(*f)) f++; /* parse the precision (ex: 10 in "%.10s") */ prec = 0; if (*f == '.') { f++; for (; Py_ISDIGIT(*f); f++) { prec = (prec * 10) + (*f - '0'); } } while (*f && *f != '%' && !Py_ISALPHA(*f)) f++; /* handle the long flag ('l'), but only for %ld and %lu. others can be added when necessary. */ longflag = 0; if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) { longflag = 1; ++f; } /* handle the size_t flag ('z'). */ size_tflag = 0; if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) { size_tflag = 1; ++f; } /* subtract bytes preallocated for the format string (ex: 2 for "%s") */ writer.min_size -= (f - p + 1); switch (*f) { case 'c': { int c = va_arg(vargs, int); if (c < 0 || c > 255) { PyErr_SetString(PyExc_OverflowError, "PyBytes_FromFormatV(): %c format " "expects an integer in range [0; 255]"); goto error; } writer.min_size++; *s++ = (unsigned char)c; break; } case 'd': if (longflag) sprintf(buffer, "%ld", va_arg(vargs, long)); else if (size_tflag) sprintf(buffer, "%" PY_FORMAT_SIZE_T "d", va_arg(vargs, Py_ssize_t)); else sprintf(buffer, "%d", va_arg(vargs, int)); assert(strlen(buffer) < sizeof(buffer)); WRITE_BYTES(buffer); break; case 'u': if (longflag) sprintf(buffer, "%lu", va_arg(vargs, unsigned long)); else if (size_tflag) sprintf(buffer, "%" PY_FORMAT_SIZE_T "u", va_arg(vargs, size_t)); else sprintf(buffer, "%u", va_arg(vargs, unsigned int)); assert(strlen(buffer) < sizeof(buffer)); WRITE_BYTES(buffer); break; case 'i': sprintf(buffer, "%i", va_arg(vargs, int)); assert(strlen(buffer) < sizeof(buffer)); WRITE_BYTES(buffer); break; case 'x': sprintf(buffer, "%x", va_arg(vargs, int)); assert(strlen(buffer) < sizeof(buffer)); WRITE_BYTES(buffer); break; case 's': { Py_ssize_t i; p = va_arg(vargs, const char*); i = strlen(p); if (prec > 0 && i > prec) i = prec; s = _PyBytesWriter_WriteBytes(&writer, s, p, i); if (s == NULL) goto error; break; } case 'p': sprintf(buffer, "%p", va_arg(vargs, void*)); assert(strlen(buffer) < sizeof(buffer)); /* %p is ill-defined: ensure leading 0x. */ if (buffer[1] == 'X') buffer[1] = 'x'; else if (buffer[1] != 'x') { memmove(buffer+2, buffer, strlen(buffer)+1); buffer[0] = '0'; buffer[1] = 'x'; } WRITE_BYTES(buffer); break; case '%': writer.min_size++; *s++ = '%'; break; default: if (*f == 0) { /* fix min_size if we reached the end of the format string */ writer.min_size++; } /* invalid format string: copy unformatted string and exit */ WRITE_BYTES(p); return _PyBytesWriter_Finish(&writer, s); } } #undef WRITE_BYTES return _PyBytesWriter_Finish(&writer, s); error: _PyBytesWriter_Dealloc(&writer); return NULL; } PyObject * PyBytes_FromFormat(const char *format, ...) { PyObject* ret; va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, format); #else va_start(vargs); #endif ret = PyBytes_FromFormatV(format, vargs); va_end(vargs); return ret; } /* Helpers for formatstring */ Py_LOCAL_INLINE(PyObject *) getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx) { Py_ssize_t argidx = *p_argidx; if (argidx < arglen) { (*p_argidx)++; if (arglen < 0) return args; else return PyTuple_GetItem(args, argidx); } PyErr_SetString(PyExc_TypeError, "not enough arguments for format string"); return NULL; } /* Format codes * F_LJUST '-' * F_SIGN '+' * F_BLANK ' ' * F_ALT '#' * F_ZERO '0' */ #define F_LJUST (1<<0) #define F_SIGN (1<<1) #define F_BLANK (1<<2) #define F_ALT (1<<3) #define F_ZERO (1<<4) /* Returns a new reference to a PyBytes object, or NULL on failure. */ static char* formatfloat(PyObject *v, int flags, int prec, int type, PyObject **p_result, _PyBytesWriter *writer, char *str) { char *p; PyObject *result; double x; size_t len; x = PyFloat_AsDouble(v); if (x == -1.0 && PyErr_Occurred()) { PyErr_Format(PyExc_TypeError, "float argument required, " "not %.200s", Py_TYPE(v)->tp_name); return NULL; } if (prec < 0) prec = 6; p = PyOS_double_to_string(x, type, prec, (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL); if (p == NULL) return NULL; len = strlen(p); if (writer != NULL) { str = _PyBytesWriter_Prepare(writer, str, len); if (str == NULL) return NULL; memcpy(str, p, len); PyMem_Free(p); str += len; return str; } result = PyBytes_FromStringAndSize(p, len); PyMem_Free(p); *p_result = result; return result != NULL ? str : NULL; } static PyObject * formatlong(PyObject *v, int flags, int prec, int type) { PyObject *result, *iobj; if (type == 'i') type = 'd'; if (PyLong_Check(v)) return _PyUnicode_FormatLong(v, flags & F_ALT, prec, type); if (PyNumber_Check(v)) { /* make sure number is a type of integer for o, x, and X */ if (type == 'o' || type == 'x' || type == 'X') iobj = PyNumber_Index(v); else iobj = PyNumber_Long(v); if (iobj == NULL) { if (!PyErr_ExceptionMatches(PyExc_TypeError)) return NULL; } else if (!PyLong_Check(iobj)) Py_CLEAR(iobj); if (iobj != NULL) { result = _PyUnicode_FormatLong(iobj, flags & F_ALT, prec, type); Py_DECREF(iobj); return result; } } PyErr_Format(PyExc_TypeError, "%%%c format: %s is required, not %.200s", type, (type == 'o' || type == 'x' || type == 'X') ? "an integer" : "a number", Py_TYPE(v)->tp_name); return NULL; } static int byte_converter(PyObject *arg, char *p) { if (PyBytes_Check(arg) && PyBytes_GET_SIZE(arg) == 1) { *p = PyBytes_AS_STRING(arg)[0]; return 1; } else if (PyByteArray_Check(arg) && PyByteArray_GET_SIZE(arg) == 1) { *p = PyByteArray_AS_STRING(arg)[0]; return 1; } else { PyObject *iobj; long ival; int overflow; /* make sure number is a type of integer */ if (PyLong_Check(arg)) { ival = PyLong_AsLongAndOverflow(arg, &overflow); } else { iobj = PyNumber_Index(arg); if (iobj == NULL) { if (!PyErr_ExceptionMatches(PyExc_TypeError)) return 0; goto onError; } ival = PyLong_AsLongAndOverflow(iobj, &overflow); Py_DECREF(iobj); } if (!overflow && ival == -1 && PyErr_Occurred()) goto onError; if (overflow || !(0 <= ival && ival <= 255)) { PyErr_SetString(PyExc_OverflowError, "%c arg not in range(256)"); return 0; } *p = (char)ival; return 1; } onError: PyErr_SetString(PyExc_TypeError, "%c requires an integer in range(256) or a single byte"); return 0; } static PyObject *_PyBytes_FromBuffer(PyObject *x); static PyObject * format_obj(PyObject *v, const char **pbuf, Py_ssize_t *plen) { PyObject *func, *result; _Py_IDENTIFIER(__bytes__); /* is it a bytes object? */ if (PyBytes_Check(v)) { *pbuf = PyBytes_AS_STRING(v); *plen = PyBytes_GET_SIZE(v); Py_INCREF(v); return v; } if (PyByteArray_Check(v)) { *pbuf = PyByteArray_AS_STRING(v); *plen = PyByteArray_GET_SIZE(v); Py_INCREF(v); return v; } /* does it support __bytes__? */ func = _PyObject_LookupSpecial(v, &PyId___bytes__); if (func != NULL) { result = PyObject_CallFunctionObjArgs(func, NULL); Py_DECREF(func); if (result == NULL) return NULL; if (!PyBytes_Check(result)) { PyErr_Format(PyExc_TypeError, "__bytes__ returned non-bytes (type %.200s)", Py_TYPE(result)->tp_name); Py_DECREF(result); return NULL; } *pbuf = PyBytes_AS_STRING(result); *plen = PyBytes_GET_SIZE(result); return result; } /* does it support buffer protocol? */ if (PyObject_CheckBuffer(v)) { /* maybe we can avoid making a copy of the buffer object here? */ result = _PyBytes_FromBuffer(v); if (result == NULL) return NULL; *pbuf = PyBytes_AS_STRING(result); *plen = PyBytes_GET_SIZE(result); return result; } PyErr_Format(PyExc_TypeError, "%%b requires a bytes-like object, " "or an object that implements __bytes__, not '%.100s'", Py_TYPE(v)->tp_name); return NULL; } /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */ PyObject * _PyBytes_FormatEx(const char *format, Py_ssize_t format_len, PyObject *args, int use_bytearray) { const char *fmt; char *res; Py_ssize_t arglen, argidx; Py_ssize_t fmtcnt; int args_owned = 0; PyObject *dict = NULL; _PyBytesWriter writer; if (args == NULL) { PyErr_BadInternalCall(); return NULL; } fmt = format; fmtcnt = format_len; _PyBytesWriter_Init(&writer); writer.use_bytearray = use_bytearray; res = _PyBytesWriter_Alloc(&writer, fmtcnt); if (res == NULL) return NULL; if (!use_bytearray) writer.overallocate = 1; if (PyTuple_Check(args)) { arglen = PyTuple_GET_SIZE(args); argidx = 0; } else { arglen = -1; argidx = -2; } if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript && !PyTuple_Check(args) && !PyBytes_Check(args) && !PyUnicode_Check(args) && !PyByteArray_Check(args)) { dict = args; } while (--fmtcnt >= 0) { if (*fmt != '%') { Py_ssize_t len; char *pos; pos = (char *)memchr(fmt + 1, '%', fmtcnt); if (pos != NULL) len = pos - fmt; else len = fmtcnt + 1; assert(len != 0); memcpy(res, fmt, len); res += len; fmt += len; fmtcnt -= (len - 1); } else { /* Got a format specifier */ int flags = 0; Py_ssize_t width = -1; int prec = -1; int c = '\0'; int fill; PyObject *v = NULL; PyObject *temp = NULL; const char *pbuf = NULL; int sign; Py_ssize_t len = 0; char onechar; /* For byte_converter() */ Py_ssize_t alloc; #ifdef Py_DEBUG char *before; #endif fmt++; if (*fmt == '(') { const char *keystart; Py_ssize_t keylen; PyObject *key; int pcount = 1; if (dict == NULL) { PyErr_SetString(PyExc_TypeError, "format requires a mapping"); goto error; } ++fmt; --fmtcnt; keystart = fmt; /* Skip over balanced parentheses */ while (pcount > 0 && --fmtcnt >= 0) { if (*fmt == ')') --pcount; else if (*fmt == '(') ++pcount; fmt++; } keylen = fmt - keystart - 1; if (fmtcnt < 0 || pcount > 0) { PyErr_SetString(PyExc_ValueError, "incomplete format key"); goto error; } key = PyBytes_FromStringAndSize(keystart, keylen); if (key == NULL) goto error; if (args_owned) { Py_DECREF(args); args_owned = 0; } args = PyObject_GetItem(dict, key); Py_DECREF(key); if (args == NULL) { goto error; } args_owned = 1; arglen = -1; argidx = -2; } /* Parse flags. Example: "%+i" => flags=F_SIGN. */ while (--fmtcnt >= 0) { switch (c = *fmt++) { case '-': flags |= F_LJUST; continue; case '+': flags |= F_SIGN; continue; case ' ': flags |= F_BLANK; continue; case '#': flags |= F_ALT; continue; case '0': flags |= F_ZERO; continue; } break; } /* Parse width. Example: "%10s" => width=10 */ if (c == '*') { v = getnextarg(args, arglen, &argidx); if (v == NULL) goto error; if (!PyLong_Check(v)) { PyErr_SetString(PyExc_TypeError, "* wants int"); goto error; } width = PyLong_AsSsize_t(v); if (width == -1 && PyErr_Occurred()) goto error; if (width < 0) { flags |= F_LJUST; width = -width; } if (--fmtcnt >= 0) c = *fmt++; } else if (c >= 0 && isdigit(c)) { width = c - '0'; while (--fmtcnt >= 0) { c = Py_CHARMASK(*fmt++); if (!isdigit(c)) break; if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) { PyErr_SetString( PyExc_ValueError, "width too big"); goto error; } width = width*10 + (c - '0'); } } /* Parse precision. Example: "%.3f" => prec=3 */ if (c == '.') { prec = 0; if (--fmtcnt >= 0) c = *fmt++; if (c == '*') { v = getnextarg(args, arglen, &argidx); if (v == NULL) goto error; if (!PyLong_Check(v)) { PyErr_SetString( PyExc_TypeError, "* wants int"); goto error; } prec = _PyLong_AsInt(v); if (prec == -1 && PyErr_Occurred()) goto error; if (prec < 0) prec = 0; if (--fmtcnt >= 0) c = *fmt++; } else if (c >= 0 && isdigit(c)) { prec = c - '0'; while (--fmtcnt >= 0) { c = Py_CHARMASK(*fmt++); if (!isdigit(c)) break; if (prec > (INT_MAX - ((int)c - '0')) / 10) { PyErr_SetString( PyExc_ValueError, "prec too big"); goto error; } prec = prec*10 + (c - '0'); } } } /* prec */ if (fmtcnt >= 0) { if (c == 'h' || c == 'l' || c == 'L') { if (--fmtcnt >= 0) c = *fmt++; } } if (fmtcnt < 0) { PyErr_SetString(PyExc_ValueError, "incomplete format"); goto error; } if (c != '%') { v = getnextarg(args, arglen, &argidx); if (v == NULL) goto error; } if (fmtcnt == 0) { /* last write: disable writer overallocation */ writer.overallocate = 0; } sign = 0; fill = ' '; switch (c) { case '%': *res++ = '%'; continue; case 'r': // %r is only for 2/3 code; 3 only code should use %a case 'a': temp = PyObject_ASCII(v); if (temp == NULL) goto error; assert(PyUnicode_IS_ASCII(temp)); pbuf = (const char *)PyUnicode_1BYTE_DATA(temp); len = PyUnicode_GET_LENGTH(temp); if (prec >= 0 && len > prec) len = prec; break; case 's': // %s is only for 2/3 code; 3 only code should use %b case 'b': temp = format_obj(v, &pbuf, &len); if (temp == NULL) goto error; if (prec >= 0 && len > prec) len = prec; break; case 'i': case 'd': case 'u': case 'o': case 'x': case 'X': if (PyLong_CheckExact(v) && width == -1 && prec == -1 && !(flags & (F_SIGN | F_BLANK)) && c != 'X') { /* Fast path */ int alternate = flags & F_ALT; int base; switch(c) { default: assert(0 && "'type' not in [diuoxX]"); case 'd': case 'i': case 'u': base = 10; break; case 'o': base = 8; break; case 'x': case 'X': base = 16; break; } /* Fast path */ writer.min_size -= 2; /* size preallocated for "%d" */ res = _PyLong_FormatBytesWriter(&writer, res, v, base, alternate); if (res == NULL) goto error; continue; } temp = formatlong(v, flags, prec, c); if (!temp) goto error; assert(PyUnicode_IS_ASCII(temp)); pbuf = (const char *)PyUnicode_1BYTE_DATA(temp); len = PyUnicode_GET_LENGTH(temp); sign = 1; if (flags & F_ZERO) fill = '0'; break; case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': if (width == -1 && prec == -1 && !(flags & (F_SIGN | F_BLANK))) { /* Fast path */ writer.min_size -= 2; /* size preallocated for "%f" */ res = formatfloat(v, flags, prec, c, NULL, &writer, res); if (res == NULL) goto error; continue; } if (!formatfloat(v, flags, prec, c, &temp, NULL, res)) goto error; pbuf = PyBytes_AS_STRING(temp); len = PyBytes_GET_SIZE(temp); sign = 1; if (flags & F_ZERO) fill = '0'; break; case 'c': pbuf = &onechar; len = byte_converter(v, &onechar); if (!len) goto error; if (width == -1) { /* Fast path */ *res++ = onechar; continue; } break; default: PyErr_Format(PyExc_ValueError, "unsupported format character '%c' (0x%x) " "at index %zd", c, c, (Py_ssize_t)(fmt - 1 - format)); goto error; } if (sign) { if (*pbuf == '-' || *pbuf == '+') { sign = *pbuf++; len--; } else if (flags & F_SIGN) sign = '+'; else if (flags & F_BLANK) sign = ' '; else sign = 0; } if (width < len) width = len; alloc = width; if (sign != 0 && len == width) alloc++; /* 2: size preallocated for %s */ if (alloc > 2) { res = _PyBytesWriter_Prepare(&writer, res, alloc - 2); if (res == NULL) goto error; } #ifdef Py_DEBUG before = res; #endif /* Write the sign if needed */ if (sign) { if (fill != ' ') *res++ = sign; if (width > len) width--; } /* Write the numeric prefix for "x", "X" and "o" formats if the alternate form is used. For example, write "0x" for the "%#x" format. */ if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) { assert(pbuf[0] == '0'); assert(pbuf[1] == c); if (fill != ' ') { *res++ = *pbuf++; *res++ = *pbuf++; } width -= 2; if (width < 0) width = 0; len -= 2; } /* Pad left with the fill character if needed */ if (width > len && !(flags & F_LJUST)) { memset(res, fill, width - len); res += (width - len); width = len; } /* If padding with spaces: write sign if needed and/or numeric prefix if the alternate form is used */ if (fill == ' ') { if (sign) *res++ = sign; if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) { assert(pbuf[0] == '0'); assert(pbuf[1] == c); *res++ = *pbuf++; *res++ = *pbuf++; } } /* Copy bytes */ memcpy(res, pbuf, len); res += len; /* Pad right with the fill character if needed */ if (width > len) { memset(res, ' ', width - len); res += (width - len); } if (dict && (argidx < arglen) && c != '%') { PyErr_SetString(PyExc_TypeError, "not all arguments converted during bytes formatting"); Py_XDECREF(temp); goto error; } Py_XDECREF(temp); #ifdef Py_DEBUG /* check that we computed the exact size for this write */ assert((res - before) == alloc); #endif } /* '%' */ /* If overallocation was disabled, ensure that it was the last write. Otherwise, we missed an optimization */ assert(writer.overallocate || fmtcnt == 0 || use_bytearray); } /* until end */ if (argidx < arglen && !dict) { PyErr_SetString(PyExc_TypeError, "not all arguments converted during bytes formatting"); goto error; } if (args_owned) { Py_DECREF(args); } return _PyBytesWriter_Finish(&writer, res); error: _PyBytesWriter_Dealloc(&writer); if (args_owned) { Py_DECREF(args); } return NULL; } /* =-= */ static void bytes_dealloc(PyObject *op) { Py_TYPE(op)->tp_free(op); } /* Unescape a backslash-escaped string. If unicode is non-zero, the string is a u-literal. If recode_encoding is non-zero, the string is UTF-8 encoded and should be re-encoded in the specified encoding. */ static char * _PyBytes_DecodeEscapeRecode(const char **s, const char *end, const char *errors, const char *recode_encoding, _PyBytesWriter *writer, char *p) { PyObject *u, *w; const char* t; t = *s; /* Decode non-ASCII bytes as UTF-8. */ while (t < end && (*t & 0x80)) t++; u = PyUnicode_DecodeUTF8(*s, t - *s, errors); if (u == NULL) return NULL; /* Recode them in target encoding. */ w = PyUnicode_AsEncodedString(u, recode_encoding, errors); Py_DECREF(u); if (w == NULL) return NULL; assert(PyBytes_Check(w)); /* Append bytes to output buffer. */ writer->min_size--; /* subtract 1 preallocated byte */ p = _PyBytesWriter_WriteBytes(writer, p, PyBytes_AS_STRING(w), PyBytes_GET_SIZE(w)); Py_DECREF(w); if (p == NULL) return NULL; *s = t; return p; } PyObject *_PyBytes_DecodeEscape(const char *s, Py_ssize_t len, const char *errors, Py_ssize_t unicode, const char *recode_encoding, const char **first_invalid_escape) { int c; char *p; const char *end; _PyBytesWriter writer; _PyBytesWriter_Init(&writer); p = _PyBytesWriter_Alloc(&writer, len); if (p == NULL) return NULL; writer.overallocate = 1; *first_invalid_escape = NULL; end = s + len; while (s < end) { if (*s != '\\') { non_esc: if (!(recode_encoding && (*s & 0x80))) { *p++ = *s++; } else { /* non-ASCII character and need to recode */ p = _PyBytes_DecodeEscapeRecode(&s, end, errors, recode_encoding, &writer, p); if (p == NULL) goto failed; } continue; } s++; if (s == end) { PyErr_SetString(PyExc_ValueError, "Trailing \\ in string"); goto failed; } switch (*s++) { /* XXX This assumes ASCII! */ case '\n': break; case '\\': *p++ = '\\'; break; case '\'': *p++ = '\''; break; case '\"': *p++ = '\"'; break; case 'b': *p++ = '\b'; break; case 'f': *p++ = '\014'; break; /* FF */ case 't': *p++ = '\t'; break; case 'n': *p++ = '\n'; break; case 'r': *p++ = '\r'; break; case 'v': *p++ = '\013'; break; /* VT */ case 'e': *p++ = '\033'; break; /* [jart] ansi escape */ case 'a': *p++ = '\007'; break; /* BEL, not classic C */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': c = s[-1] - '0'; if (s < end && '0' <= *s && *s <= '7') { c = (c<<3) + *s++ - '0'; if (s < end && '0' <= *s && *s <= '7') c = (c<<3) + *s++ - '0'; } *p++ = c; break; case 'x': if (s+1 < end) { int digit1, digit2; digit1 = _PyLong_DigitValue[Py_CHARMASK(s[0])]; digit2 = _PyLong_DigitValue[Py_CHARMASK(s[1])]; if (digit1 < 16 && digit2 < 16) { *p++ = (unsigned char)((digit1 << 4) + digit2); s += 2; break; } } /* invalid hexadecimal digits */ if (!errors || strcmp(errors, "strict") == 0) { PyErr_Format(PyExc_ValueError, "invalid \\x escape at position %d", s - 2 - (end - len)); goto failed; } if (strcmp(errors, "replace") == 0) { *p++ = '?'; } else if (strcmp(errors, "ignore") == 0) /* do nothing */; else { PyErr_Format(PyExc_ValueError, "decoding error; unknown " "error handling code: %.400s", errors); goto failed; } /* skip \x */ if (s < end && Py_ISXDIGIT(s[0])) s++; /* and a hexdigit */ break; default: if (*first_invalid_escape == NULL) { *first_invalid_escape = s-1; /* Back up one char, since we've already incremented s. */ } *p++ = '\\'; s--; goto non_esc; /* an arbitrary number of unescaped UTF-8 bytes may follow. */ } } return _PyBytesWriter_Finish(&writer, p); failed: _PyBytesWriter_Dealloc(&writer); return NULL; } PyObject *PyBytes_DecodeEscape(const char *s, Py_ssize_t len, const char *errors, Py_ssize_t unicode, const char *recode_encoding) { const char* first_invalid_escape; PyObject *result = _PyBytes_DecodeEscape(s, len, errors, unicode, recode_encoding, &first_invalid_escape); if (result == NULL) return NULL; if (first_invalid_escape != NULL) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "invalid escape sequence '\\%c'", (unsigned char)*first_invalid_escape) < 0) { Py_DECREF(result); return NULL; } } return result; } /* -------------------------------------------------------------------- */ /* object api */ Py_ssize_t PyBytes_Size(PyObject *op) { if (!PyBytes_Check(op)) { PyErr_Format(PyExc_TypeError, "expected bytes, %.200s found", Py_TYPE(op)->tp_name); return -1; } return Py_SIZE(op); } char * PyBytes_AsString(PyObject *op) { if (!PyBytes_Check(op)) { PyErr_Format(PyExc_TypeError, "expected bytes, %.200s found", Py_TYPE(op)->tp_name); return NULL; } return ((PyBytesObject *)op)->ob_sval; } int PyBytes_AsStringAndSize(PyObject *obj, char **s, Py_ssize_t *len) { if (s == NULL) { PyErr_BadInternalCall(); return -1; } if (!PyBytes_Check(obj)) { PyErr_Format(PyExc_TypeError, "expected bytes, %.200s found", Py_TYPE(obj)->tp_name); return -1; } *s = PyBytes_AS_STRING(obj); if (len != NULL) *len = PyBytes_GET_SIZE(obj); else if (strlen(*s) != (size_t)PyBytes_GET_SIZE(obj)) { PyErr_SetString(PyExc_ValueError, "embedded null byte"); return -1; } return 0; } /* -------------------------------------------------------------------- */ /* Methods */ #include "third_party/python/Objects/stringlib/stringdefs.inc" #include "third_party/python/Objects/stringlib/fastsearch.inc" #include "third_party/python/Objects/stringlib/count.inc" #include "third_party/python/Objects/stringlib/find.inc" #include "third_party/python/Objects/stringlib/join.inc" #include "third_party/python/Objects/stringlib/partition.inc" #include "third_party/python/Objects/stringlib/split.inc" #include "third_party/python/Objects/stringlib/ctype.inc" #include "third_party/python/Objects/stringlib/transmogrify.inc" PyObject * PyBytes_Repr(PyObject *obj, int smartquotes) { PyBytesObject* op = (PyBytesObject*) obj; Py_ssize_t i, length = Py_SIZE(op); Py_ssize_t newsize, squotes, dquotes; PyObject *v; unsigned char quote, *s, *p; /* Compute size of output string */ squotes = dquotes = 0; newsize = 3; /* b'' */ s = (unsigned char*)op->ob_sval; for (i = 0; i < length; i++) { Py_ssize_t incr = 1; switch(s[i]) { case '\'': squotes++; break; case '"': dquotes++; break; case '\\': case '\t': case '\n': case '\r': incr = 2; break; /* \C */ default: if (s[i] < ' ' || s[i] >= 0x7f) incr = 4; /* \xHH */ } if (newsize > PY_SSIZE_T_MAX - incr) goto overflow; newsize += incr; } quote = '\''; if (smartquotes && squotes && !dquotes) quote = '"'; if (squotes && quote == '\'') { if (newsize > PY_SSIZE_T_MAX - squotes) goto overflow; newsize += squotes; } v = PyUnicode_New(newsize, 127); if (v == NULL) { return NULL; } p = PyUnicode_1BYTE_DATA(v); *p++ = 'b', *p++ = quote; for (i = 0; i < length; i++) { unsigned char c = op->ob_sval[i]; if (c == quote || c == '\\') *p++ = '\\', *p++ = c; else if (c == '\t') *p++ = '\\', *p++ = 't'; else if (c == '\n') *p++ = '\\', *p++ = 'n'; else if (c == '\r') *p++ = '\\', *p++ = 'r'; else if (c < ' ' || c >= 0x7f) { *p++ = '\\'; *p++ = 'x'; *p++ = Py_hexdigits[(c & 0xf0) >> 4]; *p++ = Py_hexdigits[c & 0xf]; } else *p++ = c; } *p++ = quote; assert(_PyUnicode_CheckConsistency(v, 1)); return v; overflow: PyErr_SetString(PyExc_OverflowError, "bytes object is too large to make repr"); return NULL; } static PyObject * bytes_repr(PyObject *op) { return PyBytes_Repr(op, 1); } static PyObject * bytes_str(PyObject *op) { if (Py_BytesWarningFlag) { if (PyErr_WarnEx(PyExc_BytesWarning, "str() on a bytes instance", 1)) return NULL; } return bytes_repr(op); } static Py_ssize_t bytes_length(PyBytesObject *a) { return Py_SIZE(a); } /* This is also used by PyBytes_Concat() */ static PyObject * bytes_concat(PyObject *a, PyObject *b) { Py_buffer va, vb; PyObject *result = NULL; va.len = -1; vb.len = -1; if (PyObject_GetBuffer(a, &va, PyBUF_SIMPLE) != 0 || PyObject_GetBuffer(b, &vb, PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", Py_TYPE(b)->tp_name, Py_TYPE(a)->tp_name); goto done; } /* Optimize end cases */ if (va.len == 0 && PyBytes_CheckExact(b)) { result = b; Py_INCREF(result); goto done; } if (vb.len == 0 && PyBytes_CheckExact(a)) { result = a; Py_INCREF(result); goto done; } if (va.len > PY_SSIZE_T_MAX - vb.len) { PyErr_NoMemory(); goto done; } result = PyBytes_FromStringAndSize(NULL, va.len + vb.len); if (result != NULL) { memcpy(PyBytes_AS_STRING(result), va.buf, va.len); memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len); } done: if (va.len != -1) PyBuffer_Release(&va); if (vb.len != -1) PyBuffer_Release(&vb); return result; } static PyObject * bytes_repeat(PyBytesObject *a, Py_ssize_t n) { Py_ssize_t i; Py_ssize_t j; Py_ssize_t size; PyBytesObject *op; size_t nbytes; if (n < 0) n = 0; /* watch out for overflows: the size can overflow int, * and the # of bytes needed can overflow size_t */ if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n) { PyErr_SetString(PyExc_OverflowError, "repeated bytes are too long"); return NULL; } size = Py_SIZE(a) * n; if (size == Py_SIZE(a) && PyBytes_CheckExact(a)) { Py_INCREF(a); return (PyObject *)a; } nbytes = (size_t)size; if (nbytes + PyBytesObject_SIZE <= nbytes) { PyErr_SetString(PyExc_OverflowError, "repeated bytes are too long"); return NULL; } op = (PyBytesObject *)PyObject_MALLOC(PyBytesObject_SIZE + nbytes); if (op == NULL) return PyErr_NoMemory(); (void)PyObject_INIT_VAR(op, &PyBytes_Type, size); op->ob_shash = -1; op->ob_sval[size] = '\0'; if (Py_SIZE(a) == 1 && n > 0) { memset(op->ob_sval, a->ob_sval[0] , n); return (PyObject *) op; } i = 0; if (i < size) { memcpy(op->ob_sval, a->ob_sval, Py_SIZE(a)); i = Py_SIZE(a); } while (i < size) { j = (i <= size-i) ? i : size-i; memcpy(op->ob_sval+i, op->ob_sval, j); i += j; } return (PyObject *) op; } static int bytes_contains(PyObject *self, PyObject *arg) { return _Py_bytes_contains(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), arg); } static PyObject * bytes_item(PyBytesObject *a, Py_ssize_t i) { if (i < 0 || i >= Py_SIZE(a)) { PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } return PyLong_FromLong((unsigned char)a->ob_sval[i]); } static inline int bytes_compare_eq(PyBytesObject *a, PyBytesObject *b) { Py_ssize_t len; len = Py_SIZE(a); if (Py_SIZE(b) != len) return 0; return !bcmp(a->ob_sval, b->ob_sval, len); } static PyObject* bytes_richcompare(PyBytesObject *a, PyBytesObject *b, int op) { int c; Py_ssize_t len_a, len_b; Py_ssize_t min_len; PyObject *result; int rc; /* Make sure both arguments are strings. */ if (!(PyBytes_Check(a) && PyBytes_Check(b))) { if (Py_BytesWarningFlag && (op == Py_EQ || op == Py_NE)) { rc = PyObject_IsInstance((PyObject*)a, (PyObject*)&PyUnicode_Type); if (!rc) rc = PyObject_IsInstance((PyObject*)b, (PyObject*)&PyUnicode_Type); if (rc < 0) return NULL; if (rc) { if (PyErr_WarnEx(PyExc_BytesWarning, "Comparison between bytes and string", 1)) return NULL; } else { rc = PyObject_IsInstance((PyObject*)a, (PyObject*)&PyLong_Type); if (!rc) rc = PyObject_IsInstance((PyObject*)b, (PyObject*)&PyLong_Type); if (rc < 0) return NULL; if (rc) { if (PyErr_WarnEx(PyExc_BytesWarning, "Comparison between bytes and int", 1)) return NULL; } } } result = Py_NotImplemented; } else if (a == b) { switch (op) { case Py_EQ: case Py_LE: case Py_GE: /* a string is equal to itself */ result = Py_True; break; case Py_NE: case Py_LT: case Py_GT: result = Py_False; break; default: PyErr_BadArgument(); return NULL; } } else if (op == Py_EQ || op == Py_NE) { int eq = bytes_compare_eq(a, b); eq ^= (op == Py_NE); result = eq ? Py_True : Py_False; } else { len_a = Py_SIZE(a); len_b = Py_SIZE(b); min_len = Py_MIN(len_a, len_b); if (min_len > 0) { c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval); if (c == 0) c = memcmp(a->ob_sval, b->ob_sval, min_len); } else c = 0; if (c == 0) c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0; switch (op) { case Py_LT: c = c < 0; break; case Py_LE: c = c <= 0; break; case Py_GT: c = c > 0; break; case Py_GE: c = c >= 0; break; default: PyErr_BadArgument(); return NULL; } result = c ? Py_True : Py_False; } Py_INCREF(result); return result; } static Py_hash_t bytes_hash(PyBytesObject *a) { if (a->ob_shash == -1) { /* Can't fail */ a->ob_shash = _Py_HashBytes(a->ob_sval, Py_SIZE(a)); } return a->ob_shash; } static PyObject* bytes_subscript(PyBytesObject* self, PyObject* item) { if (PyIndex_Check(item)) { Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return NULL; if (i < 0) i += PyBytes_GET_SIZE(self); if (i < 0 || i >= PyBytes_GET_SIZE(self)) { PyErr_SetString(PyExc_IndexError, "index out of range"); return NULL; } return PyLong_FromLong((unsigned char)self->ob_sval[i]); } else if (PySlice_Check(item)) { Py_ssize_t start, stop, step, slicelength, cur, i; char* source_buf; char* result_buf; PyObject* result; if (PySlice_Unpack(item, &start, &stop, &step) < 0) { return NULL; } slicelength = PySlice_AdjustIndices(PyBytes_GET_SIZE(self), &start, &stop, step); if (slicelength <= 0) { return PyBytes_FromStringAndSize("", 0); } else if (start == 0 && step == 1 && slicelength == PyBytes_GET_SIZE(self) && PyBytes_CheckExact(self)) { Py_INCREF(self); return (PyObject *)self; } else if (step == 1) { return PyBytes_FromStringAndSize( PyBytes_AS_STRING(self) + start, slicelength); } else { source_buf = PyBytes_AS_STRING(self); result = PyBytes_FromStringAndSize(NULL, slicelength); if (result == NULL) return NULL; result_buf = PyBytes_AS_STRING(result); for (cur = start, i = 0; i < slicelength; cur += step, i++) { result_buf[i] = source_buf[cur]; } return result; } } else { PyErr_Format(PyExc_TypeError, "byte indices must be integers or slices, not %.200s", Py_TYPE(item)->tp_name); return NULL; } } static int bytes_buffer_getbuffer(PyBytesObject *self, Py_buffer *view, int flags) { return PyBuffer_FillInfo(view, (PyObject*)self, (void *)self->ob_sval, Py_SIZE(self), 1, flags); } static PySequenceMethods bytes_as_sequence = { (lenfunc)bytes_length, /*sq_length*/ (binaryfunc)bytes_concat, /*sq_concat*/ (ssizeargfunc)bytes_repeat, /*sq_repeat*/ (ssizeargfunc)bytes_item, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ (objobjproc)bytes_contains /*sq_contains*/ }; static PyMappingMethods bytes_as_mapping = { (lenfunc)bytes_length, (binaryfunc)bytes_subscript, 0, }; static PyBufferProcs bytes_as_buffer = { (getbufferproc)bytes_buffer_getbuffer, NULL, }; #define LEFTSTRIP 0 #define RIGHTSTRIP 1 #define BOTHSTRIP 2 /*[clinic input] bytes.split sep: object = None The delimiter according which to split the bytes. None (the default value) means split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). maxsplit: Py_ssize_t = -1 Maximum number of splits to do. -1 (the default value) means no limit. Return a list of the sections in the bytes, using sep as the delimiter. [clinic start generated code]*/ static PyObject * bytes_split_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit) /*[clinic end generated code: output=52126b5844c1d8ef input=8b809b39074abbfa]*/ { Py_ssize_t len = PyBytes_GET_SIZE(self), n; const char *s = PyBytes_AS_STRING(self), *sub; Py_buffer vsub; PyObject *list; if (maxsplit < 0) maxsplit = PY_SSIZE_T_MAX; if (sep == Py_None) return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit); if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) return NULL; sub = vsub.buf; n = vsub.len; list = stringlib_split((PyObject*) self, s, len, sub, n, maxsplit); PyBuffer_Release(&vsub); return list; } /*[clinic input] bytes.partition sep: Py_buffer / Partition the bytes into three parts using the given separator. This will search for the separator sep in the bytes. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it. If the separator is not found, returns a 3-tuple containing the original bytes object and two empty bytes objects. [clinic start generated code]*/ static PyObject * bytes_partition_impl(PyBytesObject *self, Py_buffer *sep) /*[clinic end generated code: output=f532b392a17ff695 input=61cca95519406099]*/ { return stringlib_partition( (PyObject*) self, PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), sep->obj, (const char *)sep->buf, sep->len ); } /*[clinic input] bytes.rpartition sep: Py_buffer / Partition the bytes into three parts using the given separator. This will search for the separator sep in the bytes, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it. If the separator is not found, returns a 3-tuple containing two empty bytes objects and the original bytes object. [clinic start generated code]*/ static PyObject * bytes_rpartition_impl(PyBytesObject *self, Py_buffer *sep) /*[clinic end generated code: output=191b114cbb028e50 input=d78db010c8cfdbe1]*/ { return stringlib_rpartition( (PyObject*) self, PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), sep->obj, (const char *)sep->buf, sep->len ); } /*[clinic input] bytes.rsplit = bytes.split Return a list of the sections in the bytes, using sep as the delimiter. Splitting is done starting at the end of the bytes and working to the front. [clinic start generated code]*/ static PyObject * bytes_rsplit_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit) /*[clinic end generated code: output=ba698d9ea01e1c8f input=0f86c9f28f7d7b7b]*/ { Py_ssize_t len = PyBytes_GET_SIZE(self), n; const char *s = PyBytes_AS_STRING(self), *sub; Py_buffer vsub; PyObject *list; if (maxsplit < 0) maxsplit = PY_SSIZE_T_MAX; if (sep == Py_None) return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit); if (PyObject_GetBuffer(sep, &vsub, PyBUF_SIMPLE) != 0) return NULL; sub = vsub.buf; n = vsub.len; list = stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit); PyBuffer_Release(&vsub); return list; } /*[clinic input] bytes.join iterable_of_bytes: object / Concatenate any number of bytes objects. The bytes whose method is called is inserted in between each pair. The result is returned as a new bytes object. Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'. [clinic start generated code]*/ static PyObject * bytes_join(PyBytesObject *self, PyObject *iterable_of_bytes) /*[clinic end generated code: output=a046f379f626f6f8 input=7fe377b95bd549d2]*/ { return stringlib_bytes_join((PyObject*)self, iterable_of_bytes); } PyObject * _PyBytes_Join(PyObject *sep, PyObject *x) { assert(sep != NULL && PyBytes_Check(sep)); assert(x != NULL); return bytes_join((PyBytesObject*)sep, x); } static PyObject * bytes_find(PyBytesObject *self, PyObject *args) { return _Py_bytes_find(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); } static PyObject * bytes_index(PyBytesObject *self, PyObject *args) { return _Py_bytes_index(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); } static PyObject * bytes_rfind(PyBytesObject *self, PyObject *args) { return _Py_bytes_rfind(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); } static PyObject * bytes_rindex(PyBytesObject *self, PyObject *args) { return _Py_bytes_rindex(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); } Py_LOCAL_INLINE(PyObject *) do_xstrip(PyBytesObject *self, int striptype, PyObject *sepobj) { Py_buffer vsep; char *s = PyBytes_AS_STRING(self); Py_ssize_t len = PyBytes_GET_SIZE(self); char *sep; Py_ssize_t seplen; Py_ssize_t i, j; if (PyObject_GetBuffer(sepobj, &vsep, PyBUF_SIMPLE) != 0) return NULL; sep = vsep.buf; seplen = vsep.len; i = 0; if (striptype != RIGHTSTRIP) { while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) { i++; } } j = len; if (striptype != LEFTSTRIP) { do { j--; } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen)); j++; } PyBuffer_Release(&vsep); if (i == 0 && j == len && PyBytes_CheckExact(self)) { Py_INCREF(self); return (PyObject*)self; } else return PyBytes_FromStringAndSize(s+i, j-i); } Py_LOCAL_INLINE(PyObject *) do_strip(PyBytesObject *self, int striptype) { char *s = PyBytes_AS_STRING(self); Py_ssize_t len = PyBytes_GET_SIZE(self), i, j; i = 0; if (striptype != RIGHTSTRIP) { while (i < len && Py_ISSPACE(s[i])) { i++; } } j = len; if (striptype != LEFTSTRIP) { do { j--; } while (j >= i && Py_ISSPACE(s[j])); j++; } if (i == 0 && j == len && PyBytes_CheckExact(self)) { Py_INCREF(self); return (PyObject*)self; } else return PyBytes_FromStringAndSize(s+i, j-i); } Py_LOCAL_INLINE(PyObject *) do_argstrip(PyBytesObject *self, int striptype, PyObject *bytes) { if (bytes != NULL && bytes != Py_None) { return do_xstrip(self, striptype, bytes); } return do_strip(self, striptype); } /*[clinic input] bytes.strip bytes: object = None / Strip leading and trailing bytes contained in the argument. If the argument is omitted or None, strip leading and trailing ASCII whitespace. [clinic start generated code]*/ static PyObject * bytes_strip_impl(PyBytesObject *self, PyObject *bytes) /*[clinic end generated code: output=c7c228d3bd104a1b input=8a354640e4e0b3ef]*/ { return do_argstrip(self, BOTHSTRIP, bytes); } /*[clinic input] bytes.lstrip bytes: object = None / Strip leading bytes contained in the argument. If the argument is omitted or None, strip leading ASCII whitespace. [clinic start generated code]*/ static PyObject * bytes_lstrip_impl(PyBytesObject *self, PyObject *bytes) /*[clinic end generated code: output=28602e586f524e82 input=9baff4398c3f6857]*/ { return do_argstrip(self, LEFTSTRIP, bytes); } /*[clinic input] bytes.rstrip bytes: object = None / Strip trailing bytes contained in the argument. If the argument is omitted or None, strip trailing ASCII whitespace. [clinic start generated code]*/ static PyObject * bytes_rstrip_impl(PyBytesObject *self, PyObject *bytes) /*[clinic end generated code: output=547e3815c95447da input=b78af445c727e32b]*/ { return do_argstrip(self, RIGHTSTRIP, bytes); } static PyObject * bytes_count(PyBytesObject *self, PyObject *args) { return _Py_bytes_count(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); } /*[clinic input] bytes.translate table: object Translation table, which must be a bytes object of length 256. / delete as deletechars: object(c_default="NULL") = b'' Return a copy with each character mapped by the given translation table. All characters occurring in the optional argument delete are removed. The remaining characters are mapped through the given translation table. [clinic start generated code]*/ static PyObject * bytes_translate_impl(PyBytesObject *self, PyObject *table, PyObject *deletechars) /*[clinic end generated code: output=43be3437f1956211 input=0ecdf159f654233c]*/ { char *input, *output; Py_buffer table_view = {NULL, NULL}; Py_buffer del_table_view = {NULL, NULL}; const char *table_chars; Py_ssize_t i, c, changed = 0; PyObject *input_obj = (PyObject*)self; const char *output_start, *del_table_chars=NULL; Py_ssize_t inlen, tablen, dellen = 0; PyObject *result; int trans_table[256]; if (PyBytes_Check(table)) { table_chars = PyBytes_AS_STRING(table); tablen = PyBytes_GET_SIZE(table); } else if (table == Py_None) { table_chars = NULL; tablen = 256; } else { if (PyObject_GetBuffer(table, &table_view, PyBUF_SIMPLE) != 0) return NULL; table_chars = table_view.buf; tablen = table_view.len; } if (tablen != 256) { PyErr_SetString(PyExc_ValueError, "translation table must be 256 characters long"); PyBuffer_Release(&table_view); return NULL; } if (deletechars != NULL) { if (PyBytes_Check(deletechars)) { del_table_chars = PyBytes_AS_STRING(deletechars); dellen = PyBytes_GET_SIZE(deletechars); } else { if (PyObject_GetBuffer(deletechars, &del_table_view, PyBUF_SIMPLE) != 0) { PyBuffer_Release(&table_view); return NULL; } del_table_chars = del_table_view.buf; dellen = del_table_view.len; } } else { del_table_chars = NULL; dellen = 0; } inlen = PyBytes_GET_SIZE(input_obj); result = PyBytes_FromStringAndSize((char *)NULL, inlen); if (result == NULL) { PyBuffer_Release(&del_table_view); PyBuffer_Release(&table_view); return NULL; } output_start = output = PyBytes_AS_STRING(result); input = PyBytes_AS_STRING(input_obj); if (dellen == 0 && table_chars != NULL) { /* If no deletions are required, use faster code */ for (i = inlen; --i >= 0; ) { c = Py_CHARMASK(*input++); if (Py_CHARMASK((*output++ = table_chars[c])) != c) changed = 1; } if (!changed && PyBytes_CheckExact(input_obj)) { Py_INCREF(input_obj); Py_DECREF(result); result = input_obj; } PyBuffer_Release(&del_table_view); PyBuffer_Release(&table_view); return result; } if (table_chars == NULL) { for (i = 0; i < 256; i++) trans_table[i] = Py_CHARMASK(i); } else { for (i = 0; i < 256; i++) trans_table[i] = Py_CHARMASK(table_chars[i]); } PyBuffer_Release(&table_view); for (i = 0; i < dellen; i++) trans_table[(int) Py_CHARMASK(del_table_chars[i])] = -1; PyBuffer_Release(&del_table_view); for (i = inlen; --i >= 0; ) { c = Py_CHARMASK(*input++); if (trans_table[c] != -1) if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c) continue; changed = 1; } if (!changed && PyBytes_CheckExact(input_obj)) { Py_DECREF(result); Py_INCREF(input_obj); return input_obj; } /* Fix the size of the resulting string */ if (inlen > 0) _PyBytes_Resize(&result, output - output_start); return result; } /*[clinic input] @staticmethod bytes.maketrans frm: Py_buffer to: Py_buffer / Return a translation table useable for the bytes or bytearray translate method. The returned table will be one where each byte in frm is mapped to the byte at the same position in to. The bytes objects frm and to must be of the same length. [clinic start generated code]*/ static PyObject * bytes_maketrans_impl(Py_buffer *frm, Py_buffer *to) /*[clinic end generated code: output=a36f6399d4b77f6f input=de7a8fc5632bb8f1]*/ { return _Py_bytes_maketrans(frm, to); } /*[clinic input] bytes.replace old: Py_buffer new: Py_buffer count: Py_ssize_t = -1 Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences. / Return a copy with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. [clinic start generated code]*/ static PyObject * bytes_replace_impl(PyBytesObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count) /*[clinic end generated code: output=994fa588b6b9c104 input=b2fbbf0bf04de8e5]*/ { return stringlib_replace((PyObject *)self, (const char *)old->buf, old->len, (const char *)new->buf, new->len, count); } /** End DALKE **/ static PyObject * bytes_startswith(PyBytesObject *self, PyObject *args) { return _Py_bytes_startswith(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); } static PyObject * bytes_endswith(PyBytesObject *self, PyObject *args) { return _Py_bytes_endswith(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), args); } /*[clinic input] bytes.decode encoding: str(c_default="NULL") = 'utf-8' The encoding with which to decode the bytes. errors: str(c_default="NULL") = 'strict' The error handling scheme to use for the handling of decoding errors. The default is 'strict' meaning that decoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that can handle UnicodeDecodeErrors. Decode the bytes using the codec registered for encoding. [clinic start generated code]*/ static PyObject * bytes_decode_impl(PyBytesObject *self, const char *encoding, const char *errors) /*[clinic end generated code: output=5649a53dde27b314 input=958174769d2a40ca]*/ { return PyUnicode_FromEncodedObject((PyObject*)self, encoding, errors); } /*[clinic input] bytes.splitlines keepends: int(c_default="0") = False Return a list of the lines in the bytes, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. [clinic start generated code]*/ static PyObject * bytes_splitlines_impl(PyBytesObject *self, int keepends) /*[clinic end generated code: output=3484149a5d880ffb input=7f4aac67144f9944]*/ { return stringlib_splitlines( (PyObject*) self, PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), keepends ); } /*[clinic input] @classmethod bytes.fromhex string: unicode / Create a bytes object from a string of hexadecimal numbers. Spaces between two numbers are accepted. Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'. [clinic start generated code]*/ static PyObject * bytes_fromhex_impl(PyTypeObject *type, PyObject *string) /*[clinic end generated code: output=0973acc63661bb2e input=bf4d1c361670acd3]*/ { PyObject *result = _PyBytes_FromHex(string, 0); if (type != &PyBytes_Type && result != NULL) { Py_SETREF(result, PyObject_CallFunctionObjArgs((PyObject *)type, result, NULL)); } return result; } PyObject* _PyBytes_FromHex(PyObject *string, int use_bytearray) { char *buf; Py_ssize_t hexlen, invalid_char; unsigned int top, bot; Py_UCS1 *str, *end; _PyBytesWriter writer; _PyBytesWriter_Init(&writer); writer.use_bytearray = use_bytearray; assert(PyUnicode_Check(string)); if (PyUnicode_READY(string)) return NULL; hexlen = PyUnicode_GET_LENGTH(string); if (!PyUnicode_IS_ASCII(string)) { void *data = PyUnicode_DATA(string); unsigned int kind = PyUnicode_KIND(string); Py_ssize_t i; /* search for the first non-ASCII character */ for (i = 0; i < hexlen; i++) { if (PyUnicode_READ(kind, data, i) >= 128) break; } invalid_char = i; goto error; } assert(PyUnicode_KIND(string) == PyUnicode_1BYTE_KIND); str = PyUnicode_1BYTE_DATA(string); /* This overestimates if there are spaces */ buf = _PyBytesWriter_Alloc(&writer, hexlen / 2); if (buf == NULL) return NULL; end = str + hexlen; while (str < end) { /* skip over spaces in the input */ if (*str == ' ') { do { str++; } while (*str == ' '); if (str >= end) break; } top = _PyLong_DigitValue[*str]; if (top >= 16) { invalid_char = str - PyUnicode_1BYTE_DATA(string); goto error; } str++; bot = _PyLong_DigitValue[*str]; if (bot >= 16) { invalid_char = str - PyUnicode_1BYTE_DATA(string); goto error; } str++; *buf++ = (unsigned char)((top << 4) + bot); } return _PyBytesWriter_Finish(&writer, buf); error: PyErr_Format(PyExc_ValueError, "non-hexadecimal number found in " "fromhex() arg at position %zd", invalid_char); _PyBytesWriter_Dealloc(&writer); return NULL; } PyDoc_STRVAR(hex__doc__, "B.hex() -> string\n\ \n\ Create a string of hexadecimal numbers from a bytes object.\n\ Example: b'\\xb9\\x01\\xef'.hex() -> 'b901ef'."); static PyObject * bytes_hex(PyBytesObject *self) { char* argbuf = PyBytes_AS_STRING(self); Py_ssize_t arglen = PyBytes_GET_SIZE(self); return _Py_strhex(argbuf, arglen); } static PyObject * bytes_getnewargs(PyBytesObject *v) { return Py_BuildValue("(y#)", v->ob_sval, Py_SIZE(v)); } static PyMethodDef bytes_methods[] = { {"__getnewargs__", (PyCFunction)bytes_getnewargs, METH_NOARGS}, {"capitalize", (PyCFunction)stringlib_capitalize, METH_NOARGS, _Py_capitalize__doc__}, {"center", (PyCFunction)stringlib_center, METH_VARARGS, _Py_center__doc__}, {"count", (PyCFunction)bytes_count, METH_VARARGS, _Py_count__doc__}, BYTES_DECODE_METHODDEF {"endswith", (PyCFunction)bytes_endswith, METH_VARARGS, _Py_endswith__doc__}, {"expandtabs", (PyCFunction)stringlib_expandtabs, METH_VARARGS | METH_KEYWORDS, _Py_expandtabs__doc__}, {"find", (PyCFunction)bytes_find, METH_VARARGS, _Py_find__doc__}, BYTES_FROMHEX_METHODDEF {"hex", (PyCFunction)bytes_hex, METH_NOARGS, hex__doc__}, {"index", (PyCFunction)bytes_index, METH_VARARGS, _Py_index__doc__}, {"isalnum", (PyCFunction)stringlib_isalnum, METH_NOARGS, _Py_isalnum__doc__}, {"isalpha", (PyCFunction)stringlib_isalpha, METH_NOARGS, _Py_isalpha__doc__}, {"isdigit", (PyCFunction)stringlib_isdigit, METH_NOARGS, _Py_isdigit__doc__}, {"islower", (PyCFunction)stringlib_islower, METH_NOARGS, _Py_islower__doc__}, {"isspace", (PyCFunction)stringlib_isspace, METH_NOARGS, _Py_isspace__doc__}, {"istitle", (PyCFunction)stringlib_istitle, METH_NOARGS, _Py_istitle__doc__}, {"isupper", (PyCFunction)stringlib_isupper, METH_NOARGS, _Py_isupper__doc__}, BYTES_JOIN_METHODDEF {"ljust", (PyCFunction)stringlib_ljust, METH_VARARGS, _Py_ljust__doc__}, {"lower", (PyCFunction)stringlib_lower, METH_NOARGS, _Py_lower__doc__}, BYTES_LSTRIP_METHODDEF BYTES_MAKETRANS_METHODDEF BYTES_PARTITION_METHODDEF BYTES_REPLACE_METHODDEF {"rfind", (PyCFunction)bytes_rfind, METH_VARARGS, _Py_rfind__doc__}, {"rindex", (PyCFunction)bytes_rindex, METH_VARARGS, _Py_rindex__doc__}, {"rjust", (PyCFunction)stringlib_rjust, METH_VARARGS, _Py_rjust__doc__}, BYTES_RPARTITION_METHODDEF BYTES_RSPLIT_METHODDEF BYTES_RSTRIP_METHODDEF BYTES_SPLIT_METHODDEF BYTES_SPLITLINES_METHODDEF {"startswith", (PyCFunction)bytes_startswith, METH_VARARGS, _Py_startswith__doc__}, BYTES_STRIP_METHODDEF {"swapcase", (PyCFunction)stringlib_swapcase, METH_NOARGS, _Py_swapcase__doc__}, {"title", (PyCFunction)stringlib_title, METH_NOARGS, _Py_title__doc__}, BYTES_TRANSLATE_METHODDEF {"upper", (PyCFunction)stringlib_upper, METH_NOARGS, _Py_upper__doc__}, {"zfill", (PyCFunction)stringlib_zfill, METH_VARARGS, _Py_zfill__doc__}, {NULL, NULL} /* sentinel */ }; static PyObject * bytes_mod(PyObject *self, PyObject *arg) { if (!PyBytes_Check(self)) { Py_RETURN_NOTIMPLEMENTED; } return _PyBytes_FormatEx(PyBytes_AS_STRING(self), PyBytes_GET_SIZE(self), arg, 0); } static PyNumberMethods bytes_as_number = { 0, /*nb_add*/ 0, /*nb_subtract*/ 0, /*nb_multiply*/ bytes_mod, /*nb_remainder*/ }; static PyObject * bytes_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static PyObject * bytes_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *x = NULL; const char *encoding = NULL; const char *errors = NULL; PyObject *new = NULL; PyObject *func; Py_ssize_t size; static char *kwlist[] = {"source", "encoding", "errors", 0}; _Py_IDENTIFIER(__bytes__); if (type != &PyBytes_Type) return bytes_subtype_new(type, args, kwds); if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:bytes", kwlist, &x, &encoding, &errors)) return NULL; if (x == NULL) { if (encoding != NULL || errors != NULL) { PyErr_SetString(PyExc_TypeError, "encoding or errors without sequence " "argument"); return NULL; } return PyBytes_FromStringAndSize(NULL, 0); } if (encoding != NULL) { /* Encode via the codec registry */ if (!PyUnicode_Check(x)) { PyErr_SetString(PyExc_TypeError, "encoding without a string argument"); return NULL; } new = PyUnicode_AsEncodedString(x, encoding, errors); if (new == NULL) return NULL; assert(PyBytes_Check(new)); return new; } if (errors != NULL) { PyErr_SetString(PyExc_TypeError, PyUnicode_Check(x) ? "string argument without an encoding" : "errors without a string argument"); return NULL; } /* We'd like to call PyObject_Bytes here, but we need to check for an integer argument before deferring to PyBytes_FromObject, something PyObject_Bytes doesn't do. */ func = _PyObject_LookupSpecial(x, &PyId___bytes__); if (func != NULL) { new = PyObject_CallFunctionObjArgs(func, NULL); Py_DECREF(func); if (new == NULL) return NULL; if (!PyBytes_Check(new)) { PyErr_Format(PyExc_TypeError, "__bytes__ returned non-bytes (type %.200s)", Py_TYPE(new)->tp_name); Py_DECREF(new); return NULL; } return new; } else if (PyErr_Occurred()) return NULL; if (PyUnicode_Check(x)) { PyErr_SetString(PyExc_TypeError, "string argument without an encoding"); return NULL; } /* Is it an integer? */ if (PyIndex_Check(x)) { size = PyNumber_AsSsize_t(x, PyExc_OverflowError); if (size == -1 && PyErr_Occurred()) { if (!PyErr_ExceptionMatches(PyExc_TypeError)) return NULL; PyErr_Clear(); /* fall through */ } else { if (size < 0) { PyErr_SetString(PyExc_ValueError, "negative count"); return NULL; } new = _PyBytes_FromSize(size, 1); if (new == NULL) return NULL; return new; } } return PyBytes_FromObject(x); } static PyObject* _PyBytes_FromBuffer(PyObject *x) { PyObject *new; Py_buffer view; if (PyObject_GetBuffer(x, &view, PyBUF_FULL_RO) < 0) return NULL; new = PyBytes_FromStringAndSize(NULL, view.len); if (!new) goto fail; if (PyBuffer_ToContiguous(((PyBytesObject *)new)->ob_sval, &view, view.len, 'C') < 0) goto fail; PyBuffer_Release(&view); return new; fail: Py_XDECREF(new); PyBuffer_Release(&view); return NULL; } static PyObject* _PyBytes_FromList(PyObject *x) { Py_ssize_t i, size = PyList_GET_SIZE(x); Py_ssize_t value; char *str; PyObject *item; _PyBytesWriter writer; _PyBytesWriter_Init(&writer); str = _PyBytesWriter_Alloc(&writer, size); if (str == NULL) return NULL; writer.overallocate = 1; size = writer.allocated; for (i = 0; i < PyList_GET_SIZE(x); i++) { item = PyList_GET_ITEM(x, i); Py_INCREF(item); value = PyNumber_AsSsize_t(item, NULL); Py_DECREF(item); if (value == -1 && PyErr_Occurred()) goto error; if (value < 0 || value >= 256) { PyErr_SetString(PyExc_ValueError, "bytes must be in range(0, 256)"); goto error; } if (i >= size) { str = _PyBytesWriter_Resize(&writer, str, size+1); if (str == NULL) return NULL; size = writer.allocated; } *str++ = (char) value; } return _PyBytesWriter_Finish(&writer, str); error: _PyBytesWriter_Dealloc(&writer); return NULL; } static PyObject* _PyBytes_FromTuple(PyObject *x) { PyObject *bytes; Py_ssize_t i, size = PyTuple_GET_SIZE(x); Py_ssize_t value; char *str; PyObject *item; bytes = PyBytes_FromStringAndSize(NULL, size); if (bytes == NULL) return NULL; str = ((PyBytesObject *)bytes)->ob_sval; for (i = 0; i < size; i++) { item = PyTuple_GET_ITEM(x, i); value = PyNumber_AsSsize_t(item, NULL); if (value == -1 && PyErr_Occurred()) goto error; if (value < 0 || value >= 256) { PyErr_SetString(PyExc_ValueError, "bytes must be in range(0, 256)"); goto error; } *str++ = (char) value; } return bytes; error: Py_DECREF(bytes); return NULL; } static PyObject * _PyBytes_FromIterator(PyObject *it, PyObject *x) { char *str; Py_ssize_t i, size; _PyBytesWriter writer; /* For iterator version, create a string object and resize as needed */ size = PyObject_LengthHint(x, 64); if (size == -1 && PyErr_Occurred()) return NULL; _PyBytesWriter_Init(&writer); str = _PyBytesWriter_Alloc(&writer, size); if (str == NULL) return NULL; writer.overallocate = 1; size = writer.allocated; /* Run the iterator to exhaustion */ for (i = 0; ; i++) { PyObject *item; Py_ssize_t value; /* Get the next item */ item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) goto error; break; } /* Interpret it as an int (__index__) */ value = PyNumber_AsSsize_t(item, NULL); Py_DECREF(item); if (value == -1 && PyErr_Occurred()) goto error; /* Range check */ if (value < 0 || value >= 256) { PyErr_SetString(PyExc_ValueError, "bytes must be in range(0, 256)"); goto error; } /* Append the byte */ if (i >= size) { str = _PyBytesWriter_Resize(&writer, str, size+1); if (str == NULL) return NULL; size = writer.allocated; } *str++ = (char) value; } return _PyBytesWriter_Finish(&writer, str); error: _PyBytesWriter_Dealloc(&writer); return NULL; } PyObject * PyBytes_FromObject(PyObject *x) { PyObject *it, *result; if (x == NULL) { PyErr_BadInternalCall(); return NULL; } if (PyBytes_CheckExact(x)) { Py_INCREF(x); return x; } /* Use the modern buffer interface */ if (PyObject_CheckBuffer(x)) return _PyBytes_FromBuffer(x); if (PyList_CheckExact(x)) return _PyBytes_FromList(x); if (PyTuple_CheckExact(x)) return _PyBytes_FromTuple(x); if (!PyUnicode_Check(x)) { it = PyObject_GetIter(x); if (it != NULL) { result = _PyBytes_FromIterator(it, x); Py_DECREF(it); return result; } if (!PyErr_ExceptionMatches(PyExc_TypeError)) { return NULL; } } PyErr_Format(PyExc_TypeError, "cannot convert '%.200s' object to bytes", x->ob_type->tp_name); return NULL; } static PyObject * bytes_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *tmp, *pnew; Py_ssize_t n; assert(PyType_IsSubtype(type, &PyBytes_Type)); tmp = bytes_new(&PyBytes_Type, args, kwds); if (tmp == NULL) return NULL; assert(PyBytes_Check(tmp)); n = PyBytes_GET_SIZE(tmp); pnew = type->tp_alloc(type, n); if (pnew != NULL) { memcpy(PyBytes_AS_STRING(pnew), PyBytes_AS_STRING(tmp), n+1); ((PyBytesObject *)pnew)->ob_shash = ((PyBytesObject *)tmp)->ob_shash; } Py_DECREF(tmp); return pnew; } PyDoc_STRVAR(bytes_doc, "bytes(iterable_of_ints) -> bytes\n\ bytes(string, encoding[, errors]) -> bytes\n\ bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer\n\ bytes(int) -> bytes object of size given by the parameter initialized with null bytes\n\ bytes() -> empty bytes object\n\ \n\ Construct an immutable array of bytes from:\n\ - an iterable yielding integers in range(256)\n\ - a text string encoded using the specified encoding\n\ - any object implementing the buffer API.\n\ - an integer"); static PyObject *bytes_iter(PyObject *seq); PyTypeObject PyBytes_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "bytes", PyBytesObject_SIZE, sizeof(char), bytes_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)bytes_repr, /* tp_repr */ &bytes_as_number, /* tp_as_number */ &bytes_as_sequence, /* tp_as_sequence */ &bytes_as_mapping, /* tp_as_mapping */ (hashfunc)bytes_hash, /* tp_hash */ 0, /* tp_call */ bytes_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ &bytes_as_buffer, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_BYTES_SUBCLASS, /* tp_flags */ bytes_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)bytes_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ bytes_iter, /* tp_iter */ 0, /* tp_iternext */ bytes_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ &PyBaseObject_Type, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ bytes_new, /* tp_new */ PyObject_Del, /* tp_free */ }; void PyBytes_Concat(PyObject **pv, PyObject *w) { assert(pv != NULL); if (*pv == NULL) return; if (w == NULL) { Py_CLEAR(*pv); return; } if (Py_REFCNT(*pv) == 1 && PyBytes_CheckExact(*pv)) { /* Only one reference, so we can resize in place */ Py_ssize_t oldsize; Py_buffer wb; wb.len = -1; if (PyObject_GetBuffer(w, &wb, PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "can't concat %.100s to %.100s", Py_TYPE(w)->tp_name, Py_TYPE(*pv)->tp_name); Py_CLEAR(*pv); return; } oldsize = PyBytes_GET_SIZE(*pv); if (oldsize > PY_SSIZE_T_MAX - wb.len) { PyErr_NoMemory(); goto error; } if (_PyBytes_Resize(pv, oldsize + wb.len) < 0) goto error; memcpy(PyBytes_AS_STRING(*pv) + oldsize, wb.buf, wb.len); PyBuffer_Release(&wb); return; error: PyBuffer_Release(&wb); Py_CLEAR(*pv); return; } else { /* Multiple references, need to create new object */ PyObject *v; v = bytes_concat(*pv, w); Py_SETREF(*pv, v); } } void PyBytes_ConcatAndDel(PyObject **pv, PyObject *w) { PyBytes_Concat(pv, w); Py_XDECREF(w); } /* The following function breaks the notion that bytes are immutable: it changes the size of a bytes object. We get away with this only if there is only one module referencing the object. You can also think of it as creating a new bytes object and destroying the old one, only more efficiently. In any case, don't use this if the bytes object may already be known to some other part of the code... Note that if there's not enough memory to resize the bytes object, the original bytes object at *pv is deallocated, *pv is set to NULL, an "out of memory" exception is set, and -1 is returned. Else (on success) 0 is returned, and the value in *pv may or may not be the same as on input. As always, an extra byte is allocated for a trailing \0 byte (newsize does *not* include that), and a trailing \0 byte is stored. */ int _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize) { PyObject *v; PyBytesObject *sv; v = *pv; if (!PyBytes_Check(v) || newsize < 0) { goto error; } if (Py_SIZE(v) == newsize) { /* return early if newsize equals to v->ob_size */ return 0; } if (Py_REFCNT(v) != 1) { goto error; } /* XXX UNREF/NEWREF interface should be more symmetrical */ _Py_DEC_REFTOTAL; _Py_ForgetReference(v); *pv = (PyObject *) PyObject_REALLOC(v, PyBytesObject_SIZE + newsize); if (*pv == NULL) { PyObject_Del(v); PyErr_NoMemory(); return -1; } _Py_NewReference(*pv); sv = (PyBytesObject *) *pv; Py_SIZE(sv) = newsize; sv->ob_sval[newsize] = '\0'; sv->ob_shash = -1; /* invalidate cached hash value */ return 0; error: *pv = 0; Py_DECREF(v); PyErr_BadInternalCall(); return -1; } void PyBytes_Fini(void) { int i; for (i = 0; i < UCHAR_MAX + 1; i++) Py_CLEAR(characters[i]); Py_CLEAR(nullstring); } /*********************** Bytes Iterator ****************************/ typedef struct { PyObject_HEAD Py_ssize_t it_index; PyBytesObject *it_seq; /* Set to NULL when iterator is exhausted */ } striterobject; static void striter_dealloc(striterobject *it) { _PyObject_GC_UNTRACK(it); Py_XDECREF(it->it_seq); PyObject_GC_Del(it); } static int striter_traverse(striterobject *it, visitproc visit, void *arg) { Py_VISIT(it->it_seq); return 0; } static PyObject * striter_next(striterobject *it) { PyBytesObject *seq; PyObject *item; assert(it != NULL); seq = it->it_seq; if (seq == NULL) return NULL; assert(PyBytes_Check(seq)); if (it->it_index < PyBytes_GET_SIZE(seq)) { item = PyLong_FromLong( (unsigned char)seq->ob_sval[it->it_index]); if (item != NULL) ++it->it_index; return item; } it->it_seq = NULL; Py_DECREF(seq); return NULL; } static PyObject * striter_len(striterobject *it) { Py_ssize_t len = 0; if (it->it_seq) len = PyBytes_GET_SIZE(it->it_seq) - it->it_index; return PyLong_FromSsize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * striter_reduce(striterobject *it) { if (it->it_seq != NULL) { return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"), it->it_seq, it->it_index); } else { PyObject *u = PyUnicode_FromUnicode(NULL, 0); if (u == NULL) return NULL; return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u); } } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyObject * striter_setstate(striterobject *it, PyObject *state) { Py_ssize_t index = PyLong_AsSsize_t(state); if (index == -1 && PyErr_Occurred()) return NULL; if (it->it_seq != NULL) { if (index < 0) index = 0; else if (index > PyBytes_GET_SIZE(it->it_seq)) index = PyBytes_GET_SIZE(it->it_seq); /* iterator exhausted */ it->it_index = index; } Py_RETURN_NONE; } PyDoc_STRVAR(setstate_doc, "Set state information for unpickling."); static PyMethodDef striter_methods[] = { {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)striter_reduce, METH_NOARGS, reduce_doc}, {"__setstate__", (PyCFunction)striter_setstate, METH_O, setstate_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyBytesIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "bytes_iterator", /* tp_name */ sizeof(striterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)striter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)striter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)striter_next, /* tp_iternext */ striter_methods, /* tp_methods */ 0, }; static PyObject * bytes_iter(PyObject *seq) { striterobject *it; if (!PyBytes_Check(seq)) { PyErr_BadInternalCall(); return NULL; } it = PyObject_GC_New(striterobject, &PyBytesIter_Type); if (it == NULL) return NULL; it->it_index = 0; Py_INCREF(seq); it->it_seq = (PyBytesObject *)seq; _PyObject_GC_TRACK(it); return (PyObject *)it; } /* _PyBytesWriter API */ #ifdef MS_WINDOWS /* On Windows, overallocate by 50% is the best factor */ # define OVERALLOCATE_FACTOR 2 #else /* On Linux, overallocate by 25% is the best factor */ # define OVERALLOCATE_FACTOR 4 #endif void _PyBytesWriter_Init(_PyBytesWriter *writer) { /* Set all attributes before small_buffer to 0 */ bzero(writer, offsetof(_PyBytesWriter, small_buffer)); #ifdef Py_DEBUG memset(writer->small_buffer, 0xCB, sizeof(writer->small_buffer)); #endif } void _PyBytesWriter_Dealloc(_PyBytesWriter *writer) { Py_CLEAR(writer->buffer); } Py_LOCAL_INLINE(char*) _PyBytesWriter_AsString(_PyBytesWriter *writer) { if (writer->use_small_buffer) { assert(writer->buffer == NULL); return writer->small_buffer; } else if (writer->use_bytearray) { assert(writer->buffer != NULL); return PyByteArray_AS_STRING(writer->buffer); } else { assert(writer->buffer != NULL); return PyBytes_AS_STRING(writer->buffer); } } Py_LOCAL_INLINE(Py_ssize_t) _PyBytesWriter_GetSize(_PyBytesWriter *writer, char *str) { char *start = _PyBytesWriter_AsString(writer); assert(str != NULL); assert(str >= start); assert(str - start <= writer->allocated); return str - start; } Py_LOCAL_INLINE(void) _PyBytesWriter_CheckConsistency(_PyBytesWriter *writer, char *str) { #ifdef Py_DEBUG char *start, *end; if (writer->use_small_buffer) { assert(writer->buffer == NULL); } else { assert(writer->buffer != NULL); if (writer->use_bytearray) assert(PyByteArray_CheckExact(writer->buffer)); else assert(PyBytes_CheckExact(writer->buffer)); assert(Py_REFCNT(writer->buffer) == 1); } if (writer->use_bytearray) { /* bytearray has its own overallocation algorithm, writer overallocation must be disabled */ assert(!writer->overallocate); } assert(0 <= writer->allocated); assert(0 <= writer->min_size && writer->min_size <= writer->allocated); /* the last byte must always be null */ start = _PyBytesWriter_AsString(writer); assert(start[writer->allocated] == 0); end = start + writer->allocated; assert(str != NULL); assert(start <= str && str <= end); #endif } void* _PyBytesWriter_Resize(_PyBytesWriter *writer, void *str, Py_ssize_t size) { Py_ssize_t allocated, pos; _PyBytesWriter_CheckConsistency(writer, str); assert(writer->allocated < size); allocated = size; if (writer->overallocate && allocated <= (PY_SSIZE_T_MAX - allocated / OVERALLOCATE_FACTOR)) { /* overallocate to limit the number of realloc() */ allocated += allocated / OVERALLOCATE_FACTOR; } pos = _PyBytesWriter_GetSize(writer, str); if (!writer->use_small_buffer) { if (writer->use_bytearray) { if (PyByteArray_Resize(writer->buffer, allocated)) goto error; /* writer->allocated can be smaller than writer->buffer->ob_alloc, but we cannot use ob_alloc because bytes may need to be moved to use the whole buffer. bytearray uses an internal optimization to avoid moving or copying bytes when bytes are removed at the beginning (ex: del bytearray[:1]). */ } else { if (_PyBytes_Resize(&writer->buffer, allocated)) goto error; } } else { /* convert from stack buffer to bytes object buffer */ assert(writer->buffer == NULL); if (writer->use_bytearray) writer->buffer = PyByteArray_FromStringAndSize(NULL, allocated); else writer->buffer = PyBytes_FromStringAndSize(NULL, allocated); if (writer->buffer == NULL) goto error; if (pos != 0) { char *dest; if (writer->use_bytearray) dest = PyByteArray_AS_STRING(writer->buffer); else dest = PyBytes_AS_STRING(writer->buffer); memcpy(dest, writer->small_buffer, pos); } writer->use_small_buffer = 0; #ifdef Py_DEBUG memset(writer->small_buffer, 0xDB, sizeof(writer->small_buffer)); #endif } writer->allocated = allocated; str = _PyBytesWriter_AsString(writer) + pos; _PyBytesWriter_CheckConsistency(writer, str); return str; error: _PyBytesWriter_Dealloc(writer); return NULL; } void* _PyBytesWriter_Prepare(_PyBytesWriter *writer, void *str, Py_ssize_t size) { Py_ssize_t new_min_size; _PyBytesWriter_CheckConsistency(writer, str); assert(size >= 0); if (size == 0) { /* nothing to do */ return str; } if (writer->min_size > PY_SSIZE_T_MAX - size) { PyErr_NoMemory(); _PyBytesWriter_Dealloc(writer); return NULL; } new_min_size = writer->min_size + size; if (new_min_size > writer->allocated) str = _PyBytesWriter_Resize(writer, str, new_min_size); writer->min_size = new_min_size; return str; } /* Allocate the buffer to write size bytes. Return the pointer to the beginning of buffer data. Raise an exception and return NULL on error. */ void* _PyBytesWriter_Alloc(_PyBytesWriter *writer, Py_ssize_t size) { /* ensure that _PyBytesWriter_Alloc() is only called once */ assert(writer->min_size == 0 && writer->buffer == NULL); assert(size >= 0); writer->use_small_buffer = 1; #ifdef Py_DEBUG writer->allocated = sizeof(writer->small_buffer) - 1; /* In debug mode, don't use the full small buffer because it is less efficient than bytes and bytearray objects to detect buffer underflow and buffer overflow. Use 10 bytes of the small buffer to test also code using the smaller buffer in debug mode. Don't modify the _PyBytesWriter structure (use a shorter small buffer) in debug mode to also be able to detect stack overflow when running tests in debug mode. The _PyBytesWriter is large (more than 512 bytes), if Py_EnterRecursiveCall() is not used in deep C callback, we may hit a stack overflow. */ writer->allocated = Py_MIN(writer->allocated, 10); /* _PyBytesWriter_CheckConsistency() requires the last byte to be 0, to detect buffer overflow */ writer->small_buffer[writer->allocated] = 0; #else writer->allocated = sizeof(writer->small_buffer); #endif return _PyBytesWriter_Prepare(writer, writer->small_buffer, size); } PyObject * _PyBytesWriter_Finish(_PyBytesWriter *writer, void *str) { Py_ssize_t size; PyObject *result; _PyBytesWriter_CheckConsistency(writer, str); size = _PyBytesWriter_GetSize(writer, str); if (size == 0 && !writer->use_bytearray) { Py_CLEAR(writer->buffer); /* Get the empty byte string singleton */ result = PyBytes_FromStringAndSize(NULL, 0); } else if (writer->use_small_buffer) { if (writer->use_bytearray) { result = PyByteArray_FromStringAndSize(writer->small_buffer, size); } else { result = PyBytes_FromStringAndSize(writer->small_buffer, size); } } else { result = writer->buffer; writer->buffer = NULL; if (size != writer->allocated) { if (writer->use_bytearray) { if (PyByteArray_Resize(result, size)) { Py_DECREF(result); return NULL; } } else { if (_PyBytes_Resize(&result, size)) { assert(result == NULL); return NULL; } } } } return result; } void* _PyBytesWriter_WriteBytes(_PyBytesWriter *writer, void *ptr, const void *bytes, Py_ssize_t size) { char *str = (char *)ptr; str = _PyBytesWriter_Prepare(writer, str, size); if (str == NULL) return NULL; memcpy(str, bytes, size); str += size; return str; }
103,463
3,483
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/fileobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/stdio/lock.internal.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ /* File object implementation (what's left of it -- see io.py) */ #if defined(HAVE_GETC_UNLOCKED) && !defined(_Py_MEMORY_SANITIZER) /* clang MemorySanitizer doesn't yet understand getc_unlocked. */ #define GETC(f) getc_unlocked(f) #define FLOCKFILE(f) flockfile(f) #define FUNLOCKFILE(f) funlockfile(f) #else #define GETC(f) getc(f) #define FLOCKFILE(f) #define FUNLOCKFILE(f) #endif /* Newline flags */ #define NEWLINE_UNKNOWN 0 /* No newline seen, yet */ #define NEWLINE_CR 1 /* \r newline seen */ #define NEWLINE_LF 2 /* \n newline seen */ #define NEWLINE_CRLF 4 /* \r\n newline seen */ /* External C interface */ PyObject * PyFile_GetLine(PyObject *f, int n) { PyObject *result; if (f == NULL) { PyErr_BadInternalCall(); return NULL; } { PyObject *reader; PyObject *args; _Py_IDENTIFIER(readline); reader = _PyObject_GetAttrId(f, &PyId_readline); if (reader == NULL) return NULL; if (n <= 0) args = PyTuple_New(0); else args = Py_BuildValue("(i)", n); if (args == NULL) { Py_DECREF(reader); return NULL; } result = PyEval_CallObject(reader, args); Py_DECREF(reader); Py_DECREF(args); if (result != NULL && !PyBytes_Check(result) && !PyUnicode_Check(result)) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_TypeError, "object.readline() returned non-string"); } } if (n < 0 && result != NULL && PyBytes_Check(result)) { char *s = PyBytes_AS_STRING(result); Py_ssize_t len = PyBytes_GET_SIZE(result); if (len == 0) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_EOFError, "EOF when reading a line"); } else if (s[len-1] == '\n') { if (result->ob_refcnt == 1) _PyBytes_Resize(&result, len-1); else { PyObject *v; v = PyBytes_FromStringAndSize(s, len-1); Py_DECREF(result); result = v; } } } if (n < 0 && result != NULL && PyUnicode_Check(result)) { Py_ssize_t len = PyUnicode_GET_LENGTH(result); if (len == 0) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_EOFError, "EOF when reading a line"); } else if (PyUnicode_READ_CHAR(result, len-1) == '\n') { PyObject *v; v = PyUnicode_Substring(result, 0, len-1); Py_DECREF(result); result = v; } } return result; } /* Interfaces to write objects/strings to file-like objects */ int PyFile_WriteObject(PyObject *v, PyObject *f, int flags) { PyObject *writer, *value, *result; _Py_IDENTIFIER(write); if (f == NULL) { PyErr_SetString(PyExc_TypeError, "writeobject with NULL file"); return -1; } writer = _PyObject_GetAttrId(f, &PyId_write); if (writer == NULL) return -1; if (flags & Py_PRINT_RAW) { value = PyObject_Str(v); } else value = PyObject_Repr(v); if (value == NULL) { Py_DECREF(writer); return -1; } result = _PyObject_CallArg1(writer, value); Py_DECREF(value); Py_DECREF(writer); if (result == NULL) return -1; Py_DECREF(result); return 0; } int PyFile_WriteString(const char *s, PyObject *f) { if (f == NULL) { /* Should be caused by a pre-existing error */ if (!PyErr_Occurred()) PyErr_SetString(PyExc_SystemError, "null file for PyFile_WriteString"); return -1; } else if (!PyErr_Occurred()) { PyObject *v = PyUnicode_FromString(s); int err; if (v == NULL) return -1; err = PyFile_WriteObject(v, f, Py_PRINT_RAW); Py_DECREF(v); return err; } else return -1; } /* Try to get a file-descriptor from a Python object. If the object is an integer, its value is returned. If not, the object's fileno() method is called if it exists; the method must return an integer, which is returned as the file descriptor value. -1 is returned on failure. */ int PyObject_AsFileDescriptor(PyObject *o) { int fd; PyObject *meth; _Py_IDENTIFIER(fileno); if (PyLong_Check(o)) { fd = _PyLong_AsInt(o); } else if ((meth = _PyObject_GetAttrId(o, &PyId_fileno)) != NULL) { PyObject *fno = PyEval_CallObject(meth, NULL); Py_DECREF(meth); if (fno == NULL) return -1; if (PyLong_Check(fno)) { fd = _PyLong_AsInt(fno); Py_DECREF(fno); } else { PyErr_SetString(PyExc_TypeError, "fileno() returned a non-integer"); Py_DECREF(fno); return -1; } } else { PyErr_SetString(PyExc_TypeError, "argument must be an int, or have a fileno() method."); return -1; } if (fd == -1 && PyErr_Occurred()) return -1; if (fd < 0) { PyErr_Format(PyExc_ValueError, "file descriptor cannot be a negative integer (%i)", fd); return -1; } return fd; } /* ** Py_UniversalNewlineFgets is an fgets variation that understands ** all of \r, \n and \r\n conventions. ** The stream should be opened in binary mode. ** If fobj is NULL the routine always does newline conversion, and ** it may peek one char ahead to gobble the second char in \r\n. ** If fobj is non-NULL it must be a PyFileObject. In this case there ** is no readahead but in stead a flag is used to skip a following ** \n on the next read. Also, if the file is open in binary mode ** the whole conversion is skipped. Finally, the routine keeps track of ** the different types of newlines seen. ** Note that we need no error handling: fgets() treats error and eof ** identically. */ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { char *p = buf; int c; int newlinetypes = 0; int skipnextlf = 0; if (fobj) { errno = ENXIO; /* What can you do... */ return NULL; } FLOCKFILE(stream); c = 'x'; /* Shut up gcc warning */ while (--n > 0 && (c = GETC(stream)) != EOF ) { if (skipnextlf ) { skipnextlf = 0; if (c == '\n') { /* Seeing a \n here with skipnextlf true ** means we saw a \r before. */ newlinetypes |= NEWLINE_CRLF; c = GETC(stream); if (c == EOF) break; } else { /* ** Note that c == EOF also brings us here, ** so we're okay if the last char in the file ** is a CR. */ newlinetypes |= NEWLINE_CR; } } if (c == '\r') { /* A \r is translated into a \n, and we skip ** an adjacent \n, if any. We don't set the ** newlinetypes flag until we've seen the next char. */ skipnextlf = 1; c = '\n'; } else if ( c == '\n') { newlinetypes |= NEWLINE_LF; } *p++ = c; if (c == '\n') break; } /* if ( c == EOF && skipnextlf ) newlinetypes |= NEWLINE_CR; */ FUNLOCKFILE(stream); *p = '\0'; if ( skipnextlf ) { /* If we have no file object we cannot save the ** skipnextlf flag. We have to readahead, which ** will cause a pause if we're reading from an ** interactive stream, but that is very unlikely ** unless we're doing something silly like ** exec(open("/dev/tty").read()). */ c = GETC(stream); if ( c != '\n' ) ungetc(c, stream); } if (p == buf) return NULL; return buf; } /* **************************** std printer **************************** * The stdprinter is used during the boot strapping phase as a preliminary * file like object for sys.stderr. */ typedef struct { PyObject_HEAD int fd; } PyStdPrinter_Object; static PyObject * stdprinter_new(PyTypeObject *type, PyObject *args, PyObject *kews) { PyStdPrinter_Object *self; assert(type != NULL && type->tp_alloc != NULL); self = (PyStdPrinter_Object *) type->tp_alloc(type, 0); if (self != NULL) { self->fd = -1; } return (PyObject *) self; } static int stdprinter_init(PyObject *self, PyObject *args, PyObject *kwds) { PyErr_SetString(PyExc_TypeError, "cannot create 'stderrprinter' instances"); return -1; } PyObject * PyFile_NewStdPrinter(int fd) { PyStdPrinter_Object *self; if (fd != fileno(stdout) && fd != fileno(stderr)) { /* not enough infrastructure for PyErr_BadInternalCall() */ return NULL; } self = PyObject_New(PyStdPrinter_Object, &PyStdPrinter_Type); if (self != NULL) { self->fd = fd; } return (PyObject*)self; } static PyObject * stdprinter_write(PyStdPrinter_Object *self, PyObject **args, Py_ssize_t nargs) { PyObject *unicode; PyObject *bytes = NULL; char *str; Py_ssize_t n; int err; if (self->fd < 0) { /* fd might be invalid on Windows * I can't raise an exception here. It may lead to an * unlimited recursion in the case stderr is invalid. */ Py_RETURN_NONE; } if (!_PyArg_UnpackStack(args, nargs, "write", 1, 1, &unicode)) return NULL; /* encode Unicode to UTF-8 */ str = PyUnicode_AsUTF8AndSize(unicode, &n); if (str == NULL) { PyErr_Clear(); bytes = _PyUnicode_AsUTF8String(unicode, "backslashreplace"); if (bytes == NULL) return NULL; if (PyBytes_AsStringAndSize(bytes, &str, &n) < 0) { Py_DECREF(bytes); return NULL; } } n = _Py_write(self->fd, str, n); /* save errno, it can be modified indirectly by Py_XDECREF() */ err = errno; Py_XDECREF(bytes); if (n == -1) { if (err == EAGAIN) { PyErr_Clear(); Py_RETURN_NONE; } return NULL; } return PyLong_FromSsize_t(n); } static PyObject * stdprinter_fileno(PyStdPrinter_Object *self) { return PyLong_FromLong((long) self->fd); } static PyObject * stdprinter_repr(PyStdPrinter_Object *self) { return PyUnicode_FromFormat("<stdprinter(fd=%d) object at 0x%x>", self->fd, self); } static PyObject * stdprinter_noop(PyStdPrinter_Object *self) { Py_RETURN_NONE; } static PyObject * stdprinter_isatty(PyStdPrinter_Object *self) { long res; if (self->fd < 0) { Py_RETURN_FALSE; } Py_BEGIN_ALLOW_THREADS res = isatty(self->fd); Py_END_ALLOW_THREADS return PyBool_FromLong(res); } static PyMethodDef stdprinter_methods[] = { {"close", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, {"flush", (PyCFunction)stdprinter_noop, METH_NOARGS, ""}, {"fileno", (PyCFunction)stdprinter_fileno, METH_NOARGS, ""}, {"isatty", (PyCFunction)stdprinter_isatty, METH_NOARGS, ""}, {"write", (PyCFunction)stdprinter_write, METH_FASTCALL, ""}, {NULL, NULL} /*sentinel */ }; static PyObject * get_closed(PyStdPrinter_Object *self, void *closure) { Py_INCREF(Py_False); return Py_False; } static PyObject * get_mode(PyStdPrinter_Object *self, void *closure) { return PyUnicode_FromString("w"); } static PyObject * get_encoding(PyStdPrinter_Object *self, void *closure) { Py_RETURN_NONE; } static PyGetSetDef stdprinter_getsetlist[] = { {"closed", (getter)get_closed, NULL, "True if the file is closed"}, {"encoding", (getter)get_encoding, NULL, "Encoding of the file"}, {"mode", (getter)get_mode, NULL, "String giving the file mode"}, {0}, }; PyTypeObject PyStdPrinter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "stderrprinter", /* tp_name */ sizeof(PyStdPrinter_Object), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)stdprinter_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ stdprinter_methods, /* tp_methods */ 0, /* tp_members */ stdprinter_getsetlist, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ stdprinter_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ stdprinter_new, /* tp_new */ PyObject_Del, /* tp_free */ };
16,640
527
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/dictobject.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/likely.h" #include "libc/calls/calls.h" #include "libc/log/countbranch.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/o.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Objects/dict-common.h" #include "third_party/python/pyconfig.h" /* clang-format off */ /* Dictionary object implementation using a hash table */ /* The distribution includes a separate file, Objects/dictnotes.txt, describing explorations into dictionary design and optimization. It covers typical dictionary use patterns, the parameters for tuning dictionaries, and several ideas for possible optimizations. */ /* PyDictKeysObject This implements the dictionary's hashtable. As of Python 3.6, this is compact and ordered. Basic idea is described here. https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html layout: +---------------+ | dk_refcnt | | dk_size | | dk_lookup | | dk_usable | | dk_nentries | +---------------+ | dk_indices | | | +---------------+ | dk_entries | | | +---------------+ dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1) or DKIX_DUMMY(-2). Size of indices is dk_size. Type of each index in indices is vary on dk_size: * int8 for dk_size <= 128 * int16 for 256 <= dk_size <= 2**15 * int32 for 2**16 <= dk_size <= 2**31 * int64 for 2**32 <= dk_size dk_entries is array of PyDictKeyEntry. It's size is USABLE_FRACTION(dk_size). DK_ENTRIES(dk) can be used to get pointer to entries. NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of dk_indices entry is signed integer and int16 is used for table which dk_size == 256. */ /* The DictObject can be in one of two forms. Either: A combined table: ma_values == NULL, dk_refcnt == 1. Values are stored in the me_value field of the PyDictKeysObject. Or: A split table: ma_values != NULL, dk_refcnt >= 1 Values are stored in the ma_values array. Only string (unicode) keys are allowed. All dicts sharing same key must have same insertion order. There are four kinds of slots in the table (slot is index, and DK_ENTRIES(keys)[index] if index >= 0): 1. Unused. index == DKIX_EMPTY Does not hold an active (key, value) pair now and never did. Unused can transition to Active upon key insertion. This is each slot's initial state. 2. Active. index >= 0, me_key != NULL and me_value != NULL Holds an active (key, value) pair. Active can transition to Dummy or Pending upon key deletion (for combined and split tables respectively). This is the only case in which me_value != NULL. 3. Dummy. index == DKIX_DUMMY (combined only) Previously held an active (key, value) pair, but that was deleted and an active pair has not yet overwritten the slot. Dummy can transition to Active upon key insertion. Dummy slots cannot be made Unused again else the probe sequence in case of collision would have no way to know they were once active. 4. Pending. index >= 0, key != NULL, and value == NULL (split only) Not yet inserted in split-table. */ /* Preserving insertion order It's simple for combined table. Since dk_entries is mostly append only, we can get insertion order by just iterating dk_entries. One exception is .popitem(). It removes last item in dk_entries and decrement dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in dk_indices, we can't increment dk_usable even though dk_nentries is decremented. In split table, inserting into pending entry is allowed only for dk_entries[ix] where ix == mp->ma_used. Inserting into other index and deleting item cause converting the dict to the combined table. */ /* PyDict_MINSIZE is the starting size for any new dict. * 8 allows dicts with no more than 5 active entries; experiments suggested * this suffices for the majority of dicts (consisting mostly of usually-small * dicts created to pass keyword arguments). * Making this 8, rather than 4 reduces the number of resizes for most * dictionaries, without any significant extra memory use. */ #define PyDict_MINSIZE 8 #include "third_party/python/Objects/stringlib/eq.inc" /*[clinic input] class dict "PyDictObject *" "&PyDict_Type" [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/ /* To ensure the lookup algorithm terminates, there must be at least one Unused slot (NULL key) in the table. To avoid slowing down lookups on a near-full table, we resize the table when it's USABLE_FRACTION (currently two-thirds) full. */ #define PERTURB_SHIFT 5 /* Major subtleties ahead: Most hash schemes depend on having a "good" hash function, in the sense of simulating randomness. Python doesn't: its most important hash functions (for ints) are very regular in common cases: >>>[hash(i) for i in range(4)] [0, 1, 2, 3] This isn't necessarily bad! To the contrary, in a table of size 2**i, taking the low-order i bits as the initial table index is extremely fast, and there are no collisions at all for dicts indexed by a contiguous range of ints. So this gives better-than-random behavior in common cases, and that's very desirable. OTOH, when collisions occur, the tendency to fill contiguous slices of the hash table makes a good collision resolution strategy crucial. Taking only the last i bits of the hash code is also vulnerable: for example, consider the list [i << 16 for i in range(20000)] as a set of keys. Since ints are their own hash codes, and this fits in a dict of size 2**15, the last 15 bits of every hash code are all 0: they *all* map to the same table index. But catering to unusual cases should not slow the usual ones, so we just take the last i bits anyway. It's up to collision resolution to do the rest. If we *usually* find the key we're looking for on the first try (and, it turns out, we usually do -- the table load factor is kept under 2/3, so the odds are solidly in our favor), then it makes best sense to keep the initial index computation dirt cheap. The first half of collision resolution is to visit table indices via this recurrence: j = ((5*j) + 1) mod 2**i For any initial j in range(2**i), repeating that 2**i times generates each int in range(2**i) exactly once (see any text on random-number generation for proof). By itself, this doesn't help much: like linear probing (setting j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed order. This would be bad, except that's not the only thing we do, and it's actually *good* in the common cases where hash keys are consecutive. In an example that's really too small to make this entirely clear, for a table of size 2**3 the order of indices is: 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating] If two things come in at index 5, the first place we look after is index 2, not 6, so if another comes in at index 6 the collision at 5 didn't hurt it. Linear probing is deadly in this case because there the fixed probe order is the *same* as the order consecutive keys are likely to arrive. But it's extremely unlikely hash codes will follow a 5*j+1 recurrence by accident, and certain that consecutive hash codes do not. The other half of the strategy is to get the other bits of the hash code into play. This is done by initializing a (unsigned) vrbl "perturb" to the full hash code, and changing the recurrence to: perturb >>= PERTURB_SHIFT; j = (5*j) + 1 + perturb; use j % 2**i as the next table index; Now the probe sequence depends (eventually) on every bit in the hash code, and the pseudo-scrambling property of recurring on 5*j+1 is more valuable, because it quickly magnifies small differences in the bits that didn't affect the initial index. Note that because perturb is unsigned, if the recurrence is executed often enough perturb eventually becomes and remains 0. At that point (very rarely reached) the recurrence is on (just) 5*j+1 again, and that's certain to find an empty slot eventually (since it generates every int in range(2**i), and we make sure there's always at least one empty slot). Selecting a good value for PERTURB_SHIFT is a balancing act. You want it small so that the high bits of the hash code continue to affect the probe sequence across iterations; but you want it large so that in really bad cases the high-order hash bits have an effect on early iterations. 5 was "the best" in minimizing total collisions across experiments Tim Peters ran (on both normal and pathological cases), but 4 and 6 weren't significantly worse. Historical: Reimer Behrends contributed the idea of using a polynomial-based approach, using repeated multiplication by x in GF(2**n) where an irreducible polynomial for each table size was chosen such that x was a primitive root. Christian Tismer later extended that to use division by x instead, as an efficient way to get the high bits of the hash code into play. This scheme also gave excellent collision statistics, but was more expensive: two if-tests were required inside the loop; computing "the next" index took about the same number of operations but without as much potential parallelism (e.g., computing 5*j can go on at the same time as computing 1+perturb in the above, and then shifting perturb can be done while the table index is being masked); and the PyDictObject struct required a member to hold the table's polynomial. In Tim's experiments the current scheme ran faster, produced equally good collision statistics, needed less code & used less memory. */ /* forward declarations */ static Py_ssize_t lookdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos); static Py_ssize_t lookdict_unicode(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos); static Py_ssize_t lookdict_unicode_nodummy(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos); static Py_ssize_t lookdict_split(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos); static int dictresize(PyDictObject *mp, Py_ssize_t minused); static PyObject* dict_iter(PyDictObject *dict); /*Global counter used to set ma_version_tag field of dictionary. * It is incremented each time that a dictionary is created and each * time that a dictionary is modified. */ static uint64_t pydict_global_version = 0; #define DICT_NEXT_VERSION() (++pydict_global_version) /* Dictionary reuse scheme to save calls to malloc and free */ #ifndef PyDict_MAXFREELIST #define PyDict_MAXFREELIST 80 #endif static PyDictObject *free_list[PyDict_MAXFREELIST]; static int numfree = 0; static PyDictKeysObject *keys_free_list[PyDict_MAXFREELIST]; static int numfreekeys = 0; #include "third_party/python/Objects/clinic/dictobject.inc" int PyDict_ClearFreeList(void) { PyDictObject *op; int ret = numfree + numfreekeys; while (numfree) { op = free_list[--numfree]; assert(PyDict_CheckExact(op)); PyObject_GC_Del(op); } while (numfreekeys) { PyObject_FREE(keys_free_list[--numfreekeys]); } return ret; } /* Print summary info about the state of the optimized allocator */ void _PyDict_DebugMallocStats(FILE *out) { _PyDebugAllocatorStats(out, "free PyDictObject", numfree, sizeof(PyDictObject)); } void PyDict_Fini(void) { PyDict_ClearFreeList(); } #define DK_SIZE(dk) ((dk)->dk_size) #if SIZEOF_VOID_P > 4 #define DK_IXSIZE(dk) \ (DK_SIZE(dk) <= 0xff ? \ 1 : DK_SIZE(dk) <= 0xffff ? \ 2 : DK_SIZE(dk) <= 0xffffffff ? \ 4 : sizeof(int64_t)) #else #define DK_IXSIZE(dk) \ (DK_SIZE(dk) <= 0xff ? \ 1 : DK_SIZE(dk) <= 0xffff ? \ 2 : sizeof(int32_t)) #endif #define DK_ENTRIES(dk) \ ((PyDictKeyEntry*)(&((int8_t*)((dk)->dk_indices))[DK_SIZE(dk) * DK_IXSIZE(dk)])) #define DK_DEBUG_INCREF _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA #define DK_DEBUG_DECREF _Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA #define DK_INCREF(dk) (DK_DEBUG_INCREF ++(dk)->dk_refcnt) #define DK_DECREF(dk) if (DK_DEBUG_DECREF (--(dk)->dk_refcnt) == 0) free_keys_object(dk) #define DK_MASK(dk) (((dk)->dk_size)-1) #define IS_POWER_OF_2(x) (((x) & (x-1)) == 0) /* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */ static inline Py_ssize_t dk_get_index(PyDictKeysObject *keys, Py_ssize_t i) { Py_ssize_t s = DK_SIZE(keys); Py_ssize_t ix; if (s <= 0xff) { int8_t *indices = (int8_t*)(keys->dk_indices); ix = indices[i]; } else if (s <= 0xffff) { int16_t *indices = (int16_t*)(keys->dk_indices); ix = indices[i]; } #if SIZEOF_VOID_P > 4 else if (s > 0xffffffff) { int64_t *indices = (int64_t*)(keys->dk_indices); ix = indices[i]; } #endif else { int32_t *indices = (int32_t*)(keys->dk_indices); ix = indices[i]; } assert(ix >= DKIX_DUMMY); return ix; } /* write to indices. */ static inline void dk_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix) { Py_ssize_t s = DK_SIZE(keys); assert(ix >= DKIX_DUMMY); if (s <= 0xff) { int8_t *indices = (int8_t*)(keys->dk_indices); assert(ix <= 0x7f); indices[i] = (char)ix; } else if (s <= 0xffff) { int16_t *indices = (int16_t*)(keys->dk_indices); assert(ix <= 0x7fff); indices[i] = (int16_t)ix; } #if SIZEOF_VOID_P > 4 else if (s > 0xffffffff) { int64_t *indices = (int64_t*)(keys->dk_indices); indices[i] = ix; } #endif else { int32_t *indices = (int32_t*)(keys->dk_indices); assert(ix <= 0x7fffffff); indices[i] = (int32_t)ix; } } /* USABLE_FRACTION is the maximum dictionary load. * Increasing this ratio makes dictionaries more dense resulting in more * collisions. Decreasing it improves sparseness at the expense of spreading * indices over more cache lines and at the cost of total memory consumed. * * USABLE_FRACTION must obey the following: * (0 < USABLE_FRACTION(n) < n) for all n >= 2 * * USABLE_FRACTION should be quick to calculate. * Fractions around 1/2 to 2/3 seem to work well in practice. */ #define USABLE_FRACTION(n) (((n) << 1)/3) /* ESTIMATE_SIZE is reverse function of USABLE_FRACTION. * This can be used to reserve enough size to insert n entries without * resizing. */ #define ESTIMATE_SIZE(n) (((n)*3+1) >> 1) /* Alternative fraction that is otherwise close enough to 2n/3 to make * little difference. 8 * 2/3 == 8 * 5/8 == 5. 16 * 2/3 == 16 * 5/8 == 10. * 32 * 2/3 = 21, 32 * 5/8 = 20. * Its advantage is that it is faster to compute on machines with slow division. * #define USABLE_FRACTION(n) (((n) >> 1) + ((n) >> 2) - ((n) >> 3)) */ /* GROWTH_RATE. Growth rate upon hitting maximum load. * Currently set to used*2 + capacity/2. * This means that dicts double in size when growing without deletions, * but have more head room when the number of deletions is on a par with the * number of insertions. * Raising this to used*4 doubles memory consumption depending on the size of * the dictionary, but results in half the number of resizes, less effort to * resize. * GROWTH_RATE was set to used*4 up to version 3.2. * GROWTH_RATE was set to used*2 in version 3.3.0 */ #define GROWTH_RATE(d) (((d)->ma_used*2)+((d)->ma_keys->dk_size>>1)) #define ENSURE_ALLOWS_DELETIONS(d) \ if ((d)->ma_keys->dk_lookup == lookdict_unicode_nodummy) { \ (d)->ma_keys->dk_lookup = lookdict_unicode; \ } /* This immutable, empty PyDictKeysObject is used for PyDict_Clear() * (which cannot fail and thus can do no allocation). */ static PyDictKeysObject empty_keys_struct = { 1, /* dk_refcnt */ 1, /* dk_size */ lookdict_split, /* dk_lookup */ 0, /* dk_usable (immutable) */ 0, /* dk_nentries */ {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */ }; static PyObject *empty_values[1] = { NULL }; #define Py_EMPTY_KEYS &empty_keys_struct /* Uncomment to check the dict content in _PyDict_CheckConsistency() */ /* #define DEBUG_PYDICT */ #ifndef NDEBUG static int _PyDict_CheckConsistency(PyDictObject *mp) { PyDictKeysObject *keys = mp->ma_keys; int splitted = _PyDict_HasSplitTable(mp); Py_ssize_t usable = USABLE_FRACTION(keys->dk_size); #ifdef DEBUG_PYDICT PyDictKeyEntry *entries = DK_ENTRIES(keys); Py_ssize_t i; #endif assert(0 <= mp->ma_used && mp->ma_used <= usable); assert(IS_POWER_OF_2(keys->dk_size)); assert(0 <= keys->dk_usable && keys->dk_usable <= usable); assert(0 <= keys->dk_nentries && keys->dk_nentries <= usable); assert(keys->dk_usable + keys->dk_nentries <= usable); if (!splitted) { /* combined table */ assert(keys->dk_refcnt == 1); } #ifdef DEBUG_PYDICT for (i=0; i < keys->dk_size; i++) { Py_ssize_t ix = dk_get_index(keys, i); assert(DKIX_DUMMY <= ix && ix <= usable); } for (i=0; i < usable; i++) { PyDictKeyEntry *entry = &entries[i]; PyObject *key = entry->me_key; if (key != NULL) { if (PyUnicode_CheckExact(key)) { Py_hash_t hash = ((PyASCIIObject *)key)->hash; assert(hash != -1); assert(entry->me_hash == hash); } else { /* test_dict fails if PyObject_Hash() is called again */ assert(entry->me_hash != -1); } if (!splitted) { assert(entry->me_value != NULL); } } if (splitted) { assert(entry->me_value == NULL); } } if (splitted) { /* splitted table */ for (i=0; i < mp->ma_used; i++) { assert(mp->ma_values[i] != NULL); } } #endif return 1; } #endif static PyDictKeysObject *new_keys_object(Py_ssize_t size) { PyDictKeysObject *dk; Py_ssize_t es, usable; assert(size >= PyDict_MINSIZE); assert(IS_POWER_OF_2(size)); usable = USABLE_FRACTION(size); if (size <= 0xff) { es = 1; } else if (size <= 0xffff) { es = 2; } #if SIZEOF_VOID_P > 4 else if (size <= 0xffffffff) { es = 4; } #endif else { es = sizeof(Py_ssize_t); } if (size == PyDict_MINSIZE && numfreekeys > 0) { dk = keys_free_list[--numfreekeys]; } else { dk = PyObject_MALLOC(sizeof(PyDictKeysObject) + es * size + sizeof(PyDictKeyEntry) * usable); if (dk == NULL) { PyErr_NoMemory(); return NULL; } } DK_DEBUG_INCREF dk->dk_refcnt = 1; dk->dk_size = size; dk->dk_usable = usable; dk->dk_lookup = lookdict_unicode_nodummy; dk->dk_nentries = 0; memset(&dk->dk_indices[0], 0xff, es * size); bzero(DK_ENTRIES(dk), sizeof(PyDictKeyEntry) * usable); return dk; } static void free_keys_object(PyDictKeysObject *keys) { PyDictKeyEntry *entries = DK_ENTRIES(keys); Py_ssize_t i, n; for (i = 0, n = keys->dk_nentries; i < n; i++) { Py_XDECREF(entries[i].me_key); Py_XDECREF(entries[i].me_value); } if (keys->dk_size == PyDict_MINSIZE && numfreekeys < PyDict_MAXFREELIST) { keys_free_list[numfreekeys++] = keys; return; } PyObject_FREE(keys); } #define new_values(size) PyMem_NEW(PyObject *, size) #define free_values(values) PyMem_FREE(values) /* Consumes a reference to the keys object */ static PyObject * new_dict(PyDictKeysObject *keys, PyObject **values) { PyDictObject *mp; assert(keys != NULL); if (numfree) { mp = free_list[--numfree]; assert (mp != NULL); assert (Py_TYPE(mp) == &PyDict_Type); _Py_NewReference((PyObject *)mp); } else { mp = PyObject_GC_New(PyDictObject, &PyDict_Type); if (mp == NULL) { DK_DECREF(keys); free_values(values); return NULL; } } mp->ma_keys = keys; mp->ma_values = values; mp->ma_used = 0; mp->ma_version_tag = DICT_NEXT_VERSION(); assert(_PyDict_CheckConsistency(mp)); return (PyObject *)mp; } /* Consumes a reference to the keys object */ static PyObject * new_dict_with_shared_keys(PyDictKeysObject *keys) { PyObject **values; Py_ssize_t i, size; size = USABLE_FRACTION(DK_SIZE(keys)); values = new_values(size); if (values == NULL) { DK_DECREF(keys); return PyErr_NoMemory(); } for (i = 0; i < size; i++) { values[i] = NULL; } return new_dict(keys, values); } static PyObject * clone_combined_dict(PyDictObject *orig) { assert(PyDict_CheckExact(orig)); assert(orig->ma_values == NULL); assert(orig->ma_keys->dk_refcnt == 1); Py_ssize_t keys_size = _PyDict_KeysSize(orig->ma_keys); PyDictKeysObject *keys = PyObject_Malloc(keys_size); if (keys == NULL) { PyErr_NoMemory(); return NULL; } memcpy(keys, orig->ma_keys, keys_size); /* After copying key/value pairs, we need to incref all keys and values and they are about to be co-owned by a new dict object. */ PyDictKeyEntry *ep0 = DK_ENTRIES(keys); Py_ssize_t n = keys->dk_nentries; for (Py_ssize_t i = 0; i < n; i++) { PyDictKeyEntry *entry = &ep0[i]; PyObject *value = entry->me_value; if (value != NULL) { Py_INCREF(value); Py_INCREF(entry->me_key); } } PyDictObject *new = (PyDictObject *)new_dict(keys, NULL); if (new == NULL) { /* In case of an error, `new_dict()` takes care of cleaning up `keys`. */ return NULL; } new->ma_used = orig->ma_used; assert(_PyDict_CheckConsistency(new)); if (_PyObject_GC_IS_TRACKED(orig)) { /* Maintain tracking. */ _PyObject_GC_TRACK(new); } return (PyObject *)new; } PyObject * PyDict_New(void) { PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE); if (keys == NULL) return NULL; return new_dict(keys, NULL); } /* Search index of hash table from offset of entry table */ static Py_ssize_t lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index) { size_t i; size_t mask = DK_MASK(k); Py_ssize_t ix; i = (size_t)hash & mask; ix = dk_get_index(k, i); if (ix == index) { return i; } if (ix == DKIX_EMPTY) { return DKIX_EMPTY; } for (size_t perturb = hash;;) { perturb >>= PERTURB_SHIFT; i = mask & ((i << 2) + i + perturb + 1); ix = dk_get_index(k, i); if (ix == index) { return i; } if (ix == DKIX_EMPTY) { return DKIX_EMPTY; } } unreachable; } /* The basic lookup function used by all operations. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4. Open addressing is preferred over chaining since the link overhead for chaining would be substantial (100% with typical malloc overhead). The initial probe index is computed as hash mod the table size. Subsequent probe indices are computed as explained earlier. All arithmetic on hash should ignore overflow. The details in this version are due to Tim Peters, building on many past contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and Christian Tismer. lookdict() is general-purpose, and may return DKIX_ERROR if (and only if) a comparison raises an exception. lookdict_unicode() below is specialized to string keys, comparison of which can never raise an exception; that function can never return DKIX_ERROR when key is string. Otherwise, it falls back to lookdict(). lookdict_unicode_nodummy is further specialized for string keys that cannot be the <dummy> value. For both, when the key isn't found a DKIX_EMPTY is returned. hashpos returns where the key index should be inserted. */ static Py_ssize_t _Py_HOT_FUNCTION lookdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos) { size_t i, mask; Py_ssize_t ix, freeslot; int cmp; PyDictKeysObject *dk; PyDictKeyEntry *ep0, *ep; PyObject *startkey; top: dk = mp->ma_keys; mask = DK_MASK(dk); ep0 = DK_ENTRIES(dk); i = (size_t)hash & mask; ix = dk_get_index(dk, i); if (ix == DKIX_EMPTY) { if (hashpos != NULL) *hashpos = i; *value_addr = NULL; return DKIX_EMPTY; } if (ix == DKIX_DUMMY) { freeslot = i; } else { ep = &ep0[ix]; assert(ep->me_key != NULL); if (ep->me_key == key) { *value_addr = &ep->me_value; if (hashpos != NULL) *hashpos = i; return ix; } if (ep->me_hash == hash) { startkey = ep->me_key; Py_INCREF(startkey); cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); Py_DECREF(startkey); if (cmp < 0) { *value_addr = NULL; return DKIX_ERROR; } if (dk == mp->ma_keys && ep->me_key == startkey) { if (cmp > 0) { *value_addr = &ep->me_value; if (hashpos != NULL) *hashpos = i; return ix; } } else { /* The dict was mutated, restart */ goto top; } } freeslot = -1; } for (size_t perturb = hash;;) { perturb >>= PERTURB_SHIFT; i = ((i << 2) + i + perturb + 1) & mask; ix = dk_get_index(dk, i); if (ix == DKIX_EMPTY) { if (hashpos != NULL) { *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot; } *value_addr = NULL; return ix; } if (ix == DKIX_DUMMY) { if (freeslot == -1) freeslot = i; continue; } ep = &ep0[ix]; assert(ep->me_key != NULL); if (ep->me_key == key) { if (hashpos != NULL) { *hashpos = i; } *value_addr = &ep->me_value; return ix; } if (ep->me_hash == hash) { startkey = ep->me_key; Py_INCREF(startkey); cmp = PyObject_RichCompareBool(startkey, key, Py_EQ); Py_DECREF(startkey); if (cmp < 0) { *value_addr = NULL; return DKIX_ERROR; } if (dk == mp->ma_keys && ep->me_key == startkey) { if (cmp > 0) { if (hashpos != NULL) { *hashpos = i; } *value_addr = &ep->me_value; return ix; } } else { /* The dict was mutated, restart */ goto top; } } } unreachable; } /* Specialized version for string-only keys */ static Py_ssize_t _Py_HOT_FUNCTION lookdict_unicode(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos) { size_t i; size_t mask = DK_MASK(mp->ma_keys); Py_ssize_t ix, freeslot; PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys); assert(mp->ma_values == NULL); /* Make sure this function doesn't have to handle non-unicode keys, including subclasses of str; e.g., one reason to subclass unicodes is to override __eq__, and for speed we don't cater to that here. */ if (!PyUnicode_CheckExact(key)) { mp->ma_keys->dk_lookup = lookdict; return lookdict(mp, key, hash, value_addr, hashpos); } i = (size_t)hash & mask; ix = dk_get_index(mp->ma_keys, i); if (ix == DKIX_EMPTY) { if (hashpos != NULL) *hashpos = i; *value_addr = NULL; return DKIX_EMPTY; } if (ix == DKIX_DUMMY) { freeslot = i; } else { ep = &ep0[ix]; assert(ep->me_key != NULL); if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) { if (hashpos != NULL) *hashpos = i; *value_addr = &ep->me_value; return ix; } freeslot = -1; } for (size_t perturb = hash;;) { perturb >>= PERTURB_SHIFT; i = mask & ((i << 2) + i + perturb + 1); ix = dk_get_index(mp->ma_keys, i); if (ix == DKIX_EMPTY) { if (hashpos != NULL) { *hashpos = (freeslot == -1) ? (Py_ssize_t)i : freeslot; } *value_addr = NULL; return DKIX_EMPTY; } if (ix == DKIX_DUMMY) { if (freeslot == -1) freeslot = i; continue; } ep = &ep0[ix]; assert(ep->me_key != NULL); if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) { *value_addr = &ep->me_value; if (hashpos != NULL) { *hashpos = i; } return ix; } } unreachable; } /* Faster version of lookdict_unicode when it is known that no <dummy> keys * will be present. */ static Py_ssize_t _Py_HOT_FUNCTION lookdict_unicode_nodummy(PyDictObject *restrict mp, PyObject *restrict key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos) { size_t i; size_t mask = DK_MASK(mp->ma_keys); Py_ssize_t ix; PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys); assert(mp->ma_values == NULL); /* Make sure this function doesn't have to handle non-unicode keys, including subclasses of str; e.g., one reason to subclass unicodes is to override __eq__, and for speed we don't cater to that here. */ if (UNLIKELY(!PyUnicode_CheckExact(key)) /* 0.00001% taken */) { mp->ma_keys->dk_lookup = lookdict; return lookdict(mp, key, hash, value_addr, hashpos); } i = (size_t)hash & mask; ix = dk_get_index(mp->ma_keys, i); assert(ix != DKIX_DUMMY); if (UNLIKELY(ix == DKIX_EMPTY)) { /* 4% taken */ if (hashpos != NULL) *hashpos = i; *value_addr = NULL; return DKIX_EMPTY; } ep = &ep0[ix]; assert(ep->me_key); assert(PyUnicode_CheckExact(ep->me_key)); if (ep->me_key == key || /* 70.671% taken */ (ep->me_hash == hash && unicode_eq(ep->me_key, key))) { if (hashpos != NULL) *hashpos = i; *value_addr = &ep->me_value; return ix; } for (size_t perturb = hash;;) { perturb >>= PERTURB_SHIFT; i = mask & ((i << 2) + i + perturb + 1); ix = dk_get_index(mp->ma_keys, i); assert(ix != DKIX_DUMMY); if (UNLIKELY(ix == DKIX_EMPTY)) { if (hashpos != NULL) *hashpos = i; *value_addr = NULL; return DKIX_EMPTY; } ep = &ep0[ix]; assert(ep->me_key); assert(PyUnicode_CheckExact(ep->me_key)); if (LIKELY(ep->me_key == key) || /* 99.8697% taken (interning?) */ (ep->me_hash == hash && unicode_eq(ep->me_key, key))) { if (hashpos != NULL) *hashpos = i; *value_addr = &ep->me_value; return ix; } } unreachable; } /* Version of lookdict for split tables. * All split tables and only split tables use this lookup function. * Split tables only contain unicode keys and no dummy keys, * so algorithm is the same as lookdict_unicode_nodummy. */ static Py_ssize_t _Py_HOT_FUNCTION lookdict_split(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos) { size_t i; size_t mask = DK_MASK(mp->ma_keys); Py_ssize_t ix; PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys); /* mp must split table */ assert(mp->ma_values != NULL); if (!PyUnicode_CheckExact(key)) { ix = lookdict(mp, key, hash, value_addr, hashpos); if (ix >= 0) { *value_addr = &mp->ma_values[ix]; } return ix; } i = (size_t)hash & mask; ix = dk_get_index(mp->ma_keys, i); if (ix == DKIX_EMPTY) { if (hashpos != NULL) *hashpos = i; *value_addr = NULL; return DKIX_EMPTY; } assert(ix >= 0); ep = &ep0[ix]; assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key)); if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) { if (hashpos != NULL) *hashpos = i; *value_addr = &mp->ma_values[ix]; return ix; } for (size_t perturb = hash;;) { perturb >>= PERTURB_SHIFT; i = mask & ((i << 2) + i + perturb + 1); ix = dk_get_index(mp->ma_keys, i); if (ix == DKIX_EMPTY) { if (hashpos != NULL) *hashpos = i; *value_addr = NULL; return DKIX_EMPTY; } assert(ix >= 0); ep = &ep0[ix]; assert(ep->me_key != NULL && PyUnicode_CheckExact(ep->me_key)); if (ep->me_key == key || (ep->me_hash == hash && unicode_eq(ep->me_key, key))) { if (hashpos != NULL) *hashpos = i; *value_addr = &mp->ma_values[ix]; return ix; } } unreachable; } int _PyDict_HasOnlyStringKeys(PyObject *dict) { Py_ssize_t pos = 0; PyObject *key, *value; assert(PyDict_Check(dict)); /* Shortcut */ if (((PyDictObject *)dict)->ma_keys->dk_lookup != lookdict) return 1; while (PyDict_Next(dict, &pos, &key, &value)) if (!PyUnicode_Check(key)) return 0; return 1; } #define MAINTAIN_TRACKING(mp, key, value) \ do { \ if (!_PyObject_GC_IS_TRACKED(mp)) { \ if (_PyObject_GC_MAY_BE_TRACKED(key) || \ _PyObject_GC_MAY_BE_TRACKED(value)) { \ _PyObject_GC_TRACK(mp); \ } \ } \ } while(0) void _PyDict_MaybeUntrack(PyObject *op) { PyDictObject *mp; PyObject *value; Py_ssize_t i, numentries; PyDictKeyEntry *ep0; if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op)) return; mp = (PyDictObject *) op; ep0 = DK_ENTRIES(mp->ma_keys); numentries = mp->ma_keys->dk_nentries; if (_PyDict_HasSplitTable(mp)) { for (i = 0; i < numentries; i++) { if ((value = mp->ma_values[i]) == NULL) continue; if (_PyObject_GC_MAY_BE_TRACKED(value)) { assert(!_PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key)); return; } } } else { for (i = 0; i < numentries; i++) { if ((value = ep0[i].me_value) == NULL) continue; if (_PyObject_GC_MAY_BE_TRACKED(value) || _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key)) return; } } _PyObject_GC_UNTRACK(op); } /* Internal function to find slot for an item from its hash when it is known that the key is not present in the dict. The dict must be combined. */ static void find_empty_slot(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject ***value_addr, Py_ssize_t *hashpos) { size_t i; size_t mask = DK_MASK(mp->ma_keys); Py_ssize_t ix; PyDictKeyEntry *ep, *ep0 = DK_ENTRIES(mp->ma_keys); assert(!_PyDict_HasSplitTable(mp)); assert(hashpos != NULL); assert(key != NULL); if (!PyUnicode_CheckExact(key)) mp->ma_keys->dk_lookup = lookdict; i = hash & mask; ix = dk_get_index(mp->ma_keys, i); for (size_t perturb = hash; ix != DKIX_EMPTY;) { perturb >>= PERTURB_SHIFT; i = (i << 2) + i + perturb + 1; ix = dk_get_index(mp->ma_keys, i & mask); } ep = &ep0[mp->ma_keys->dk_nentries]; *hashpos = i & mask; assert(ep->me_value == NULL); *value_addr = &ep->me_value; } static int insertion_resize(PyDictObject *mp) { return dictresize(mp, GROWTH_RATE(mp)); } /* Internal routine to insert a new item into the table. Used both by the internal resize routine and by the public insert routine. Returns -1 if an error occurred, or 0 on success. */ static int insertdict(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value) { PyObject *old_value; PyObject **value_addr; PyDictKeyEntry *ep, *ep0; Py_ssize_t hashpos, ix; Py_INCREF(key); Py_INCREF(value); if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) { if (insertion_resize(mp) < 0) goto Fail; } ix = mp->ma_keys->dk_lookup(mp, key, hash, &value_addr, &hashpos); if (ix == DKIX_ERROR) goto Fail; assert(PyUnicode_CheckExact(key) || mp->ma_keys->dk_lookup == lookdict); MAINTAIN_TRACKING(mp, key, value); /* When insertion order is different from shared key, we can't share * the key anymore. Convert this instance to combine table. */ if (_PyDict_HasSplitTable(mp) && ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) || (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) { if (insertion_resize(mp) < 0) goto Fail; find_empty_slot(mp, key, hash, &value_addr, &hashpos); ix = DKIX_EMPTY; } if (ix == DKIX_EMPTY) { /* Insert into new slot. */ if (mp->ma_keys->dk_usable <= 0) { /* Need to resize. */ if (insertion_resize(mp) < 0) goto Fail; find_empty_slot(mp, key, hash, &value_addr, &hashpos); } ep0 = DK_ENTRIES(mp->ma_keys); ep = &ep0[mp->ma_keys->dk_nentries]; dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries); ep->me_key = key; ep->me_hash = hash; if (mp->ma_values) { assert (mp->ma_values[mp->ma_keys->dk_nentries] == NULL); mp->ma_values[mp->ma_keys->dk_nentries] = value; } else { ep->me_value = value; } mp->ma_used++; mp->ma_version_tag = DICT_NEXT_VERSION(); mp->ma_keys->dk_usable--; mp->ma_keys->dk_nentries++; assert(mp->ma_keys->dk_usable >= 0); assert(_PyDict_CheckConsistency(mp)); return 0; } assert(value_addr != NULL); old_value = *value_addr; if (old_value != NULL) { *value_addr = value; mp->ma_version_tag = DICT_NEXT_VERSION(); assert(_PyDict_CheckConsistency(mp)); Py_DECREF(old_value); /* which **CAN** re-enter (see issue #22653) */ Py_DECREF(key); return 0; } /* pending state */ assert(_PyDict_HasSplitTable(mp)); assert(ix == mp->ma_used); *value_addr = value; mp->ma_used++; mp->ma_version_tag = DICT_NEXT_VERSION(); assert(_PyDict_CheckConsistency(mp)); Py_DECREF(key); return 0; Fail: Py_DECREF(value); Py_DECREF(key); return -1; } /* Internal routine used by dictresize() to insert an item which is known to be absent from the dict. This routine also assumes that the dict contains no deleted entries. Besides the performance benefit, using insertdict() in dictresize() is dangerous (SF bug #1456209). Note that no refcounts are changed by this routine; if needed, the caller is responsible for incref'ing `key` and `value`. Neither mp->ma_used nor k->dk_usable are modified by this routine; the caller must set them correctly */ static void insertdict_clean(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject *value) { size_t i; PyDictKeysObject *k = mp->ma_keys; size_t mask = (size_t)DK_SIZE(k)-1; PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys); PyDictKeyEntry *ep; assert(k->dk_lookup != NULL); assert(value != NULL); assert(key != NULL); assert(PyUnicode_CheckExact(key) || k->dk_lookup == lookdict); i = hash & mask; for (size_t perturb = hash; dk_get_index(k, i) != DKIX_EMPTY;) { perturb >>= PERTURB_SHIFT; i = mask & ((i << 2) + i + perturb + 1); } ep = &ep0[k->dk_nentries]; assert(ep->me_value == NULL); dk_set_index(k, i, k->dk_nentries); k->dk_nentries++; ep->me_key = key; ep->me_hash = hash; ep->me_value = value; } /* Restructure the table by allocating a new table and reinserting all items again. When entries have been deleted, the new table may actually be smaller than the old one. If a table is split (its keys and hashes are shared, its values are not), then the values are temporarily copied into the table, it is resized as a combined table, then the me_value slots in the old table are NULLed out. After resizing a table is always combined, but can be resplit by make_keys_shared(). */ static int dictresize(PyDictObject *mp, Py_ssize_t minsize) { Py_ssize_t i, newsize; PyDictKeysObject *oldkeys; PyObject **oldvalues; PyDictKeyEntry *ep0; /* Find the smallest table size > minused. */ for (newsize = PyDict_MINSIZE; newsize < minsize && newsize > 0; newsize <<= 1) ; if (newsize <= 0) { PyErr_NoMemory(); return -1; } oldkeys = mp->ma_keys; oldvalues = mp->ma_values; /* Allocate a new table. */ mp->ma_keys = new_keys_object(newsize); if (mp->ma_keys == NULL) { mp->ma_keys = oldkeys; return -1; } // New table must be large enough. assert(mp->ma_keys->dk_usable >= mp->ma_used); if (oldkeys->dk_lookup == lookdict) mp->ma_keys->dk_lookup = lookdict; mp->ma_values = NULL; ep0 = DK_ENTRIES(oldkeys); /* Main loop below assumes we can transfer refcount to new keys * and that value is stored in me_value. * Increment ref-counts and copy values here to compensate * This (resizing a split table) should be relatively rare */ if (oldvalues != NULL) { for (i = 0; i < oldkeys->dk_nentries; i++) { if (oldvalues[i] != NULL) { Py_INCREF(ep0[i].me_key); ep0[i].me_value = oldvalues[i]; } } } /* Main loop */ for (i = 0; i < oldkeys->dk_nentries; i++) { PyDictKeyEntry *ep = &ep0[i]; if (ep->me_value != NULL) { insertdict_clean(mp, ep->me_key, ep->me_hash, ep->me_value); } } mp->ma_keys->dk_usable -= mp->ma_used; if (oldvalues != NULL) { /* NULL out me_value slot in oldkeys, in case it was shared */ for (i = 0; i < oldkeys->dk_nentries; i++) ep0[i].me_value = NULL; DK_DECREF(oldkeys); if (oldvalues != empty_values) { free_values(oldvalues); } } else { assert(oldkeys->dk_lookup != lookdict_split); assert(oldkeys->dk_refcnt == 1); DK_DEBUG_DECREF PyObject_FREE(oldkeys); } return 0; } /* Returns NULL if unable to split table. * A NULL return does not necessarily indicate an error */ static PyDictKeysObject * make_keys_shared(PyObject *op) { Py_ssize_t i; Py_ssize_t size; PyDictObject *mp = (PyDictObject *)op; if (!PyDict_CheckExact(op)) return NULL; if (!_PyDict_HasSplitTable(mp)) { PyDictKeyEntry *ep0; PyObject **values; assert(mp->ma_keys->dk_refcnt == 1); if (mp->ma_keys->dk_lookup == lookdict) { return NULL; } else if (mp->ma_keys->dk_lookup == lookdict_unicode) { /* Remove dummy keys */ if (dictresize(mp, DK_SIZE(mp->ma_keys))) return NULL; } assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy); /* Copy values into a new array */ ep0 = DK_ENTRIES(mp->ma_keys); size = USABLE_FRACTION(DK_SIZE(mp->ma_keys)); values = new_values(size); if (values == NULL) { PyErr_SetString(PyExc_MemoryError, "Not enough memory to allocate new values array"); return NULL; } for (i = 0; i < size; i++) { values[i] = ep0[i].me_value; ep0[i].me_value = NULL; } mp->ma_keys->dk_lookup = lookdict_split; mp->ma_values = values; } DK_INCREF(mp->ma_keys); return mp->ma_keys; } PyObject * _PyDict_NewPresized(Py_ssize_t minused) { const Py_ssize_t max_presize = 128 * 1024; Py_ssize_t newsize; PyDictKeysObject *new_keys; /* There are no strict guarantee that returned dict can contain minused * items without resize. So we create medium size dict instead of very * large dict or MemoryError. */ if (minused > USABLE_FRACTION(max_presize)) { newsize = max_presize; } else { Py_ssize_t minsize = ESTIMATE_SIZE(minused); newsize = PyDict_MINSIZE; while (newsize < minsize) { newsize <<= 1; } } assert(IS_POWER_OF_2(newsize)); new_keys = new_keys_object(newsize); if (new_keys == NULL) return NULL; return new_dict(new_keys, NULL); } /* Note that, for historical reasons, PyDict_GetItem() suppresses all errors * that may occur (originally dicts supported only string keys, and exceptions * weren't possible). So, while the original intent was that a NULL return * meant the key wasn't present, in reality it can mean that, or that an error * (suppressed) occurred while computing the key's hash, or that some error * (suppressed) occurred when comparing keys in the dict's internal probe * sequence. A nasty example of the latter is when a Python-coded comparison * function hits a stack-depth error, which can cause this to return NULL * even if the key is present. */ PyObject * PyDict_GetItem(PyObject *op, PyObject *key) { Py_hash_t hash; Py_ssize_t ix; PyDictObject *mp = (PyDictObject *)op; PyThreadState *tstate; PyObject **value_addr; if (UNLIKELY(!PyDict_Check(op))) return NULL; if (UNLIKELY(!PyUnicode_CheckExact(key)) || UNLIKELY((hash = ((PyASCIIObject *) key)->hash) == -1)) { hash = PyObject_Hash(key); if (hash == -1) { PyErr_Clear(); return NULL; } } /* We can arrive here with a NULL tstate during initialization: try running "python -Wi" for an example related to string interning. Let's just hope that no exception occurs then... This must be _PyThreadState_Current and not PyThreadState_GET() because in debug mode, the latter complains if tstate is NULL. */ tstate = _PyThreadState_UncheckedGet(); if (UNLIKELY(tstate != NULL && tstate->curexc_type != NULL)) { /* preserve the existing exception */ PyObject *err_type, *err_value, *err_tb; PyErr_Fetch(&err_type, &err_value, &err_tb); ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); /* ignore errors */ PyErr_Restore(err_type, err_value, err_tb); if (ix < 0) return NULL; } else { ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); if (ix < 0) { /* [jart] don't clear the error if there is no error */ if (UNLIKELY(ix == DKIX_ERROR)) PyErr_Clear(); return NULL; } } return *value_addr; } /* Same as PyDict_GetItemWithError() but with hash supplied by caller. This returns NULL *with* an exception set if an exception occurred. It returns NULL *without* an exception set if the key wasn't present. */ PyObject * _PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash) { Py_ssize_t ix; PyDictObject *mp = (PyDictObject *)op; PyObject **value_addr; if (!PyDict_Check(op)) { PyErr_BadInternalCall(); return NULL; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); if (ix < 0) { return NULL; } return *value_addr; } /* Variant of PyDict_GetItem() that doesn't suppress exceptions. This returns NULL *with* an exception set if an exception occurred. It returns NULL *without* an exception set if the key wasn't present. */ PyObject * PyDict_GetItemWithError(PyObject *op, PyObject *key) { Py_ssize_t ix; Py_hash_t hash; PyDictObject*mp = (PyDictObject *)op; PyObject **value_addr; if (!PyDict_Check(op)) { PyErr_BadInternalCall(); return NULL; } if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) { return NULL; } } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); if (ix < 0) return NULL; return *value_addr; } PyObject * _PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key) { PyObject *kv; kv = _PyUnicode_FromId(key); /* borrowed */ if (kv == NULL) return NULL; return PyDict_GetItemWithError(dp, kv); } /* Fast version of global value lookup (LOAD_GLOBAL). * Lookup in globals, then builtins. * * Raise an exception and return NULL if an error occurred (ex: computing the * key hash failed, key comparison failed, ...). Return NULL if the key doesn't * exist. Return the value if the key exists. */ PyObject * _PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key) { Py_ssize_t ix; Py_hash_t hash; PyObject **value_addr; if (UNLIKELY(!PyUnicode_CheckExact(key)) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; } /* namespace 1: globals */ ix = globals->ma_keys->dk_lookup(globals, key, hash, &value_addr, NULL); if (UNLIKELY(ix == DKIX_ERROR)) /* 0% taken */ return NULL; if (LIKELY(ix != DKIX_EMPTY) && /* 90.3814% taken */ LIKELY(*value_addr != NULL)) /* 100% taken */ return *value_addr; /* namespace 2: builtins */ ix = builtins->ma_keys->dk_lookup(builtins, key, hash, &value_addr, NULL); if (UNLIKELY(ix < 0)) /* 5.9974e-05% taken */ return NULL; return *value_addr; } /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the * dictionary if it's merely replacing the value for an existing key. * This means that it's safe to loop over a dictionary with PyDict_Next() * and occasionally replace a value -- but you can't insert new keys or * remove them. */ int PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value) { PyDictObject *mp; Py_hash_t hash; if (!PyDict_Check(op)) { PyErr_BadInternalCall(); return -1; } assert(key); assert(value); mp = (PyDictObject *)op; if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; } /* insertdict() handles any resizing that might be necessary */ return insertdict(mp, key, hash, value); } int _PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value, Py_hash_t hash) { PyDictObject *mp; if (!PyDict_Check(op)) { PyErr_BadInternalCall(); return -1; } assert(key); assert(value); assert(hash != -1); mp = (PyDictObject *)op; /* insertdict() handles any resizing that might be necessary */ return insertdict(mp, key, hash, value); } static int delitem_common(PyDictObject *mp, Py_ssize_t hashpos, Py_ssize_t ix, PyObject **value_addr) { PyObject *old_key, *old_value; PyDictKeyEntry *ep; old_value = *value_addr; assert(old_value != NULL); *value_addr = NULL; mp->ma_used--; mp->ma_version_tag = DICT_NEXT_VERSION(); ep = &DK_ENTRIES(mp->ma_keys)[ix]; dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY); ENSURE_ALLOWS_DELETIONS(mp); old_key = ep->me_key; ep->me_key = NULL; Py_DECREF(old_key); Py_DECREF(old_value); assert(_PyDict_CheckConsistency(mp)); return 0; } int PyDict_DelItem(PyObject *op, PyObject *key) { Py_hash_t hash; assert(key); if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; } return _PyDict_DelItem_KnownHash(op, key, hash); } int _PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash) { Py_ssize_t hashpos, ix; PyDictObject *mp; PyObject **value_addr; if (!PyDict_Check(op)) { PyErr_BadInternalCall(); return -1; } assert(key); assert(hash != -1); mp = (PyDictObject *)op; ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos); if (ix == DKIX_ERROR) return -1; if (ix == DKIX_EMPTY || *value_addr == NULL) { _PyErr_SetKeyError(key); return -1; } assert(dk_get_index(mp->ma_keys, hashpos) == ix); // Split table doesn't allow deletion. Combine it. if (_PyDict_HasSplitTable(mp)) { if (dictresize(mp, DK_SIZE(mp->ma_keys))) { return -1; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos); assert(ix >= 0); } return delitem_common(mp, hashpos, ix, value_addr); } /* This function promises that the predicate -> deletion sequence is atomic * (i.e. protected by the GIL), assuming the predicate itself doesn't * release the GIL. */ int _PyDict_DelItemIf(PyObject *op, PyObject *key, int (*predicate)(PyObject *value)) { Py_ssize_t hashpos, ix; PyDictObject *mp; Py_hash_t hash; PyObject **value_addr; int res; if (!PyDict_Check(op)) { PyErr_BadInternalCall(); return -1; } assert(key); hash = PyObject_Hash(key); if (hash == -1) return -1; mp = (PyDictObject *)op; ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos); if (ix == DKIX_ERROR) return -1; if (ix == DKIX_EMPTY || *value_addr == NULL) { _PyErr_SetKeyError(key); return -1; } assert(dk_get_index(mp->ma_keys, hashpos) == ix); // Split table doesn't allow deletion. Combine it. if (_PyDict_HasSplitTable(mp)) { if (dictresize(mp, DK_SIZE(mp->ma_keys))) { return -1; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos); assert(ix >= 0); } res = predicate(*value_addr); if (res == -1) return -1; if (res > 0) return delitem_common(mp, hashpos, ix, value_addr); else return 0; } void PyDict_Clear(PyObject *op) { PyDictObject *mp; PyDictKeysObject *oldkeys; PyObject **oldvalues; Py_ssize_t i, n; if (!PyDict_Check(op)) return; mp = ((PyDictObject *)op); oldkeys = mp->ma_keys; oldvalues = mp->ma_values; if (oldvalues == empty_values) return; /* Empty the dict... */ DK_INCREF(Py_EMPTY_KEYS); mp->ma_keys = Py_EMPTY_KEYS; mp->ma_values = empty_values; mp->ma_used = 0; mp->ma_version_tag = DICT_NEXT_VERSION(); /* ...then clear the keys and values */ if (oldvalues != NULL) { n = oldkeys->dk_nentries; for (i = 0; i < n; i++) Py_CLEAR(oldvalues[i]); free_values(oldvalues); DK_DECREF(oldkeys); } else { assert(oldkeys->dk_refcnt == 1); DK_DECREF(oldkeys); } assert(_PyDict_CheckConsistency(mp)); } /* Internal version of PyDict_Next that returns a hash value in addition * to the key and value. * Return 1 on success, return 0 when the reached the end of the dictionary * (or if op is not a dictionary) */ int _PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, Py_hash_t *phash) { Py_ssize_t i, n; PyDictObject *mp; PyDictKeyEntry *entry_ptr; PyObject *value; if (!PyDict_Check(op)) return 0; mp = (PyDictObject *)op; i = *ppos; n = mp->ma_keys->dk_nentries; if ((size_t)i >= (size_t)n) return 0; if (mp->ma_values) { PyObject **value_ptr = &mp->ma_values[i]; while (i < n && *value_ptr == NULL) { value_ptr++; i++; } if (i >= n) return 0; entry_ptr = &DK_ENTRIES(mp->ma_keys)[i]; value = *value_ptr; } else { entry_ptr = &DK_ENTRIES(mp->ma_keys)[i]; while (i < n && entry_ptr->me_value == NULL) { entry_ptr++; i++; } if (i >= n) return 0; value = entry_ptr->me_value; } *ppos = i+1; if (pkey) *pkey = entry_ptr->me_key; if (phash) *phash = entry_ptr->me_hash; if (pvalue) *pvalue = value; return 1; } /* * Iterate over a dict. Use like so: * * Py_ssize_t i; * PyObject *key, *value; * i = 0; # important! i should not otherwise be changed by you * while (PyDict_Next(yourdict, &i, &key, &value)) { * Refer to borrowed references in key and value. * } * * Return 1 on success, return 0 when the reached the end of the dictionary * (or if op is not a dictionary) * * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that * mutates the dict. One exception: it is safe if the loop merely changes * the values associated with the keys (but doesn't insert new keys or * delete keys), via PyDict_SetItem(). */ int PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { return _PyDict_Next(op, ppos, pkey, pvalue, NULL); } /* Internal version of dict.pop(). */ PyObject * _PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt) { Py_ssize_t ix, hashpos; PyObject *old_value, *old_key; PyDictKeyEntry *ep; PyObject **value_addr; PyDictObject *mp; assert(PyDict_Check(dict)); mp = (PyDictObject *)dict; if (mp->ma_used == 0) { if (deflt) { Py_INCREF(deflt); return deflt; } _PyErr_SetKeyError(key); return NULL; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos); if (ix == DKIX_ERROR) return NULL; if (ix == DKIX_EMPTY || *value_addr == NULL) { if (deflt) { Py_INCREF(deflt); return deflt; } _PyErr_SetKeyError(key); return NULL; } // Split table doesn't allow deletion. Combine it. if (_PyDict_HasSplitTable(mp)) { if (dictresize(mp, DK_SIZE(mp->ma_keys))) { return NULL; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos); assert(ix >= 0); } old_value = *value_addr; assert(old_value != NULL); *value_addr = NULL; mp->ma_used--; mp->ma_version_tag = DICT_NEXT_VERSION(); dk_set_index(mp->ma_keys, hashpos, DKIX_DUMMY); ep = &DK_ENTRIES(mp->ma_keys)[ix]; ENSURE_ALLOWS_DELETIONS(mp); old_key = ep->me_key; ep->me_key = NULL; Py_DECREF(old_key); assert(_PyDict_CheckConsistency(mp)); return old_value; } PyObject * _PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt) { Py_hash_t hash; if (((PyDictObject *)dict)->ma_used == 0) { if (deflt) { Py_INCREF(deflt); return deflt; } _PyErr_SetKeyError(key); return NULL; } if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; } return _PyDict_Pop_KnownHash(dict, key, hash, deflt); } /* Internal version of dict.from_keys(). It is subclass-friendly. */ PyObject * _PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value) { PyObject *it; /* iter(iterable) */ PyObject *key; PyObject *d; int status; d = PyObject_CallObject(cls, NULL); if (d == NULL) return NULL; if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) { if (PyDict_CheckExact(iterable)) { PyDictObject *mp = (PyDictObject *)d; PyObject *oldvalue; Py_ssize_t pos = 0; PyObject *key; Py_hash_t hash; if (dictresize(mp, ESTIMATE_SIZE(((PyDictObject *)iterable)->ma_used))) { Py_DECREF(d); return NULL; } while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) { if (insertdict(mp, key, hash, value)) { Py_DECREF(d); return NULL; } } return d; } if (PyAnySet_CheckExact(iterable)) { PyDictObject *mp = (PyDictObject *)d; Py_ssize_t pos = 0; PyObject *key; Py_hash_t hash; if (dictresize(mp, ESTIMATE_SIZE(PySet_GET_SIZE(iterable)))) { Py_DECREF(d); return NULL; } while (_PySet_NextEntry(iterable, &pos, &key, &hash)) { if (insertdict(mp, key, hash, value)) { Py_DECREF(d); return NULL; } } return d; } } it = PyObject_GetIter(iterable); if (it == NULL){ Py_DECREF(d); return NULL; } if (PyDict_CheckExact(d)) { while ((key = PyIter_Next(it)) != NULL) { status = PyDict_SetItem(d, key, value); Py_DECREF(key); if (status < 0) goto Fail; } } else { while ((key = PyIter_Next(it)) != NULL) { status = PyObject_SetItem(d, key, value); Py_DECREF(key); if (status < 0) goto Fail; } } if (PyErr_Occurred()) goto Fail; Py_DECREF(it); return d; Fail: Py_DECREF(it); Py_DECREF(d); return NULL; } /* Methods */ static void dict_dealloc(PyDictObject *mp) { PyObject **values = mp->ma_values; PyDictKeysObject *keys = mp->ma_keys; Py_ssize_t i, n; /* bpo-31095: UnTrack is needed before calling any callbacks */ PyObject_GC_UnTrack(mp); Py_TRASHCAN_SAFE_BEGIN(mp) if (values != NULL) { if (values != empty_values) { for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) { Py_XDECREF(values[i]); } free_values(values); } DK_DECREF(keys); } else if (keys != NULL) { assert(keys->dk_refcnt == 1); DK_DECREF(keys); } if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type) free_list[numfree++] = mp; else Py_TYPE(mp)->tp_free((PyObject *)mp); Py_TRASHCAN_SAFE_END(mp) } static PyObject * dict_repr(PyDictObject *mp) { Py_ssize_t i; PyObject *key = NULL, *value = NULL; _PyUnicodeWriter writer; int first; i = Py_ReprEnter((PyObject *)mp); if (i != 0) { return i > 0 ? PyUnicode_FromString("{...}") : NULL; } if (mp->ma_used == 0) { Py_ReprLeave((PyObject *)mp); return PyUnicode_FromString("{}"); } _PyUnicodeWriter_Init(&writer); writer.overallocate = 1; /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */ writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1; if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0) goto error; /* Do repr() on each key+value pair, and insert ": " between them. Note that repr may mutate the dict. */ i = 0; first = 1; while (PyDict_Next((PyObject *)mp, &i, &key, &value)) { PyObject *s; int res; /* Prevent repr from deleting key or value during key format. */ Py_INCREF(key); Py_INCREF(value); if (!first) { if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) goto error; } first = 0; s = PyObject_Repr(key); if (s == NULL) goto error; res = _PyUnicodeWriter_WriteStr(&writer, s); Py_DECREF(s); if (res < 0) goto error; if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0) goto error; s = PyObject_Repr(value); if (s == NULL) goto error; res = _PyUnicodeWriter_WriteStr(&writer, s); Py_DECREF(s); if (res < 0) goto error; Py_CLEAR(key); Py_CLEAR(value); } writer.overallocate = 0; if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0) goto error; Py_ReprLeave((PyObject *)mp); return _PyUnicodeWriter_Finish(&writer); error: Py_ReprLeave((PyObject *)mp); _PyUnicodeWriter_Dealloc(&writer); Py_XDECREF(key); Py_XDECREF(value); return NULL; } static Py_ssize_t dict_length(PyDictObject *mp) { return mp->ma_used; } static PyObject * dict_subscript(PyDictObject *mp, PyObject *key) { PyObject *v; Py_ssize_t ix; Py_hash_t hash; PyObject **value_addr; if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); if (ix == DKIX_ERROR) return NULL; if (ix == DKIX_EMPTY || *value_addr == NULL) { if (!PyDict_CheckExact(mp)) { /* Look up __missing__ method if we're a subclass. */ PyObject *missing, *res; _Py_IDENTIFIER(__missing__); missing = _PyObject_LookupSpecial((PyObject *)mp, &PyId___missing__); if (missing != NULL) { res = PyObject_CallFunctionObjArgs(missing, key, NULL); Py_DECREF(missing); return res; } else if (PyErr_Occurred()) return NULL; } _PyErr_SetKeyError(key); return NULL; } v = *value_addr; Py_INCREF(v); return v; } static int dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w) { if (w == NULL) return PyDict_DelItem((PyObject *)mp, v); else return PyDict_SetItem((PyObject *)mp, v, w); } static PyMappingMethods dict_as_mapping = { (lenfunc)dict_length, /*mp_length*/ (binaryfunc)dict_subscript, /*mp_subscript*/ (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/ }; static PyObject * dict_keys(PyDictObject *mp) { PyObject *v; Py_ssize_t i, j; PyDictKeyEntry *ep; Py_ssize_t size, n, offset; PyObject **value_ptr; again: n = mp->ma_used; v = PyList_New(n); if (v == NULL) return NULL; if (n != mp->ma_used) { /* Durnit. The allocations caused the dict to resize. * Just start over, this shouldn't normally happen. */ Py_DECREF(v); goto again; } ep = DK_ENTRIES(mp->ma_keys); size = mp->ma_keys->dk_nentries; if (mp->ma_values) { value_ptr = mp->ma_values; offset = sizeof(PyObject *); } else { value_ptr = &ep[0].me_value; offset = sizeof(PyDictKeyEntry); } for (i = 0, j = 0; i < size; i++) { if (*value_ptr != NULL) { PyObject *key = ep[i].me_key; Py_INCREF(key); PyList_SET_ITEM(v, j, key); j++; } value_ptr = (PyObject **)(((char *)value_ptr) + offset); } assert(j == n); return v; } static PyObject * dict_values(PyDictObject *mp) { PyObject *v; Py_ssize_t i, j; PyDictKeyEntry *ep; Py_ssize_t size, n, offset; PyObject **value_ptr; again: n = mp->ma_used; v = PyList_New(n); if (v == NULL) return NULL; if (n != mp->ma_used) { /* Durnit. The allocations caused the dict to resize. * Just start over, this shouldn't normally happen. */ Py_DECREF(v); goto again; } ep = DK_ENTRIES(mp->ma_keys); size = mp->ma_keys->dk_nentries; if (mp->ma_values) { value_ptr = mp->ma_values; offset = sizeof(PyObject *); } else { value_ptr = &ep[0].me_value; offset = sizeof(PyDictKeyEntry); } for (i = 0, j = 0; i < size; i++) { PyObject *value = *value_ptr; value_ptr = (PyObject **)(((char *)value_ptr) + offset); if (value != NULL) { Py_INCREF(value); PyList_SET_ITEM(v, j, value); j++; } } assert(j == n); return v; } static PyObject * dict_items(PyDictObject *mp) { PyObject *v; Py_ssize_t i, j, n; Py_ssize_t size, offset; PyObject *item, *key; PyDictKeyEntry *ep; PyObject **value_ptr; /* Preallocate the list of tuples, to avoid allocations during * the loop over the items, which could trigger GC, which * could resize the dict. :-( */ again: n = mp->ma_used; v = PyList_New(n); if (v == NULL) return NULL; for (i = 0; i < n; i++) { item = PyTuple_New(2); if (item == NULL) { Py_DECREF(v); return NULL; } PyList_SET_ITEM(v, i, item); } if (n != mp->ma_used) { /* Durnit. The allocations caused the dict to resize. * Just start over, this shouldn't normally happen. */ Py_DECREF(v); goto again; } /* Nothing we do below makes any function calls. */ ep = DK_ENTRIES(mp->ma_keys); size = mp->ma_keys->dk_nentries; if (mp->ma_values) { value_ptr = mp->ma_values; offset = sizeof(PyObject *); } else { value_ptr = &ep[0].me_value; offset = sizeof(PyDictKeyEntry); } for (i = 0, j = 0; i < size; i++) { PyObject *value = *value_ptr; value_ptr = (PyObject **)(((char *)value_ptr) + offset); if (value != NULL) { key = ep[i].me_key; item = PyList_GET_ITEM(v, j); Py_INCREF(key); PyTuple_SET_ITEM(item, 0, key); Py_INCREF(value); PyTuple_SET_ITEM(item, 1, value); j++; } } assert(j == n); return v; } /*[clinic input] @classmethod dict.fromkeys iterable: object value: object=None / Returns a new dict with keys from iterable and values equal to value. [clinic start generated code]*/ static PyObject * dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value) /*[clinic end generated code: output=8fb98e4b10384999 input=b85a667f9bf4669d]*/ { return _PyDict_FromKeys((PyObject *)type, iterable, value); } static int dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, const char *methname) { PyObject *arg = NULL; int result = 0; if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) result = -1; else if (arg != NULL) { _Py_IDENTIFIER(keys); if (_PyObject_HasAttrId(arg, &PyId_keys)) result = PyDict_Merge(self, arg, 1); else result = PyDict_MergeFromSeq2(self, arg, 1); } if (result == 0 && kwds != NULL) { if (PyArg_ValidateKeywordArguments(kwds)) result = PyDict_Merge(self, kwds, 1); else result = -1; } return result; } static PyObject * dict_update(PyObject *self, PyObject *args, PyObject *kwds) { if (dict_update_common(self, args, kwds, "update") != -1) Py_RETURN_NONE; return NULL; } /* Update unconditionally replaces existing items. Merge has a 3rd argument 'override'; if set, it acts like Update, otherwise it leaves existing items unchanged. PyDict_{Update,Merge} update/merge from a mapping object. PyDict_MergeFromSeq2 updates/merges from any iterable object producing iterable objects of length 2. */ int PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override) { PyObject *it; /* iter(seq2) */ Py_ssize_t i; /* index into seq2 of current element */ PyObject *item; /* seq2[i] */ PyObject *fast; /* item as a 2-tuple or 2-list */ assert(d != NULL); assert(PyDict_Check(d)); assert(seq2 != NULL); it = PyObject_GetIter(seq2); if (it == NULL) return -1; for (i = 0; ; ++i) { PyObject *key, *value; Py_ssize_t n; fast = NULL; item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) goto Fail; break; } /* Convert item to sequence, and verify length 2. */ fast = PySequence_Fast(item, ""); if (fast == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) PyErr_Format(PyExc_TypeError, "cannot convert dictionary update " "sequence element #%zd to a sequence", i); goto Fail; } n = PySequence_Fast_GET_SIZE(fast); if (n != 2) { PyErr_Format(PyExc_ValueError, "dictionary update sequence element #%zd " "has length %zd; 2 is required", i, n); goto Fail; } /* Update/merge with this (key, value) pair. */ key = PySequence_Fast_GET_ITEM(fast, 0); value = PySequence_Fast_GET_ITEM(fast, 1); Py_INCREF(key); Py_INCREF(value); if (override || PyDict_GetItem(d, key) == NULL) { int status = PyDict_SetItem(d, key, value); if (status < 0) { Py_DECREF(key); Py_DECREF(value); goto Fail; } } Py_DECREF(key); Py_DECREF(value); Py_DECREF(fast); Py_DECREF(item); } i = 0; assert(_PyDict_CheckConsistency((PyDictObject *)d)); goto Return; Fail: Py_XDECREF(item); Py_XDECREF(fast); i = -1; Return: Py_DECREF(it); return Py_SAFE_DOWNCAST(i, Py_ssize_t, int); } static int dict_merge(PyObject *a, PyObject *b, int override) { PyDictObject *mp, *other; Py_ssize_t i, n; PyDictKeyEntry *entry, *ep0; assert(0 <= override && override <= 2); /* We accept for the argument either a concrete dictionary object, * or an abstract "mapping" object. For the former, we can do * things quite efficiently. For the latter, we only require that * PyMapping_Keys() and PyObject_GetItem() be supported. */ if (a == NULL || !PyDict_Check(a) || b == NULL) { PyErr_BadInternalCall(); return -1; } mp = (PyDictObject*)a; if (PyDict_Check(b) && (Py_TYPE(b)->tp_iter == (getiterfunc)dict_iter)) { other = (PyDictObject*)b; if (other == mp || other->ma_used == 0) /* a.update(a) or a.update({}); nothing to do */ return 0; if (mp->ma_used == 0) /* Since the target dict is empty, PyDict_GetItem() * always returns NULL. Setting override to 1 * skips the unnecessary test. */ override = 1; /* Do one big resize at the start, rather than * incrementally resizing as we insert new items. Expect * that there will be no (or few) overlapping keys. */ if (USABLE_FRACTION(mp->ma_keys->dk_size) < other->ma_used) { if (dictresize(mp, ESTIMATE_SIZE(mp->ma_used + other->ma_used))) { return -1; } } ep0 = DK_ENTRIES(other->ma_keys); for (i = 0, n = other->ma_keys->dk_nentries; i < n; i++) { PyObject *key, *value; Py_hash_t hash; entry = &ep0[i]; key = entry->me_key; hash = entry->me_hash; if (other->ma_values) value = other->ma_values[i]; else value = entry->me_value; if (value != NULL) { int err = 0; Py_INCREF(key); Py_INCREF(value); if (override == 1) err = insertdict(mp, key, hash, value); else if (_PyDict_GetItem_KnownHash(a, key, hash) == NULL) { if (PyErr_Occurred()) { Py_DECREF(value); Py_DECREF(key); return -1; } err = insertdict(mp, key, hash, value); } else if (override != 0) { _PyErr_SetKeyError(key); Py_DECREF(value); Py_DECREF(key); return -1; } Py_DECREF(value); Py_DECREF(key); if (err != 0) return -1; if (n != other->ma_keys->dk_nentries) { PyErr_SetString(PyExc_RuntimeError, "dict mutated during update"); return -1; } } } } else { /* Do it the generic, slower way */ PyObject *keys = PyMapping_Keys(b); PyObject *iter; PyObject *key, *value; int status; if (keys == NULL) /* Docstring says this is equivalent to E.keys() so * if E doesn't have a .keys() method we want * AttributeError to percolate up. Might as well * do the same for any other error. */ return -1; iter = PyObject_GetIter(keys); Py_DECREF(keys); if (iter == NULL) return -1; for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) { if (override != 1 && PyDict_GetItem(a, key) != NULL) { if (override != 0) { _PyErr_SetKeyError(key); Py_DECREF(key); Py_DECREF(iter); return -1; } Py_DECREF(key); continue; } value = PyObject_GetItem(b, key); if (value == NULL) { Py_DECREF(iter); Py_DECREF(key); return -1; } status = PyDict_SetItem(a, key, value); Py_DECREF(key); Py_DECREF(value); if (status < 0) { Py_DECREF(iter); return -1; } } Py_DECREF(iter); if (PyErr_Occurred()) /* Iterator completed, via error */ return -1; } assert(_PyDict_CheckConsistency((PyDictObject *)a)); return 0; } int PyDict_Update(PyObject *a, PyObject *b) { return dict_merge(a, b, 1); } int PyDict_Merge(PyObject *a, PyObject *b, int override) { /* XXX Deprecate override not in (0, 1). */ return dict_merge(a, b, override != 0); } int _PyDict_MergeEx(PyObject *a, PyObject *b, int override) { return dict_merge(a, b, override); } static PyObject * dict_copy(PyDictObject *mp) { return PyDict_Copy((PyObject*)mp); } PyObject * PyDict_Copy(PyObject *o) { PyObject *copy; PyDictObject *mp; Py_ssize_t i, n; if (o == NULL || !PyDict_Check(o)) { PyErr_BadInternalCall(); return NULL; } mp = (PyDictObject *)o; if (mp->ma_used == 0) { /* The dict is empty; just return a new dict. */ return PyDict_New(); } if (_PyDict_HasSplitTable(mp)) { PyDictObject *split_copy; Py_ssize_t size = USABLE_FRACTION(DK_SIZE(mp->ma_keys)); PyObject **newvalues; newvalues = new_values(size); if (newvalues == NULL) return PyErr_NoMemory(); split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type); if (split_copy == NULL) { free_values(newvalues); return NULL; } split_copy->ma_values = newvalues; split_copy->ma_keys = mp->ma_keys; split_copy->ma_used = mp->ma_used; split_copy->ma_version_tag = DICT_NEXT_VERSION(); DK_INCREF(mp->ma_keys); for (i = 0, n = size; i < n; i++) { PyObject *value = mp->ma_values[i]; Py_XINCREF(value); split_copy->ma_values[i] = value; } if (_PyObject_GC_IS_TRACKED(mp)) _PyObject_GC_TRACK(split_copy); return (PyObject *)split_copy; } if (PyDict_CheckExact(mp) && mp->ma_values == NULL && (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3)) { /* Use fast-copy if: (1) 'mp' is an instance of a subclassed dict; and (2) 'mp' is not a split-dict; and (3) if 'mp' is non-compact ('del' operation does not resize dicts), do fast-copy only if it has at most 1/3 non-used keys. The last condition (3) is important to guard against a pathalogical case when a large dict is almost emptied with multiple del/pop operations and copied after that. In cases like this, we defer to PyDict_Merge, which produces a compacted copy. */ return clone_combined_dict(mp); } copy = PyDict_New(); if (copy == NULL) return NULL; if (PyDict_Merge(copy, o, 1) == 0) return copy; Py_DECREF(copy); return NULL; } Py_ssize_t PyDict_Size(PyObject *mp) { if (mp == NULL || !PyDict_Check(mp)) { PyErr_BadInternalCall(); return -1; } return ((PyDictObject *)mp)->ma_used; } PyObject * PyDict_Keys(PyObject *mp) { if (mp == NULL || !PyDict_Check(mp)) { PyErr_BadInternalCall(); return NULL; } return dict_keys((PyDictObject *)mp); } PyObject * PyDict_Values(PyObject *mp) { if (mp == NULL || !PyDict_Check(mp)) { PyErr_BadInternalCall(); return NULL; } return dict_values((PyDictObject *)mp); } PyObject * PyDict_Items(PyObject *mp) { if (mp == NULL || !PyDict_Check(mp)) { PyErr_BadInternalCall(); return NULL; } return dict_items((PyDictObject *)mp); } /* Return 1 if dicts equal, 0 if not, -1 if error. * Gets out as soon as any difference is detected. * Uses only Py_EQ comparison. */ static int dict_equal(PyDictObject *a, PyDictObject *b) { Py_ssize_t i; if (a->ma_used != b->ma_used) /* can't be equal if # of entries differ */ return 0; /* Same # of entries -- check all of 'em. Exit early on any diff. */ for (i = 0; i < a->ma_keys->dk_nentries; i++) { PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i]; PyObject *aval; if (a->ma_values) aval = a->ma_values[i]; else aval = ep->me_value; if (aval != NULL) { int cmp; PyObject *bval; PyObject **vaddr; PyObject *key = ep->me_key; /* temporarily bump aval's refcount to ensure it stays alive until we're done with it */ Py_INCREF(aval); /* ditto for key */ Py_INCREF(key); /* reuse the known hash value */ if ((b->ma_keys->dk_lookup)(b, key, ep->me_hash, &vaddr, NULL) < 0) bval = NULL; else bval = *vaddr; if (bval == NULL) { Py_DECREF(key); Py_DECREF(aval); if (PyErr_Occurred()) return -1; return 0; } cmp = PyObject_RichCompareBool(aval, bval, Py_EQ); Py_DECREF(key); Py_DECREF(aval); if (cmp <= 0) /* error or not equal */ return cmp; } } return 1; } static PyObject * dict_richcompare(PyObject *v, PyObject *w, int op) { int cmp; PyObject *res; if (!PyDict_Check(v) || !PyDict_Check(w)) { res = Py_NotImplemented; } else if (op == Py_EQ || op == Py_NE) { cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w); if (cmp < 0) return NULL; res = (cmp == (op == Py_EQ)) ? Py_True : Py_False; } else res = Py_NotImplemented; Py_INCREF(res); return res; } /*[clinic input] @coexist dict.__contains__ key: object / True if D has a key k, else False. [clinic start generated code]*/ static PyObject * dict___contains__(PyDictObject *self, PyObject *key) /*[clinic end generated code: output=a3d03db709ed6e6b input=b852b2a19b51ab24]*/ { register PyDictObject *mp = self; Py_hash_t hash; Py_ssize_t ix; PyObject **value_addr; if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); if (ix == DKIX_ERROR) return NULL; if (ix == DKIX_EMPTY || *value_addr == NULL) Py_RETURN_FALSE; Py_RETURN_TRUE; } static PyObject * dict_get(PyDictObject *mp, PyObject **args, Py_ssize_t nargs) { PyObject *key; PyObject *failobj = Py_None; PyObject *val = NULL; Py_hash_t hash; Py_ssize_t ix; PyObject **value_addr; if (!_PyArg_UnpackStack(args, nargs, "get", 1, 2, &key, &failobj)) return NULL; if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); if (ix == DKIX_ERROR) return NULL; if (ix == DKIX_EMPTY || *value_addr == NULL) val = failobj; else val = *value_addr; Py_INCREF(val); return val; } PyObject * PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj) { PyDictObject *mp = (PyDictObject *)d; PyObject *value; Py_hash_t hash; Py_ssize_t hashpos, ix; PyObject **value_addr; if (!PyDict_Check(d)) { PyErr_BadInternalCall(); return NULL; } if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; } if (mp->ma_values != NULL && !PyUnicode_CheckExact(key)) { if (insertion_resize(mp) < 0) return NULL; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, &hashpos); if (ix == DKIX_ERROR) return NULL; if (_PyDict_HasSplitTable(mp) && ((ix >= 0 && *value_addr == NULL && mp->ma_used != ix) || (ix == DKIX_EMPTY && mp->ma_used != mp->ma_keys->dk_nentries))) { if (insertion_resize(mp) < 0) { return NULL; } find_empty_slot(mp, key, hash, &value_addr, &hashpos); ix = DKIX_EMPTY; } if (ix == DKIX_EMPTY) { PyDictKeyEntry *ep, *ep0; value = defaultobj; if (mp->ma_keys->dk_usable <= 0) { if (insertion_resize(mp) < 0) { return NULL; } find_empty_slot(mp, key, hash, &value_addr, &hashpos); } ep0 = DK_ENTRIES(mp->ma_keys); ep = &ep0[mp->ma_keys->dk_nentries]; dk_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries); Py_INCREF(key); Py_INCREF(value); MAINTAIN_TRACKING(mp, key, value); ep->me_key = key; ep->me_hash = hash; if (mp->ma_values) { assert(mp->ma_values[mp->ma_keys->dk_nentries] == NULL); mp->ma_values[mp->ma_keys->dk_nentries] = value; } else { ep->me_value = value; } mp->ma_used++; mp->ma_version_tag = DICT_NEXT_VERSION(); mp->ma_keys->dk_usable--; mp->ma_keys->dk_nentries++; assert(mp->ma_keys->dk_usable >= 0); } else if (*value_addr == NULL) { value = defaultobj; assert(_PyDict_HasSplitTable(mp)); assert(ix == mp->ma_used); Py_INCREF(value); MAINTAIN_TRACKING(mp, key, value); *value_addr = value; mp->ma_used++; mp->ma_version_tag = DICT_NEXT_VERSION(); } else { value = *value_addr; } assert(_PyDict_CheckConsistency(mp)); return value; } static PyObject * dict_setdefault(PyDictObject *mp, PyObject **args, Py_ssize_t nargs) { PyObject *key, *val; PyObject *defaultobj = Py_None; if (!_PyArg_UnpackStack(args, nargs, "setdefault", 1, 2, &key, &defaultobj)) return NULL; val = PyDict_SetDefault((PyObject *)mp, key, defaultobj); Py_XINCREF(val); return val; } static PyObject * dict_clear(PyDictObject *mp) { PyDict_Clear((PyObject *)mp); Py_RETURN_NONE; } static PyObject * dict_pop(PyDictObject *mp, PyObject **args, Py_ssize_t nargs) { PyObject *key, *deflt = NULL; if(!_PyArg_UnpackStack(args, nargs, "pop", 1, 2, &key, &deflt)) return NULL; return _PyDict_Pop((PyObject*)mp, key, deflt); } static PyObject * dict_popitem(PyDictObject *mp) { Py_ssize_t i, j; PyDictKeyEntry *ep0, *ep; PyObject *res; /* Allocate the result tuple before checking the size. Believe it * or not, this allocation could trigger a garbage collection which * could empty the dict, so if we checked the size first and that * happened, the result would be an infinite loop (searching for an * entry that no longer exists). Note that the usual popitem() * idiom is "while d: k, v = d.popitem()". so needing to throw the * tuple away if the dict *is* empty isn't a significant * inefficiency -- possible, but unlikely in practice. */ res = PyTuple_New(2); if (res == NULL) return NULL; if (mp->ma_used == 0) { Py_DECREF(res); PyErr_SetString(PyExc_KeyError, "popitem(): dictionary is empty"); return NULL; } /* Convert split table to combined table */ if (mp->ma_keys->dk_lookup == lookdict_split) { if (dictresize(mp, DK_SIZE(mp->ma_keys))) { Py_DECREF(res); return NULL; } } ENSURE_ALLOWS_DELETIONS(mp); /* Pop last item */ ep0 = DK_ENTRIES(mp->ma_keys); i = mp->ma_keys->dk_nentries - 1; while (i >= 0 && ep0[i].me_value == NULL) { i--; } assert(i >= 0); ep = &ep0[i]; j = lookdict_index(mp->ma_keys, ep->me_hash, i); assert(j >= 0); assert(dk_get_index(mp->ma_keys, j) == i); dk_set_index(mp->ma_keys, j, DKIX_DUMMY); PyTuple_SET_ITEM(res, 0, ep->me_key); PyTuple_SET_ITEM(res, 1, ep->me_value); ep->me_key = NULL; ep->me_value = NULL; /* We can't dk_usable++ since there is DKIX_DUMMY in indices */ mp->ma_keys->dk_nentries = i; mp->ma_used--; mp->ma_version_tag = DICT_NEXT_VERSION(); assert(_PyDict_CheckConsistency(mp)); return res; } static int dict_traverse(PyObject *op, visitproc visit, void *arg) { PyDictObject *mp = (PyDictObject *)op; PyDictKeysObject *keys = mp->ma_keys; PyDictKeyEntry *entries = DK_ENTRIES(keys); Py_ssize_t i, n = keys->dk_nentries; if (keys->dk_lookup == lookdict) { for (i = 0; i < n; i++) { if (entries[i].me_value != NULL) { Py_VISIT(entries[i].me_value); Py_VISIT(entries[i].me_key); } } } else { if (mp->ma_values != NULL) { for (i = 0; i < n; i++) { Py_VISIT(mp->ma_values[i]); } } else { for (i = 0; i < n; i++) { Py_VISIT(entries[i].me_value); } } } return 0; } static int dict_tp_clear(PyObject *op) { PyDict_Clear(op); return 0; } static PyObject *dictiter_new(PyDictObject *, PyTypeObject *); Py_ssize_t _PyDict_SizeOf(PyDictObject *mp) { Py_ssize_t size, usable, res; size = DK_SIZE(mp->ma_keys); usable = USABLE_FRACTION(size); res = _PyObject_SIZE(Py_TYPE(mp)); if (mp->ma_values) res += usable * sizeof(PyObject*); /* If the dictionary is split, the keys portion is accounted-for in the type object. */ if (mp->ma_keys->dk_refcnt == 1) res += (sizeof(PyDictKeysObject) + DK_IXSIZE(mp->ma_keys) * size + sizeof(PyDictKeyEntry) * usable); return res; } Py_ssize_t _PyDict_KeysSize(PyDictKeysObject *keys) { return (sizeof(PyDictKeysObject) + DK_IXSIZE(keys) * DK_SIZE(keys) + USABLE_FRACTION(DK_SIZE(keys)) * sizeof(PyDictKeyEntry)); } static PyObject * dict_sizeof(PyDictObject *mp) { return PyLong_FromSsize_t(_PyDict_SizeOf(mp)); } PyDoc_STRVAR(getitem__doc__, "x.__getitem__(y) <==> x[y]"); PyDoc_STRVAR(sizeof__doc__, "D.__sizeof__() -> size of D in memory, in bytes"); PyDoc_STRVAR(get__doc__, "D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None."); PyDoc_STRVAR(setdefault_doc__, "D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D"); PyDoc_STRVAR(pop__doc__, "D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n\ If key is not found, d is returned if given, otherwise KeyError is raised"); PyDoc_STRVAR(popitem__doc__, "D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\ 2-tuple; but raise KeyError if D is empty."); PyDoc_STRVAR(update__doc__, "D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\ If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\ If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\ In either case, this is followed by: for k in F: D[k] = F[k]"); PyDoc_STRVAR(clear__doc__, "D.clear() -> None. Remove all items from D."); PyDoc_STRVAR(copy__doc__, "D.copy() -> a shallow copy of D"); /* Forward */ static PyObject *dictkeys_new(PyObject *); static PyObject *dictitems_new(PyObject *); static PyObject *dictvalues_new(PyObject *); PyDoc_STRVAR(keys__doc__, "D.keys() -> a set-like object providing a view on D's keys"); PyDoc_STRVAR(items__doc__, "D.items() -> a set-like object providing a view on D's items"); PyDoc_STRVAR(values__doc__, "D.values() -> an object providing a view on D's values"); static PyMethodDef mapp_methods[] = { DICT___CONTAINS___METHODDEF {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST, getitem__doc__}, {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS, sizeof__doc__}, {"get", (PyCFunction)dict_get, METH_FASTCALL, get__doc__}, {"setdefault", (PyCFunction)dict_setdefault, METH_FASTCALL, setdefault_doc__}, {"pop", (PyCFunction)dict_pop, METH_FASTCALL, pop__doc__}, {"popitem", (PyCFunction)dict_popitem, METH_NOARGS, popitem__doc__}, {"keys", (PyCFunction)dictkeys_new, METH_NOARGS, keys__doc__}, {"items", (PyCFunction)dictitems_new, METH_NOARGS, items__doc__}, {"values", (PyCFunction)dictvalues_new, METH_NOARGS, values__doc__}, {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS, update__doc__}, DICT_FROMKEYS_METHODDEF {"clear", (PyCFunction)dict_clear, METH_NOARGS, clear__doc__}, {"copy", (PyCFunction)dict_copy, METH_NOARGS, copy__doc__}, {NULL, NULL} /* sentinel */ }; /* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */ int PyDict_Contains(PyObject *op, PyObject *key) { Py_hash_t hash; Py_ssize_t ix; PyDictObject *mp = (PyDictObject *)op; PyObject **value_addr; if (!PyUnicode_CheckExact(key) || (hash = ((PyASCIIObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; } ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); if (ix == DKIX_ERROR) return -1; return (ix != DKIX_EMPTY && *value_addr != NULL); } /* Internal version of PyDict_Contains used when the hash value is already known */ int _PyDict_Contains(PyObject *op, PyObject *key, Py_hash_t hash) { PyDictObject *mp = (PyDictObject *)op; PyObject **value_addr; Py_ssize_t ix; ix = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr, NULL); if (ix == DKIX_ERROR) return -1; return (ix != DKIX_EMPTY && *value_addr != NULL); } /* Hack to implement "key in dict" */ static PySequenceMethods dict_as_sequence = { 0, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ 0, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ PyDict_Contains, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; static PyObject * dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *self; PyDictObject *d; assert(type != NULL && type->tp_alloc != NULL); self = type->tp_alloc(type, 0); if (self == NULL) return NULL; d = (PyDictObject *)self; /* The object has been implicitly tracked by tp_alloc */ if (type == &PyDict_Type) _PyObject_GC_UNTRACK(d); d->ma_used = 0; d->ma_version_tag = DICT_NEXT_VERSION(); d->ma_keys = new_keys_object(PyDict_MINSIZE); if (d->ma_keys == NULL) { Py_DECREF(self); return NULL; } assert(_PyDict_CheckConsistency(d)); return self; } static int dict_init(PyObject *self, PyObject *args, PyObject *kwds) { return dict_update_common(self, args, kwds, "dict"); } static PyObject * dict_iter(PyDictObject *dict) { return dictiter_new(dict, &PyDictIterKey_Type); } PyDoc_STRVAR(dictionary_doc, "dict() -> new empty dictionary\n" "dict(mapping) -> new dictionary initialized from a mapping object's\n" " (key, value) pairs\n" "dict(iterable) -> new dictionary initialized as if via:\n" " d = {}\n" " for k, v in iterable:\n" " d[k] = v\n" "dict(**kwargs) -> new dictionary initialized with the name=value pairs\n" " in the keyword argument list. For example: dict(one=1, two=2)"); PyTypeObject PyDict_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "dict", sizeof(PyDictObject), 0, (destructor)dict_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)dict_repr, /* tp_repr */ 0, /* tp_as_number */ &dict_as_sequence, /* tp_as_sequence */ &dict_as_mapping, /* tp_as_mapping */ PyObject_HashNotImplemented, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */ dictionary_doc, /* tp_doc */ dict_traverse, /* tp_traverse */ dict_tp_clear, /* tp_clear */ dict_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)dict_iter, /* tp_iter */ 0, /* tp_iternext */ mapp_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ dict_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ dict_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; PyObject * _PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key) { PyObject *kv; kv = _PyUnicode_FromId(key); /* borrowed */ if (kv == NULL) { PyErr_Clear(); return NULL; } return PyDict_GetItem(dp, kv); } /* For backward compatibility with old dictionary interface */ PyObject * PyDict_GetItemString(PyObject *v, const char *key) { PyObject *kv, *rv; kv = PyUnicode_FromString(key); if (kv == NULL) { PyErr_Clear(); return NULL; } rv = PyDict_GetItem(v, kv); Py_DECREF(kv); return rv; } int _PyDict_SetItemId(PyObject *v, struct _Py_Identifier *key, PyObject *item) { PyObject *kv; kv = _PyUnicode_FromId(key); /* borrowed */ if (kv == NULL) return -1; return PyDict_SetItem(v, kv, item); } int PyDict_SetItemString(PyObject *v, const char *key, PyObject *item) { PyObject *kv; int err; kv = PyUnicode_FromString(key); if (kv == NULL) return -1; PyUnicode_InternInPlace(&kv); /* XXX Should we really? */ err = PyDict_SetItem(v, kv, item); Py_DECREF(kv); return err; } int _PyDict_DelItemId(PyObject *v, _Py_Identifier *key) { PyObject *kv = _PyUnicode_FromId(key); /* borrowed */ if (kv == NULL) return -1; return PyDict_DelItem(v, kv); } int PyDict_DelItemString(PyObject *v, const char *key) { PyObject *kv; int err; kv = PyUnicode_FromString(key); if (kv == NULL) return -1; err = PyDict_DelItem(v, kv); Py_DECREF(kv); return err; } /* Dictionary iterator types */ typedef struct { PyObject_HEAD PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */ Py_ssize_t di_used; Py_ssize_t di_pos; PyObject* di_result; /* reusable result tuple for iteritems */ Py_ssize_t len; } dictiterobject; static PyObject * dictiter_new(PyDictObject *dict, PyTypeObject *itertype) { dictiterobject *di; di = PyObject_GC_New(dictiterobject, itertype); if (di == NULL) return NULL; Py_INCREF(dict); di->di_dict = dict; di->di_used = dict->ma_used; di->di_pos = 0; di->len = dict->ma_used; if (itertype == &PyDictIterItem_Type) { di->di_result = PyTuple_Pack(2, Py_None, Py_None); if (di->di_result == NULL) { Py_DECREF(di); return NULL; } } else di->di_result = NULL; _PyObject_GC_TRACK(di); return (PyObject *)di; } static void dictiter_dealloc(dictiterobject *di) { /* bpo-31095: UnTrack is needed before calling any callbacks */ _PyObject_GC_UNTRACK(di); Py_XDECREF(di->di_dict); Py_XDECREF(di->di_result); PyObject_GC_Del(di); } static int dictiter_traverse(dictiterobject *di, visitproc visit, void *arg) { Py_VISIT(di->di_dict); Py_VISIT(di->di_result); return 0; } static PyObject * dictiter_len(dictiterobject *di) { Py_ssize_t len = 0; if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used) len = di->len; return PyLong_FromSize_t(len); } PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyObject * dictiter_reduce(dictiterobject *di); PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef dictiter_methods[] = { {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc}, {"__reduce__", (PyCFunction)dictiter_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; static PyObject* dictiter_iternextkey(dictiterobject *di) { PyObject *key; Py_ssize_t i, n; PyDictKeysObject *k; PyDictObject *d = di->di_dict; if (d == NULL) return NULL; assert (PyDict_Check(d)); if (di->di_used != d->ma_used) { PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); di->di_used = -1; /* Make this state sticky */ return NULL; } i = di->di_pos; k = d->ma_keys; n = k->dk_nentries; if (d->ma_values) { PyObject **value_ptr = &d->ma_values[i]; while (i < n && *value_ptr == NULL) { value_ptr++; i++; } if (i >= n) goto fail; key = DK_ENTRIES(k)[i].me_key; } else { PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i]; while (i < n && entry_ptr->me_value == NULL) { entry_ptr++; i++; } if (i >= n) goto fail; key = entry_ptr->me_key; } di->di_pos = i+1; di->len--; Py_INCREF(key); return key; fail: di->di_dict = NULL; Py_DECREF(d); return NULL; } PyTypeObject PyDictIterKey_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "dict_keyiterator", /* tp_name */ sizeof(dictiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)dictiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)dictiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)dictiter_iternextkey, /* tp_iternext */ dictiter_methods, /* tp_methods */ 0, }; static PyObject * dictiter_iternextvalue(dictiterobject *di) { PyObject *value; Py_ssize_t i, n; PyDictObject *d = di->di_dict; if (d == NULL) return NULL; assert (PyDict_Check(d)); if (di->di_used != d->ma_used) { PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); di->di_used = -1; /* Make this state sticky */ return NULL; } i = di->di_pos; n = d->ma_keys->dk_nentries; if (d->ma_values) { PyObject **value_ptr = &d->ma_values[i]; while (i < n && *value_ptr == NULL) { value_ptr++; i++; } if (i >= n) goto fail; value = *value_ptr; } else { PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i]; while (i < n && entry_ptr->me_value == NULL) { entry_ptr++; i++; } if (i >= n) goto fail; value = entry_ptr->me_value; } di->di_pos = i+1; di->len--; Py_INCREF(value); return value; fail: di->di_dict = NULL; Py_DECREF(d); return NULL; } PyTypeObject PyDictIterValue_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "dict_valueiterator", /* tp_name */ sizeof(dictiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)dictiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)dictiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)dictiter_iternextvalue, /* tp_iternext */ dictiter_methods, /* tp_methods */ 0, }; static PyObject * dictiter_iternextitem(dictiterobject *di) { PyObject *key, *value, *result; Py_ssize_t i, n; PyDictObject *d = di->di_dict; if (d == NULL) return NULL; assert (PyDict_Check(d)); if (di->di_used != d->ma_used) { PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); di->di_used = -1; /* Make this state sticky */ return NULL; } i = di->di_pos; n = d->ma_keys->dk_nentries; if (d->ma_values) { PyObject **value_ptr = &d->ma_values[i]; while (i < n && *value_ptr == NULL) { value_ptr++; i++; } if (i >= n) goto fail; key = DK_ENTRIES(d->ma_keys)[i].me_key; value = *value_ptr; } else { PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i]; while (i < n && entry_ptr->me_value == NULL) { entry_ptr++; i++; } if (i >= n) goto fail; key = entry_ptr->me_key; value = entry_ptr->me_value; } di->di_pos = i+1; di->len--; Py_INCREF(key); Py_INCREF(value); result = di->di_result; if (Py_REFCNT(result) == 1) { PyObject *oldkey = PyTuple_GET_ITEM(result, 0); PyObject *oldvalue = PyTuple_GET_ITEM(result, 1); PyTuple_SET_ITEM(result, 0, key); /* steals reference */ PyTuple_SET_ITEM(result, 1, value); /* steals reference */ Py_INCREF(result); Py_DECREF(oldkey); Py_DECREF(oldvalue); } else { result = PyTuple_New(2); if (result == NULL) return NULL; PyTuple_SET_ITEM(result, 0, key); /* steals reference */ PyTuple_SET_ITEM(result, 1, value); /* steals reference */ } return result; fail: di->di_dict = NULL; Py_DECREF(d); return NULL; } PyTypeObject PyDictIterItem_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "dict_itemiterator", /* tp_name */ sizeof(dictiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)dictiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)dictiter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)dictiter_iternextitem, /* tp_iternext */ dictiter_methods, /* tp_methods */ 0, }; static PyObject * dictiter_reduce(dictiterobject *di) { PyObject *list; dictiterobject tmp; list = PyList_New(0); if (!list) return NULL; /* copy the itertor state */ tmp = *di; Py_XINCREF(tmp.di_dict); /* iterate the temporary into a list */ for(;;) { PyObject *element = 0; if (Py_TYPE(di) == &PyDictIterItem_Type) element = dictiter_iternextitem(&tmp); else if (Py_TYPE(di) == &PyDictIterKey_Type) element = dictiter_iternextkey(&tmp); else if (Py_TYPE(di) == &PyDictIterValue_Type) element = dictiter_iternextvalue(&tmp); else assert(0); if (element) { if (PyList_Append(list, element)) { Py_DECREF(element); Py_DECREF(list); Py_XDECREF(tmp.di_dict); return NULL; } Py_DECREF(element); } else break; } Py_XDECREF(tmp.di_dict); /* check for error */ if (tmp.di_dict != NULL) { /* we have an error */ Py_DECREF(list); return NULL; } return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list); } /***********************************************/ /* View objects for keys(), items(), values(). */ /***********************************************/ /* The instance lay-out is the same for all three; but the type differs. */ static void dictview_dealloc(_PyDictViewObject *dv) { /* bpo-31095: UnTrack is needed before calling any callbacks */ _PyObject_GC_UNTRACK(dv); Py_XDECREF(dv->dv_dict); PyObject_GC_Del(dv); } static int dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg) { Py_VISIT(dv->dv_dict); return 0; } static Py_ssize_t dictview_len(_PyDictViewObject *dv) { Py_ssize_t len = 0; if (dv->dv_dict != NULL) len = dv->dv_dict->ma_used; return len; } PyObject * _PyDictView_New(PyObject *dict, PyTypeObject *type) { _PyDictViewObject *dv; if (dict == NULL) { PyErr_BadInternalCall(); return NULL; } if (!PyDict_Check(dict)) { /* XXX Get rid of this restriction later */ PyErr_Format(PyExc_TypeError, "%s() requires a dict argument, not '%s'", type->tp_name, dict->ob_type->tp_name); return NULL; } dv = PyObject_GC_New(_PyDictViewObject, type); if (dv == NULL) return NULL; Py_INCREF(dict); dv->dv_dict = (PyDictObject *)dict; _PyObject_GC_TRACK(dv); return (PyObject *)dv; } /* TODO(guido): The views objects are not complete: * support more set operations * support arbitrary mappings? - either these should be static or exported in dictobject.h - if public then they should probably be in builtins */ /* Return 1 if self is a subset of other, iterating over self; 0 if not; -1 if an error occurred. */ static int all_contained_in(PyObject *self, PyObject *other) { PyObject *iter = PyObject_GetIter(self); int ok = 1; if (iter == NULL) return -1; for (;;) { PyObject *next = PyIter_Next(iter); if (next == NULL) { if (PyErr_Occurred()) ok = -1; break; } ok = PySequence_Contains(other, next); Py_DECREF(next); if (ok <= 0) break; } Py_DECREF(iter); return ok; } static PyObject * dictview_richcompare(PyObject *self, PyObject *other, int op) { Py_ssize_t len_self, len_other; int ok; PyObject *result; assert(self != NULL); assert(PyDictViewSet_Check(self)); assert(other != NULL); if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) Py_RETURN_NOTIMPLEMENTED; len_self = PyObject_Size(self); if (len_self < 0) return NULL; len_other = PyObject_Size(other); if (len_other < 0) return NULL; ok = 0; switch(op) { case Py_NE: case Py_EQ: if (len_self == len_other) ok = all_contained_in(self, other); if (op == Py_NE && ok >= 0) ok = !ok; break; case Py_LT: if (len_self < len_other) ok = all_contained_in(self, other); break; case Py_LE: if (len_self <= len_other) ok = all_contained_in(self, other); break; case Py_GT: if (len_self > len_other) ok = all_contained_in(other, self); break; case Py_GE: if (len_self >= len_other) ok = all_contained_in(other, self); break; } if (ok < 0) return NULL; result = ok ? Py_True : Py_False; Py_INCREF(result); return result; } static PyObject * dictview_repr(_PyDictViewObject *dv) { PyObject *seq; PyObject *result = NULL; Py_ssize_t rc; rc = Py_ReprEnter((PyObject *)dv); if (rc != 0) { return rc > 0 ? PyUnicode_FromString("...") : NULL; } seq = PySequence_List((PyObject *)dv); if (seq == NULL) { goto Done; } result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq); Py_DECREF(seq); Done: Py_ReprLeave((PyObject *)dv); return result; } /*** dict_keys ***/ static PyObject * dictkeys_iter(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return dictiter_new(dv->dv_dict, &PyDictIterKey_Type); } static int dictkeys_contains(_PyDictViewObject *dv, PyObject *obj) { if (dv->dv_dict == NULL) return 0; return PyDict_Contains((PyObject *)dv->dv_dict, obj); } static PySequenceMethods dictkeys_as_sequence = { (lenfunc)dictview_len, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ 0, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)dictkeys_contains, /* sq_contains */ }; static PyObject* dictviews_sub(PyObject* self, PyObject *other) { PyObject *result = PySet_New(self); PyObject *tmp; _Py_IDENTIFIER(difference_update); if (result == NULL) return NULL; tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_difference_update, other, NULL); if (tmp == NULL) { Py_DECREF(result); return NULL; } Py_DECREF(tmp); return result; } PyObject* _PyDictView_Intersect(PyObject* self, PyObject *other) { PyObject *result = PySet_New(self); PyObject *tmp; _Py_IDENTIFIER(intersection_update); if (result == NULL) return NULL; tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_intersection_update, other, NULL); if (tmp == NULL) { Py_DECREF(result); return NULL; } Py_DECREF(tmp); return result; } static PyObject* dictviews_or(PyObject* self, PyObject *other) { PyObject *result = PySet_New(self); PyObject *tmp; _Py_IDENTIFIER(update); if (result == NULL) return NULL; tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_update, other, NULL); if (tmp == NULL) { Py_DECREF(result); return NULL; } Py_DECREF(tmp); return result; } static PyObject* dictviews_xor(PyObject* self, PyObject *other) { PyObject *result = PySet_New(self); PyObject *tmp; _Py_IDENTIFIER(symmetric_difference_update); if (result == NULL) return NULL; tmp = _PyObject_CallMethodIdObjArgs(result, &PyId_symmetric_difference_update, other, NULL); if (tmp == NULL) { Py_DECREF(result); return NULL; } Py_DECREF(tmp); return result; } static PyNumberMethods dictviews_as_number = { 0, /*nb_add*/ (binaryfunc)dictviews_sub, /*nb_subtract*/ 0, /*nb_multiply*/ 0, /*nb_remainder*/ 0, /*nb_divmod*/ 0, /*nb_power*/ 0, /*nb_negative*/ 0, /*nb_positive*/ 0, /*nb_absolute*/ 0, /*nb_bool*/ 0, /*nb_invert*/ 0, /*nb_lshift*/ 0, /*nb_rshift*/ (binaryfunc)_PyDictView_Intersect, /*nb_and*/ (binaryfunc)dictviews_xor, /*nb_xor*/ (binaryfunc)dictviews_or, /*nb_or*/ }; static PyObject* dictviews_isdisjoint(PyObject *self, PyObject *other) { PyObject *it; PyObject *item = NULL; if (self == other) { if (dictview_len((_PyDictViewObject *)self) == 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; } /* Iterate over the shorter object (only if other is a set, * because PySequence_Contains may be expensive otherwise): */ if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) { Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self); Py_ssize_t len_other = PyObject_Size(other); if (len_other == -1) return NULL; if ((len_other > len_self)) { PyObject *tmp = other; other = self; self = tmp; } } it = PyObject_GetIter(other); if (it == NULL) return NULL; while ((item = PyIter_Next(it)) != NULL) { int contains = PySequence_Contains(self, item); Py_DECREF(item); if (contains == -1) { Py_DECREF(it); return NULL; } if (contains) { Py_DECREF(it); Py_RETURN_FALSE; } } Py_DECREF(it); if (PyErr_Occurred()) return NULL; /* PyIter_Next raised an exception. */ Py_RETURN_TRUE; } PyDoc_STRVAR(isdisjoint_doc, "Return True if the view and the given iterable have a null intersection."); static PyMethodDef dictkeys_methods[] = { {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O, isdisjoint_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictKeys_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "dict_keys", /* tp_name */ sizeof(_PyDictViewObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)dictview_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)dictview_repr, /* tp_repr */ &dictviews_as_number, /* tp_as_number */ &dictkeys_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)dictview_traverse, /* tp_traverse */ 0, /* tp_clear */ dictview_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)dictkeys_iter, /* tp_iter */ 0, /* tp_iternext */ dictkeys_methods, /* tp_methods */ 0, }; static PyObject * dictkeys_new(PyObject *dict) { return _PyDictView_New(dict, &PyDictKeys_Type); } /*** dict_items ***/ static PyObject * dictitems_iter(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return dictiter_new(dv->dv_dict, &PyDictIterItem_Type); } static int dictitems_contains(_PyDictViewObject *dv, PyObject *obj) { int result; PyObject *key, *value, *found; if (dv->dv_dict == NULL) return 0; if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2) return 0; key = PyTuple_GET_ITEM(obj, 0); value = PyTuple_GET_ITEM(obj, 1); found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key); if (found == NULL) { if (PyErr_Occurred()) return -1; return 0; } Py_INCREF(found); result = PyObject_RichCompareBool(value, found, Py_EQ); Py_DECREF(found); return result; } static PySequenceMethods dictitems_as_sequence = { (lenfunc)dictview_len, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ 0, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)dictitems_contains, /* sq_contains */ }; static PyMethodDef dictitems_methods[] = { {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O, isdisjoint_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictItems_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "dict_items", /* tp_name */ sizeof(_PyDictViewObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)dictview_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)dictview_repr, /* tp_repr */ &dictviews_as_number, /* tp_as_number */ &dictitems_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)dictview_traverse, /* tp_traverse */ 0, /* tp_clear */ dictview_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)dictitems_iter, /* tp_iter */ 0, /* tp_iternext */ dictitems_methods, /* tp_methods */ 0, }; static PyObject * dictitems_new(PyObject *dict) { return _PyDictView_New(dict, &PyDictItems_Type); } /*** dict_values ***/ static PyObject * dictvalues_iter(_PyDictViewObject *dv) { if (dv->dv_dict == NULL) { Py_RETURN_NONE; } return dictiter_new(dv->dv_dict, &PyDictIterValue_Type); } static PySequenceMethods dictvalues_as_sequence = { (lenfunc)dictview_len, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ 0, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)0, /* sq_contains */ }; static PyMethodDef dictvalues_methods[] = { {NULL, NULL} /* sentinel */ }; PyTypeObject PyDictValues_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "dict_values", /* tp_name */ sizeof(_PyDictViewObject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)dictview_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)dictview_repr, /* tp_repr */ 0, /* tp_as_number */ &dictvalues_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ 0, /* tp_doc */ (traverseproc)dictview_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)dictvalues_iter, /* tp_iter */ 0, /* tp_iternext */ dictvalues_methods, /* tp_methods */ 0, }; static PyObject * dictvalues_new(PyObject *dict) { return _PyDictView_New(dict, &PyDictValues_Type); } /* Returns NULL if cannot allocate a new PyDictKeysObject, but does not set an error */ PyDictKeysObject * _PyDict_NewKeysForClass(void) { PyDictKeysObject *keys = new_keys_object(PyDict_MINSIZE); if (keys == NULL) PyErr_Clear(); else keys->dk_lookup = lookdict_split; return keys; } #define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys) PyObject * PyObject_GenericGetDict(PyObject *obj, void *context) { PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj); if (dictptr == NULL) { PyErr_SetString(PyExc_AttributeError, "This object has no __dict__"); return NULL; } dict = *dictptr; if (dict == NULL) { PyTypeObject *tp = Py_TYPE(obj); if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) { DK_INCREF(CACHED_KEYS(tp)); *dictptr = dict = new_dict_with_shared_keys(CACHED_KEYS(tp)); } else { *dictptr = dict = PyDict_New(); } } Py_XINCREF(dict); return dict; } int _PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr, PyObject *key, PyObject *value) { PyObject *dict; int res; PyDictKeysObject *cached; assert(dictptr != NULL); if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) { assert(dictptr != NULL); dict = *dictptr; if (dict == NULL) { DK_INCREF(cached); dict = new_dict_with_shared_keys(cached); if (dict == NULL) return -1; *dictptr = dict; } if (value == NULL) { res = PyDict_DelItem(dict, key); // Since key sharing dict doesn't allow deletion, PyDict_DelItem() // always converts dict to combined form. if ((cached = CACHED_KEYS(tp)) != NULL) { CACHED_KEYS(tp) = NULL; DK_DECREF(cached); } } else { int was_shared = (cached == ((PyDictObject *)dict)->ma_keys); res = PyDict_SetItem(dict, key, value); if (was_shared && (cached = CACHED_KEYS(tp)) != NULL && cached != ((PyDictObject *)dict)->ma_keys) { /* PyDict_SetItem() may call dictresize and convert split table * into combined table. In such case, convert it to split * table again and update type's shared key only when this is * the only dict sharing key with the type. * * This is to allow using shared key in class like this: * * class C: * def __init__(self): * # one dict resize happens * self.a, self.b, self.c = 1, 2, 3 * self.d, self.e, self.f = 4, 5, 6 * a = C() */ if (cached->dk_refcnt == 1) { CACHED_KEYS(tp) = make_keys_shared(dict); } else { CACHED_KEYS(tp) = NULL; } DK_DECREF(cached); if (CACHED_KEYS(tp) == NULL && PyErr_Occurred()) return -1; } } } else { dict = *dictptr; if (dict == NULL) { dict = PyDict_New(); if (dict == NULL) return -1; *dictptr = dict; } if (value == NULL) { res = PyDict_DelItem(dict, key); } else { res = PyDict_SetItem(dict, key, value); } } return res; } void _PyDictKeys_DecRef(PyDictKeysObject *keys) { DK_DECREF(keys); }
139,158
4,561
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/clinic/unicodeobject.inc
/* clang-format off */ /*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(unicode_maketrans__doc__, "maketrans(x, y=None, z=None, /)\n" "--\n" "\n" "Return a translation table usable for str.translate().\n" "\n" "If there is only one argument, it must be a dictionary mapping Unicode\n" "ordinals (integers) or characters to Unicode ordinals, strings or None.\n" "Character keys will be then converted to ordinals.\n" "If there are two arguments, they must be strings of equal length, and\n" "in the resulting dictionary, each character in x will be mapped to the\n" "character at the same position in y. If there is a third argument, it\n" "must be a string, whose characters will be mapped to None in the result."); #define UNICODE_MAKETRANS_METHODDEF \ {"maketrans", (PyCFunction)unicode_maketrans, METH_FASTCALL|METH_STATIC, unicode_maketrans__doc__}, static PyObject * unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z); static PyObject * unicode_maketrans(void *null, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *x; PyObject *y = NULL; PyObject *z = NULL; if (!_PyArg_ParseStack(args, nargs, "O|UU:maketrans", &x, &y, &z)) { goto exit; } return_value = unicode_maketrans_impl(x, y, z); exit: return return_value; } /*[clinic end generated code: output=d1e48260a99031c2 input=a9049054013a1b77]*/
1,426
44
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/clinic/bytearrayobject.inc
/* clang-format off */ /*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(bytearray_clear__doc__, "clear($self, /)\n" "--\n" "\n" "Remove all items from the bytearray."); #define BYTEARRAY_CLEAR_METHODDEF \ {"clear", (PyCFunction)bytearray_clear, METH_NOARGS, bytearray_clear__doc__}, static PyObject * bytearray_clear_impl(PyByteArrayObject *self); static PyObject * bytearray_clear(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored)) { return bytearray_clear_impl(self); } PyDoc_STRVAR(bytearray_copy__doc__, "copy($self, /)\n" "--\n" "\n" "Return a copy of B."); #define BYTEARRAY_COPY_METHODDEF \ {"copy", (PyCFunction)bytearray_copy, METH_NOARGS, bytearray_copy__doc__}, static PyObject * bytearray_copy_impl(PyByteArrayObject *self); static PyObject * bytearray_copy(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored)) { return bytearray_copy_impl(self); } PyDoc_STRVAR(bytearray_translate__doc__, "translate($self, table, /, delete=b\'\')\n" "--\n" "\n" "Return a copy with each character mapped by the given translation table.\n" "\n" " table\n" " Translation table, which must be a bytes object of length 256.\n" "\n" "All characters occurring in the optional argument delete are removed.\n" "The remaining characters are mapped through the given translation table."); #define BYTEARRAY_TRANSLATE_METHODDEF \ {"translate", (PyCFunction)bytearray_translate, METH_FASTCALL|METH_KEYWORDS, bytearray_translate__doc__}, static PyObject * bytearray_translate_impl(PyByteArrayObject *self, PyObject *table, PyObject *deletechars); static PyObject * bytearray_translate(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"", "delete", NULL}; static _PyArg_Parser _parser = {"O|O:translate", _keywords, 0}; PyObject *table; PyObject *deletechars = NULL; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &table, &deletechars)) { goto exit; } return_value = bytearray_translate_impl(self, table, deletechars); exit: return return_value; } PyDoc_STRVAR(bytearray_maketrans__doc__, "maketrans(frm, to, /)\n" "--\n" "\n" "Return a translation table useable for the bytes or bytearray translate method.\n" "\n" "The returned table will be one where each byte in frm is mapped to the byte at\n" "the same position in to.\n" "\n" "The bytes objects frm and to must be of the same length."); #define BYTEARRAY_MAKETRANS_METHODDEF \ {"maketrans", (PyCFunction)bytearray_maketrans, METH_FASTCALL|METH_STATIC, bytearray_maketrans__doc__}, static PyObject * bytearray_maketrans_impl(Py_buffer *frm, Py_buffer *to); static PyObject * bytearray_maketrans(void *null, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; Py_buffer frm = {NULL, NULL}; Py_buffer to = {NULL, NULL}; if (!_PyArg_ParseStack(args, nargs, "y*y*:maketrans", &frm, &to)) { goto exit; } return_value = bytearray_maketrans_impl(&frm, &to); exit: /* Cleanup for frm */ if (frm.obj) { PyBuffer_Release(&frm); } /* Cleanup for to */ if (to.obj) { PyBuffer_Release(&to); } return return_value; } PyDoc_STRVAR(bytearray_replace__doc__, "replace($self, old, new, count=-1, /)\n" "--\n" "\n" "Return a copy with all occurrences of substring old replaced by new.\n" "\n" " count\n" " Maximum number of occurrences to replace.\n" " -1 (the default value) means replace all occurrences.\n" "\n" "If the optional argument count is given, only the first count occurrences are\n" "replaced."); #define BYTEARRAY_REPLACE_METHODDEF \ {"replace", (PyCFunction)bytearray_replace, METH_FASTCALL, bytearray_replace__doc__}, static PyObject * bytearray_replace_impl(PyByteArrayObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count); static PyObject * bytearray_replace(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; Py_buffer old = {NULL, NULL}; Py_buffer new = {NULL, NULL}; Py_ssize_t count = -1; if (!_PyArg_ParseStack(args, nargs, "y*y*|n:replace", &old, &new, &count)) { goto exit; } return_value = bytearray_replace_impl(self, &old, &new, count); exit: /* Cleanup for old */ if (old.obj) { PyBuffer_Release(&old); } /* Cleanup for new */ if (new.obj) { PyBuffer_Release(&new); } return return_value; } PyDoc_STRVAR(bytearray_split__doc__, "split($self, /, sep=None, maxsplit=-1)\n" "--\n" "\n" "Return a list of the sections in the bytearray, using sep as the delimiter.\n" "\n" " sep\n" " The delimiter according which to split the bytearray.\n" " None (the default value) means split on ASCII whitespace characters\n" " (space, tab, return, newline, formfeed, vertical tab).\n" " maxsplit\n" " Maximum number of splits to do.\n" " -1 (the default value) means no limit."); #define BYTEARRAY_SPLIT_METHODDEF \ {"split", (PyCFunction)bytearray_split, METH_FASTCALL|METH_KEYWORDS, bytearray_split__doc__}, static PyObject * bytearray_split_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit); static PyObject * bytearray_split(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"sep", "maxsplit", NULL}; static _PyArg_Parser _parser = {"|On:split", _keywords, 0}; PyObject *sep = Py_None; Py_ssize_t maxsplit = -1; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &sep, &maxsplit)) { goto exit; } return_value = bytearray_split_impl(self, sep, maxsplit); exit: return return_value; } PyDoc_STRVAR(bytearray_partition__doc__, "partition($self, sep, /)\n" "--\n" "\n" "Partition the bytearray into three parts using the given separator.\n" "\n" "This will search for the separator sep in the bytearray. If the separator is\n" "found, returns a 3-tuple containing the part before the separator, the\n" "separator itself, and the part after it as new bytearray objects.\n" "\n" "If the separator is not found, returns a 3-tuple containing the copy of the\n" "original bytearray object and two empty bytearray objects."); #define BYTEARRAY_PARTITION_METHODDEF \ {"partition", (PyCFunction)bytearray_partition, METH_O, bytearray_partition__doc__}, PyDoc_STRVAR(bytearray_rpartition__doc__, "rpartition($self, sep, /)\n" "--\n" "\n" "Partition the bytearray into three parts using the given separator.\n" "\n" "This will search for the separator sep in the bytearray, starting at the end.\n" "If the separator is found, returns a 3-tuple containing the part before the\n" "separator, the separator itself, and the part after it as new bytearray\n" "objects.\n" "\n" "If the separator is not found, returns a 3-tuple containing two empty bytearray\n" "objects and the copy of the original bytearray object."); #define BYTEARRAY_RPARTITION_METHODDEF \ {"rpartition", (PyCFunction)bytearray_rpartition, METH_O, bytearray_rpartition__doc__}, PyDoc_STRVAR(bytearray_rsplit__doc__, "rsplit($self, /, sep=None, maxsplit=-1)\n" "--\n" "\n" "Return a list of the sections in the bytearray, using sep as the delimiter.\n" "\n" " sep\n" " The delimiter according which to split the bytearray.\n" " None (the default value) means split on ASCII whitespace characters\n" " (space, tab, return, newline, formfeed, vertical tab).\n" " maxsplit\n" " Maximum number of splits to do.\n" " -1 (the default value) means no limit.\n" "\n" "Splitting is done starting at the end of the bytearray and working to the front."); #define BYTEARRAY_RSPLIT_METHODDEF \ {"rsplit", (PyCFunction)bytearray_rsplit, METH_FASTCALL|METH_KEYWORDS, bytearray_rsplit__doc__}, static PyObject * bytearray_rsplit_impl(PyByteArrayObject *self, PyObject *sep, Py_ssize_t maxsplit); static PyObject * bytearray_rsplit(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"sep", "maxsplit", NULL}; static _PyArg_Parser _parser = {"|On:rsplit", _keywords, 0}; PyObject *sep = Py_None; Py_ssize_t maxsplit = -1; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &sep, &maxsplit)) { goto exit; } return_value = bytearray_rsplit_impl(self, sep, maxsplit); exit: return return_value; } PyDoc_STRVAR(bytearray_reverse__doc__, "reverse($self, /)\n" "--\n" "\n" "Reverse the order of the values in B in place."); #define BYTEARRAY_REVERSE_METHODDEF \ {"reverse", (PyCFunction)bytearray_reverse, METH_NOARGS, bytearray_reverse__doc__}, static PyObject * bytearray_reverse_impl(PyByteArrayObject *self); static PyObject * bytearray_reverse(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored)) { return bytearray_reverse_impl(self); } PyDoc_STRVAR(bytearray_insert__doc__, "insert($self, index, item, /)\n" "--\n" "\n" "Insert a single item into the bytearray before the given index.\n" "\n" " index\n" " The index where the value is to be inserted.\n" " item\n" " The item to be inserted."); #define BYTEARRAY_INSERT_METHODDEF \ {"insert", (PyCFunction)bytearray_insert, METH_FASTCALL, bytearray_insert__doc__}, static PyObject * bytearray_insert_impl(PyByteArrayObject *self, Py_ssize_t index, int item); static PyObject * bytearray_insert(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; Py_ssize_t index; int item; if (!_PyArg_ParseStack(args, nargs, "nO&:insert", &index, _getbytevalue, &item)) { goto exit; } return_value = bytearray_insert_impl(self, index, item); exit: return return_value; } PyDoc_STRVAR(bytearray_append__doc__, "append($self, item, /)\n" "--\n" "\n" "Append a single item to the end of the bytearray.\n" "\n" " item\n" " The item to be appended."); #define BYTEARRAY_APPEND_METHODDEF \ {"append", (PyCFunction)bytearray_append, METH_O, bytearray_append__doc__}, static PyObject * bytearray_append_impl(PyByteArrayObject *self, int item); static PyObject * bytearray_append(PyByteArrayObject *self, PyObject *arg) { PyObject *return_value = NULL; int item; if (!PyArg_Parse(arg, "O&:append", _getbytevalue, &item)) { goto exit; } return_value = bytearray_append_impl(self, item); exit: return return_value; } PyDoc_STRVAR(bytearray_extend__doc__, "extend($self, iterable_of_ints, /)\n" "--\n" "\n" "Append all the items from the iterator or sequence to the end of the bytearray.\n" "\n" " iterable_of_ints\n" " The iterable of items to append."); #define BYTEARRAY_EXTEND_METHODDEF \ {"extend", (PyCFunction)bytearray_extend, METH_O, bytearray_extend__doc__}, PyDoc_STRVAR(bytearray_pop__doc__, "pop($self, index=-1, /)\n" "--\n" "\n" "Remove and return a single item from B.\n" "\n" " index\n" " The index from where to remove the item.\n" " -1 (the default value) means remove the last item.\n" "\n" "If no index argument is given, will pop the last item."); #define BYTEARRAY_POP_METHODDEF \ {"pop", (PyCFunction)bytearray_pop, METH_FASTCALL, bytearray_pop__doc__}, static PyObject * bytearray_pop_impl(PyByteArrayObject *self, Py_ssize_t index); static PyObject * bytearray_pop(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; Py_ssize_t index = -1; if (!_PyArg_ParseStack(args, nargs, "|n:pop", &index)) { goto exit; } return_value = bytearray_pop_impl(self, index); exit: return return_value; } PyDoc_STRVAR(bytearray_remove__doc__, "remove($self, value, /)\n" "--\n" "\n" "Remove the first occurrence of a value in the bytearray.\n" "\n" " value\n" " The value to remove."); #define BYTEARRAY_REMOVE_METHODDEF \ {"remove", (PyCFunction)bytearray_remove, METH_O, bytearray_remove__doc__}, static PyObject * bytearray_remove_impl(PyByteArrayObject *self, int value); static PyObject * bytearray_remove(PyByteArrayObject *self, PyObject *arg) { PyObject *return_value = NULL; int value; if (!PyArg_Parse(arg, "O&:remove", _getbytevalue, &value)) { goto exit; } return_value = bytearray_remove_impl(self, value); exit: return return_value; } PyDoc_STRVAR(bytearray_strip__doc__, "strip($self, bytes=None, /)\n" "--\n" "\n" "Strip leading and trailing bytes contained in the argument.\n" "\n" "If the argument is omitted or None, strip leading and trailing ASCII whitespace."); #define BYTEARRAY_STRIP_METHODDEF \ {"strip", (PyCFunction)bytearray_strip, METH_FASTCALL, bytearray_strip__doc__}, static PyObject * bytearray_strip_impl(PyByteArrayObject *self, PyObject *bytes); static PyObject * bytearray_strip(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *bytes = Py_None; if (!_PyArg_UnpackStack(args, nargs, "strip", 0, 1, &bytes)) { goto exit; } return_value = bytearray_strip_impl(self, bytes); exit: return return_value; } PyDoc_STRVAR(bytearray_lstrip__doc__, "lstrip($self, bytes=None, /)\n" "--\n" "\n" "Strip leading bytes contained in the argument.\n" "\n" "If the argument is omitted or None, strip leading ASCII whitespace."); #define BYTEARRAY_LSTRIP_METHODDEF \ {"lstrip", (PyCFunction)bytearray_lstrip, METH_FASTCALL, bytearray_lstrip__doc__}, static PyObject * bytearray_lstrip_impl(PyByteArrayObject *self, PyObject *bytes); static PyObject * bytearray_lstrip(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *bytes = Py_None; if (!_PyArg_UnpackStack(args, nargs, "lstrip", 0, 1, &bytes)) { goto exit; } return_value = bytearray_lstrip_impl(self, bytes); exit: return return_value; } PyDoc_STRVAR(bytearray_rstrip__doc__, "rstrip($self, bytes=None, /)\n" "--\n" "\n" "Strip trailing bytes contained in the argument.\n" "\n" "If the argument is omitted or None, strip trailing ASCII whitespace."); #define BYTEARRAY_RSTRIP_METHODDEF \ {"rstrip", (PyCFunction)bytearray_rstrip, METH_FASTCALL, bytearray_rstrip__doc__}, static PyObject * bytearray_rstrip_impl(PyByteArrayObject *self, PyObject *bytes); static PyObject * bytearray_rstrip(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *bytes = Py_None; if (!_PyArg_UnpackStack(args, nargs, "rstrip", 0, 1, &bytes)) { goto exit; } return_value = bytearray_rstrip_impl(self, bytes); exit: return return_value; } PyDoc_STRVAR(bytearray_decode__doc__, "decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n" "--\n" "\n" "Decode the bytearray using the codec registered for encoding.\n" "\n" " encoding\n" " The encoding with which to decode the bytearray.\n" " errors\n" " The error handling scheme to use for the handling of decoding errors.\n" " The default is \'strict\' meaning that decoding errors raise a\n" " UnicodeDecodeError. Other possible values are \'ignore\' and \'replace\'\n" " as well as any other name registered with codecs.register_error that\n" " can handle UnicodeDecodeErrors."); #define BYTEARRAY_DECODE_METHODDEF \ {"decode", (PyCFunction)bytearray_decode, METH_FASTCALL|METH_KEYWORDS, bytearray_decode__doc__}, static PyObject * bytearray_decode_impl(PyByteArrayObject *self, const char *encoding, const char *errors); static PyObject * bytearray_decode(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"encoding", "errors", NULL}; static _PyArg_Parser _parser = {"|ss:decode", _keywords, 0}; const char *encoding = NULL; const char *errors = NULL; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &encoding, &errors)) { goto exit; } return_value = bytearray_decode_impl(self, encoding, errors); exit: return return_value; } PyDoc_STRVAR(bytearray_join__doc__, "join($self, iterable_of_bytes, /)\n" "--\n" "\n" "Concatenate any number of bytes/bytearray objects.\n" "\n" "The bytearray whose method is called is inserted in between each pair.\n" "\n" "The result is returned as a new bytearray object."); #define BYTEARRAY_JOIN_METHODDEF \ {"join", (PyCFunction)bytearray_join, METH_O, bytearray_join__doc__}, PyDoc_STRVAR(bytearray_splitlines__doc__, "splitlines($self, /, keepends=False)\n" "--\n" "\n" "Return a list of the lines in the bytearray, breaking at line boundaries.\n" "\n" "Line breaks are not included in the resulting list unless keepends is given and\n" "true."); #define BYTEARRAY_SPLITLINES_METHODDEF \ {"splitlines", (PyCFunction)bytearray_splitlines, METH_FASTCALL|METH_KEYWORDS, bytearray_splitlines__doc__}, static PyObject * bytearray_splitlines_impl(PyByteArrayObject *self, int keepends); static PyObject * bytearray_splitlines(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"keepends", NULL}; static _PyArg_Parser _parser = {"|i:splitlines", _keywords, 0}; int keepends = 0; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &keepends)) { goto exit; } return_value = bytearray_splitlines_impl(self, keepends); exit: return return_value; } PyDoc_STRVAR(bytearray_fromhex__doc__, "fromhex($type, string, /)\n" "--\n" "\n" "Create a bytearray object from a string of hexadecimal numbers.\n" "\n" "Spaces between two numbers are accepted.\n" "Example: bytearray.fromhex(\'B9 01EF\') -> bytearray(b\'\\\\xb9\\\\x01\\\\xef\')"); #define BYTEARRAY_FROMHEX_METHODDEF \ {"fromhex", (PyCFunction)bytearray_fromhex, METH_O|METH_CLASS, bytearray_fromhex__doc__}, static PyObject * bytearray_fromhex_impl(PyTypeObject *type, PyObject *string); static PyObject * bytearray_fromhex(PyTypeObject *type, PyObject *arg) { PyObject *return_value = NULL; PyObject *string; if (!PyArg_Parse(arg, "U:fromhex", &string)) { goto exit; } return_value = bytearray_fromhex_impl(type, string); exit: return return_value; } PyDoc_STRVAR(bytearray_reduce__doc__, "__reduce__($self, /)\n" "--\n" "\n" "Return state information for pickling."); #define BYTEARRAY_REDUCE_METHODDEF \ {"__reduce__", (PyCFunction)bytearray_reduce, METH_NOARGS, bytearray_reduce__doc__}, static PyObject * bytearray_reduce_impl(PyByteArrayObject *self); static PyObject * bytearray_reduce(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored)) { return bytearray_reduce_impl(self); } PyDoc_STRVAR(bytearray_reduce_ex__doc__, "__reduce_ex__($self, proto=0, /)\n" "--\n" "\n" "Return state information for pickling."); #define BYTEARRAY_REDUCE_EX_METHODDEF \ {"__reduce_ex__", (PyCFunction)bytearray_reduce_ex, METH_FASTCALL, bytearray_reduce_ex__doc__}, static PyObject * bytearray_reduce_ex_impl(PyByteArrayObject *self, int proto); static PyObject * bytearray_reduce_ex(PyByteArrayObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; int proto = 0; if (!_PyArg_ParseStack(args, nargs, "|i:__reduce_ex__", &proto)) { goto exit; } return_value = bytearray_reduce_ex_impl(self, proto); exit: return return_value; } PyDoc_STRVAR(bytearray_sizeof__doc__, "__sizeof__($self, /)\n" "--\n" "\n" "Returns the size of the bytearray object in memory, in bytes."); #define BYTEARRAY_SIZEOF_METHODDEF \ {"__sizeof__", (PyCFunction)bytearray_sizeof, METH_NOARGS, bytearray_sizeof__doc__}, static PyObject * bytearray_sizeof_impl(PyByteArrayObject *self); static PyObject * bytearray_sizeof(PyByteArrayObject *self, PyObject *Py_UNUSED(ignored)) { return bytearray_sizeof_impl(self); } /*[clinic end generated code: output=c2804d009182328c input=a9049054013a1b77]*/
20,430
717
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/clinic/bytesobject.inc
/* clang-format off */ /*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(bytes_split__doc__, "split($self, /, sep=None, maxsplit=-1)\n" "--\n" "\n" "Return a list of the sections in the bytes, using sep as the delimiter.\n" "\n" " sep\n" " The delimiter according which to split the bytes.\n" " None (the default value) means split on ASCII whitespace characters\n" " (space, tab, return, newline, formfeed, vertical tab).\n" " maxsplit\n" " Maximum number of splits to do.\n" " -1 (the default value) means no limit."); #define BYTES_SPLIT_METHODDEF \ {"split", (PyCFunction)bytes_split, METH_FASTCALL|METH_KEYWORDS, bytes_split__doc__}, static PyObject * bytes_split_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit); static PyObject * bytes_split(PyBytesObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"sep", "maxsplit", NULL}; static _PyArg_Parser _parser = {"|On:split", _keywords, 0}; PyObject *sep = Py_None; Py_ssize_t maxsplit = -1; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &sep, &maxsplit)) { goto exit; } return_value = bytes_split_impl(self, sep, maxsplit); exit: return return_value; } PyDoc_STRVAR(bytes_partition__doc__, "partition($self, sep, /)\n" "--\n" "\n" "Partition the bytes into three parts using the given separator.\n" "\n" "This will search for the separator sep in the bytes. If the separator is found,\n" "returns a 3-tuple containing the part before the separator, the separator\n" "itself, and the part after it.\n" "\n" "If the separator is not found, returns a 3-tuple containing the original bytes\n" "object and two empty bytes objects."); #define BYTES_PARTITION_METHODDEF \ {"partition", (PyCFunction)bytes_partition, METH_O, bytes_partition__doc__}, static PyObject * bytes_partition_impl(PyBytesObject *self, Py_buffer *sep); static PyObject * bytes_partition(PyBytesObject *self, PyObject *arg) { PyObject *return_value = NULL; Py_buffer sep = {NULL, NULL}; if (!PyArg_Parse(arg, "y*:partition", &sep)) { goto exit; } return_value = bytes_partition_impl(self, &sep); exit: /* Cleanup for sep */ if (sep.obj) { PyBuffer_Release(&sep); } return return_value; } PyDoc_STRVAR(bytes_rpartition__doc__, "rpartition($self, sep, /)\n" "--\n" "\n" "Partition the bytes into three parts using the given separator.\n" "\n" "This will search for the separator sep in the bytes, starting at the end. If\n" "the separator is found, returns a 3-tuple containing the part before the\n" "separator, the separator itself, and the part after it.\n" "\n" "If the separator is not found, returns a 3-tuple containing two empty bytes\n" "objects and the original bytes object."); #define BYTES_RPARTITION_METHODDEF \ {"rpartition", (PyCFunction)bytes_rpartition, METH_O, bytes_rpartition__doc__}, static PyObject * bytes_rpartition_impl(PyBytesObject *self, Py_buffer *sep); static PyObject * bytes_rpartition(PyBytesObject *self, PyObject *arg) { PyObject *return_value = NULL; Py_buffer sep = {NULL, NULL}; if (!PyArg_Parse(arg, "y*:rpartition", &sep)) { goto exit; } return_value = bytes_rpartition_impl(self, &sep); exit: /* Cleanup for sep */ if (sep.obj) { PyBuffer_Release(&sep); } return return_value; } PyDoc_STRVAR(bytes_rsplit__doc__, "rsplit($self, /, sep=None, maxsplit=-1)\n" "--\n" "\n" "Return a list of the sections in the bytes, using sep as the delimiter.\n" "\n" " sep\n" " The delimiter according which to split the bytes.\n" " None (the default value) means split on ASCII whitespace characters\n" " (space, tab, return, newline, formfeed, vertical tab).\n" " maxsplit\n" " Maximum number of splits to do.\n" " -1 (the default value) means no limit.\n" "\n" "Splitting is done starting at the end of the bytes and working to the front."); #define BYTES_RSPLIT_METHODDEF \ {"rsplit", (PyCFunction)bytes_rsplit, METH_FASTCALL|METH_KEYWORDS, bytes_rsplit__doc__}, static PyObject * bytes_rsplit_impl(PyBytesObject *self, PyObject *sep, Py_ssize_t maxsplit); static PyObject * bytes_rsplit(PyBytesObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"sep", "maxsplit", NULL}; static _PyArg_Parser _parser = {"|On:rsplit", _keywords, 0}; PyObject *sep = Py_None; Py_ssize_t maxsplit = -1; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &sep, &maxsplit)) { goto exit; } return_value = bytes_rsplit_impl(self, sep, maxsplit); exit: return return_value; } PyDoc_STRVAR(bytes_join__doc__, "join($self, iterable_of_bytes, /)\n" "--\n" "\n" "Concatenate any number of bytes objects.\n" "\n" "The bytes whose method is called is inserted in between each pair.\n" "\n" "The result is returned as a new bytes object.\n" "\n" "Example: b\'.\'.join([b\'ab\', b\'pq\', b\'rs\']) -> b\'ab.pq.rs\'."); #define BYTES_JOIN_METHODDEF \ {"join", (PyCFunction)bytes_join, METH_O, bytes_join__doc__}, PyDoc_STRVAR(bytes_strip__doc__, "strip($self, bytes=None, /)\n" "--\n" "\n" "Strip leading and trailing bytes contained in the argument.\n" "\n" "If the argument is omitted or None, strip leading and trailing ASCII whitespace."); #define BYTES_STRIP_METHODDEF \ {"strip", (PyCFunction)bytes_strip, METH_FASTCALL, bytes_strip__doc__}, static PyObject * bytes_strip_impl(PyBytesObject *self, PyObject *bytes); static PyObject * bytes_strip(PyBytesObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *bytes = Py_None; if (!_PyArg_UnpackStack(args, nargs, "strip", 0, 1, &bytes)) { goto exit; } return_value = bytes_strip_impl(self, bytes); exit: return return_value; } PyDoc_STRVAR(bytes_lstrip__doc__, "lstrip($self, bytes=None, /)\n" "--\n" "\n" "Strip leading bytes contained in the argument.\n" "\n" "If the argument is omitted or None, strip leading ASCII whitespace."); #define BYTES_LSTRIP_METHODDEF \ {"lstrip", (PyCFunction)bytes_lstrip, METH_FASTCALL, bytes_lstrip__doc__}, static PyObject * bytes_lstrip_impl(PyBytesObject *self, PyObject *bytes); static PyObject * bytes_lstrip(PyBytesObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *bytes = Py_None; if (!_PyArg_UnpackStack(args, nargs, "lstrip", 0, 1, &bytes)) { goto exit; } return_value = bytes_lstrip_impl(self, bytes); exit: return return_value; } PyDoc_STRVAR(bytes_rstrip__doc__, "rstrip($self, bytes=None, /)\n" "--\n" "\n" "Strip trailing bytes contained in the argument.\n" "\n" "If the argument is omitted or None, strip trailing ASCII whitespace."); #define BYTES_RSTRIP_METHODDEF \ {"rstrip", (PyCFunction)bytes_rstrip, METH_FASTCALL, bytes_rstrip__doc__}, static PyObject * bytes_rstrip_impl(PyBytesObject *self, PyObject *bytes); static PyObject * bytes_rstrip(PyBytesObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *bytes = Py_None; if (!_PyArg_UnpackStack(args, nargs, "rstrip", 0, 1, &bytes)) { goto exit; } return_value = bytes_rstrip_impl(self, bytes); exit: return return_value; } PyDoc_STRVAR(bytes_translate__doc__, "translate($self, table, /, delete=b\'\')\n" "--\n" "\n" "Return a copy with each character mapped by the given translation table.\n" "\n" " table\n" " Translation table, which must be a bytes object of length 256.\n" "\n" "All characters occurring in the optional argument delete are removed.\n" "The remaining characters are mapped through the given translation table."); #define BYTES_TRANSLATE_METHODDEF \ {"translate", (PyCFunction)bytes_translate, METH_FASTCALL|METH_KEYWORDS, bytes_translate__doc__}, static PyObject * bytes_translate_impl(PyBytesObject *self, PyObject *table, PyObject *deletechars); static PyObject * bytes_translate(PyBytesObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"", "delete", NULL}; static _PyArg_Parser _parser = {"O|O:translate", _keywords, 0}; PyObject *table; PyObject *deletechars = NULL; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &table, &deletechars)) { goto exit; } return_value = bytes_translate_impl(self, table, deletechars); exit: return return_value; } PyDoc_STRVAR(bytes_maketrans__doc__, "maketrans(frm, to, /)\n" "--\n" "\n" "Return a translation table useable for the bytes or bytearray translate method.\n" "\n" "The returned table will be one where each byte in frm is mapped to the byte at\n" "the same position in to.\n" "\n" "The bytes objects frm and to must be of the same length."); #define BYTES_MAKETRANS_METHODDEF \ {"maketrans", (PyCFunction)bytes_maketrans, METH_FASTCALL|METH_STATIC, bytes_maketrans__doc__}, static PyObject * bytes_maketrans_impl(Py_buffer *frm, Py_buffer *to); static PyObject * bytes_maketrans(void *null, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; Py_buffer frm = {NULL, NULL}; Py_buffer to = {NULL, NULL}; if (!_PyArg_ParseStack(args, nargs, "y*y*:maketrans", &frm, &to)) { goto exit; } return_value = bytes_maketrans_impl(&frm, &to); exit: /* Cleanup for frm */ if (frm.obj) { PyBuffer_Release(&frm); } /* Cleanup for to */ if (to.obj) { PyBuffer_Release(&to); } return return_value; } PyDoc_STRVAR(bytes_replace__doc__, "replace($self, old, new, count=-1, /)\n" "--\n" "\n" "Return a copy with all occurrences of substring old replaced by new.\n" "\n" " count\n" " Maximum number of occurrences to replace.\n" " -1 (the default value) means replace all occurrences.\n" "\n" "If the optional argument count is given, only the first count occurrences are\n" "replaced."); #define BYTES_REPLACE_METHODDEF \ {"replace", (PyCFunction)bytes_replace, METH_FASTCALL, bytes_replace__doc__}, static PyObject * bytes_replace_impl(PyBytesObject *self, Py_buffer *old, Py_buffer *new, Py_ssize_t count); static PyObject * bytes_replace(PyBytesObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; Py_buffer old = {NULL, NULL}; Py_buffer new = {NULL, NULL}; Py_ssize_t count = -1; if (!_PyArg_ParseStack(args, nargs, "y*y*|n:replace", &old, &new, &count)) { goto exit; } return_value = bytes_replace_impl(self, &old, &new, count); exit: /* Cleanup for old */ if (old.obj) { PyBuffer_Release(&old); } /* Cleanup for new */ if (new.obj) { PyBuffer_Release(&new); } return return_value; } PyDoc_STRVAR(bytes_decode__doc__, "decode($self, /, encoding=\'utf-8\', errors=\'strict\')\n" "--\n" "\n" "Decode the bytes using the codec registered for encoding.\n" "\n" " encoding\n" " The encoding with which to decode the bytes.\n" " errors\n" " The error handling scheme to use for the handling of decoding errors.\n" " The default is \'strict\' meaning that decoding errors raise a\n" " UnicodeDecodeError. Other possible values are \'ignore\' and \'replace\'\n" " as well as any other name registered with codecs.register_error that\n" " can handle UnicodeDecodeErrors."); #define BYTES_DECODE_METHODDEF \ {"decode", (PyCFunction)bytes_decode, METH_FASTCALL|METH_KEYWORDS, bytes_decode__doc__}, static PyObject * bytes_decode_impl(PyBytesObject *self, const char *encoding, const char *errors); static PyObject * bytes_decode(PyBytesObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"encoding", "errors", NULL}; static _PyArg_Parser _parser = {"|ss:decode", _keywords, 0}; const char *encoding = NULL; const char *errors = NULL; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &encoding, &errors)) { goto exit; } return_value = bytes_decode_impl(self, encoding, errors); exit: return return_value; } PyDoc_STRVAR(bytes_splitlines__doc__, "splitlines($self, /, keepends=False)\n" "--\n" "\n" "Return a list of the lines in the bytes, breaking at line boundaries.\n" "\n" "Line breaks are not included in the resulting list unless keepends is given and\n" "true."); #define BYTES_SPLITLINES_METHODDEF \ {"splitlines", (PyCFunction)bytes_splitlines, METH_FASTCALL|METH_KEYWORDS, bytes_splitlines__doc__}, static PyObject * bytes_splitlines_impl(PyBytesObject *self, int keepends); static PyObject * bytes_splitlines(PyBytesObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *return_value = NULL; static const char * const _keywords[] = {"keepends", NULL}; static _PyArg_Parser _parser = {"|i:splitlines", _keywords, 0}; int keepends = 0; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &_parser, &keepends)) { goto exit; } return_value = bytes_splitlines_impl(self, keepends); exit: return return_value; } PyDoc_STRVAR(bytes_fromhex__doc__, "fromhex($type, string, /)\n" "--\n" "\n" "Create a bytes object from a string of hexadecimal numbers.\n" "\n" "Spaces between two numbers are accepted.\n" "Example: bytes.fromhex(\'B9 01EF\') -> b\'\\\\xb9\\\\x01\\\\xef\'."); #define BYTES_FROMHEX_METHODDEF \ {"fromhex", (PyCFunction)bytes_fromhex, METH_O|METH_CLASS, bytes_fromhex__doc__}, static PyObject * bytes_fromhex_impl(PyTypeObject *type, PyObject *string); static PyObject * bytes_fromhex(PyTypeObject *type, PyObject *arg) { PyObject *return_value = NULL; PyObject *string; if (!PyArg_Parse(arg, "U:fromhex", &string)) { goto exit; } return_value = bytes_fromhex_impl(type, string); exit: return return_value; } /*[clinic end generated code: output=fc9e02359cc56d36 input=a9049054013a1b77]*/
14,390
504
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/clinic/dictobject.inc
/* clang-format off */ /*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(dict_fromkeys__doc__, "fromkeys($type, iterable, value=None, /)\n" "--\n" "\n" "Returns a new dict with keys from iterable and values equal to value."); #define DICT_FROMKEYS_METHODDEF \ {"fromkeys", (PyCFunction)dict_fromkeys, METH_FASTCALL|METH_CLASS, dict_fromkeys__doc__}, static PyObject * dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value); static PyObject * dict_fromkeys(PyTypeObject *type, PyObject **args, Py_ssize_t nargs) { PyObject *return_value = NULL; PyObject *iterable; PyObject *value = Py_None; if (!_PyArg_UnpackStack(args, nargs, "fromkeys", 1, 2, &iterable, &value)) { goto exit; } return_value = dict_fromkeys_impl(type, iterable, value); exit: return return_value; } PyDoc_STRVAR(dict___contains____doc__, "__contains__($self, key, /)\n" "--\n" "\n" "True if D has a key k, else False."); #define DICT___CONTAINS___METHODDEF \ {"__contains__", (PyCFunction)dict___contains__, METH_O|METH_COEXIST, dict___contains____doc__}, /*[clinic end generated code: output=d6997a57899cf28d input=a9049054013a1b77]*/
1,221
45
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/eq.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ /* Fast unicode equal function optimized for dictobject.c and setobject.c */ /* Return 1 if two unicode objects are equal, 0 if not. * unicode_eq() is called when the hash of two unicode objects is equal. */ Py_LOCAL_INLINE(int) unicode_eq(PyObject *aa, PyObject *bb) { PyUnicodeObject *a = (PyUnicodeObject *)aa; PyUnicodeObject *b = (PyUnicodeObject *)bb; if (UNLIKELY(PyUnicode_READY(a) == -1) || UNLIKELY(PyUnicode_READY(b) == -1)) { assert(0 && "unicode_eq ready fail"); return 0; } if (UNLIKELY(PyUnicode_GET_LENGTH(a) != PyUnicode_GET_LENGTH(b))) return 0; if (UNLIKELY(PyUnicode_GET_LENGTH(a) == 0)) return 1; if (UNLIKELY(PyUnicode_KIND(a) != PyUnicode_KIND(b))) return 0; return bcmp(PyUnicode_1BYTE_DATA(a), PyUnicode_1BYTE_DATA(b), PyUnicode_GET_LENGTH(a) * PyUnicode_KIND(a)) == 0; }
1,736
33
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/README.txt
bits shared by the bytesobject and unicodeobject implementations (and possibly other modules, in a not too distant future). the stuff in here is included into relevant places; see the individual source files for details. -------------------------------------------------------------------- the following defines used by the different modules: STRINGLIB_CHAR the type used to hold a character (char or Py_UNICODE) STRINGLIB_EMPTY a PyObject representing the empty string, only to be used if STRINGLIB_MUTABLE is 0 Py_ssize_t STRINGLIB_LEN(PyObject*) returns the length of the given string object (which must be of the right type) PyObject* STRINGLIB_NEW(STRINGLIB_CHAR*, Py_ssize_t) creates a new string object STRINGLIB_CHAR* STRINGLIB_STR(PyObject*) returns the pointer to the character data for the given string object (which must be of the right type) int STRINGLIB_CHECK_EXACT(PyObject *) returns true if the object is an instance of our type, not a subclass STRINGLIB_MUTABLE must be 0 or 1 to tell the cpp macros in stringlib code if the object being operated on is mutable or not
1,147
41
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/undef.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #undef FASTSEARCH #undef STRINGLIB #undef STRINGLIB_SIZEOF_CHAR #undef STRINGLIB_MAX_CHAR #undef STRINGLIB_CHAR #undef STRINGLIB_STR #undef STRINGLIB_LEN #undef STRINGLIB_NEW #undef _Py_InsertThousandsGrouping #undef STRINGLIB_IS_UNICODE
1,055
18
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/transmogrify.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ #if STRINGLIB_IS_UNICODE # error "transmogrify.h only compatible with byte-wise strings" #endif /* the more complicated methods. parts of these should be pulled out into the shared code in bytes_methods.c to cut down on duplicate code bloat. */ static inline PyObject * return_self(PyObject *self) { #if !STRINGLIB_MUTABLE if (STRINGLIB_CHECK_EXACT(self)) { Py_INCREF(self); return self; } #endif return STRINGLIB_NEW(STRINGLIB_STR(self), STRINGLIB_LEN(self)); } static PyObject* stringlib_expandtabs(PyObject *self, PyObject *args, PyObject *kwds) { const char *e, *p; char *q; Py_ssize_t i, j; PyObject *u; static char *kwlist[] = {"tabsize", 0}; int tabsize = 8; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs", kwlist, &tabsize)) return NULL; /* First pass: determine size of output string */ i = j = 0; e = STRINGLIB_STR(self) + STRINGLIB_LEN(self); for (p = STRINGLIB_STR(self); p < e; p++) { if (*p == '\t') { if (tabsize > 0) { Py_ssize_t incr = tabsize - (j % tabsize); if (j > PY_SSIZE_T_MAX - incr) goto overflow; j += incr; } } else { if (j > PY_SSIZE_T_MAX - 1) goto overflow; j++; if (*p == '\n' || *p == '\r') { if (i > PY_SSIZE_T_MAX - j) goto overflow; i += j; j = 0; } } } if (i > PY_SSIZE_T_MAX - j) goto overflow; /* Second pass: create output string and fill it */ u = STRINGLIB_NEW(NULL, i + j); if (!u) return NULL; j = 0; q = STRINGLIB_STR(u); for (p = STRINGLIB_STR(self); p < e; p++) { if (*p == '\t') { if (tabsize > 0) { i = tabsize - (j % tabsize); j += i; while (i--) *q++ = ' '; } } else { j++; *q++ = *p; if (*p == '\n' || *p == '\r') j = 0; } } return u; overflow: PyErr_SetString(PyExc_OverflowError, "result too long"); return NULL; } static inline PyObject * pad(PyObject *self, Py_ssize_t left, Py_ssize_t right, char fill) { PyObject *u; if (left < 0) left = 0; if (right < 0) right = 0; if (left == 0 && right == 0) { return return_self(self); } u = STRINGLIB_NEW(NULL, left + STRINGLIB_LEN(self) + right); if (u) { if (left) memset(STRINGLIB_STR(u), fill, left); memcpy(STRINGLIB_STR(u) + left, STRINGLIB_STR(self), STRINGLIB_LEN(self)); if (right) memset(STRINGLIB_STR(u) + left + STRINGLIB_LEN(self), fill, right); } return u; } static PyObject * stringlib_ljust(PyObject *self, PyObject *args) { Py_ssize_t width; char fillchar = ' '; if (!PyArg_ParseTuple(args, "n|c:ljust", &width, &fillchar)) return NULL; if (STRINGLIB_LEN(self) >= width) { return return_self(self); } return pad(self, 0, width - STRINGLIB_LEN(self), fillchar); } static PyObject * stringlib_rjust(PyObject *self, PyObject *args) { Py_ssize_t width; char fillchar = ' '; if (!PyArg_ParseTuple(args, "n|c:rjust", &width, &fillchar)) return NULL; if (STRINGLIB_LEN(self) >= width) { return return_self(self); } return pad(self, width - STRINGLIB_LEN(self), 0, fillchar); } static PyObject * stringlib_center(PyObject *self, PyObject *args) { Py_ssize_t marg, left; Py_ssize_t width; char fillchar = ' '; if (!PyArg_ParseTuple(args, "n|c:center", &width, &fillchar)) return NULL; if (STRINGLIB_LEN(self) >= width) { return return_self(self); } marg = width - STRINGLIB_LEN(self); left = marg / 2 + (marg & width & 1); return pad(self, left, marg - left, fillchar); } static PyObject * stringlib_zfill(PyObject *self, PyObject *args) { Py_ssize_t fill; PyObject *s; char *p; Py_ssize_t width; if (!PyArg_ParseTuple(args, "n:zfill", &width)) return NULL; if (STRINGLIB_LEN(self) >= width) { return return_self(self); } fill = width - STRINGLIB_LEN(self); s = pad(self, fill, 0, '0'); if (s == NULL) return NULL; p = STRINGLIB_STR(s); if (p[fill] == '+' || p[fill] == '-') { /* move sign to beginning of string */ p[0] = p[fill]; p[fill] = '0'; } return s; } /* find and count characters and substrings */ #define findchar(target, target_len, c) \ ((char *)memchr((const void *)(target), c, target_len)) static Py_ssize_t countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount) { Py_ssize_t count = 0; const char *start = target; const char *end = target + target_len; while ((start = findchar(start, end - start, c)) != NULL) { count++; if (count >= maxcount) break; start += 1; } return count; } /* Algorithms for different cases of string replacement */ /* len(self)>=1, from="", len(to)>=1, maxcount>=1 */ static PyObject * stringlib_replace_interleave(PyObject *self, const char *to_s, Py_ssize_t to_len, Py_ssize_t maxcount) { const char *self_s; char *result_s; Py_ssize_t self_len, result_len; Py_ssize_t count, i; PyObject *result; self_len = STRINGLIB_LEN(self); /* 1 at the end plus 1 after every character; count = min(maxcount, self_len + 1) */ if (maxcount <= self_len) { count = maxcount; } else { /* Can't overflow: self_len + 1 <= maxcount <= PY_SSIZE_T_MAX. */ count = self_len + 1; } /* Check for overflow */ /* result_len = count * to_len + self_len; */ assert(count > 0); if (to_len > (PY_SSIZE_T_MAX - self_len) / count) { PyErr_SetString(PyExc_OverflowError, "replace bytes are too long"); return NULL; } result_len = count * to_len + self_len; result = STRINGLIB_NEW(NULL, result_len); if (result == NULL) { return NULL; } self_s = STRINGLIB_STR(self); result_s = STRINGLIB_STR(result); if (to_len > 1) { /* Lay the first one down (guaranteed this will occur) */ memcpy(result_s, to_s, to_len); result_s += to_len; count -= 1; for (i = 0; i < count; i++) { *result_s++ = *self_s++; memcpy(result_s, to_s, to_len); result_s += to_len; } } else { result_s[0] = to_s[0]; result_s += to_len; count -= 1; for (i = 0; i < count; i++) { *result_s++ = *self_s++; result_s[0] = to_s[0]; result_s += to_len; } } /* Copy the rest of the original string */ memcpy(result_s, self_s, self_len - i); return result; } /* Special case for deleting a single character */ /* len(self)>=1, len(from)==1, to="", maxcount>=1 */ static PyObject * stringlib_replace_delete_single_character(PyObject *self, char from_c, Py_ssize_t maxcount) { const char *self_s, *start, *next, *end; char *result_s; Py_ssize_t self_len, result_len; Py_ssize_t count; PyObject *result; self_len = STRINGLIB_LEN(self); self_s = STRINGLIB_STR(self); count = countchar(self_s, self_len, from_c, maxcount); if (count == 0) { return return_self(self); } result_len = self_len - count; /* from_len == 1 */ assert(result_len>=0); result = STRINGLIB_NEW(NULL, result_len); if (result == NULL) { return NULL; } result_s = STRINGLIB_STR(result); start = self_s; end = self_s + self_len; while (count-- > 0) { next = findchar(start, end - start, from_c); if (next == NULL) break; memcpy(result_s, start, next - start); result_s += (next - start); start = next + 1; } memcpy(result_s, start, end - start); return result; } /* len(self)>=1, len(from)>=2, to="", maxcount>=1 */ static PyObject * stringlib_replace_delete_substring(PyObject *self, const char *from_s, Py_ssize_t from_len, Py_ssize_t maxcount) { const char *self_s, *start, *next, *end; char *result_s; Py_ssize_t self_len, result_len; Py_ssize_t count, offset; PyObject *result; self_len = STRINGLIB_LEN(self); self_s = STRINGLIB_STR(self); count = stringlib_count(self_s, self_len, from_s, from_len, maxcount); if (count == 0) { /* no matches */ return return_self(self); } result_len = self_len - (count * from_len); assert (result_len>=0); result = STRINGLIB_NEW(NULL, result_len); if (result == NULL) { return NULL; } result_s = STRINGLIB_STR(result); start = self_s; end = self_s + self_len; while (count-- > 0) { offset = stringlib_find(start, end - start, from_s, from_len, 0); if (offset == -1) break; next = start + offset; memcpy(result_s, start, next - start); result_s += (next - start); start = next + from_len; } memcpy(result_s, start, end - start); return result; } /* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */ static PyObject * stringlib_replace_single_character_in_place(PyObject *self, char from_c, char to_c, Py_ssize_t maxcount) { const char *self_s, *end; char *result_s, *start, *next; Py_ssize_t self_len; PyObject *result; /* The result string will be the same size */ self_s = STRINGLIB_STR(self); self_len = STRINGLIB_LEN(self); next = findchar(self_s, self_len, from_c); if (next == NULL) { /* No matches; return the original bytes */ return return_self(self); } /* Need to make a new bytes */ result = STRINGLIB_NEW(NULL, self_len); if (result == NULL) { return NULL; } result_s = STRINGLIB_STR(result); memcpy(result_s, self_s, self_len); /* change everything in-place, starting with this one */ start = result_s + (next - self_s); *start = to_c; start++; end = result_s + self_len; while (--maxcount > 0) { next = findchar(start, end - start, from_c); if (next == NULL) break; *next = to_c; start = next + 1; } return result; } /* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */ static PyObject * stringlib_replace_substring_in_place(PyObject *self, const char *from_s, Py_ssize_t from_len, const char *to_s, Py_ssize_t to_len, Py_ssize_t maxcount) { const char *self_s, *end; char *result_s, *start; Py_ssize_t self_len, offset; PyObject *result; /* The result bytes will be the same size */ self_s = STRINGLIB_STR(self); self_len = STRINGLIB_LEN(self); offset = stringlib_find(self_s, self_len, from_s, from_len, 0); if (offset == -1) { /* No matches; return the original bytes */ return return_self(self); } /* Need to make a new bytes */ result = STRINGLIB_NEW(NULL, self_len); if (result == NULL) { return NULL; } result_s = STRINGLIB_STR(result); memcpy(result_s, self_s, self_len); /* change everything in-place, starting with this one */ start = result_s + offset; memcpy(start, to_s, from_len); start += from_len; end = result_s + self_len; while ( --maxcount > 0) { offset = stringlib_find(start, end - start, from_s, from_len, 0); if (offset == -1) break; memcpy(start + offset, to_s, from_len); start += offset + from_len; } return result; } /* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */ static PyObject * stringlib_replace_single_character(PyObject *self, char from_c, const char *to_s, Py_ssize_t to_len, Py_ssize_t maxcount) { const char *self_s, *start, *next, *end; char *result_s; Py_ssize_t self_len, result_len; Py_ssize_t count; PyObject *result; self_s = STRINGLIB_STR(self); self_len = STRINGLIB_LEN(self); count = countchar(self_s, self_len, from_c, maxcount); if (count == 0) { /* no matches, return unchanged */ return return_self(self); } /* use the difference between current and new, hence the "-1" */ /* result_len = self_len + count * (to_len-1) */ assert(count > 0); if (to_len - 1 > (PY_SSIZE_T_MAX - self_len) / count) { PyErr_SetString(PyExc_OverflowError, "replace bytes is too long"); return NULL; } result_len = self_len + count * (to_len - 1); result = STRINGLIB_NEW(NULL, result_len); if (result == NULL) { return NULL; } result_s = STRINGLIB_STR(result); start = self_s; end = self_s + self_len; while (count-- > 0) { next = findchar(start, end - start, from_c); if (next == NULL) break; if (next == start) { /* replace with the 'to' */ memcpy(result_s, to_s, to_len); result_s += to_len; start += 1; } else { /* copy the unchanged old then the 'to' */ memcpy(result_s, start, next - start); result_s += (next - start); memcpy(result_s, to_s, to_len); result_s += to_len; start = next + 1; } } /* Copy the remainder of the remaining bytes */ memcpy(result_s, start, end - start); return result; } /* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */ static PyObject * stringlib_replace_substring(PyObject *self, const char *from_s, Py_ssize_t from_len, const char *to_s, Py_ssize_t to_len, Py_ssize_t maxcount) { const char *self_s, *start, *next, *end; char *result_s; Py_ssize_t self_len, result_len; Py_ssize_t count, offset; PyObject *result; self_s = STRINGLIB_STR(self); self_len = STRINGLIB_LEN(self); count = stringlib_count(self_s, self_len, from_s, from_len, maxcount); if (count == 0) { /* no matches, return unchanged */ return return_self(self); } /* Check for overflow */ /* result_len = self_len + count * (to_len-from_len) */ assert(count > 0); if (to_len - from_len > (PY_SSIZE_T_MAX - self_len) / count) { PyErr_SetString(PyExc_OverflowError, "replace bytes is too long"); return NULL; } result_len = self_len + count * (to_len - from_len); result = STRINGLIB_NEW(NULL, result_len); if (result == NULL) { return NULL; } result_s = STRINGLIB_STR(result); start = self_s; end = self_s + self_len; while (count-- > 0) { offset = stringlib_find(start, end - start, from_s, from_len, 0); if (offset == -1) break; next = start + offset; if (next == start) { /* replace with the 'to' */ memcpy(result_s, to_s, to_len); result_s += to_len; start += from_len; } else { /* copy the unchanged old then the 'to' */ memcpy(result_s, start, next - start); result_s += (next - start); memcpy(result_s, to_s, to_len); result_s += to_len; start = next + from_len; } } /* Copy the remainder of the remaining bytes */ memcpy(result_s, start, end - start); return result; } static PyObject * stringlib_replace(PyObject *self, const char *from_s, Py_ssize_t from_len, const char *to_s, Py_ssize_t to_len, Py_ssize_t maxcount) { if (maxcount < 0) { maxcount = PY_SSIZE_T_MAX; } else if (maxcount == 0 || STRINGLIB_LEN(self) == 0) { /* nothing to do; return the original bytes */ return return_self(self); } /* Handle zero-length special cases */ if (from_len == 0) { if (to_len == 0) { /* nothing to do; return the original bytes */ return return_self(self); } /* insert the 'to' bytes everywhere. */ /* >>> b"Python".replace(b"", b".") */ /* b'.P.y.t.h.o.n.' */ return stringlib_replace_interleave(self, to_s, to_len, maxcount); } /* Except for b"".replace(b"", b"A") == b"A" there is no way beyond this */ /* point for an empty self bytes to generate a non-empty bytes */ /* Special case so the remaining code always gets a non-empty bytes */ if (STRINGLIB_LEN(self) == 0) { return return_self(self); } if (to_len == 0) { /* delete all occurrences of 'from' bytes */ if (from_len == 1) { return stringlib_replace_delete_single_character( self, from_s[0], maxcount); } else { return stringlib_replace_delete_substring( self, from_s, from_len, maxcount); } } /* Handle special case where both bytes have the same length */ if (from_len == to_len) { if (from_len == 1) { return stringlib_replace_single_character_in_place( self, from_s[0], to_s[0], maxcount); } else { return stringlib_replace_substring_in_place( self, from_s, from_len, to_s, to_len, maxcount); } } /* Otherwise use the more generic algorithms */ if (from_len == 1) { return stringlib_replace_single_character( self, from_s[0], to_s, to_len, maxcount); } else { /* len('from')>=2, len('to')>=1 */ return stringlib_replace_substring( self, from_s, from_len, to_s, to_len, maxcount); } } #undef findchar
19,780
710
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/ctype.inc
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ #if STRINGLIB_IS_UNICODE # error "ctype.h only compatible with byte-wise strings" #endif #include "third_party/python/Include/bytes_methods.h" static PyObject* stringlib_isspace(PyObject *self) { return _Py_bytes_isspace(STRINGLIB_STR(self), STRINGLIB_LEN(self)); } static PyObject* stringlib_isalpha(PyObject *self) { return _Py_bytes_isalpha(STRINGLIB_STR(self), STRINGLIB_LEN(self)); } static PyObject* stringlib_isalnum(PyObject *self) { return _Py_bytes_isalnum(STRINGLIB_STR(self), STRINGLIB_LEN(self)); } static PyObject* stringlib_isdigit(PyObject *self) { return _Py_bytes_isdigit(STRINGLIB_STR(self), STRINGLIB_LEN(self)); } static PyObject* stringlib_islower(PyObject *self) { return _Py_bytes_islower(STRINGLIB_STR(self), STRINGLIB_LEN(self)); } static PyObject* stringlib_isupper(PyObject *self) { return _Py_bytes_isupper(STRINGLIB_STR(self), STRINGLIB_LEN(self)); } static PyObject* stringlib_istitle(PyObject *self) { return _Py_bytes_istitle(STRINGLIB_STR(self), STRINGLIB_LEN(self)); } /* functions that return a new object partially translated by ctype funcs: */ static PyObject* stringlib_lower(PyObject *self) { PyObject* newobj; newobj = STRINGLIB_NEW(NULL, STRINGLIB_LEN(self)); if (!newobj) return NULL; _Py_bytes_lower(STRINGLIB_STR(newobj), STRINGLIB_STR(self), STRINGLIB_LEN(self)); return newobj; } static PyObject* stringlib_upper(PyObject *self) { PyObject* newobj; newobj = STRINGLIB_NEW(NULL, STRINGLIB_LEN(self)); if (!newobj) return NULL; _Py_bytes_upper(STRINGLIB_STR(newobj), STRINGLIB_STR(self), STRINGLIB_LEN(self)); return newobj; } static PyObject* stringlib_title(PyObject *self) { PyObject* newobj; newobj = STRINGLIB_NEW(NULL, STRINGLIB_LEN(self)); if (!newobj) return NULL; _Py_bytes_title(STRINGLIB_STR(newobj), STRINGLIB_STR(self), STRINGLIB_LEN(self)); return newobj; } static PyObject* stringlib_capitalize(PyObject *self) { PyObject* newobj; newobj = STRINGLIB_NEW(NULL, STRINGLIB_LEN(self)); if (!newobj) return NULL; _Py_bytes_capitalize(STRINGLIB_STR(newobj), STRINGLIB_STR(self), STRINGLIB_LEN(self)); return newobj; } static PyObject* stringlib_swapcase(PyObject *self) { PyObject* newobj; newobj = STRINGLIB_NEW(NULL, STRINGLIB_LEN(self)); if (!newobj) return NULL; _Py_bytes_swapcase(STRINGLIB_STR(newobj), STRINGLIB_STR(self), STRINGLIB_LEN(self)); return newobj; }
3,459
119
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/unicodedefs.inc
#ifndef STRINGLIB_UNICODEDEFS_H #define STRINGLIB_UNICODEDEFS_H /* this is sort of a hack. there's at least one place (formatting floats) where some stringlib code takes a different path if it's compiled as unicode. */ #define STRINGLIB_IS_UNICODE 1 #define FASTSEARCH fastsearch #define STRINGLIB(F) stringlib_##F #define STRINGLIB_OBJECT PyUnicodeObject #define STRINGLIB_SIZEOF_CHAR Py_UNICODE_SIZE #define STRINGLIB_CHAR Py_UNICODE #define STRINGLIB_TYPE_NAME "unicode" #define STRINGLIB_PARSE_CODE "U" #define STRINGLIB_EMPTY unicode_empty #define STRINGLIB_ISSPACE Py_UNICODE_ISSPACE #define STRINGLIB_ISLINEBREAK BLOOM_LINEBREAK #define STRINGLIB_ISDECIMAL Py_UNICODE_ISDECIMAL #define STRINGLIB_TODECIMAL Py_UNICODE_TODECIMAL #define STRINGLIB_STR PyUnicode_AS_UNICODE #define STRINGLIB_LEN PyUnicode_GET_SIZE #define STRINGLIB_NEW PyUnicode_FromUnicode #define STRINGLIB_CHECK PyUnicode_Check #define STRINGLIB_CHECK_EXACT PyUnicode_CheckExact #define STRINGLIB_TOSTR PyObject_Str #define STRINGLIB_TOASCII PyObject_ASCII #define STRINGLIB_WANT_CONTAINS_OBJ 1 #endif /* !STRINGLIB_UNICODEDEFS_H */
1,200
33
jart/cosmopolitan
false