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/Objects/stringlib/ucs1lib.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 */ /* 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 ucs1lib_fastsearch #define STRINGLIB(F) ucs1lib_##F #define STRINGLIB_OBJECT PyUnicodeObject #define STRINGLIB_SIZEOF_CHAR 1 #define STRINGLIB_MAX_CHAR 0xFFu #define STRINGLIB_CHAR Py_UCS1 #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_1BYTE_DATA #define STRINGLIB_LEN PyUnicode_GET_LENGTH #define STRINGLIB_NEW _PyUnicode_FromUCS1 #define STRINGLIB_CHECK PyUnicode_Check #define STRINGLIB_CHECK_EXACT PyUnicode_CheckExact #define STRINGLIB_TOSTR PyObject_Str #define STRINGLIB_TOASCII PyObject_ASCII #define _Py_InsertThousandsGrouping _PyUnicode_ucs1_InsertThousandsGrouping
2,073
39
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/partition.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 */ /* stringlib: partition implementation */ #ifndef STRINGLIB_FASTSEARCH_H #error must include fastsearch.inc before including this module #endif Py_LOCAL_INLINE(PyObject*) STRINGLIB(partition)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, PyObject* sep_obj, const STRINGLIB_CHAR* sep, Py_ssize_t sep_len) { PyObject* out; Py_ssize_t pos; if (sep_len == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); return NULL; } out = PyTuple_New(3); if (!out) return NULL; pos = FASTSEARCH(str, str_len, sep, sep_len, -1, FAST_SEARCH); if (pos < 0) { #if STRINGLIB_MUTABLE PyTuple_SET_ITEM(out, 0, STRINGLIB_NEW(str, str_len)); PyTuple_SET_ITEM(out, 1, STRINGLIB_NEW(NULL, 0)); PyTuple_SET_ITEM(out, 2, STRINGLIB_NEW(NULL, 0)); if (PyErr_Occurred()) { Py_DECREF(out); return NULL; } #else Py_INCREF(str_obj); PyTuple_SET_ITEM(out, 0, (PyObject*) str_obj); Py_INCREF(STRINGLIB_EMPTY); PyTuple_SET_ITEM(out, 1, (PyObject*) STRINGLIB_EMPTY); Py_INCREF(STRINGLIB_EMPTY); PyTuple_SET_ITEM(out, 2, (PyObject*) STRINGLIB_EMPTY); #endif return out; } PyTuple_SET_ITEM(out, 0, STRINGLIB_NEW(str, pos)); Py_INCREF(sep_obj); PyTuple_SET_ITEM(out, 1, sep_obj); pos += sep_len; PyTuple_SET_ITEM(out, 2, STRINGLIB_NEW(str + pos, str_len - pos)); if (PyErr_Occurred()) { Py_DECREF(out); return NULL; } return out; } Py_LOCAL_INLINE(PyObject*) STRINGLIB(rpartition)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, PyObject* sep_obj, const STRINGLIB_CHAR* sep, Py_ssize_t sep_len) { PyObject* out; Py_ssize_t pos; if (sep_len == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); return NULL; } out = PyTuple_New(3); if (!out) return NULL; pos = FASTSEARCH(str, str_len, sep, sep_len, -1, FAST_RSEARCH); if (pos < 0) { #if STRINGLIB_MUTABLE PyTuple_SET_ITEM(out, 0, STRINGLIB_NEW(NULL, 0)); PyTuple_SET_ITEM(out, 1, STRINGLIB_NEW(NULL, 0)); PyTuple_SET_ITEM(out, 2, STRINGLIB_NEW(str, str_len)); if (PyErr_Occurred()) { Py_DECREF(out); return NULL; } #else Py_INCREF(STRINGLIB_EMPTY); PyTuple_SET_ITEM(out, 0, (PyObject*) STRINGLIB_EMPTY); Py_INCREF(STRINGLIB_EMPTY); PyTuple_SET_ITEM(out, 1, (PyObject*) STRINGLIB_EMPTY); Py_INCREF(str_obj); PyTuple_SET_ITEM(out, 2, (PyObject*) str_obj); #endif return out; } PyTuple_SET_ITEM(out, 0, STRINGLIB_NEW(str, pos)); Py_INCREF(sep_obj); PyTuple_SET_ITEM(out, 1, sep_obj); pos += sep_len; PyTuple_SET_ITEM(out, 2, STRINGLIB_NEW(str + pos, str_len - pos)); if (PyErr_Occurred()) { Py_DECREF(out); return NULL; } return out; }
3,935
125
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/ucs2lib.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 */ /* 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 ucs2lib_fastsearch #define STRINGLIB(F) ucs2lib_##F #define STRINGLIB_OBJECT PyUnicodeObject #define STRINGLIB_SIZEOF_CHAR 2 #define STRINGLIB_MAX_CHAR 0xFFFFu #define STRINGLIB_CHAR Py_UCS2 #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_2BYTE_DATA #define STRINGLIB_LEN PyUnicode_GET_LENGTH #define STRINGLIB_NEW _PyUnicode_FromUCS2 #define STRINGLIB_CHECK PyUnicode_Check #define STRINGLIB_CHECK_EXACT PyUnicode_CheckExact #define STRINGLIB_TOSTR PyObject_Str #define STRINGLIB_TOASCII PyObject_ASCII #define _Py_InsertThousandsGrouping _PyUnicode_ucs2_InsertThousandsGrouping
2,074
38
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/localeutil.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 */ /* _PyUnicode_InsertThousandsGrouping() helper functions */ typedef struct { const char *grouping; char previous; Py_ssize_t i; /* Where we're currently pointing in grouping. */ } GroupGenerator; static void GroupGenerator_init(GroupGenerator *self, const char *grouping) { self->grouping = grouping; self->i = 0; self->previous = 0; } /* Returns the next grouping, or 0 to signify end. */ static Py_ssize_t GroupGenerator_next(GroupGenerator *self) { /* Note that we don't really do much error checking here. If a grouping string contains just CHAR_MAX, for example, then just terminate the generator. That shouldn't happen, but at least we fail gracefully. */ switch (self->grouping[self->i]) { case 0: return self->previous; case CHAR_MAX: /* Stop the generator. */ return 0; default: { char ch = self->grouping[self->i]; self->previous = ch; self->i++; return (Py_ssize_t)ch; } } } /* Fill in some digits, leading zeros, and thousands separator. All are optional, depending on when we're called. */ static void InsertThousandsGrouping_fill(_PyUnicodeWriter *writer, Py_ssize_t *buffer_pos, PyObject *digits, Py_ssize_t *digits_pos, Py_ssize_t n_chars, Py_ssize_t n_zeros, PyObject *thousands_sep, Py_ssize_t thousands_sep_len, Py_UCS4 *maxchar) { if (!writer) { /* if maxchar > 127, maxchar is already set */ if (*maxchar == 127 && thousands_sep) { Py_UCS4 maxchar2 = PyUnicode_MAX_CHAR_VALUE(thousands_sep); *maxchar = Py_MAX(*maxchar, maxchar2); } return; } if (thousands_sep) { *buffer_pos -= thousands_sep_len; /* Copy the thousands_sep chars into the buffer. */ _PyUnicode_FastCopyCharacters(writer->buffer, *buffer_pos, thousands_sep, 0, thousands_sep_len); } *buffer_pos -= n_chars; *digits_pos -= n_chars; _PyUnicode_FastCopyCharacters(writer->buffer, *buffer_pos, digits, *digits_pos, n_chars); if (n_zeros) { *buffer_pos -= n_zeros; enum PyUnicode_Kind kind = PyUnicode_KIND(writer->buffer); void *data = PyUnicode_DATA(writer->buffer); FILL(kind, data, '0', *buffer_pos, n_zeros); } }
3,391
91
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/find.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 │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/modsupport.h" /* clang-format off */ /* stringlib: find/index implementation */ #ifndef STRINGLIB_FASTSEARCH_H #error must include fastsearch.inc before including this module #endif Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(find)(const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR* sub, Py_ssize_t sub_len, Py_ssize_t offset) { Py_ssize_t pos; assert(str_len >= 0); if (sub_len == 0) return offset; pos = FASTSEARCH(str, str_len, sub, sub_len, -1, FAST_SEARCH); if (pos >= 0) pos += offset; return pos; } Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(rfind)(const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR* sub, Py_ssize_t sub_len, Py_ssize_t offset) { Py_ssize_t pos; assert(str_len >= 0); if (sub_len == 0) return str_len + offset; pos = FASTSEARCH(str, str_len, sub, sub_len, -1, FAST_RSEARCH); if (pos >= 0) pos += offset; return pos; } Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(find_slice)(const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR* sub, Py_ssize_t sub_len, Py_ssize_t start, Py_ssize_t end) { return STRINGLIB(find)(str + start, end - start, sub, sub_len, start); } Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(rfind_slice)(const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR* sub, Py_ssize_t sub_len, Py_ssize_t start, Py_ssize_t end) { return STRINGLIB(rfind)(str + start, end - start, sub, sub_len, start); } #ifdef STRINGLIB_WANT_CONTAINS_OBJ Py_LOCAL_INLINE(int) STRINGLIB(contains_obj)(PyObject* str, PyObject* sub) { return STRINGLIB(find)( STRINGLIB_STR(str), STRINGLIB_LEN(str), STRINGLIB_STR(sub), STRINGLIB_LEN(sub), 0 ) != -1; } #endif /* STRINGLIB_WANT_CONTAINS_OBJ */ /* This function is a helper for the "find" family (find, rfind, index, rindex) and for count, startswith and endswith, because they all have the same behaviour for the arguments. It does not touch the variables received until it knows everything is ok. */ #define FORMAT_BUFFER_SIZE 50 Py_LOCAL_INLINE(int) STRINGLIB(parse_args_finds)(const char * function_name, PyObject *args, PyObject **subobj, Py_ssize_t *start, Py_ssize_t *end) { PyObject *tmp_subobj; Py_ssize_t tmp_start = 0; Py_ssize_t tmp_end = PY_SSIZE_T_MAX; PyObject *obj_start=Py_None, *obj_end=Py_None; char format[FORMAT_BUFFER_SIZE] = "O|OO:"; size_t len = strlen(format); strncpy(format + len, function_name, FORMAT_BUFFER_SIZE - len - 1); format[FORMAT_BUFFER_SIZE - 1] = '\0'; if (!PyArg_ParseTuple(args, format, &tmp_subobj, &obj_start, &obj_end)) return 0; /* To support None in "start" and "end" arguments, meaning the same as if they were not passed. */ if (obj_start != Py_None) if (!_PyEval_SliceIndex(obj_start, &tmp_start)) return 0; if (obj_end != Py_None) if (!_PyEval_SliceIndex(obj_end, &tmp_end)) return 0; *start = tmp_start; *end = tmp_end; *subobj = tmp_subobj; return 1; } #undef FORMAT_BUFFER_SIZE
4,151
129
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/find_max_char.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 */ /* Finding the optimal width of unicode characters in a buffer */ #if !STRINGLIB_IS_UNICODE # error "find_max_char.h is specific to Unicode" #endif /* Mask to quickly check whether a C 'long' contains a non-ASCII, UTF8-encoded char. */ #if (SIZEOF_LONG == 8) # define UCS1_ASCII_CHAR_MASK 0x8080808080808080UL #elif (SIZEOF_LONG == 4) # define UCS1_ASCII_CHAR_MASK 0x80808080UL #else # error C 'long' size should be either 4 or 8! #endif #if STRINGLIB_SIZEOF_CHAR == 1 Py_LOCAL_INLINE(Py_UCS4) STRINGLIB(find_max_char)(const STRINGLIB_CHAR *begin, const STRINGLIB_CHAR *end) { const unsigned char *p = (const unsigned char *) begin; const unsigned char *aligned_end = (const unsigned char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG); while (p < end) { if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) { /* Help register allocation */ const unsigned char *_p = p; while (_p < aligned_end) { unsigned long value = *(unsigned long *) _p; if (value & UCS1_ASCII_CHAR_MASK) return 255; _p += SIZEOF_LONG; } p = _p; if (p == end) break; } if (*p++ & 0x80) return 255; } return 127; } #undef ASCII_CHAR_MASK #else /* STRINGLIB_SIZEOF_CHAR == 1 */ #define MASK_ASCII 0xFFFFFF80 #define MASK_UCS1 0xFFFFFF00 #define MASK_UCS2 0xFFFF0000 #define MAX_CHAR_ASCII 0x7f #define MAX_CHAR_UCS1 0xff #define MAX_CHAR_UCS2 0xffff #define MAX_CHAR_UCS4 0x10ffff Py_LOCAL_INLINE(Py_UCS4) STRINGLIB(find_max_char)(const STRINGLIB_CHAR *begin, const STRINGLIB_CHAR *end) { #if STRINGLIB_SIZEOF_CHAR == 2 const Py_UCS4 mask_limit = MASK_UCS1; const Py_UCS4 max_char_limit = MAX_CHAR_UCS2; #elif STRINGLIB_SIZEOF_CHAR == 4 const Py_UCS4 mask_limit = MASK_UCS2; const Py_UCS4 max_char_limit = MAX_CHAR_UCS4; #else #error Invalid STRINGLIB_SIZEOF_CHAR (must be 1, 2 or 4) #endif Py_UCS4 mask; Py_ssize_t n = end - begin; const STRINGLIB_CHAR *p = begin; const STRINGLIB_CHAR *unrolled_end = begin + _Py_SIZE_ROUND_DOWN(n, 4); Py_UCS4 max_char; max_char = MAX_CHAR_ASCII; mask = MASK_ASCII; while (p < unrolled_end) { STRINGLIB_CHAR bits = p[0] | p[1] | p[2] | p[3]; if (bits & mask) { if (mask == mask_limit) { /* Limit reached */ return max_char_limit; } if (mask == MASK_ASCII) { max_char = MAX_CHAR_UCS1; mask = MASK_UCS1; } else { /* mask can't be MASK_UCS2 because of mask_limit above */ assert(mask == MASK_UCS1); max_char = MAX_CHAR_UCS2; mask = MASK_UCS2; } /* We check the new mask on the same chars in the next iteration */ continue; } p += 4; } while (p < end) { if (p[0] & mask) { if (mask == mask_limit) { /* Limit reached */ return max_char_limit; } if (mask == MASK_ASCII) { max_char = MAX_CHAR_UCS1; mask = MASK_UCS1; } else { /* mask can't be MASK_UCS2 because of mask_limit above */ assert(mask == MASK_UCS1); max_char = MAX_CHAR_UCS2; mask = MASK_UCS2; } /* We check the new mask on the same chars in the next iteration */ continue; } p++; } return max_char; } #undef MASK_ASCII #undef MASK_UCS1 #undef MASK_UCS2 #undef MAX_CHAR_ASCII #undef MAX_CHAR_UCS1 #undef MAX_CHAR_UCS2 #undef MAX_CHAR_UCS4 #endif /* STRINGLIB_SIZEOF_CHAR == 1 */
4,662
143
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/stringdefs.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 */ #ifndef STRINGLIB_STRINGDEFS_H #define STRINGLIB_STRINGDEFS_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 0 #define FASTSEARCH fastsearch #define STRINGLIB(F) stringlib_##F #define STRINGLIB_OBJECT PyBytesObject #define STRINGLIB_SIZEOF_CHAR 1 #define STRINGLIB_CHAR char #define STRINGLIB_TYPE_NAME "string" #define STRINGLIB_PARSE_CODE "S" #define STRINGLIB_EMPTY nullstring #define STRINGLIB_ISSPACE Py_ISSPACE #define STRINGLIB_ISLINEBREAK(x) ((x == '\n') || (x == '\r')) #define STRINGLIB_ISDECIMAL(x) ((x >= '0') && (x <= '9')) #define STRINGLIB_TODECIMAL(x) (STRINGLIB_ISDECIMAL(x) ? (x - '0') : -1) #define STRINGLIB_STR PyBytes_AS_STRING #define STRINGLIB_LEN PyBytes_GET_SIZE #define STRINGLIB_NEW PyBytes_FromStringAndSize #define STRINGLIB_CHECK PyBytes_Check #define STRINGLIB_CHECK_EXACT PyBytes_CheckExact #define STRINGLIB_TOSTR PyObject_Str #define STRINGLIB_TOASCII PyObject_Repr #endif /* !STRINGLIB_STRINGDEFS_H */
2,039
37
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/replace.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 */ /* stringlib: replace implementation */ #ifndef STRINGLIB_FASTSEARCH_H #error must include fastsearch.inc before including this module #endif Py_LOCAL_INLINE(void) STRINGLIB(replace_1char_inplace)(STRINGLIB_CHAR* s, STRINGLIB_CHAR* end, Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount) { *s = u2; while (--maxcount && ++s != end) { /* Find the next character to be replaced. If it occurs often, it is faster to scan for it using an inline loop. If it occurs seldom, it is faster to scan for it using a function call; the overhead of the function call is amortized across the many characters that call covers. We start with an inline loop and use a heuristic to determine whether to fall back to a function call. */ if (*s != u1) { int attempts = 10; /* search u1 in a dummy loop */ while (1) { if (++s == end) return; if (*s == u1) break; if (!--attempts) { /* if u1 was not found for attempts iterations, use FASTSEARCH() or memchr() */ #if STRINGLIB_SIZEOF_CHAR == 1 s++; s = memchr(s, u1, end - s); if (s == NULL) return; #else Py_ssize_t i; STRINGLIB_CHAR ch1 = (STRINGLIB_CHAR) u1; s++; i = FASTSEARCH(s, end - s, &ch1, 1, 0, FAST_SEARCH); if (i < 0) return; s += i; #endif /* restart the dummy loop */ break; } } } *s = u2; } }
2,681
62
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/codecs.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 */ /* stringlib: codec implementations */ #if !STRINGLIB_IS_UNICODE # error "codecs.h is specific to Unicode" #endif /* 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 /* 10xxxxxx */ #define IS_CONTINUATION_BYTE(ch) ((ch) >= 0x80 && (ch) < 0xC0) Py_LOCAL_INLINE(Py_UCS4) STRINGLIB(utf8_decode)(const char **inptr, const char *end, STRINGLIB_CHAR *dest, Py_ssize_t *outpos) { Py_UCS4 ch; const char *s = *inptr; const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG); STRINGLIB_CHAR *p = dest + *outpos; while (s < end) { ch = (unsigned char)*s; if (ch < 0x80) { /* Fast path for runs of ASCII characters. Given that common UTF-8 input will consist of an overwhelming majority of ASCII characters, we try to optimize for this case by checking as many characters as a C 'long' can contain. First, check if we can do an aligned read, as most CPUs have a penalty for unaligned reads. */ if (_Py_IS_ALIGNED(s, SIZEOF_LONG)) { /* Help register allocation */ const char *_s = s; STRINGLIB_CHAR *_p = p; while (_s < aligned_end) { /* Read a whole long at a time (either 4 or 8 bytes), and do a fast unrolled copy if it only contains ASCII characters. */ unsigned long value = *(unsigned long *) _s; if (value & ASCII_CHAR_MASK) break; #if PY_LITTLE_ENDIAN _p[0] = (STRINGLIB_CHAR)(value & 0xFFu); _p[1] = (STRINGLIB_CHAR)((value >> 8) & 0xFFu); _p[2] = (STRINGLIB_CHAR)((value >> 16) & 0xFFu); _p[3] = (STRINGLIB_CHAR)((value >> 24) & 0xFFu); # if SIZEOF_LONG == 8 _p[4] = (STRINGLIB_CHAR)((value >> 32) & 0xFFu); _p[5] = (STRINGLIB_CHAR)((value >> 40) & 0xFFu); _p[6] = (STRINGLIB_CHAR)((value >> 48) & 0xFFu); _p[7] = (STRINGLIB_CHAR)((value >> 56) & 0xFFu); # endif #else # if SIZEOF_LONG == 8 _p[0] = (STRINGLIB_CHAR)((value >> 56) & 0xFFu); _p[1] = (STRINGLIB_CHAR)((value >> 48) & 0xFFu); _p[2] = (STRINGLIB_CHAR)((value >> 40) & 0xFFu); _p[3] = (STRINGLIB_CHAR)((value >> 32) & 0xFFu); _p[4] = (STRINGLIB_CHAR)((value >> 24) & 0xFFu); _p[5] = (STRINGLIB_CHAR)((value >> 16) & 0xFFu); _p[6] = (STRINGLIB_CHAR)((value >> 8) & 0xFFu); _p[7] = (STRINGLIB_CHAR)(value & 0xFFu); # else _p[0] = (STRINGLIB_CHAR)((value >> 24) & 0xFFu); _p[1] = (STRINGLIB_CHAR)((value >> 16) & 0xFFu); _p[2] = (STRINGLIB_CHAR)((value >> 8) & 0xFFu); _p[3] = (STRINGLIB_CHAR)(value & 0xFFu); # endif #endif _s += SIZEOF_LONG; _p += SIZEOF_LONG; } s = _s; p = _p; if (s == end) break; ch = (unsigned char)*s; } if (ch < 0x80) { s++; *p++ = ch; continue; } } if (ch < 0xE0) { /* \xC2\x80-\xDF\xBF -- 0080-07FF */ Py_UCS4 ch2; if (ch < 0xC2) { /* invalid sequence \x80-\xBF -- continuation byte \xC0-\xC1 -- fake 0000-007F */ goto InvalidStart; } if (end - s < 2) { /* unexpected end of data: the caller will decide whether it's an error or not */ break; } ch2 = (unsigned char)s[1]; if (!IS_CONTINUATION_BYTE(ch2)) /* invalid continuation byte */ goto InvalidContinuation1; ch = (ch << 6) + ch2 - ((0xC0 << 6) + 0x80); assert ((ch > 0x007F) && (ch <= 0x07FF)); s += 2; if (STRINGLIB_MAX_CHAR <= 0x007F || (STRINGLIB_MAX_CHAR < 0x07FF && ch > STRINGLIB_MAX_CHAR)) /* Out-of-range */ goto Return; *p++ = ch; continue; } if (ch < 0xF0) { /* \xE0\xA0\x80-\xEF\xBF\xBF -- 0800-FFFF */ Py_UCS4 ch2, ch3; if (end - s < 3) { /* unexpected end of data: the caller will decide whether it's an error or not */ if (end - s < 2) break; ch2 = (unsigned char)s[1]; if (!IS_CONTINUATION_BYTE(ch2) || (ch2 < 0xA0 ? ch == 0xE0 : ch == 0xED)) /* for clarification see comments below */ goto InvalidContinuation1; break; } ch2 = (unsigned char)s[1]; ch3 = (unsigned char)s[2]; if (!IS_CONTINUATION_BYTE(ch2)) { /* invalid continuation byte */ goto InvalidContinuation1; } if (ch == 0xE0) { if (ch2 < 0xA0) /* invalid sequence \xE0\x80\x80-\xE0\x9F\xBF -- fake 0000-0800 */ goto InvalidContinuation1; } else if (ch == 0xED && ch2 >= 0xA0) { /* Decoding UTF-8 sequences in range \xED\xA0\x80-\xED\xBF\xBF will result in surrogates in range D800-DFFF. Surrogates are not valid UTF-8 so they are rejected. See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */ goto InvalidContinuation1; } if (!IS_CONTINUATION_BYTE(ch3)) { /* invalid continuation byte */ goto InvalidContinuation2; } ch = (ch << 12) + (ch2 << 6) + ch3 - ((0xE0 << 12) + (0x80 << 6) + 0x80); assert ((ch > 0x07FF) && (ch <= 0xFFFF)); s += 3; if (STRINGLIB_MAX_CHAR <= 0x07FF || (STRINGLIB_MAX_CHAR < 0xFFFF && ch > STRINGLIB_MAX_CHAR)) /* Out-of-range */ goto Return; *p++ = ch; continue; } if (ch < 0xF5) { /* \xF0\x90\x80\x80-\xF4\x8F\xBF\xBF -- 10000-10FFFF */ Py_UCS4 ch2, ch3, ch4; if (end - s < 4) { /* unexpected end of data: the caller will decide whether it's an error or not */ if (end - s < 2) break; ch2 = (unsigned char)s[1]; if (!IS_CONTINUATION_BYTE(ch2) || (ch2 < 0x90 ? ch == 0xF0 : ch == 0xF4)) /* for clarification see comments below */ goto InvalidContinuation1; if (end - s < 3) break; ch3 = (unsigned char)s[2]; if (!IS_CONTINUATION_BYTE(ch3)) goto InvalidContinuation2; break; } ch2 = (unsigned char)s[1]; ch3 = (unsigned char)s[2]; ch4 = (unsigned char)s[3]; if (!IS_CONTINUATION_BYTE(ch2)) { /* invalid continuation byte */ goto InvalidContinuation1; } if (ch == 0xF0) { if (ch2 < 0x90) /* invalid sequence \xF0\x80\x80\x80-\xF0\x8F\xBF\xBF -- fake 0000-FFFF */ goto InvalidContinuation1; } else if (ch == 0xF4 && ch2 >= 0x90) { /* invalid sequence \xF4\x90\x80\80- -- 110000- overflow */ goto InvalidContinuation1; } if (!IS_CONTINUATION_BYTE(ch3)) { /* invalid continuation byte */ goto InvalidContinuation2; } if (!IS_CONTINUATION_BYTE(ch4)) { /* invalid continuation byte */ goto InvalidContinuation3; } ch = (ch << 18) + (ch2 << 12) + (ch3 << 6) + ch4 - ((0xF0 << 18) + (0x80 << 12) + (0x80 << 6) + 0x80); assert ((ch > 0xFFFF) && (ch <= 0x10FFFF)); s += 4; if (STRINGLIB_MAX_CHAR <= 0xFFFF || (STRINGLIB_MAX_CHAR < 0x10FFFF && ch > STRINGLIB_MAX_CHAR)) /* Out-of-range */ goto Return; *p++ = ch; continue; } goto InvalidStart; } ch = 0; Return: *inptr = s; *outpos = p - dest; return ch; InvalidStart: ch = 1; goto Return; InvalidContinuation1: ch = 2; goto Return; InvalidContinuation2: ch = 3; goto Return; InvalidContinuation3: ch = 4; goto Return; } #undef ASCII_CHAR_MASK /* UTF-8 encoder specialized for a Unicode kind to avoid the slow PyUnicode_READ() macro. Delete some parts of the code depending on the kind: UCS-1 strings don't need to handle surrogates for example. */ Py_LOCAL_INLINE(PyObject *) STRINGLIB(utf8_encoder)(PyObject *unicode, STRINGLIB_CHAR *data, Py_ssize_t size, const char *errors) { Py_ssize_t i; /* index into data of next input character */ char *p; /* next free byte in output buffer */ #if STRINGLIB_SIZEOF_CHAR > 1 PyObject *error_handler_obj = NULL; PyObject *exc = NULL; PyObject *rep = NULL; _Py_error_handler error_handler = _Py_ERROR_UNKNOWN; #endif #if STRINGLIB_SIZEOF_CHAR == 1 const Py_ssize_t max_char_size = 2; #elif STRINGLIB_SIZEOF_CHAR == 2 const Py_ssize_t max_char_size = 3; #else /* STRINGLIB_SIZEOF_CHAR == 4 */ const Py_ssize_t max_char_size = 4; #endif _PyBytesWriter writer; assert(size >= 0); _PyBytesWriter_Init(&writer); if (size > PY_SSIZE_T_MAX / max_char_size) { /* integer overflow */ return PyErr_NoMemory(); } p = _PyBytesWriter_Alloc(&writer, size * max_char_size); if (p == NULL) return NULL; for (i = 0; i < size;) { Py_UCS4 ch = data[i++]; if (ch < 0x80) { /* Encode ASCII */ *p++ = (char) ch; } else #if STRINGLIB_SIZEOF_CHAR > 1 if (ch < 0x0800) #endif { /* Encode Latin-1 */ *p++ = (char)(0xc0 | (ch >> 6)); *p++ = (char)(0x80 | (ch & 0x3f)); } #if STRINGLIB_SIZEOF_CHAR > 1 else if (Py_UNICODE_IS_SURROGATE(ch)) { Py_ssize_t startpos, endpos, newpos; Py_ssize_t k; if (error_handler == _Py_ERROR_UNKNOWN) { error_handler = get_error_handler(errors); } startpos = i-1; endpos = startpos+1; while ((endpos < size) && Py_UNICODE_IS_SURROGATE(data[endpos])) endpos++; /* Only overallocate the buffer if it's not the last write */ writer.overallocate = (endpos < size); switch (error_handler) { case _Py_ERROR_REPLACE: memset(p, '?', endpos - startpos); p += (endpos - startpos); /* fall through */ case _Py_ERROR_IGNORE: i += (endpos - startpos - 1); break; case _Py_ERROR_SURROGATEPASS: for (k=startpos; k<endpos; k++) { ch = data[k]; *p++ = (char)(0xe0 | (ch >> 12)); *p++ = (char)(0x80 | ((ch >> 6) & 0x3f)); *p++ = (char)(0x80 | (ch & 0x3f)); } i += (endpos - startpos - 1); break; case _Py_ERROR_BACKSLASHREPLACE: /* subtract preallocated bytes */ writer.min_size -= max_char_size * (endpos - startpos); p = backslashreplace(&writer, p, unicode, startpos, endpos); if (p == NULL) goto error; i += (endpos - startpos - 1); break; case _Py_ERROR_XMLCHARREFREPLACE: /* subtract preallocated bytes */ writer.min_size -= max_char_size * (endpos - startpos); p = xmlcharrefreplace(&writer, p, unicode, startpos, endpos); if (p == NULL) goto error; i += (endpos - startpos - 1); break; case _Py_ERROR_SURROGATEESCAPE: for (k=startpos; k<endpos; k++) { ch = data[k]; if (!(0xDC80 <= ch && ch <= 0xDCFF)) break; *p++ = (char)(ch & 0xff); } if (k >= endpos) { i += (endpos - startpos - 1); break; } startpos = k; assert(startpos < endpos); /* fall through */ default: rep = unicode_encode_call_errorhandler( errors, &error_handler_obj, "utf-8", "surrogates not allowed", unicode, &exc, startpos, endpos, &newpos); if (!rep) goto error; /* subtract preallocated bytes */ writer.min_size -= max_char_size * (newpos - startpos); if (PyBytes_Check(rep)) { p = _PyBytesWriter_WriteBytes(&writer, p, PyBytes_AS_STRING(rep), PyBytes_GET_SIZE(rep)); } else { /* rep is unicode */ if (PyUnicode_READY(rep) < 0) goto error; if (!PyUnicode_IS_ASCII(rep)) { raise_encode_exception(&exc, "utf-8", unicode, startpos, endpos, "surrogates not allowed"); goto error; } p = _PyBytesWriter_WriteBytes(&writer, p, PyUnicode_DATA(rep), PyUnicode_GET_LENGTH(rep)); } if (p == NULL) goto error; Py_CLEAR(rep); i = newpos; } /* If overallocation was disabled, ensure that it was the last write. Otherwise, we missed an optimization */ assert(writer.overallocate || i == size); } else #if STRINGLIB_SIZEOF_CHAR > 2 if (ch < 0x10000) #endif { *p++ = (char)(0xe0 | (ch >> 12)); *p++ = (char)(0x80 | ((ch >> 6) & 0x3f)); *p++ = (char)(0x80 | (ch & 0x3f)); } #if STRINGLIB_SIZEOF_CHAR > 2 else /* ch >= 0x10000 */ { assert(ch <= MAX_UNICODE); /* Encode UCS4 Unicode ordinals */ *p++ = (char)(0xf0 | (ch >> 18)); *p++ = (char)(0x80 | ((ch >> 12) & 0x3f)); *p++ = (char)(0x80 | ((ch >> 6) & 0x3f)); *p++ = (char)(0x80 | (ch & 0x3f)); } #endif /* STRINGLIB_SIZEOF_CHAR > 2 */ #endif /* STRINGLIB_SIZEOF_CHAR > 1 */ } #if STRINGLIB_SIZEOF_CHAR > 1 Py_XDECREF(error_handler_obj); Py_XDECREF(exc); #endif return _PyBytesWriter_Finish(&writer, p); #if STRINGLIB_SIZEOF_CHAR > 1 error: Py_XDECREF(rep); Py_XDECREF(error_handler_obj); Py_XDECREF(exc); _PyBytesWriter_Dealloc(&writer); return NULL; #endif } /* The pattern for constructing UCS2-repeated masks. */ #if SIZEOF_LONG == 8 # define UCS2_REPEAT_MASK 0x0001000100010001ul #elif SIZEOF_LONG == 4 # define UCS2_REPEAT_MASK 0x00010001ul #else # error C 'long' size should be either 4 or 8! #endif /* The mask for fast checking. */ #if STRINGLIB_SIZEOF_CHAR == 1 /* The mask for fast checking of whether a C 'long' contains a non-ASCII or non-Latin1 UTF16-encoded characters. */ # define FAST_CHAR_MASK (UCS2_REPEAT_MASK * (0xFFFFu & ~STRINGLIB_MAX_CHAR)) #else /* The mask for fast checking of whether a C 'long' may contain UTF16-encoded surrogate characters. This is an efficient heuristic, assuming that non-surrogate characters with a code point >= 0x8000 are rare in most input. */ # define FAST_CHAR_MASK (UCS2_REPEAT_MASK * 0x8000u) #endif /* The mask for fast byte-swapping. */ #define STRIPPED_MASK (UCS2_REPEAT_MASK * 0x00FFu) /* Swap bytes. */ #define SWAB(value) ((((value) >> 8) & STRIPPED_MASK) | \ (((value) & STRIPPED_MASK) << 8)) Py_LOCAL_INLINE(Py_UCS4) STRINGLIB(utf16_decode)(const unsigned char **inptr, const unsigned char *e, STRINGLIB_CHAR *dest, Py_ssize_t *outpos, int native_ordering) { Py_UCS4 ch; const unsigned char *aligned_end = (const unsigned char *) _Py_ALIGN_DOWN(e, SIZEOF_LONG); const unsigned char *q = *inptr; STRINGLIB_CHAR *p = dest + *outpos; /* Offsets from q for retrieving byte pairs in the right order. */ #if PY_LITTLE_ENDIAN int ihi = !!native_ordering, ilo = !native_ordering; #else int ihi = !native_ordering, ilo = !!native_ordering; #endif --e; while (q < e) { Py_UCS4 ch2; /* First check for possible aligned read of a C 'long'. Unaligned reads are more expensive, better to defer to another iteration. */ if (_Py_IS_ALIGNED(q, SIZEOF_LONG)) { /* Fast path for runs of in-range non-surrogate chars. */ const unsigned char *_q = q; while (_q < aligned_end) { unsigned long block = * (unsigned long *) _q; if (native_ordering) { /* Can use buffer directly */ if (block & FAST_CHAR_MASK) break; } else { /* Need to byte-swap */ if (block & SWAB(FAST_CHAR_MASK)) break; #if STRINGLIB_SIZEOF_CHAR == 1 block >>= 8; #else block = SWAB(block); #endif } #if PY_LITTLE_ENDIAN # if SIZEOF_LONG == 4 p[0] = (STRINGLIB_CHAR)(block & 0xFFFFu); p[1] = (STRINGLIB_CHAR)(block >> 16); # elif SIZEOF_LONG == 8 p[0] = (STRINGLIB_CHAR)(block & 0xFFFFu); p[1] = (STRINGLIB_CHAR)((block >> 16) & 0xFFFFu); p[2] = (STRINGLIB_CHAR)((block >> 32) & 0xFFFFu); p[3] = (STRINGLIB_CHAR)(block >> 48); # endif #else # if SIZEOF_LONG == 4 p[0] = (STRINGLIB_CHAR)(block >> 16); p[1] = (STRINGLIB_CHAR)(block & 0xFFFFu); # elif SIZEOF_LONG == 8 p[0] = (STRINGLIB_CHAR)(block >> 48); p[1] = (STRINGLIB_CHAR)((block >> 32) & 0xFFFFu); p[2] = (STRINGLIB_CHAR)((block >> 16) & 0xFFFFu); p[3] = (STRINGLIB_CHAR)(block & 0xFFFFu); # endif #endif _q += SIZEOF_LONG; p += SIZEOF_LONG / 2; } q = _q; if (q >= e) break; } ch = (q[ihi] << 8) | q[ilo]; q += 2; if (!Py_UNICODE_IS_SURROGATE(ch)) { #if STRINGLIB_SIZEOF_CHAR < 2 if (ch > STRINGLIB_MAX_CHAR) /* Out-of-range */ goto Return; #endif *p++ = (STRINGLIB_CHAR)ch; continue; } /* UTF-16 code pair: */ if (q >= e) goto UnexpectedEnd; if (!Py_UNICODE_IS_HIGH_SURROGATE(ch)) goto IllegalEncoding; ch2 = (q[ihi] << 8) | q[ilo]; q += 2; if (!Py_UNICODE_IS_LOW_SURROGATE(ch2)) goto IllegalSurrogate; ch = Py_UNICODE_JOIN_SURROGATES(ch, ch2); #if STRINGLIB_SIZEOF_CHAR < 4 /* Out-of-range */ goto Return; #else *p++ = (STRINGLIB_CHAR)ch; #endif } ch = 0; Return: *inptr = q; *outpos = p - dest; return ch; UnexpectedEnd: ch = 1; goto Return; IllegalEncoding: ch = 2; goto Return; IllegalSurrogate: ch = 3; goto Return; } #undef UCS2_REPEAT_MASK #undef FAST_CHAR_MASK #undef STRIPPED_MASK #undef SWAB #if STRINGLIB_MAX_CHAR >= 0x80 Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(utf16_encode)(const STRINGLIB_CHAR *in, Py_ssize_t len, unsigned short **outptr, int native_ordering) { unsigned short *out = *outptr; const STRINGLIB_CHAR *end = in + len; #if STRINGLIB_SIZEOF_CHAR == 1 if (native_ordering) { const STRINGLIB_CHAR *unrolled_end = in + _Py_SIZE_ROUND_DOWN(len, 4); while (in < unrolled_end) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; in += 4; out += 4; } while (in < end) { *out++ = *in++; } } else { # define SWAB2(CH) ((CH) << 8) /* high byte is zero */ const STRINGLIB_CHAR *unrolled_end = in + _Py_SIZE_ROUND_DOWN(len, 4); while (in < unrolled_end) { out[0] = SWAB2(in[0]); out[1] = SWAB2(in[1]); out[2] = SWAB2(in[2]); out[3] = SWAB2(in[3]); in += 4; out += 4; } while (in < end) { Py_UCS4 ch = *in++; *out++ = SWAB2((Py_UCS2)ch); } #undef SWAB2 } *outptr = out; return len; #else if (native_ordering) { #if STRINGLIB_MAX_CHAR < 0x10000 const STRINGLIB_CHAR *unrolled_end = in + _Py_SIZE_ROUND_DOWN(len, 4); while (in < unrolled_end) { /* check if any character is a surrogate character */ if (((in[0] ^ 0xd800) & (in[1] ^ 0xd800) & (in[2] ^ 0xd800) & (in[3] ^ 0xd800) & 0xf800) == 0) break; out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; in += 4; out += 4; } #endif while (in < end) { Py_UCS4 ch; ch = *in++; if (ch < 0xd800) *out++ = ch; else if (ch < 0xe000) /* reject surrogate characters (U+D800-U+DFFF) */ goto fail; #if STRINGLIB_MAX_CHAR >= 0x10000 else if (ch >= 0x10000) { out[0] = Py_UNICODE_HIGH_SURROGATE(ch); out[1] = Py_UNICODE_LOW_SURROGATE(ch); out += 2; } #endif else *out++ = ch; } } else { #define SWAB2(CH) (((CH) << 8) | ((CH) >> 8)) #if STRINGLIB_MAX_CHAR < 0x10000 const STRINGLIB_CHAR *unrolled_end = in + _Py_SIZE_ROUND_DOWN(len, 4); while (in < unrolled_end) { /* check if any character is a surrogate character */ if (((in[0] ^ 0xd800) & (in[1] ^ 0xd800) & (in[2] ^ 0xd800) & (in[3] ^ 0xd800) & 0xf800) == 0) break; out[0] = SWAB2(in[0]); out[1] = SWAB2(in[1]); out[2] = SWAB2(in[2]); out[3] = SWAB2(in[3]); in += 4; out += 4; } #endif while (in < end) { Py_UCS4 ch = *in++; if (ch < 0xd800) *out++ = SWAB2((Py_UCS2)ch); else if (ch < 0xe000) /* reject surrogate characters (U+D800-U+DFFF) */ goto fail; #if STRINGLIB_MAX_CHAR >= 0x10000 else if (ch >= 0x10000) { Py_UCS2 ch1 = Py_UNICODE_HIGH_SURROGATE(ch); Py_UCS2 ch2 = Py_UNICODE_LOW_SURROGATE(ch); out[0] = SWAB2(ch1); out[1] = SWAB2(ch2); out += 2; } #endif else *out++ = SWAB2((Py_UCS2)ch); } #undef SWAB2 } *outptr = out; return len; fail: *outptr = out; return len - (end - in + 1); #endif } #if STRINGLIB_SIZEOF_CHAR == 1 # define SWAB4(CH, tmp) ((CH) << 24) /* high bytes are zero */ #elif STRINGLIB_SIZEOF_CHAR == 2 # define SWAB4(CH, tmp) (tmp = (CH), \ ((tmp & 0x00FFu) << 24) + ((tmp & 0xFF00u) << 8)) /* high bytes are zero */ #else # define SWAB4(CH, tmp) (tmp = (CH), \ tmp = ((tmp & 0x00FF00FFu) << 8) + ((tmp >> 8) & 0x00FF00FFu), \ ((tmp & 0x0000FFFFu) << 16) + ((tmp >> 16) & 0x0000FFFFu)) #endif Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(utf32_encode)(const STRINGLIB_CHAR *in, Py_ssize_t len, PY_UINT32_T **outptr, int native_ordering) { PY_UINT32_T *out = *outptr; const STRINGLIB_CHAR *end = in + len; if (native_ordering) { const STRINGLIB_CHAR *unrolled_end = in + _Py_SIZE_ROUND_DOWN(len, 4); while (in < unrolled_end) { #if STRINGLIB_SIZEOF_CHAR > 1 /* check if any character is a surrogate character */ if (((in[0] ^ 0xd800) & (in[1] ^ 0xd800) & (in[2] ^ 0xd800) & (in[3] ^ 0xd800) & 0xf800) == 0) break; #endif out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; in += 4; out += 4; } while (in < end) { Py_UCS4 ch; ch = *in++; #if STRINGLIB_SIZEOF_CHAR > 1 if (Py_UNICODE_IS_SURROGATE(ch)) { /* reject surrogate characters (U+D800-U+DFFF) */ goto fail; } #endif *out++ = ch; } } else { const STRINGLIB_CHAR *unrolled_end = in + _Py_SIZE_ROUND_DOWN(len, 4); while (in < unrolled_end) { #if STRINGLIB_SIZEOF_CHAR > 1 Py_UCS4 ch1, ch2, ch3, ch4; /* check if any character is a surrogate character */ if (((in[0] ^ 0xd800) & (in[1] ^ 0xd800) & (in[2] ^ 0xd800) & (in[3] ^ 0xd800) & 0xf800) == 0) break; #endif out[0] = SWAB4(in[0], ch1); out[1] = SWAB4(in[1], ch2); out[2] = SWAB4(in[2], ch3); out[3] = SWAB4(in[3], ch4); in += 4; out += 4; } while (in < end) { Py_UCS4 ch = *in++; #if STRINGLIB_SIZEOF_CHAR > 1 if (Py_UNICODE_IS_SURROGATE(ch)) { /* reject surrogate characters (U+D800-U+DFFF) */ goto fail; } #endif *out++ = SWAB4(ch, ch); } } *outptr = out; return len; #if STRINGLIB_SIZEOF_CHAR > 1 fail: *outptr = out; return len - (end - in + 1); #endif } #undef SWAB4 #endif
28,662
831
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/ucs4lib.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 */ /* 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 ucs4lib_fastsearch #define STRINGLIB(F) ucs4lib_##F #define STRINGLIB_OBJECT PyUnicodeObject #define STRINGLIB_SIZEOF_CHAR 4 #define STRINGLIB_MAX_CHAR 0x10FFFFu #define STRINGLIB_CHAR Py_UCS4 #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_4BYTE_DATA #define STRINGLIB_LEN PyUnicode_GET_LENGTH #define STRINGLIB_NEW _PyUnicode_FromUCS4 #define STRINGLIB_CHECK PyUnicode_Check #define STRINGLIB_CHECK_EXACT PyUnicode_CheckExact #define STRINGLIB_TOSTR PyObject_Str #define STRINGLIB_TOASCII PyObject_ASCII #define _Py_InsertThousandsGrouping _PyUnicode_ucs4_InsertThousandsGrouping
2,076
38
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/count.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 */ /* stringlib: count implementation */ #ifndef STRINGLIB_FASTSEARCH_H #error must include fastsearch.inc before including this module #endif Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(count)(const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR* sub, Py_ssize_t sub_len, Py_ssize_t maxcount) { Py_ssize_t count; if (str_len < 0) return 0; /* start > len(str) */ if (sub_len == 0) return (str_len < maxcount) ? str_len + 1 : maxcount; count = FASTSEARCH(str, str_len, sub, sub_len, maxcount, FAST_COUNT); if (count < 0) return 0; /* no match */ return count; }
1,496
36
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/split.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 */ /* stringlib: split implementation */ #ifndef STRINGLIB_FASTSEARCH_H #error must include fastsearch.inc before including this module #endif /* Overallocate the initial list to reduce the number of reallocs for small split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three resizes, to sizes 4, 8, then 16. Most observed string splits are for human text (roughly 11 words per line) and field delimited data (usually 1-10 fields). For large strings the split algorithms are bandwidth limited so increasing the preallocation likely will not improve things.*/ #define MAX_PREALLOC 12 /* 5 splits gives 6 elements */ #define PREALLOC_SIZE(maxsplit) \ (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1) #define SPLIT_APPEND(data, left, right) \ sub = STRINGLIB_NEW((data) + (left), \ (right) - (left)); \ if (sub == NULL) \ goto onError; \ if (PyList_Append(list, sub)) { \ Py_DECREF(sub); \ goto onError; \ } \ else \ Py_DECREF(sub); #define SPLIT_ADD(data, left, right) { \ sub = STRINGLIB_NEW((data) + (left), \ (right) - (left)); \ if (sub == NULL) \ goto onError; \ if (count < MAX_PREALLOC) { \ PyList_SET_ITEM(list, count, sub); \ } else { \ if (PyList_Append(list, sub)) { \ Py_DECREF(sub); \ goto onError; \ } \ else \ Py_DECREF(sub); \ } \ count++; } /* Always force the list to the expected size. */ #define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count Py_LOCAL_INLINE(PyObject *) STRINGLIB(split_whitespace)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, Py_ssize_t maxcount) { Py_ssize_t i, j, count=0; PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); PyObject *sub; if (list == NULL) return NULL; i = j = 0; while (maxcount-- > 0) { while (i < str_len && STRINGLIB_ISSPACE(str[i])) i++; if (i == str_len) break; j = i; i++; while (i < str_len && !STRINGLIB_ISSPACE(str[i])) i++; #ifndef STRINGLIB_MUTABLE if (j == 0 && i == str_len && STRINGLIB_CHECK_EXACT(str_obj)) { /* No whitespace in str_obj, so just use it as list[0] */ Py_INCREF(str_obj); PyList_SET_ITEM(list, 0, (PyObject *)str_obj); count++; break; } #endif SPLIT_ADD(str, j, i); } if (i < str_len) { /* Only occurs when maxcount was reached */ /* Skip any remaining whitespace and copy to end of string */ while (i < str_len && STRINGLIB_ISSPACE(str[i])) i++; if (i != str_len) SPLIT_ADD(str, i, str_len); } FIX_PREALLOC_SIZE(list); return list; onError: Py_DECREF(list); return NULL; } Py_LOCAL_INLINE(PyObject *) STRINGLIB(split_char)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR ch, Py_ssize_t maxcount) { Py_ssize_t i, j, count=0; PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); PyObject *sub; if (list == NULL) return NULL; i = j = 0; while ((j < str_len) && (maxcount-- > 0)) { for(; j < str_len; j++) { /* I found that using memchr makes no difference */ if (str[j] == ch) { SPLIT_ADD(str, i, j); i = j = j + 1; break; } } } #ifndef STRINGLIB_MUTABLE if (count == 0 && STRINGLIB_CHECK_EXACT(str_obj)) { /* ch not in str_obj, so just use str_obj as list[0] */ Py_INCREF(str_obj); PyList_SET_ITEM(list, 0, (PyObject *)str_obj); count++; } else #endif if (i <= str_len) { SPLIT_ADD(str, i, str_len); } FIX_PREALLOC_SIZE(list); return list; onError: Py_DECREF(list); return NULL; } Py_LOCAL_INLINE(PyObject *) STRINGLIB(split)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR* sep, Py_ssize_t sep_len, Py_ssize_t maxcount) { Py_ssize_t i, j, pos, count=0; PyObject *list, *sub; if (sep_len == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); return NULL; } else if (sep_len == 1) return STRINGLIB(split_char)(str_obj, str, str_len, sep[0], maxcount); list = PyList_New(PREALLOC_SIZE(maxcount)); if (list == NULL) return NULL; i = j = 0; while (maxcount-- > 0) { pos = FASTSEARCH(str+i, str_len-i, sep, sep_len, -1, FAST_SEARCH); if (pos < 0) break; j = i + pos; SPLIT_ADD(str, i, j); i = j + sep_len; } #ifndef STRINGLIB_MUTABLE if (count == 0 && STRINGLIB_CHECK_EXACT(str_obj)) { /* No match in str_obj, so just use it as list[0] */ Py_INCREF(str_obj); PyList_SET_ITEM(list, 0, (PyObject *)str_obj); count++; } else #endif { SPLIT_ADD(str, i, str_len); } FIX_PREALLOC_SIZE(list); return list; onError: Py_DECREF(list); return NULL; } Py_LOCAL_INLINE(PyObject *) STRINGLIB(rsplit_whitespace)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, Py_ssize_t maxcount) { Py_ssize_t i, j, count=0; PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); PyObject *sub; if (list == NULL) return NULL; i = j = str_len - 1; while (maxcount-- > 0) { while (i >= 0 && STRINGLIB_ISSPACE(str[i])) i--; if (i < 0) break; j = i; i--; while (i >= 0 && !STRINGLIB_ISSPACE(str[i])) i--; #ifndef STRINGLIB_MUTABLE if (j == str_len - 1 && i < 0 && STRINGLIB_CHECK_EXACT(str_obj)) { /* No whitespace in str_obj, so just use it as list[0] */ Py_INCREF(str_obj); PyList_SET_ITEM(list, 0, (PyObject *)str_obj); count++; break; } #endif SPLIT_ADD(str, i + 1, j + 1); } if (i >= 0) { /* Only occurs when maxcount was reached */ /* Skip any remaining whitespace and copy to beginning of string */ while (i >= 0 && STRINGLIB_ISSPACE(str[i])) i--; if (i >= 0) SPLIT_ADD(str, 0, i + 1); } FIX_PREALLOC_SIZE(list); if (PyList_Reverse(list) < 0) goto onError; return list; onError: Py_DECREF(list); return NULL; } Py_LOCAL_INLINE(PyObject *) STRINGLIB(rsplit_char)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR ch, Py_ssize_t maxcount) { Py_ssize_t i, j, count=0; PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); PyObject *sub; if (list == NULL) return NULL; i = j = str_len - 1; while ((i >= 0) && (maxcount-- > 0)) { for(; i >= 0; i--) { if (str[i] == ch) { SPLIT_ADD(str, i + 1, j + 1); j = i = i - 1; break; } } } #ifndef STRINGLIB_MUTABLE if (count == 0 && STRINGLIB_CHECK_EXACT(str_obj)) { /* ch not in str_obj, so just use str_obj as list[0] */ Py_INCREF(str_obj); PyList_SET_ITEM(list, 0, (PyObject *)str_obj); count++; } else #endif if (j >= -1) { SPLIT_ADD(str, 0, j + 1); } FIX_PREALLOC_SIZE(list); if (PyList_Reverse(list) < 0) goto onError; return list; onError: Py_DECREF(list); return NULL; } Py_LOCAL_INLINE(PyObject *) STRINGLIB(rsplit)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, const STRINGLIB_CHAR* sep, Py_ssize_t sep_len, Py_ssize_t maxcount) { Py_ssize_t j, pos, count=0; PyObject *list, *sub; if (sep_len == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); return NULL; } else if (sep_len == 1) return STRINGLIB(rsplit_char)(str_obj, str, str_len, sep[0], maxcount); list = PyList_New(PREALLOC_SIZE(maxcount)); if (list == NULL) return NULL; j = str_len; while (maxcount-- > 0) { pos = FASTSEARCH(str, j, sep, sep_len, -1, FAST_RSEARCH); if (pos < 0) break; SPLIT_ADD(str, pos + sep_len, j); j = pos; } #ifndef STRINGLIB_MUTABLE if (count == 0 && STRINGLIB_CHECK_EXACT(str_obj)) { /* No match in str_obj, so just use it as list[0] */ Py_INCREF(str_obj); PyList_SET_ITEM(list, 0, (PyObject *)str_obj); count++; } else #endif { SPLIT_ADD(str, 0, j); } FIX_PREALLOC_SIZE(list); if (PyList_Reverse(list) < 0) goto onError; return list; onError: Py_DECREF(list); return NULL; } Py_LOCAL_INLINE(PyObject *) STRINGLIB(splitlines)(PyObject* str_obj, const STRINGLIB_CHAR* str, Py_ssize_t str_len, int keepends) { /* This does not use the preallocated list because splitlines is usually run with hundreds of newlines. The overhead of switching between PyList_SET_ITEM and append causes about a 2-3% slowdown for that common case. A smarter implementation could move the if check out, so the SET_ITEMs are done first and the appends only done when the prealloc buffer is full. That's too much work for little gain.*/ Py_ssize_t i; Py_ssize_t j; PyObject *list = PyList_New(0); PyObject *sub; if (list == NULL) return NULL; for (i = j = 0; i < str_len; ) { Py_ssize_t eol; /* Find a line and append it */ while (i < str_len && !STRINGLIB_ISLINEBREAK(str[i])) i++; /* Skip the line break reading CRLF as one line break */ eol = i; if (i < str_len) { if (str[i] == '\r' && i + 1 < str_len && str[i+1] == '\n') i += 2; else i++; if (keepends) eol = i; } #ifndef STRINGLIB_MUTABLE if (j == 0 && eol == str_len && STRINGLIB_CHECK_EXACT(str_obj)) { /* No linebreak in str_obj, so just use it as list[0] */ if (PyList_Append(list, str_obj)) goto onError; break; } #endif SPLIT_APPEND(str, j, eol); j = i; } return list; onError: Py_DECREF(list); return NULL; }
12,138
399
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/join.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 */ /* stringlib: bytes joining implementation */ #if STRINGLIB_IS_UNICODE #error join.h only compatible with byte-wise strings #endif Py_LOCAL_INLINE(PyObject *) STRINGLIB(bytes_join)(PyObject *sep, PyObject *iterable) { char *sepstr = STRINGLIB_STR(sep); const Py_ssize_t seplen = STRINGLIB_LEN(sep); PyObject *res = NULL; char *p; Py_ssize_t seqlen = 0; Py_ssize_t sz = 0; Py_ssize_t i, nbufs; PyObject *seq, *item; Py_buffer *buffers = NULL; #define NB_STATIC_BUFFERS 10 Py_buffer static_buffers[NB_STATIC_BUFFERS]; seq = PySequence_Fast(iterable, "can only join an iterable"); if (seq == NULL) { return NULL; } seqlen = PySequence_Fast_GET_SIZE(seq); if (seqlen == 0) { Py_DECREF(seq); return STRINGLIB_NEW(NULL, 0); } #ifndef STRINGLIB_MUTABLE if (seqlen == 1) { item = PySequence_Fast_GET_ITEM(seq, 0); if (STRINGLIB_CHECK_EXACT(item)) { Py_INCREF(item); Py_DECREF(seq); return item; } } #endif if (seqlen > NB_STATIC_BUFFERS) { buffers = PyMem_NEW(Py_buffer, seqlen); if (buffers == NULL) { Py_DECREF(seq); PyErr_NoMemory(); return NULL; } } else { buffers = static_buffers; } /* Here is the general case. Do a pre-pass to figure out the total * amount of space we'll need (sz), and see whether all arguments are * bytes-like. */ for (i = 0, nbufs = 0; i < seqlen; i++) { Py_ssize_t itemlen; item = PySequence_Fast_GET_ITEM(seq, i); if (PyBytes_CheckExact(item)) { /* Fast path. */ Py_INCREF(item); buffers[i].obj = item; buffers[i].buf = PyBytes_AS_STRING(item); buffers[i].len = PyBytes_GET_SIZE(item); } else if (PyObject_GetBuffer(item, &buffers[i], PyBUF_SIMPLE) != 0) { PyErr_Format(PyExc_TypeError, "sequence item %zd: expected a bytes-like object, " "%.80s found", i, Py_TYPE(item)->tp_name); goto error; } nbufs = i + 1; /* for error cleanup */ itemlen = buffers[i].len; if (itemlen > PY_SSIZE_T_MAX - sz) { PyErr_SetString(PyExc_OverflowError, "join() result is too long"); goto error; } sz += itemlen; if (i != 0) { if (seplen > PY_SSIZE_T_MAX - sz) { PyErr_SetString(PyExc_OverflowError, "join() result is too long"); goto error; } sz += seplen; } if (seqlen != PySequence_Fast_GET_SIZE(seq)) { PyErr_SetString(PyExc_RuntimeError, "sequence changed size during iteration"); goto error; } } /* Allocate result space. */ res = STRINGLIB_NEW(NULL, sz); if (res == NULL) goto error; /* Catenate everything. */ p = STRINGLIB_STR(res); if (!seplen) { /* fast path */ for (i = 0; i < nbufs; i++) { Py_ssize_t n = buffers[i].len; char *q = buffers[i].buf; memcpy(p, q, n); p += n; } goto done; } for (i = 0; i < nbufs; i++) { Py_ssize_t n; char *q; if (i) { memcpy(p, sepstr, seplen); p += seplen; } n = buffers[i].len; q = buffers[i].buf; memcpy(p, q, n); p += n; } goto done; error: res = NULL; done: Py_DECREF(seq); for (i = 0; i < nbufs; i++) PyBuffer_Release(&buffers[i]); if (buffers != static_buffers) PyMem_FREE(buffers); return res; } #undef NB_STATIC_BUFFERS
4,730
149
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/asciilib.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 */ /* 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 asciilib_fastsearch #define STRINGLIB(F) asciilib_##F #define STRINGLIB_OBJECT PyUnicodeObject #define STRINGLIB_SIZEOF_CHAR 1 #define STRINGLIB_MAX_CHAR 0x7Fu #define STRINGLIB_CHAR Py_UCS1 #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_1BYTE_DATA #define STRINGLIB_LEN PyUnicode_GET_LENGTH #define STRINGLIB_NEW(STR,LEN) _PyUnicode_FromASCII((char*)(STR),(LEN)) #define STRINGLIB_CHECK PyUnicode_Check #define STRINGLIB_CHECK_EXACT PyUnicode_CheckExact #define STRINGLIB_TOSTR PyObject_Str #define STRINGLIB_TOASCII PyObject_ASCII #define _Py_InsertThousandsGrouping _PyUnicode_ascii_InsertThousandsGrouping
2,096
38
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/unicode_format.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 */ /* unicode_format.h -- implementation of str.format(). */ /************************************************************************/ /*********** Global data structures and forward declarations *********/ /************************************************************************/ /* A SubString consists of the characters between two string or unicode pointers. */ typedef struct { PyObject *str; /* borrowed reference */ Py_ssize_t start, end; } SubString; typedef enum { ANS_INIT, ANS_AUTO, ANS_MANUAL } AutoNumberState; /* Keep track if we're auto-numbering fields */ /* Keeps track of our auto-numbering state, and which number field we're on */ typedef struct { AutoNumberState an_state; int an_field_number; } AutoNumber; /* forward declaration for recursion */ static PyObject * build_string(SubString *input, PyObject *args, PyObject *kwargs, int recursion_depth, AutoNumber *auto_number); /************************************************************************/ /************************** Utility functions ************************/ /************************************************************************/ static void AutoNumber_Init(AutoNumber *auto_number) { auto_number->an_state = ANS_INIT; auto_number->an_field_number = 0; } /* fill in a SubString from a pointer and length */ Py_LOCAL_INLINE(void) SubString_init(SubString *str, PyObject *s, Py_ssize_t start, Py_ssize_t end) { str->str = s; str->start = start; str->end = end; } /* return a new string. if str->str is NULL, return None */ Py_LOCAL_INLINE(PyObject *) SubString_new_object(SubString *str) { if (str->str == NULL) { Py_INCREF(Py_None); return Py_None; } return PyUnicode_Substring(str->str, str->start, str->end); } /* return a new string. if str->str is NULL, return a new empty string */ Py_LOCAL_INLINE(PyObject *) SubString_new_object_or_empty(SubString *str) { if (str->str == NULL) { return PyUnicode_New(0, 0); } return SubString_new_object(str); } /* Return 1 if an error has been detected switching between automatic field numbering and manual field specification, else return 0. Set ValueError on error. */ static int autonumber_state_error(AutoNumberState state, int field_name_is_empty) { if (state == ANS_MANUAL) { if (field_name_is_empty) { PyErr_SetString(PyExc_ValueError, "cannot switch from " "manual field specification to " "automatic field numbering"); return 1; } } else { if (!field_name_is_empty) { PyErr_SetString(PyExc_ValueError, "cannot switch from " "automatic field numbering to " "manual field specification"); return 1; } } return 0; } /************************************************************************/ /*********** Format string parsing -- integers and identifiers *********/ /************************************************************************/ static Py_ssize_t get_integer(const SubString *str) { Py_ssize_t accumulator = 0; Py_ssize_t digitval; Py_ssize_t i; /* empty string is an error */ if (str->start >= str->end) return -1; for (i = str->start; i < str->end; i++) { digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ_CHAR(str->str, i)); if (digitval < 0) return -1; /* Detect possible overflow before it happens: accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if accumulator > (PY_SSIZE_T_MAX - digitval) / 10. */ if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) { PyErr_Format(PyExc_ValueError, "Too many decimal digits in format string"); return -1; } accumulator = accumulator * 10 + digitval; } return accumulator; } /************************************************************************/ /******** Functions to get field objects and specification strings ******/ /************************************************************************/ /* do the equivalent of obj.name */ static PyObject * getattr(PyObject *obj, SubString *name) { PyObject *newobj; PyObject *str = SubString_new_object(name); if (str == NULL) return NULL; newobj = PyObject_GetAttr(obj, str); Py_DECREF(str); return newobj; } /* do the equivalent of obj[idx], where obj is a sequence */ static PyObject * getitem_sequence(PyObject *obj, Py_ssize_t idx) { return PySequence_GetItem(obj, idx); } /* do the equivalent of obj[idx], where obj is not a sequence */ static PyObject * getitem_idx(PyObject *obj, Py_ssize_t idx) { PyObject *newobj; PyObject *idx_obj = PyLong_FromSsize_t(idx); if (idx_obj == NULL) return NULL; newobj = PyObject_GetItem(obj, idx_obj); Py_DECREF(idx_obj); return newobj; } /* do the equivalent of obj[name] */ static PyObject * getitem_str(PyObject *obj, SubString *name) { PyObject *newobj; PyObject *str = SubString_new_object(name); if (str == NULL) return NULL; newobj = PyObject_GetItem(obj, str); Py_DECREF(str); return newobj; } typedef struct { /* the entire string we're parsing. we assume that someone else is managing its lifetime, and that it will exist for the lifetime of the iterator. can be empty */ SubString str; /* index to where we are inside field_name */ Py_ssize_t index; } FieldNameIterator; static int FieldNameIterator_init(FieldNameIterator *self, PyObject *s, Py_ssize_t start, Py_ssize_t end) { SubString_init(&self->str, s, start, end); self->index = start; return 1; } static int _FieldNameIterator_attr(FieldNameIterator *self, SubString *name) { Py_UCS4 c; name->str = self->str.str; name->start = self->index; /* return everything until '.' or '[' */ while (self->index < self->str.end) { c = PyUnicode_READ_CHAR(self->str.str, self->index++); switch (c) { case '[': case '.': /* backup so that we this character will be seen next time */ self->index--; break; default: continue; } break; } /* end of string is okay */ name->end = self->index; return 1; } static int _FieldNameIterator_item(FieldNameIterator *self, SubString *name) { int bracket_seen = 0; Py_UCS4 c; name->str = self->str.str; name->start = self->index; /* return everything until ']' */ while (self->index < self->str.end) { c = PyUnicode_READ_CHAR(self->str.str, self->index++); switch (c) { case ']': bracket_seen = 1; break; default: continue; } break; } /* make sure we ended with a ']' */ if (!bracket_seen) { PyErr_SetString(PyExc_ValueError, "Missing ']' in format string"); return 0; } /* end of string is okay */ /* don't include the ']' */ name->end = self->index-1; return 1; } /* returns 0 on error, 1 on non-error termination, and 2 if it returns a value */ static int FieldNameIterator_next(FieldNameIterator *self, int *is_attribute, Py_ssize_t *name_idx, SubString *name) { /* check at end of input */ if (self->index >= self->str.end) return 1; switch (PyUnicode_READ_CHAR(self->str.str, self->index++)) { case '.': *is_attribute = 1; if (_FieldNameIterator_attr(self, name) == 0) return 0; *name_idx = -1; break; case '[': *is_attribute = 0; if (_FieldNameIterator_item(self, name) == 0) return 0; *name_idx = get_integer(name); if (*name_idx == -1 && PyErr_Occurred()) return 0; break; default: /* Invalid character follows ']' */ PyErr_SetString(PyExc_ValueError, "Only '.' or '[' may " "follow ']' in format field specifier"); return 0; } /* empty string is an error */ if (name->start == name->end) { PyErr_SetString(PyExc_ValueError, "Empty attribute in format string"); return 0; } return 2; } /* input: field_name output: 'first' points to the part before the first '[' or '.' 'first_idx' is -1 if 'first' is not an integer, otherwise it's the value of first converted to an integer 'rest' is an iterator to return the rest */ static int field_name_split(PyObject *str, Py_ssize_t start, Py_ssize_t end, SubString *first, Py_ssize_t *first_idx, FieldNameIterator *rest, AutoNumber *auto_number) { Py_UCS4 c; Py_ssize_t i = start; int field_name_is_empty; int using_numeric_index; /* find the part up until the first '.' or '[' */ while (i < end) { switch (c = PyUnicode_READ_CHAR(str, i++)) { case '[': case '.': /* backup so that we this character is available to the "rest" iterator */ i--; break; default: continue; } break; } /* set up the return values */ SubString_init(first, str, start, i); FieldNameIterator_init(rest, str, i, end); /* see if "first" is an integer, in which case it's used as an index */ *first_idx = get_integer(first); if (*first_idx == -1 && PyErr_Occurred()) return 0; field_name_is_empty = first->start >= first->end; /* If the field name is omitted or if we have a numeric index specified, then we're doing numeric indexing into args. */ using_numeric_index = field_name_is_empty || *first_idx != -1; /* We always get here exactly one time for each field we're processing. And we get here in field order (counting by left braces). So this is the perfect place to handle automatic field numbering if the field name is omitted. */ /* Check if we need to do the auto-numbering. It's not needed if we're called from string.Format routines, because it's handled in that class by itself. */ if (auto_number) { /* Initialize our auto numbering state if this is the first time we're either auto-numbering or manually numbering. */ if (auto_number->an_state == ANS_INIT && using_numeric_index) auto_number->an_state = field_name_is_empty ? ANS_AUTO : ANS_MANUAL; /* Make sure our state is consistent with what we're doing this time through. Only check if we're using a numeric index. */ if (using_numeric_index) if (autonumber_state_error(auto_number->an_state, field_name_is_empty)) return 0; /* Zero length field means we want to do auto-numbering of the fields. */ if (field_name_is_empty) *first_idx = (auto_number->an_field_number)++; } return 1; } /* get_field_object returns the object inside {}, before the format_spec. It handles getindex and getattr lookups and consumes the entire input string. */ static PyObject * get_field_object(SubString *input, PyObject *args, PyObject *kwargs, AutoNumber *auto_number) { PyObject *obj = NULL; int ok; int is_attribute; SubString name; SubString first; Py_ssize_t index; FieldNameIterator rest; if (!field_name_split(input->str, input->start, input->end, &first, &index, &rest, auto_number)) { goto error; } if (index == -1) { /* look up in kwargs */ PyObject *key = SubString_new_object(&first); if (key == NULL) { goto error; } if (kwargs == NULL) { PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); goto error; } /* Use PyObject_GetItem instead of PyDict_GetItem because this code is no longer just used with kwargs. It might be passed a non-dict when called through format_map. */ obj = PyObject_GetItem(kwargs, key); Py_DECREF(key); if (obj == NULL) { goto error; } } else { /* If args is NULL, we have a format string with a positional field with only kwargs to retrieve it from. This can only happen when used with format_map(), where positional arguments are not allowed. */ if (args == NULL) { PyErr_SetString(PyExc_ValueError, "Format string contains " "positional fields"); goto error; } /* look up in args */ obj = PySequence_GetItem(args, index); if (obj == NULL) goto error; } /* iterate over the rest of the field_name */ while ((ok = FieldNameIterator_next(&rest, &is_attribute, &index, &name)) == 2) { PyObject *tmp; if (is_attribute) /* getattr lookup "." */ tmp = getattr(obj, &name); else /* getitem lookup "[]" */ if (index == -1) tmp = getitem_str(obj, &name); else if (PySequence_Check(obj)) tmp = getitem_sequence(obj, index); else /* not a sequence */ tmp = getitem_idx(obj, index); if (tmp == NULL) goto error; /* assign to obj */ Py_DECREF(obj); obj = tmp; } /* end of iterator, this is the non-error case */ if (ok == 1) return obj; error: Py_XDECREF(obj); return NULL; } /************************************************************************/ /***************** Field rendering functions **************************/ /************************************************************************/ /* render_field() is the main function in this section. It takes the field object and field specification string generated by get_field_and_spec, and renders the field into the output string. render_field calls fieldobj.__format__(format_spec) method, and appends to the output. */ static int render_field(PyObject *fieldobj, SubString *format_spec, _PyUnicodeWriter *writer) { int ok = 0; PyObject *result = NULL; PyObject *format_spec_object = NULL; int (*formatter) (_PyUnicodeWriter*, PyObject *, PyObject *, Py_ssize_t, Py_ssize_t) = NULL; int err; /* If we know the type exactly, skip the lookup of __format__ and just call the formatter directly. */ if (PyUnicode_CheckExact(fieldobj)) formatter = _PyUnicode_FormatAdvancedWriter; else if (PyLong_CheckExact(fieldobj)) formatter = _PyLong_FormatAdvancedWriter; else if (PyFloat_CheckExact(fieldobj)) formatter = _PyFloat_FormatAdvancedWriter; else if (PyComplex_CheckExact(fieldobj)) formatter = _PyComplex_FormatAdvancedWriter; if (formatter) { /* we know exactly which formatter will be called when __format__ is looked up, so call it directly, instead. */ err = formatter(writer, fieldobj, format_spec->str, format_spec->start, format_spec->end); return (err == 0); } else { /* We need to create an object out of the pointers we have, because __format__ takes a string/unicode object for format_spec. */ if (format_spec->str) format_spec_object = PyUnicode_Substring(format_spec->str, format_spec->start, format_spec->end); else format_spec_object = PyUnicode_New(0, 0); if (format_spec_object == NULL) goto done; result = PyObject_Format(fieldobj, format_spec_object); } if (result == NULL) goto done; if (_PyUnicodeWriter_WriteStr(writer, result) == -1) goto done; ok = 1; done: Py_XDECREF(format_spec_object); Py_XDECREF(result); return ok; } static int parse_field(SubString *str, SubString *field_name, SubString *format_spec, int *format_spec_needs_expanding, Py_UCS4 *conversion) { /* Note this function works if the field name is zero length, which is good. Zero length field names are handled later, in field_name_split. */ Py_UCS4 c = 0; /* initialize these, as they may be empty */ *conversion = '\0'; SubString_init(format_spec, NULL, 0, 0); /* Search for the field name. it's terminated by the end of the string, or a ':' or '!' */ field_name->str = str->str; field_name->start = str->start; while (str->start < str->end) { switch ((c = PyUnicode_READ_CHAR(str->str, str->start++))) { case '{': PyErr_SetString(PyExc_ValueError, "unexpected '{' in field name"); return 0; case '[': for (; str->start < str->end; str->start++) if (PyUnicode_READ_CHAR(str->str, str->start) == ']') break; continue; case '}': case ':': case '!': break; default: continue; } break; } field_name->end = str->start - 1; if (c == '!' || c == ':') { Py_ssize_t count; /* we have a format specifier and/or a conversion */ /* don't include the last character */ /* see if there's a conversion specifier */ if (c == '!') { /* there must be another character present */ if (str->start >= str->end) { PyErr_SetString(PyExc_ValueError, "end of string while looking for conversion " "specifier"); return 0; } *conversion = PyUnicode_READ_CHAR(str->str, str->start++); if (str->start < str->end) { c = PyUnicode_READ_CHAR(str->str, str->start++); if (c == '}') return 1; if (c != ':') { PyErr_SetString(PyExc_ValueError, "expected ':' after conversion specifier"); return 0; } } } format_spec->str = str->str; format_spec->start = str->start; count = 1; while (str->start < str->end) { switch ((c = PyUnicode_READ_CHAR(str->str, str->start++))) { case '{': *format_spec_needs_expanding = 1; count++; break; case '}': count--; if (count == 0) { format_spec->end = str->start - 1; return 1; } break; default: break; } } PyErr_SetString(PyExc_ValueError, "unmatched '{' in format spec"); return 0; } else if (c != '}') { PyErr_SetString(PyExc_ValueError, "expected '}' before end of string"); return 0; } return 1; } /************************************************************************/ /******* Output string allocation and escape-to-markup processing ******/ /************************************************************************/ /* MarkupIterator breaks the string into pieces of either literal text, or things inside {} that need to be marked up. it is designed to make it easy to wrap a Python iterator around it, for use with the Formatter class */ typedef struct { SubString str; } MarkupIterator; static int MarkupIterator_init(MarkupIterator *self, PyObject *str, Py_ssize_t start, Py_ssize_t end) { SubString_init(&self->str, str, start, end); return 1; } /* returns 0 on error, 1 on non-error termination, and 2 if it got a string (or something to be expanded) */ static int MarkupIterator_next(MarkupIterator *self, SubString *literal, int *field_present, SubString *field_name, SubString *format_spec, Py_UCS4 *conversion, int *format_spec_needs_expanding) { int at_end; Py_UCS4 c = 0; Py_ssize_t start; Py_ssize_t len; int markup_follows = 0; /* initialize all of the output variables */ SubString_init(literal, NULL, 0, 0); SubString_init(field_name, NULL, 0, 0); SubString_init(format_spec, NULL, 0, 0); *conversion = '\0'; *format_spec_needs_expanding = 0; *field_present = 0; /* No more input, end of iterator. This is the normal exit path. */ if (self->str.start >= self->str.end) return 1; start = self->str.start; /* First read any literal text. Read until the end of string, an escaped '{' or '}', or an unescaped '{'. In order to never allocate memory and so I can just pass pointers around, if there's an escaped '{' or '}' then we'll return the literal including the brace, but no format object. The next time through, we'll return the rest of the literal, skipping past the second consecutive brace. */ while (self->str.start < self->str.end) { switch (c = PyUnicode_READ_CHAR(self->str.str, self->str.start++)) { case '{': case '}': markup_follows = 1; break; default: continue; } break; } at_end = self->str.start >= self->str.end; len = self->str.start - start; if ((c == '}') && (at_end || (c != PyUnicode_READ_CHAR(self->str.str, self->str.start)))) { PyErr_SetString(PyExc_ValueError, "Single '}' encountered " "in format string"); return 0; } if (at_end && c == '{') { PyErr_SetString(PyExc_ValueError, "Single '{' encountered " "in format string"); return 0; } if (!at_end) { if (c == PyUnicode_READ_CHAR(self->str.str, self->str.start)) { /* escaped } or {, skip it in the input. there is no markup object following us, just this literal text */ self->str.start++; markup_follows = 0; } else len--; } /* record the literal text */ literal->str = self->str.str; literal->start = start; literal->end = start + len; if (!markup_follows) return 2; /* this is markup; parse the field */ *field_present = 1; if (!parse_field(&self->str, field_name, format_spec, format_spec_needs_expanding, conversion)) return 0; return 2; } /* do the !r or !s conversion on obj */ static PyObject * do_conversion(PyObject *obj, Py_UCS4 conversion) { /* XXX in pre-3.0, do we need to convert this to unicode, since it might have returned a string? */ switch (conversion) { case 'r': return PyObject_Repr(obj); case 's': return PyObject_Str(obj); case 'a': return PyObject_ASCII(obj); default: if (conversion > 32 && conversion < 127) { /* It's the ASCII subrange; casting to char is safe (assuming the execution character set is an ASCII superset). */ PyErr_Format(PyExc_ValueError, "Unknown conversion specifier %c", (char)conversion); } else PyErr_Format(PyExc_ValueError, "Unknown conversion specifier \\x%x", (unsigned int)conversion); return NULL; } } /* given: {field_name!conversion:format_spec} compute the result and write it to output. format_spec_needs_expanding is an optimization. if it's false, just output the string directly, otherwise recursively expand the format_spec string. field_name is allowed to be zero length, in which case we are doing auto field numbering. */ static int output_markup(SubString *field_name, SubString *format_spec, int format_spec_needs_expanding, Py_UCS4 conversion, _PyUnicodeWriter *writer, PyObject *args, PyObject *kwargs, int recursion_depth, AutoNumber *auto_number) { PyObject *tmp = NULL; PyObject *fieldobj = NULL; SubString expanded_format_spec; SubString *actual_format_spec; int result = 0; /* convert field_name to an object */ fieldobj = get_field_object(field_name, args, kwargs, auto_number); if (fieldobj == NULL) goto done; if (conversion != '\0') { tmp = do_conversion(fieldobj, conversion); if (tmp == NULL || PyUnicode_READY(tmp) == -1) goto done; /* do the assignment, transferring ownership: fieldobj = tmp */ Py_DECREF(fieldobj); fieldobj = tmp; tmp = NULL; } /* if needed, recurively compute the format_spec */ if (format_spec_needs_expanding) { tmp = build_string(format_spec, args, kwargs, recursion_depth-1, auto_number); if (tmp == NULL || PyUnicode_READY(tmp) == -1) goto done; /* note that in the case we're expanding the format string, tmp must be kept around until after the call to render_field. */ SubString_init(&expanded_format_spec, tmp, 0, PyUnicode_GET_LENGTH(tmp)); actual_format_spec = &expanded_format_spec; } else actual_format_spec = format_spec; if (render_field(fieldobj, actual_format_spec, writer) == 0) goto done; result = 1; done: Py_XDECREF(fieldobj); Py_XDECREF(tmp); return result; } /* do_markup is the top-level loop for the format() method. It searches through the format string for escapes to markup codes, and calls other functions to move non-markup text to the output, and to perform the markup to the output. */ static int do_markup(SubString *input, PyObject *args, PyObject *kwargs, _PyUnicodeWriter *writer, int recursion_depth, AutoNumber *auto_number) { MarkupIterator iter; int format_spec_needs_expanding; int result; int field_present; SubString literal; SubString field_name; SubString format_spec; Py_UCS4 conversion; MarkupIterator_init(&iter, input->str, input->start, input->end); while ((result = MarkupIterator_next(&iter, &literal, &field_present, &field_name, &format_spec, &conversion, &format_spec_needs_expanding)) == 2) { if (literal.end != literal.start) { if (!field_present && iter.str.start == iter.str.end) writer->overallocate = 0; if (_PyUnicodeWriter_WriteSubstring(writer, literal.str, literal.start, literal.end) < 0) return 0; } if (field_present) { if (iter.str.start == iter.str.end) writer->overallocate = 0; if (!output_markup(&field_name, &format_spec, format_spec_needs_expanding, conversion, writer, args, kwargs, recursion_depth, auto_number)) return 0; } } return result; } /* build_string allocates the output string and then calls do_markup to do the heavy lifting. */ static PyObject * build_string(SubString *input, PyObject *args, PyObject *kwargs, int recursion_depth, AutoNumber *auto_number) { _PyUnicodeWriter writer; /* check the recursion level */ if (recursion_depth <= 0) { PyErr_SetString(PyExc_ValueError, "Max string recursion exceeded"); return NULL; } _PyUnicodeWriter_Init(&writer); writer.overallocate = 1; writer.min_length = PyUnicode_GET_LENGTH(input->str) + 100; if (!do_markup(input, args, kwargs, &writer, recursion_depth, auto_number)) { _PyUnicodeWriter_Dealloc(&writer); return NULL; } return _PyUnicodeWriter_Finish(&writer); } /************************************************************************/ /*********** main routine ***********************************************/ /************************************************************************/ /* this is the main entry point */ static PyObject * do_string_format(PyObject *self, PyObject *args, PyObject *kwargs) { SubString input; /* PEP 3101 says only 2 levels, so that "{0:{1}}".format('abc', 's') # works "{0:{1:{2}}}".format('abc', 's', '') # fails */ int recursion_depth = 2; AutoNumber auto_number; if (PyUnicode_READY(self) == -1) return NULL; AutoNumber_Init(&auto_number); SubString_init(&input, self, 0, PyUnicode_GET_LENGTH(self)); return build_string(&input, args, kwargs, recursion_depth, &auto_number); } static PyObject * do_string_format_map(PyObject *self, PyObject *obj) { return do_string_format(self, NULL, obj); } /************************************************************************/ /*********** formatteriterator ******************************************/ /************************************************************************/ /* This is used to implement string.Formatter.vparse(). It exists so Formatter can share code with the built in unicode.format() method. It's really just a wrapper around MarkupIterator that is callable from Python. */ typedef struct { PyObject_HEAD PyObject *str; MarkupIterator it_markup; } formatteriterobject; static void formatteriter_dealloc(formatteriterobject *it) { Py_XDECREF(it->str); PyObject_FREE(it); } /* returns a tuple: (literal, field_name, format_spec, conversion) literal is any literal text to output. might be zero length field_name is the string before the ':'. might be None format_spec is the string after the ':'. mibht be None conversion is either None, or the string after the '!' */ static PyObject * formatteriter_next(formatteriterobject *it) { SubString literal; SubString field_name; SubString format_spec; Py_UCS4 conversion; int format_spec_needs_expanding; int field_present; int result = MarkupIterator_next(&it->it_markup, &literal, &field_present, &field_name, &format_spec, &conversion, &format_spec_needs_expanding); /* all of the SubString objects point into it->str, so no memory management needs to be done on them */ assert(0 <= result && result <= 2); if (result == 0 || result == 1) /* if 0, error has already been set, if 1, iterator is empty */ return NULL; else { PyObject *literal_str = NULL; PyObject *field_name_str = NULL; PyObject *format_spec_str = NULL; PyObject *conversion_str = NULL; PyObject *tuple = NULL; literal_str = SubString_new_object(&literal); if (literal_str == NULL) goto done; field_name_str = SubString_new_object(&field_name); if (field_name_str == NULL) goto done; /* if field_name is non-zero length, return a string for format_spec (even if zero length), else return None */ format_spec_str = (field_present ? SubString_new_object_or_empty : SubString_new_object)(&format_spec); if (format_spec_str == NULL) goto done; /* if the conversion is not specified, return a None, otherwise create a one length string with the conversion character */ if (conversion == '\0') { conversion_str = Py_None; Py_INCREF(conversion_str); } else conversion_str = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, &conversion, 1); if (conversion_str == NULL) goto done; tuple = PyTuple_Pack(4, literal_str, field_name_str, format_spec_str, conversion_str); done: Py_XDECREF(literal_str); Py_XDECREF(field_name_str); Py_XDECREF(format_spec_str); Py_XDECREF(conversion_str); return tuple; } } static PyMethodDef formatteriter_methods[] = { {NULL, NULL} /* sentinel */ }; static PyTypeObject PyFormatterIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "formatteriterator", /* tp_name */ sizeof(formatteriterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)formatteriter_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)formatteriter_next, /* tp_iternext */ formatteriter_methods, /* tp_methods */ 0, }; /* unicode_formatter_parser is used to implement string.Formatter.vformat. it parses a string and returns tuples describing the parsed elements. It's a wrapper around stringlib/string_format.h's MarkupIterator */ static PyObject * formatter_parser(PyObject *ignored, PyObject *self) { formatteriterobject *it; if (!PyUnicode_Check(self)) { PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name); return NULL; } if (PyUnicode_READY(self) == -1) return NULL; it = PyObject_New(formatteriterobject, &PyFormatterIter_Type); if (it == NULL) return NULL; /* take ownership, give the object to the iterator */ Py_INCREF(self); it->str = self; /* initialize the contained MarkupIterator */ MarkupIterator_init(&it->it_markup, (PyObject*)self, 0, PyUnicode_GET_LENGTH(self)); return (PyObject *)it; } /************************************************************************/ /*********** fieldnameiterator ******************************************/ /************************************************************************/ /* This is used to implement string.Formatter.vparse(). It parses the field name into attribute and item values. It's a Python-callable wrapper around FieldNameIterator */ typedef struct { PyObject_HEAD PyObject *str; FieldNameIterator it_field; } fieldnameiterobject; static void fieldnameiter_dealloc(fieldnameiterobject *it) { Py_XDECREF(it->str); PyObject_FREE(it); } /* returns a tuple: (is_attr, value) is_attr is true if we used attribute syntax (e.g., '.foo') false if we used index syntax (e.g., '[foo]') value is an integer or string */ static PyObject * fieldnameiter_next(fieldnameiterobject *it) { int result; int is_attr; Py_ssize_t idx; SubString name; result = FieldNameIterator_next(&it->it_field, &is_attr, &idx, &name); if (result == 0 || result == 1) /* if 0, error has already been set, if 1, iterator is empty */ return NULL; else { PyObject* result = NULL; PyObject* is_attr_obj = NULL; PyObject* obj = NULL; is_attr_obj = PyBool_FromLong(is_attr); if (is_attr_obj == NULL) goto done; /* either an integer or a string */ if (idx != -1) obj = PyLong_FromSsize_t(idx); else obj = SubString_new_object(&name); if (obj == NULL) goto done; /* return a tuple of values */ result = PyTuple_Pack(2, is_attr_obj, obj); done: Py_XDECREF(is_attr_obj); Py_XDECREF(obj); return result; } } static PyMethodDef fieldnameiter_methods[] = { {NULL, NULL} /* sentinel */ }; static PyTypeObject PyFieldNameIter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "fieldnameiterator", /* tp_name */ sizeof(fieldnameiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)fieldnameiter_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)fieldnameiter_next, /* tp_iternext */ fieldnameiter_methods, /* tp_methods */ 0}; /* unicode_formatter_field_name_split is used to implement string.Formatter.vformat. it takes a PEP 3101 "field name", and returns a tuple of (first, rest): "first", the part before the first '.' or '['; and "rest", an iterator for the rest of the field name. it's a wrapper around stringlib/string_format.h's field_name_split. The iterator it returns is a FieldNameIterator */ static PyObject * formatter_field_name_split(PyObject *ignored, PyObject *self) { SubString first; Py_ssize_t first_idx; fieldnameiterobject *it; PyObject *first_obj = NULL; PyObject *result = NULL; if (!PyUnicode_Check(self)) { PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name); return NULL; } if (PyUnicode_READY(self) == -1) return NULL; it = PyObject_New(fieldnameiterobject, &PyFieldNameIter_Type); if (it == NULL) return NULL; /* take ownership, give the object to the iterator. this is just to keep the field_name alive */ Py_INCREF(self); it->str = self; /* Pass in auto_number = NULL. We'll return an empty string for first_obj in that case. */ if (!field_name_split((PyObject*)self, 0, PyUnicode_GET_LENGTH(self), &first, &first_idx, &it->it_field, NULL)) goto done; /* first becomes an integer, if possible; else a string */ if (first_idx != -1) first_obj = PyLong_FromSsize_t(first_idx); else /* convert "first" into a string object */ first_obj = SubString_new_object(&first); if (first_obj == NULL) goto done; /* return a tuple of values */ result = PyTuple_Pack(2, first_obj, it); done: Py_XDECREF(it); Py_XDECREF(first_obj); return result; }
41,975
1,297
jart/cosmopolitan
false
cosmopolitan/third_party/python/Objects/stringlib/fastsearch.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 */ /* stringlib: fastsearch implementation */ #define STRINGLIB_FASTSEARCH_H /* fast search/count implementation, based on a mix between boyer- moore and horspool, with a few more bells and whistles on the top. for some more background, see: http://effbot.org/zone/stringlib.htm */ /* note: fastsearch may access s[n], which isn't a problem when using Python's ordinary string types, but may cause problems if you're using this code in other contexts. also, the count mode returns -1 if there cannot possible be a match in the target string, and 0 if it has actually checked for matches, but didn't find any. callers beware! */ #define FAST_COUNT 0 #define FAST_SEARCH 1 #define FAST_RSEARCH 2 #if LONG_BIT >= 128 #define STRINGLIB_BLOOM_WIDTH 128 #elif LONG_BIT >= 64 #define STRINGLIB_BLOOM_WIDTH 64 #elif LONG_BIT >= 32 #define STRINGLIB_BLOOM_WIDTH 32 #else #error "LONG_BIT is smaller than 32" #endif #define STRINGLIB_BLOOM_ADD(mask, ch) \ ((mask |= (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH -1))))) #define STRINGLIB_BLOOM(mask, ch) \ ((mask & (1UL << ((ch) & (STRINGLIB_BLOOM_WIDTH -1))))) Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(find_char)(const STRINGLIB_CHAR* s, Py_ssize_t n, STRINGLIB_CHAR ch) { const STRINGLIB_CHAR *p, *e; p = s; e = s + n; if (n > 10) { #if STRINGLIB_SIZEOF_CHAR == 1 p = memchr(s, ch, n); if (p != NULL) return (p - s); return -1; #else /* use memchr if we can choose a needle without two many likely false positives */ unsigned char needle = ch & 0xff; /* If looking for a multiple of 256, we'd have too many false positives looking for the '\0' byte in UCS2 and UCS4 representations. */ if (needle != 0) { while (p < e) { void *candidate = memchr(p, needle, (e - p) * sizeof(STRINGLIB_CHAR)); if (candidate == NULL) return -1; p = (const STRINGLIB_CHAR *) _Py_ALIGN_DOWN(candidate, sizeof(STRINGLIB_CHAR)); if (*p == ch) return (p - s); /* False positive */ p++; } return -1; } #endif } while (p < e) { if (*p == ch) return (p - s); p++; } return -1; } Py_LOCAL_INLINE(Py_ssize_t) STRINGLIB(rfind_char)(const STRINGLIB_CHAR* s, Py_ssize_t n, STRINGLIB_CHAR ch) { const STRINGLIB_CHAR *p; #ifdef HAVE_MEMRCHR /* memrchr() is a GNU extension, available since glibc 2.1.91. it doesn't seem as optimized as memchr(), but is still quite faster than our hand-written loop below */ if (n > 10) { #if STRINGLIB_SIZEOF_CHAR == 1 p = memrchr(s, ch, n); if (p != NULL) return (p - s); return -1; #else /* use memrchr if we can choose a needle without two many likely false positives */ unsigned char needle = ch & 0xff; /* If looking for a multiple of 256, we'd have too many false positives looking for the '\0' byte in UCS2 and UCS4 representations. */ if (needle != 0) { while (n > 0) { void *candidate = memrchr(s, needle, n * sizeof(STRINGLIB_CHAR)); if (candidate == NULL) return -1; p = (const STRINGLIB_CHAR *) _Py_ALIGN_DOWN(candidate, sizeof(STRINGLIB_CHAR)); n = p - s; if (*p == ch) return n; /* False positive */ } return -1; } #endif } #endif /* HAVE_MEMRCHR */ p = s + n; while (p > s) { p--; if (*p == ch) return (p - s); } return -1; } Py_LOCAL_INLINE(Py_ssize_t) FASTSEARCH(const STRINGLIB_CHAR* s, Py_ssize_t n, const STRINGLIB_CHAR* p, Py_ssize_t m, Py_ssize_t maxcount, int mode) { unsigned long mask; Py_ssize_t skip, count = 0; Py_ssize_t i, j, mlast, w; w = n - m; if (w < 0 || (mode == FAST_COUNT && maxcount == 0)) return -1; /* look for special cases */ if (m <= 1) { if (m <= 0) return -1; /* use special case for 1-character strings */ if (mode == FAST_SEARCH) return STRINGLIB(find_char)(s, n, p[0]); else if (mode == FAST_RSEARCH) return STRINGLIB(rfind_char)(s, n, p[0]); else { /* FAST_COUNT */ for (i = 0; i < n; i++) if (s[i] == p[0]) { count++; if (count == maxcount) return maxcount; } return count; } return -1; } mlast = m - 1; skip = mlast - 1; mask = 0; if (mode != FAST_RSEARCH) { const STRINGLIB_CHAR *ss = s + m - 1; const STRINGLIB_CHAR *pp = p + m - 1; /* create compressed boyer-moore delta 1 table */ /* process pattern[:-1] */ for (i = 0; i < mlast; i++) { STRINGLIB_BLOOM_ADD(mask, p[i]); if (p[i] == p[mlast]) skip = mlast - i - 1; } /* process pattern[-1] outside the loop */ STRINGLIB_BLOOM_ADD(mask, p[mlast]); for (i = 0; i <= w; i++) { /* note: using mlast in the skip path slows things down on x86 */ if (ss[i] == pp[0]) { /* candidate match */ for (j = 0; j < mlast; j++) if (s[i+j] != p[j]) break; if (j == mlast) { /* got a match! */ if (mode != FAST_COUNT) return i; count++; if (count == maxcount) return maxcount; i = i + mlast; continue; } /* miss: check if next character is part of pattern */ if (!STRINGLIB_BLOOM(mask, ss[i+1])) i = i + m; else i = i + skip; } else { /* skip: check if next character is part of pattern */ if (!STRINGLIB_BLOOM(mask, ss[i+1])) i = i + m; } } } else { /* FAST_RSEARCH */ /* create compressed boyer-moore delta 1 table */ /* process pattern[0] outside the loop */ STRINGLIB_BLOOM_ADD(mask, p[0]); /* process pattern[:0:-1] */ for (i = mlast; i > 0; i--) { STRINGLIB_BLOOM_ADD(mask, p[i]); if (p[i] == p[0]) skip = i - 1; } for (i = w; i >= 0; i--) { if (s[i] == p[0]) { /* candidate match */ for (j = mlast; j > 0; j--) if (s[i+j] != p[j]) break; if (j == 0) /* got a match! */ return i; /* miss: check if previous character is part of pattern */ if (i > 0 && !STRINGLIB_BLOOM(mask, s[i-1])) i = i - m; else i = i - skip; } else { /* skip: check if previous character is part of pattern */ if (i > 0 && !STRINGLIB_BLOOM(mask, s[i-1])) i = i - m; } } } if (mode != FAST_COUNT) return -1; return count; }
8,560
259
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/import.h
#ifndef Py_IMPORT_H #define Py_IMPORT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API void _PyImportZip_Init(void); PyMODINIT_FUNC PyInit_imp(void); #endif /* !Py_LIMITED_API */ long PyImport_GetMagicNumber(void); const char * PyImport_GetMagicTag(void); PyObject * PyImport_ExecCodeModule( const char *name, /* UTF-8 encoded string */ PyObject *co ); PyObject * PyImport_ExecCodeModuleEx( const char *name, /* UTF-8 encoded string */ PyObject *co, const char *pathname /* decoded from the filesystem encoding */ ); PyObject * PyImport_ExecCodeModuleWithPathnames( const char *name, /* UTF-8 encoded string */ PyObject *co, const char *pathname, /* decoded from the filesystem encoding */ const char *cpathname /* decoded from the filesystem encoding */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject * PyImport_ExecCodeModuleObject( PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname ); #endif PyObject * PyImport_GetModuleDict(void); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject * PyImport_AddModuleObject( PyObject *name ); #endif PyObject * PyImport_AddModule( const char *name /* UTF-8 encoded string */ ); PyObject * PyImport_ImportModule( const char *name /* UTF-8 encoded string */ ); PyObject * PyImport_ImportModuleNoBlock( const char *name /* UTF-8 encoded string */ ); PyObject * PyImport_ImportModuleLevel( const char *name, /* UTF-8 encoded string */ PyObject *globals, PyObject *locals, PyObject *fromlist, int level ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 PyObject * PyImport_ImportModuleLevelObject( PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level ); #endif #define PyImport_ImportModuleEx(n, g, l, f) \ PyImport_ImportModuleLevel(n, g, l, f, 0) PyObject * PyImport_GetImporter(PyObject *path); PyObject * PyImport_Import(PyObject *name); PyObject * PyImport_ReloadModule(PyObject *m); void PyImport_Cleanup(void); void _PyImportLookupTables_Init(void); void _PyImportLookupTables_Cleanup(void); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 int PyImport_ImportFrozenModuleObject( PyObject *name ); #endif int PyImport_ImportFrozenModule( const char *name /* UTF-8 encoded string */ ); #ifndef Py_LIMITED_API #ifdef WITH_THREAD void _PyImport_AcquireLock(void); int _PyImport_ReleaseLock(void); #else #define _PyImport_AcquireLock() #define _PyImport_ReleaseLock() 1 #endif void _PyImport_ReInitLock(void); PyObject * _PyImport_FindBuiltin( const char *name /* UTF-8 encoded string */ ); PyObject * _PyImport_FindExtensionObject(PyObject *, PyObject *); int _PyImport_FixupBuiltin( PyObject *mod, const char *name /* UTF-8 encoded string */ ); int _PyImport_FixupExtensionObject(PyObject*, PyObject *, PyObject *); struct _inittab { const char *name; /* ASCII encoded string */ PyObject* (*initfunc)(void); }; extern const struct _inittab _PyImport_Inittab[]; extern struct _inittab * PyImport_Inittab; int PyImport_ExtendInittab(struct _inittab *newtab); #endif /* Py_LIMITED_API */ extern PyTypeObject PyNullImporter_Type; int PyImport_AppendInittab( const char *name, /* ASCII encoded string */ PyObject* (*initfunc)(void) ); #ifndef Py_LIMITED_API struct _frozen { const char *name; /* ASCII encoded string */ const unsigned char *code; int size; }; /* Embedding apps may change this pointer to point to their favorite collection of frozen modules: */ extern const struct _frozen * PyImport_FrozenModules; extern const struct _frozen _PyImport_FrozenModules[]; #endif COSMOPOLITAN_C_END_ #endif /* !Py_IMPORT_H */
4,054
140
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/Python-ast.h
#ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_PYTHON_AST_H_ #define COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_PYTHON_AST_H_ #include "third_party/python/Include/asdl.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ /* clang-format off */ /* File automatically generated by Parser/asdl_c.py. */ typedef struct _mod *mod_ty; typedef struct _stmt *stmt_ty; typedef struct _expr *expr_ty; typedef enum _expr_context { Load=1, Store=2, Del=3, AugLoad=4, AugStore=5, Param=6 } expr_context_ty; typedef struct _slice *slice_ty; typedef enum _boolop { And=1, Or=2 } boolop_ty; typedef enum _operator { Add=1, Sub=2, Mult=3, MatMult=4, Div=5, Mod=6, Pow=7, LShift=8, RShift=9, BitOr=10, BitXor=11, BitAnd=12, FloorDiv=13 } operator_ty; typedef enum _unaryop { Invert=1, Not=2, UAdd=3, USub=4 } unaryop_ty; typedef enum _cmpop { Eq=1, NotEq=2, Lt=3, LtE=4, Gt=5, GtE=6, Is=7, IsNot=8, In=9, NotIn=10 } cmpop_ty; typedef struct _comprehension *comprehension_ty; typedef struct _excepthandler *excepthandler_ty; typedef struct _arguments *arguments_ty; typedef struct _arg *arg_ty; typedef struct _keyword *keyword_ty; typedef struct _alias *alias_ty; typedef struct _withitem *withitem_ty; enum _mod_kind {Module_kind=1, Interactive_kind=2, Expression_kind=3, Suite_kind=4}; struct _mod { enum _mod_kind kind; union { struct { asdl_seq *body; } Module; struct { asdl_seq *body; } Interactive; struct { expr_ty body; } Expression; struct { asdl_seq *body; } Suite; } v; }; enum _stmt_kind {FunctionDef_kind=1, AsyncFunctionDef_kind=2, ClassDef_kind=3, Return_kind=4, Delete_kind=5, Assign_kind=6, AugAssign_kind=7, AnnAssign_kind=8, For_kind=9, AsyncFor_kind=10, While_kind=11, If_kind=12, With_kind=13, AsyncWith_kind=14, Raise_kind=15, Try_kind=16, Assert_kind=17, Import_kind=18, ImportFrom_kind=19, Global_kind=20, Nonlocal_kind=21, Expr_kind=22, Pass_kind=23, Break_kind=24, Continue_kind=25}; struct _stmt { enum _stmt_kind kind; union { struct { identifier name; arguments_ty args; asdl_seq *body; asdl_seq *decorator_list; expr_ty returns; } FunctionDef; struct { identifier name; arguments_ty args; asdl_seq *body; asdl_seq *decorator_list; expr_ty returns; } AsyncFunctionDef; struct { identifier name; asdl_seq *bases; asdl_seq *keywords; asdl_seq *body; asdl_seq *decorator_list; } ClassDef; struct { expr_ty value; } Return; struct { asdl_seq *targets; } Delete; struct { asdl_seq *targets; expr_ty value; } Assign; struct { expr_ty target; operator_ty op; expr_ty value; } AugAssign; struct { expr_ty target; expr_ty annotation; expr_ty value; int simple; } AnnAssign; struct { expr_ty target; expr_ty iter; asdl_seq *body; asdl_seq *orelse; } For; struct { expr_ty target; expr_ty iter; asdl_seq *body; asdl_seq *orelse; } AsyncFor; struct { expr_ty test; asdl_seq *body; asdl_seq *orelse; } While; struct { expr_ty test; asdl_seq *body; asdl_seq *orelse; } If; struct { asdl_seq *items; asdl_seq *body; } With; struct { asdl_seq *items; asdl_seq *body; } AsyncWith; struct { expr_ty exc; expr_ty cause; } Raise; struct { asdl_seq *body; asdl_seq *handlers; asdl_seq *orelse; asdl_seq *finalbody; } Try; struct { expr_ty test; expr_ty msg; } Assert; struct { asdl_seq *names; } Import; struct { identifier module; asdl_seq *names; int level; } ImportFrom; struct { asdl_seq *names; } Global; struct { asdl_seq *names; } Nonlocal; struct { expr_ty value; } Expr; } v; int lineno; int col_offset; }; enum _expr_kind {BoolOp_kind=1, BinOp_kind=2, UnaryOp_kind=3, Lambda_kind=4, IfExp_kind=5, Dict_kind=6, Set_kind=7, ListComp_kind=8, SetComp_kind=9, DictComp_kind=10, GeneratorExp_kind=11, Await_kind=12, Yield_kind=13, YieldFrom_kind=14, Compare_kind=15, Call_kind=16, Num_kind=17, Str_kind=18, FormattedValue_kind=19, JoinedStr_kind=20, Bytes_kind=21, NameConstant_kind=22, Ellipsis_kind=23, Constant_kind=24, Attribute_kind=25, Subscript_kind=26, Starred_kind=27, Name_kind=28, List_kind=29, Tuple_kind=30}; struct _expr { enum _expr_kind kind; union { struct { boolop_ty op; asdl_seq *values; } BoolOp; struct { expr_ty left; operator_ty op; expr_ty right; } BinOp; struct { unaryop_ty op; expr_ty operand; } UnaryOp; struct { arguments_ty args; expr_ty body; } Lambda; struct { expr_ty test; expr_ty body; expr_ty orelse; } IfExp; struct { asdl_seq *keys; asdl_seq *values; } Dict; struct { asdl_seq *elts; } Set; struct { expr_ty elt; asdl_seq *generators; } ListComp; struct { expr_ty elt; asdl_seq *generators; } SetComp; struct { expr_ty key; expr_ty value; asdl_seq *generators; } DictComp; struct { expr_ty elt; asdl_seq *generators; } GeneratorExp; struct { expr_ty value; } Await; struct { expr_ty value; } Yield; struct { expr_ty value; } YieldFrom; struct { expr_ty left; asdl_int_seq *ops; asdl_seq *comparators; } Compare; struct { expr_ty func; asdl_seq *args; asdl_seq *keywords; } Call; struct { object n; } Num; struct { string s; } Str; struct { expr_ty value; int conversion; expr_ty format_spec; } FormattedValue; struct { asdl_seq *values; } JoinedStr; struct { bytes s; } Bytes; struct { singleton value; } NameConstant; struct { constant value; } Constant; struct { expr_ty value; identifier attr; expr_context_ty ctx; } Attribute; struct { expr_ty value; slice_ty slice; expr_context_ty ctx; } Subscript; struct { expr_ty value; expr_context_ty ctx; } Starred; struct { identifier id; expr_context_ty ctx; } Name; struct { asdl_seq *elts; expr_context_ty ctx; } List; struct { asdl_seq *elts; expr_context_ty ctx; } Tuple; } v; int lineno; int col_offset; }; enum _slice_kind {Slice_kind=1, ExtSlice_kind=2, Index_kind=3}; struct _slice { enum _slice_kind kind; union { struct { expr_ty lower; expr_ty upper; expr_ty step; } Slice; struct { asdl_seq *dims; } ExtSlice; struct { expr_ty value; } Index; } v; }; struct _comprehension { expr_ty target; expr_ty iter; asdl_seq *ifs; int is_async; }; enum _excepthandler_kind {ExceptHandler_kind=1}; struct _excepthandler { enum _excepthandler_kind kind; union { struct { expr_ty type; identifier name; asdl_seq *body; } ExceptHandler; } v; int lineno; int col_offset; }; struct _arguments { asdl_seq *args; arg_ty vararg; asdl_seq *kwonlyargs; asdl_seq *kw_defaults; arg_ty kwarg; asdl_seq *defaults; }; struct _arg { identifier arg; expr_ty annotation; int lineno; int col_offset; }; struct _keyword { identifier arg; expr_ty value; }; struct _alias { identifier name; identifier asname; }; struct _withitem { expr_ty context_expr; expr_ty optional_vars; }; #define Module(a0, a1) _Py_Module(a0, a1) mod_ty _Py_Module(asdl_seq * body, PyArena *arena); #define Interactive(a0, a1) _Py_Interactive(a0, a1) mod_ty _Py_Interactive(asdl_seq * body, PyArena *arena); #define Expression(a0, a1) _Py_Expression(a0, a1) mod_ty _Py_Expression(expr_ty body, PyArena *arena); #define Suite(a0, a1) _Py_Suite(a0, a1) mod_ty _Py_Suite(asdl_seq * body, PyArena *arena); #define FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq * decorator_list, expr_ty returns, int lineno, int col_offset, PyArena *arena); #define AsyncFunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_AsyncFunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_AsyncFunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq * decorator_list, expr_ty returns, int lineno, int col_offset, PyArena *arena); #define ClassDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_ClassDef(a0, a1, a2, a3, a4, a5, a6, a7) stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * keywords, asdl_seq * body, asdl_seq * decorator_list, int lineno, int col_offset, PyArena *arena); #define Return(a0, a1, a2, a3) _Py_Return(a0, a1, a2, a3) stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, PyArena *arena); #define Delete(a0, a1, a2, a3) _Py_Delete(a0, a1, a2, a3) stmt_ty _Py_Delete(asdl_seq * targets, int lineno, int col_offset, PyArena *arena); #define Assign(a0, a1, a2, a3, a4) _Py_Assign(a0, a1, a2, a3, a4) stmt_ty _Py_Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset, PyArena *arena); #define AugAssign(a0, a1, a2, a3, a4, a5) _Py_AugAssign(a0, a1, a2, a3, a4, a5) stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno, int col_offset, PyArena *arena); #define AnnAssign(a0, a1, a2, a3, a4, a5, a6) _Py_AnnAssign(a0, a1, a2, a3, a4, a5, a6) stmt_ty _Py_AnnAssign(expr_ty target, expr_ty annotation, expr_ty value, int simple, int lineno, int col_offset, PyArena *arena); #define For(a0, a1, a2, a3, a4, a5, a6) _Py_For(a0, a1, a2, a3, a4, a5, a6) stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena); #define AsyncFor(a0, a1, a2, a3, a4, a5, a6) _Py_AsyncFor(a0, a1, a2, a3, a4, a5, a6) stmt_ty _Py_AsyncFor(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena); #define While(a0, a1, a2, a3, a4, a5) _Py_While(a0, a1, a2, a3, a4, a5) stmt_ty _Py_While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena); #define If(a0, a1, a2, a3, a4, a5) _Py_If(a0, a1, a2, a3, a4, a5) stmt_ty _Py_If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int col_offset, PyArena *arena); #define With(a0, a1, a2, a3, a4) _Py_With(a0, a1, a2, a3, a4) stmt_ty _Py_With(asdl_seq * items, asdl_seq * body, int lineno, int col_offset, PyArena *arena); #define AsyncWith(a0, a1, a2, a3, a4) _Py_AsyncWith(a0, a1, a2, a3, a4) stmt_ty _Py_AsyncWith(asdl_seq * items, asdl_seq * body, int lineno, int col_offset, PyArena *arena); #define Raise(a0, a1, a2, a3, a4) _Py_Raise(a0, a1, a2, a3, a4) stmt_ty _Py_Raise(expr_ty exc, expr_ty cause, int lineno, int col_offset, PyArena *arena); #define Try(a0, a1, a2, a3, a4, a5, a6) _Py_Try(a0, a1, a2, a3, a4, a5, a6) stmt_ty _Py_Try(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, asdl_seq * finalbody, int lineno, int col_offset, PyArena *arena); #define Assert(a0, a1, a2, a3, a4) _Py_Assert(a0, a1, a2, a3, a4) stmt_ty _Py_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, PyArena *arena); #define Import(a0, a1, a2, a3) _Py_Import(a0, a1, a2, a3) stmt_ty _Py_Import(asdl_seq * names, int lineno, int col_offset, PyArena *arena); #define ImportFrom(a0, a1, a2, a3, a4, a5) _Py_ImportFrom(a0, a1, a2, a3, a4, a5) stmt_ty _Py_ImportFrom(identifier module, asdl_seq * names, int level, int lineno, int col_offset, PyArena *arena); #define Global(a0, a1, a2, a3) _Py_Global(a0, a1, a2, a3) stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena); #define Nonlocal(a0, a1, a2, a3) _Py_Nonlocal(a0, a1, a2, a3) stmt_ty _Py_Nonlocal(asdl_seq * names, int lineno, int col_offset, PyArena *arena); #define Expr(a0, a1, a2, a3) _Py_Expr(a0, a1, a2, a3) stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, PyArena *arena); #define Pass(a0, a1, a2) _Py_Pass(a0, a1, a2) stmt_ty _Py_Pass(int lineno, int col_offset, PyArena *arena); #define Break(a0, a1, a2) _Py_Break(a0, a1, a2) stmt_ty _Py_Break(int lineno, int col_offset, PyArena *arena); #define Continue(a0, a1, a2) _Py_Continue(a0, a1, a2) stmt_ty _Py_Continue(int lineno, int col_offset, PyArena *arena); #define BoolOp(a0, a1, a2, a3, a4) _Py_BoolOp(a0, a1, a2, a3, a4) expr_ty _Py_BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset, PyArena *arena); #define BinOp(a0, a1, a2, a3, a4, a5) _Py_BinOp(a0, a1, a2, a3, a4, a5) expr_ty _Py_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int col_offset, PyArena *arena); #define UnaryOp(a0, a1, a2, a3, a4) _Py_UnaryOp(a0, a1, a2, a3, a4) expr_ty _Py_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset, PyArena *arena); #define Lambda(a0, a1, a2, a3, a4) _Py_Lambda(a0, a1, a2, a3, a4) expr_ty _Py_Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset, PyArena *arena); #define IfExp(a0, a1, a2, a3, a4, a5) _Py_IfExp(a0, a1, a2, a3, a4, a5) expr_ty _Py_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int col_offset, PyArena *arena); #define Dict(a0, a1, a2, a3, a4) _Py_Dict(a0, a1, a2, a3, a4) expr_ty _Py_Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, PyArena *arena); #define Set(a0, a1, a2, a3) _Py_Set(a0, a1, a2, a3) expr_ty _Py_Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena); #define ListComp(a0, a1, a2, a3, a4) _Py_ListComp(a0, a1, a2, a3, a4) expr_ty _Py_ListComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena); #define SetComp(a0, a1, a2, a3, a4) _Py_SetComp(a0, a1, a2, a3, a4) expr_ty _Py_SetComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena); #define DictComp(a0, a1, a2, a3, a4, a5) _Py_DictComp(a0, a1, a2, a3, a4, a5) expr_ty _Py_DictComp(expr_ty key, expr_ty value, asdl_seq * generators, int lineno, int col_offset, PyArena *arena); #define GeneratorExp(a0, a1, a2, a3, a4) _Py_GeneratorExp(a0, a1, a2, a3, a4) expr_ty _Py_GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena); #define Await(a0, a1, a2, a3) _Py_Await(a0, a1, a2, a3) expr_ty _Py_Await(expr_ty value, int lineno, int col_offset, PyArena *arena); #define Yield(a0, a1, a2, a3) _Py_Yield(a0, a1, a2, a3) expr_ty _Py_Yield(expr_ty value, int lineno, int col_offset, PyArena *arena); #define YieldFrom(a0, a1, a2, a3) _Py_YieldFrom(a0, a1, a2, a3) expr_ty _Py_YieldFrom(expr_ty value, int lineno, int col_offset, PyArena *arena); #define Compare(a0, a1, a2, a3, a4, a5) _Py_Compare(a0, a1, a2, a3, a4, a5) expr_ty _Py_Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, int lineno, int col_offset, PyArena *arena); #define Call(a0, a1, a2, a3, a4, a5) _Py_Call(a0, a1, a2, a3, a4, a5) expr_ty _Py_Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, int lineno, int col_offset, PyArena *arena); #define Num(a0, a1, a2, a3) _Py_Num(a0, a1, a2, a3) expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena); #define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3) expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena); #define FormattedValue(a0, a1, a2, a3, a4, a5) _Py_FormattedValue(a0, a1, a2, a3, a4, a5) expr_ty _Py_FormattedValue(expr_ty value, int conversion, expr_ty format_spec, int lineno, int col_offset, PyArena *arena); #define JoinedStr(a0, a1, a2, a3) _Py_JoinedStr(a0, a1, a2, a3) expr_ty _Py_JoinedStr(asdl_seq * values, int lineno, int col_offset, PyArena *arena); #define Bytes(a0, a1, a2, a3) _Py_Bytes(a0, a1, a2, a3) expr_ty _Py_Bytes(bytes s, int lineno, int col_offset, PyArena *arena); #define NameConstant(a0, a1, a2, a3) _Py_NameConstant(a0, a1, a2, a3) expr_ty _Py_NameConstant(singleton value, int lineno, int col_offset, PyArena *arena); #define Ellipsis(a0, a1, a2) _Py_Ellipsis(a0, a1, a2) expr_ty _Py_Ellipsis(int lineno, int col_offset, PyArena *arena); #define Constant(a0, a1, a2, a3) _Py_Constant(a0, a1, a2, a3) expr_ty _Py_Constant(constant value, int lineno, int col_offset, PyArena *arena); #define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5) expr_ty _Py_Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena); #define Subscript(a0, a1, a2, a3, a4, a5) _Py_Subscript(a0, a1, a2, a3, a4, a5) expr_ty _Py_Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena); #define Starred(a0, a1, a2, a3, a4) _Py_Starred(a0, a1, a2, a3, a4) expr_ty _Py_Starred(expr_ty value, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena); #define Name(a0, a1, a2, a3, a4) _Py_Name(a0, a1, a2, a3, a4) expr_ty _Py_Name(identifier id, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena); #define List(a0, a1, a2, a3, a4) _Py_List(a0, a1, a2, a3, a4) expr_ty _Py_List(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena); #define Tuple(a0, a1, a2, a3, a4) _Py_Tuple(a0, a1, a2, a3, a4) expr_ty _Py_Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset, PyArena *arena); #define Slice(a0, a1, a2, a3) _Py_Slice(a0, a1, a2, a3) slice_ty _Py_Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena); #define ExtSlice(a0, a1) _Py_ExtSlice(a0, a1) slice_ty _Py_ExtSlice(asdl_seq * dims, PyArena *arena); #define Index(a0, a1) _Py_Index(a0, a1) slice_ty _Py_Index(expr_ty value, PyArena *arena); #define comprehension(a0, a1, a2, a3, a4) _Py_comprehension(a0, a1, a2, a3, a4) comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq * ifs, int is_async, PyArena *arena); #define ExceptHandler(a0, a1, a2, a3, a4, a5) _Py_ExceptHandler(a0, a1, a2, a3, a4, a5) excepthandler_ty _Py_ExceptHandler(expr_ty type, identifier name, asdl_seq * body, int lineno, int col_offset, PyArena *arena); #define arguments(a0, a1, a2, a3, a4, a5, a6) _Py_arguments(a0, a1, a2, a3, a4, a5, a6) arguments_ty _Py_arguments(asdl_seq * args, arg_ty vararg, asdl_seq * kwonlyargs, asdl_seq * kw_defaults, arg_ty kwarg, asdl_seq * defaults, PyArena *arena); #define arg(a0, a1, a2, a3, a4) _Py_arg(a0, a1, a2, a3, a4) arg_ty _Py_arg(identifier arg, expr_ty annotation, int lineno, int col_offset, PyArena *arena); #define keyword(a0, a1, a2) _Py_keyword(a0, a1, a2) keyword_ty _Py_keyword(identifier arg, expr_ty value, PyArena *arena); #define alias(a0, a1, a2) _Py_alias(a0, a1, a2) alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena); #define withitem(a0, a1, a2) _Py_withitem(a0, a1, a2) withitem_ty _Py_withitem(expr_ty context_expr, expr_ty optional_vars, PyArena *arena); PyObject* PyAST_mod2obj(mod_ty t); mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode); int PyAST_Check(PyObject* obj); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_PYTHON_AST_H_ */
22,642
646
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/namespaceobject.h
#ifndef NAMESPACEOBJECT_H #define NAMESPACEOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API extern PyTypeObject _PyNamespace_Type; PyObject * _PyNamespace_New(PyObject *kwds); #endif /* !Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !NAMESPACEOBJECT_H */
335
15
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/Python.h
#ifndef Py_PYTHON_H #define Py_PYTHON_H /* clang-format off */ /* * PYTHON DIAMOND DEPENDENCY HEADER * * If your editor isn't able to automatically insert #include lines, * then this header can make development easier. It's also great for * making beginner's tutorials simpler and more attractive. * * However it's sloppy to use something like this in the long term since * it's not a scalable dependency model. It makes builds slower, because * changing any single header will invalidate all the build artifacts. * * So please consider doing the conscientious thing and avoid using it! */ #include "libc/errno.h" #include "third_party/python/pyconfig.h" #include "third_party/python/Include/patchlevel.h" #include "third_party/python/pyconfig.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pyatomic.h" #include "third_party/python/Include/pymath.h" #include "third_party/python/Include/pytime.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/typeslots.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/longintrepr.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/rangeobject.h" #include "third_party/python/Include/memoryobject.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/odictobject.h" #include "third_party/python/Include/enumobject.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/classobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/pycapsule.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/cellobject.h" #include "third_party/python/Include/iterobject.h" #include "third_party/python/Include/genobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Include/weakrefobject.h" #include "third_party/python/Include/structseq.h" #include "third_party/python/Include/namespaceobject.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/pyarena.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/osmodule.h" #include "third_party/python/Include/intrcheck.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bltinmodule.h" #include "third_party/python/Include/compile.h" #include "third_party/python/Include/eval.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pystrtod.h" #include "third_party/python/Include/pystrcmp.h" #include "third_party/python/Include/dtoa.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/pyfpe.h" #endif /* !Py_PYTHON_H */
4,043
90
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/opcode.h
#ifndef Py_OPCODE_H #define Py_OPCODE_H #include "third_party/python/Include/op.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Auto-generated by Tools/scripts/generate_opcode_h.py */ /* Instruction opcodes for compiled code */ #define POP_TOP 1 #define ROT_TWO 2 #define ROT_THREE 3 #define DUP_TOP 4 #define DUP_TOP_TWO 5 #define NOP 9 #define UNARY_POSITIVE 10 #define UNARY_NEGATIVE 11 #define UNARY_NOT 12 #define UNARY_INVERT 15 #define BINARY_MATRIX_MULTIPLY 16 #define INPLACE_MATRIX_MULTIPLY 17 #define BINARY_POWER 19 #define BINARY_MULTIPLY 20 #define BINARY_MODULO 22 #define BINARY_ADD 23 #define BINARY_SUBTRACT 24 #define BINARY_SUBSCR 25 #define BINARY_FLOOR_DIVIDE 26 #define BINARY_TRUE_DIVIDE 27 #define INPLACE_FLOOR_DIVIDE 28 #define INPLACE_TRUE_DIVIDE 29 #define GET_AITER 50 #define GET_ANEXT 51 #define BEFORE_ASYNC_WITH 52 #define INPLACE_ADD 55 #define INPLACE_SUBTRACT 56 #define INPLACE_MULTIPLY 57 #define INPLACE_MODULO 59 #define STORE_SUBSCR 60 #define DELETE_SUBSCR 61 #define BINARY_LSHIFT 62 #define BINARY_RSHIFT 63 #define BINARY_AND 64 #define BINARY_XOR 65 #define BINARY_OR 66 #define INPLACE_POWER 67 #define GET_ITER 68 #define GET_YIELD_FROM_ITER 69 #define PRINT_EXPR 70 #define LOAD_BUILD_CLASS 71 #define YIELD_FROM 72 #define GET_AWAITABLE 73 #define INPLACE_LSHIFT 75 #define INPLACE_RSHIFT 76 #define INPLACE_AND 77 #define INPLACE_XOR 78 #define INPLACE_OR 79 #define BREAK_LOOP 80 #define WITH_CLEANUP_START 81 #define WITH_CLEANUP_FINISH 82 #define RETURN_VALUE 83 #define IMPORT_STAR 84 #define SETUP_ANNOTATIONS 85 #define YIELD_VALUE 86 #define POP_BLOCK 87 #define END_FINALLY 88 #define POP_EXCEPT 89 #define HAVE_ARGUMENT 90 #define STORE_NAME 90 #define DELETE_NAME 91 #define UNPACK_SEQUENCE 92 #define FOR_ITER 93 #define UNPACK_EX 94 #define STORE_ATTR 95 #define DELETE_ATTR 96 #define STORE_GLOBAL 97 #define DELETE_GLOBAL 98 #define LOAD_CONST 100 #define LOAD_NAME 101 #define BUILD_TUPLE 102 #define BUILD_LIST 103 #define BUILD_SET 104 #define BUILD_MAP 105 #define LOAD_ATTR 106 #define COMPARE_OP 107 #define IMPORT_NAME 108 #define IMPORT_FROM 109 #define JUMP_FORWARD 110 #define JUMP_IF_FALSE_OR_POP 111 #define JUMP_IF_TRUE_OR_POP 112 #define JUMP_ABSOLUTE 113 #define POP_JUMP_IF_FALSE 114 #define POP_JUMP_IF_TRUE 115 #define LOAD_GLOBAL 116 #define CONTINUE_LOOP 119 #define SETUP_LOOP 120 #define SETUP_EXCEPT 121 #define SETUP_FINALLY 122 #define LOAD_FAST 124 #define STORE_FAST 125 #define DELETE_FAST 126 #define STORE_ANNOTATION 127 #define RAISE_VARARGS 130 #define CALL_FUNCTION 131 #define MAKE_FUNCTION 132 #define BUILD_SLICE 133 #define LOAD_CLOSURE 135 #define LOAD_DEREF 136 #define STORE_DEREF 137 #define DELETE_DEREF 138 #define CALL_FUNCTION_KW 141 #define CALL_FUNCTION_EX 142 #define SETUP_WITH 143 #define EXTENDED_ARG 144 #define LIST_APPEND 145 #define SET_ADD 146 #define MAP_ADD 147 #define LOAD_CLASSDEREF 148 #define BUILD_LIST_UNPACK 149 #define BUILD_MAP_UNPACK 150 #define BUILD_MAP_UNPACK_WITH_CALL 151 #define BUILD_TUPLE_UNPACK 152 #define BUILD_SET_UNPACK 153 #define SETUP_ASYNC_WITH 154 #define FORMAT_VALUE 155 #define BUILD_CONST_KEY_MAP 156 #define BUILD_STRING 157 #define BUILD_TUPLE_UNPACK_WITH_CALL 158 #define LOAD_METHOD 160 #define CALL_METHOD 161 /* EXCEPT_HANDLER is a special, implicit block type which is created when entering an except handler. It is not an opcode but we define it here as we want it to be available to both frameobject.c and ceval.c, while remaining private.*/ #define EXCEPT_HANDLER 257 enum cmp_op {PyCmp_LT=Py_LT, PyCmp_LE=Py_LE, PyCmp_EQ=Py_EQ, PyCmp_NE=Py_NE, PyCmp_GT=Py_GT, PyCmp_GE=Py_GE, PyCmp_IN, PyCmp_NOT_IN, PyCmp_IS, PyCmp_IS_NOT, PyCmp_EXC_MATCH, PyCmp_BAD}; #define HAS_ARG(op) ((op) >= HAVE_ARGUMENT) COSMOPOLITAN_C_END_ #endif /* !Py_OPCODE_H */
5,180
145
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/asdl.h
#ifndef Py_ASDL_H #define Py_ASDL_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyarena.h" /* clang-format off */ typedef PyObject * identifier; typedef PyObject * string; typedef PyObject * bytes; typedef PyObject * object; typedef PyObject * singleton; typedef PyObject * constant; /* It would be nice if the code generated by asdl_c.py was completely independent of Python, but it is a goal the requires too much work at this stage. So, for example, I'll represent identifiers as interned Python strings. */ /* XXX A sequence should be typed so that its use can be typechecked. */ typedef struct { Py_ssize_t size; void *elements[1]; } asdl_seq; typedef struct { Py_ssize_t size; int elements[1]; } asdl_int_seq; asdl_seq *_Py_asdl_seq_new(Py_ssize_t size, PyArena *arena); asdl_int_seq *_Py_asdl_int_seq_new(Py_ssize_t size, PyArena *arena); #define asdl_seq_GET(S, I) (S)->elements[(I)] #define asdl_seq_LEN(S) ((S) == NULL ? 0 : (S)->size) #ifdef Py_DEBUG #define asdl_seq_SET(S, I, V) \ do { \ Py_ssize_t _asdl_i = (I); \ assert((S) != NULL); \ assert(_asdl_i < (S)->size); \ (S)->elements[_asdl_i] = (V); \ } while (0) #else #define asdl_seq_SET(S, I, V) (S)->elements[I] = (V) #endif #endif /* !Py_ASDL_H */
1,331
50
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/code.h
#ifndef Py_LIMITED_API #ifndef Py_CODE_H #define Py_CODE_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ typedef uint16_t _Py_CODEUNIT; #ifdef WORDS_BIGENDIAN #define _Py_OPCODE(word) ((word) >> 8) #define _Py_OPARG(word) ((word)&255) #else #define _Py_OPCODE(word) ((word)&255) #define _Py_OPARG(word) ((word) >> 8) #endif /* Bytecode object */ typedef struct { PyObject_HEAD int co_argcount; /* #arguments, except *args */ int co_kwonlyargcount; /* #keyword only arguments */ int co_nlocals; /* #local variables */ int co_stacksize; /* #entries needed for evaluation stack */ int co_flags; /* CO_..., see below */ int co_firstlineno; /* first source line number */ PyObject *co_code; /* instruction opcodes */ PyObject *co_consts; /* list (constants used) */ PyObject *co_names; /* list of strings (names used) */ PyObject *co_varnames; /* tuple of strings (local variable names) */ PyObject *co_freevars; /* tuple of strings (free variable names) */ PyObject *co_cellvars; /* tuple of strings (cell variable names) */ /* The rest aren't used in either hash or comparisons, except for co_name, used in both. This is done to preserve the name and line number for tracebacks and debuggers; otherwise, constant de-duplication would collapse identical functions/lambdas defined on different lines. */ unsigned char *co_cell2arg; /* Maps cell vars which are arguments. */ PyObject *co_filename; /* unicode (where it was loaded from) */ PyObject *co_name; /* unicode (name, for reference) */ PyObject *co_lnotab; /* string (encoding addr<->lineno mapping) See Objects/lnotab_notes.txt for details. */ void *co_zombieframe; /* for optimization only (see frameobject.c) */ PyObject *co_weakreflist; /* to support weakrefs to code objects */ /* Scratch space for extra data relating to the code object. Type is a void* to keep the format private in codeobject.c to force people to go through the proper APIs. */ void *co_extra; } PyCodeObject; /* Masks for co_flags above */ #define CO_OPTIMIZED 0x0001 #define CO_NEWLOCALS 0x0002 #define CO_VARARGS 0x0004 #define CO_VARKEYWORDS 0x0008 #define CO_NESTED 0x0010 #define CO_GENERATOR 0x0020 /* The CO_NOFREE flag is set if there are no free or cell variables. This information is redundant, but it allows a single flag test to determine whether there is any extra work to be done when the call frame it setup. */ #define CO_NOFREE 0x0040 /* The CO_COROUTINE flag is set for coroutine functions (defined with ``async def`` keywords) */ #define CO_COROUTINE 0x0080 #define CO_ITERABLE_COROUTINE 0x0100 #define CO_ASYNC_GENERATOR 0x0200 /* These are no longer used. */ #if 0 #define CO_GENERATOR_ALLOWED 0x1000 #endif #define CO_FUTURE_DIVISION 0x2000 #define CO_FUTURE_ABSOLUTE_IMPORT 0x4000 /* do absolute imports by default */ #define CO_FUTURE_WITH_STATEMENT 0x8000 #define CO_FUTURE_PRINT_FUNCTION 0x10000 #define CO_FUTURE_UNICODE_LITERALS 0x20000 #define CO_FUTURE_BARRY_AS_BDFL 0x40000 #define CO_FUTURE_GENERATOR_STOP 0x80000 /* This value is found in the co_cell2arg array when the associated cell variable does not correspond to an argument. The maximum number of arguments is 255 (indexed up to 254), so 255 work as a special flag.*/ #define CO_CELL_NOT_AN_ARG 255 /* This should be defined if a future statement modifies the syntax. For example, when a keyword is added. */ #define PY_PARSER_REQUIRES_FUTURE_KEYWORD #define CO_MAXBLOCKS 20 /* Max static block nesting within a function */ extern PyTypeObject PyCode_Type; #define PyCode_Check(op) (Py_TYPE(op) == &PyCode_Type) #define PyCode_GetNumFree(op) (PyTuple_GET_SIZE((op)->co_freevars)) /* Public interface */ PyCodeObject *PyCode_New(int, int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *); /* same as struct above */ /* Creates a new empty code object with the specified source location. */ PyCodeObject *PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno); /* Return the line number associated with the specified bytecode index in this code object. If you just need the line number of a frame, use PyFrame_GetLineNumber() instead. */ int PyCode_Addr2Line(PyCodeObject *, int); /* for internal use only */ typedef struct _addr_pair { int ap_lower; int ap_upper; } PyAddrPair; #ifndef Py_LIMITED_API /* 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); /* Create a comparable key used to compare constants taking in account the * object type. It is used to make sure types are not coerced (e.g., float and * complex) _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms * * Return (type(obj), obj, ...): a tuple with variable size (at least 2 items) * depending on the type and the value. The type is the first item to not * compare bytes and str which can raise a BytesWarning exception. */ PyObject *_PyCode_ConstantKey(PyObject *obj); #endif PyObject *PyCode_Optimize(PyObject *code, PyObject *consts, PyObject *names, PyObject *lnotab); #ifndef Py_LIMITED_API int _PyCode_GetExtra(PyObject *code, Py_ssize_t index, void **extra); int _PyCode_SetExtra(PyObject *code, Py_ssize_t index, void *extra); #endif COSMOPOLITAN_C_END_ #endif /* !Py_CODE_H */ #endif /* Py_LIMITED_API */
5,859
147
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/abstract.h
#ifndef Py_ABSTRACTOBJECT_H #define Py_ABSTRACTOBJECT_H #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/tupleobject.h" COSMOPOLITAN_C_START_ /* Abstract Object Interface (many thanks to Jim Fulton) */ #define PyObject_DelAttrString(O, A) PyObject_SetAttrString((O), (A), NULL) #define PyObject_DelAttr(O, A) PyObject_SetAttr((O), (A), NULL) PyObject *PyObject_Call(PyObject *callable_object, PyObject *args, PyObject *kwargs); #ifndef Py_LIMITED_API PyObject *_PyStack_AsTuple(PyObject **stack, Py_ssize_t nargs); PyObject *_PyStack_AsTupleSlice(PyObject **stack, Py_ssize_t nargs, Py_ssize_t start, Py_ssize_t end); PyObject *_PyStack_AsDict(PyObject **values, PyObject *kwnames); int _PyStack_UnpackDict( PyObject **args, Py_ssize_t nargs, PyObject *kwargs, PyObject ***p_stack, PyObject **p_kwnames); PyObject *_PyObject_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); PyObject *_PyObject_FastCallKeywords(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwnames); #define _PyObject_FastCall(func, args, nargs) \ _PyObject_FastCallDict((func), (args), (nargs), NULL) #define _PyObject_CallNoArg(func) _PyObject_FastCall((func), NULL, 0) #define _PyObject_CallArg1(func, arg) _PyObject_FastCall((func), &(arg), 1) PyObject *_PyObject_Call_Prepend(PyObject *func, PyObject *obj, PyObject *args, PyObject *kwargs); #define _PY_FASTCALL_SMALL_STACK 5 int _PyObject_HasFastCall(PyObject *callable); PyObject *_PyObject_FastCall_Prepend( PyObject *callable, PyObject *obj, PyObject **args, Py_ssize_t nargs); #if IsModeDbg() PyObject *_Py_CheckFunctionResult(PyObject *func, PyObject *result, const char *where); #else #define _Py_CheckFunctionResult(func, result, where) (result) #endif #endif /* Py_LIMITED_API */ PyObject *PyObject_CallObject(PyObject *callable_object, PyObject *args); /* Call a callable Python object, callable_object, with arguments given by the tuple, args. If no arguments are needed, then args may be NULL. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: o(*args). */ PyObject *PyObject_CallFunction(PyObject *callable_object, const char *format, ...); /* Call a callable Python object, callable_object, with a variable number of C arguments. The C arguments are described using a mkvalue-style format string. The format may be NULL, indicating that no arguments are provided. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: o(*args). */ PyObject *PyObject_CallMethod(PyObject *o, const char *method, const char *format, ...); /* Call the method named m of object o with a variable number of C arguments. The C arguments are described by a mkvalue format string. The format may be NULL, indicating that no arguments are provided. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: o.method(args). */ #ifndef Py_LIMITED_API PyObject *_PyObject_CallMethodId(PyObject *o, _Py_Identifier *method, const char *format, ...); /* Like PyObject_CallMethod, but expect a _Py_Identifier* as the method name. */ #endif /* !Py_LIMITED_API */ #ifdef PY_SSIZE_T_CLEAN #define PyObject_CallFunction _PyObject_CallFunction_SizeT #define PyObject_CallMethod _PyObject_CallMethod_SizeT #ifndef Py_LIMITED_API #define _PyObject_CallMethodId _PyObject_CallMethodId_SizeT #endif /* !Py_LIMITED_API */ #endif PyObject *_PyObject_CallFunction_SizeT(PyObject *callable, const char *format, ...); PyObject *_PyObject_CallMethod_SizeT(PyObject *o, const char *name, const char *format, ...); #ifndef Py_LIMITED_API PyObject *_PyObject_CallMethodId_SizeT(PyObject *o, _Py_Identifier *name, const char *format, ...); #endif /* !Py_LIMITED_API */ PyObject *PyObject_CallFunctionObjArgs(PyObject *callable, ...); /* Call a callable Python object, callable_object, with a variable number of C arguments. The C arguments are provided as PyObject * values, terminated by a NULL. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: o(*args). */ PyObject *PyObject_CallMethodObjArgs(PyObject *o, PyObject *method, ...); #ifndef Py_LIMITED_API PyObject *_PyObject_CallMethodIdObjArgs(PyObject *o, struct _Py_Identifier *method, ...); #endif /* !Py_LIMITED_API */ /* Call the method named m of object o with a variable number of C arguments. The C arguments are provided as PyObject * values, terminated by NULL. Returns the result of the call on success, or NULL on failure. This is the equivalent of the Python expression: o.method(args). */ /* Implemented elsewhere: long PyObject_Hash(PyObject *o); Compute and return the hash, hash_value, of an object, o. On failure, return -1. This is the equivalent of the Python expression: hash(o). */ /* Implemented elsewhere: int PyObject_IsTrue(PyObject *o); Returns 1 if the object, o, is considered to be true, 0 if o is considered to be false and -1 on failure. This is equivalent to the Python expression: not not o */ /* Implemented elsewhere: int PyObject_Not(PyObject *o); Returns 0 if the object, o, is considered to be true, 1 if o is considered to be false and -1 on failure. This is equivalent to the Python expression: not o */ PyObject *PyObject_Type(PyObject *o); /* On success, returns a type object corresponding to the object type of object o. On failure, returns NULL. This is equivalent to the Python expression: type(o). */ Py_ssize_t PyObject_Size(PyObject *o); /* Return the size of object o. If the object, o, provides both sequence and mapping protocols, the sequence size is returned. On error, -1 is returned. This is the equivalent to the Python expression: len(o). */ /* For DLL compatibility */ #undef PyObject_Length Py_ssize_t PyObject_Length(PyObject *o); #define PyObject_Length PyObject_Size #ifndef Py_LIMITED_API int _PyObject_HasLen(PyObject *o); Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t); #endif /* Guess the size of object o using len(o) or o.__length_hint__(). If neither of those return a non-negative value, then return the default value. If one of the calls fails, this function returns -1. */ PyObject *PyObject_GetItem(PyObject *o, PyObject *key); /* Return element of o corresponding to the object, key, or NULL on failure. This is the equivalent of the Python expression: o[key]. */ int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v); /* Map the object key to the value v. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o[key]=v. */ int PyObject_DelItemString(PyObject *o, const char *key); /* Remove the mapping for object, key, from the object *o. Returns -1 on failure. This is equivalent to the Python statement: del o[key]. */ int PyObject_DelItem(PyObject *o, PyObject *key); /* Delete the mapping for key from *o. Returns -1 on failure. This is the equivalent of the Python statement: del o[key]. */ /* old buffer API FIXME: usage of these should all be replaced in Python itself but for backwards compatibility we will implement them. Their usage without a corresponding "unlock" mechanism may create issues (but they would already be there). */ int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len); /* Takes an arbitrary object which must support the (character, single segment) buffer interface and returns a pointer to a read-only memory location useable as character based input for subsequent processing. 0 is returned on success. buffer and buffer_len are only set in case no error occurs. Otherwise, -1 is returned and an exception set. */ int PyObject_CheckReadBuffer(PyObject *obj); /* Checks whether an arbitrary object supports the (character, single segment) buffer interface. Returns 1 on success, 0 on failure. */ int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len); /* Same as PyObject_AsCharBuffer() except that this API expects (readable, single segment) buffer interface and returns a pointer to a read-only memory location which can contain arbitrary data. 0 is returned on success. buffer and buffer_len are only set in case no error occurs. Otherwise, -1 is returned and an exception set. */ int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len); /* Takes an arbitrary object which must support the (writable, single segment) buffer interface and returns a pointer to a writable memory location in buffer of size buffer_len. 0 is returned on success. buffer and buffer_len are only set in case no error occurs. Otherwise, -1 is returned and an exception set. */ /* new buffer API */ #ifndef Py_LIMITED_API #define PyObject_CheckBuffer(obj) \ (((obj)->ob_type->tp_as_buffer != NULL) && \ ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL)) /* Return 1 if the getbuffer function is available, otherwise return 0 */ int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags); /* This is a C-API version of the getbuffer function call. It checks to make sure object has the required function pointer and issues the call. Returns -1 and raises an error on failure and returns 0 on success */ void *PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices); /* Get the memory area pointed to by the indices for the buffer given. Note that view->ndim is the assumed size of indices */ int PyBuffer_SizeFromFormat(const char *); /* Return the implied itemsize of the data-format area from a struct-style description */ /* Implementation in memoryobject.c */ int PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char order); int PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char order); /* Copy len bytes of data from the contiguous chunk of memory pointed to by buf into the buffer exported by obj. Return 0 on success and return -1 and raise a PyBuffer_Error on error (i.e. the object does not have a buffer interface or it is not working). If fort is 'F', then if the object is multi-dimensional, then the data will be copied into the array in Fortran-style (first dimension varies the fastest). If fort is 'C', then the data will be copied into the array in C-style (last dimension varies the fastest). If fort is 'A', then it does not matter and the copy will be made in whatever way is more efficient. */ int PyObject_CopyData(PyObject *dest, PyObject *src); /* Copy the data from the src buffer to the buffer of destination */ int PyBuffer_IsContiguous(const Py_buffer *view, char fort); void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char fort); /* Fill the strides array with byte-strides of a contiguous (Fortran-style if fort is 'F' or C-style otherwise) array of the given shape with the given number of bytes per element. */ int PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf, Py_ssize_t len, int readonly, int flags); /* Fills in a buffer-info structure correctly for an exporter that can only share a contiguous chunk of memory of "unsigned bytes" of the given length. Returns 0 on success and -1 (with raising an error) on error. */ void PyBuffer_Release(Py_buffer *view); /* Releases a Py_buffer obtained from getbuffer ParseTuple's s*. */ #endif /* Py_LIMITED_API */ PyObject *PyObject_Format(PyObject *obj, PyObject *format_spec); /* Takes an arbitrary object and returns the result of calling obj.__format__(format_spec). */ /* Iterators */ PyObject *PyObject_GetIter(PyObject *); /* Takes an object and returns an iterator for it. This is typically a new iterator but if the argument is an iterator, this returns itself. */ #define PyIter_Check(obj) \ ((obj)->ob_type->tp_iternext != NULL && \ (obj)->ob_type->tp_iternext != &_PyObject_NextNotImplemented) PyObject *PyIter_Next(PyObject *); /* Takes an iterator object and calls its tp_iternext slot, returning the next value. If the iterator is exhausted, this returns NULL without setting an exception. NULL with an exception means an error occurred. */ /* Number Protocol:*/ int PyNumber_Check(PyObject *o); /* Returns 1 if the object, o, provides numeric protocols, and false otherwise. This function always succeeds. */ PyObject *PyNumber_Add(PyObject *o1, PyObject *o2); /* Returns the result of adding o1 and o2, or null on failure. This is the equivalent of the Python expression: o1+o2. */ PyObject *PyNumber_Subtract(PyObject *o1, PyObject *o2); /* Returns the result of subtracting o2 from o1, or null on failure. This is the equivalent of the Python expression: o1-o2. */ PyObject *PyNumber_Multiply(PyObject *o1, PyObject *o2); /* Returns the result of multiplying o1 and o2, or null on failure. This is the equivalent of the Python expression: o1*o2. */ #if !defined(Py_LIMITED_API) || Py_LIMITED_API + 0 >= 0x03050000 PyObject *PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2); /* This is the equivalent of the Python expression: o1 @ o2. */ #endif PyObject *PyNumber_FloorDivide(PyObject *o1, PyObject *o2); /* Returns the result of dividing o1 by o2 giving an integral result, or null on failure. This is the equivalent of the Python expression: o1//o2. */ PyObject *PyNumber_TrueDivide(PyObject *o1, PyObject *o2); /* Returns the result of dividing o1 by o2 giving a float result, or null on failure. This is the equivalent of the Python expression: o1/o2. */ PyObject *PyNumber_Remainder(PyObject *o1, PyObject *o2); /* Returns the remainder of dividing o1 by o2, or null on failure. This is the equivalent of the Python expression: o1%o2. */ PyObject *PyNumber_Divmod(PyObject *o1, PyObject *o2); /* See the built-in function divmod. Returns NULL on failure. This is the equivalent of the Python expression: divmod(o1,o2). */ PyObject *PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3); /* See the built-in function pow. Returns NULL on failure. This is the equivalent of the Python expression: pow(o1,o2,o3), where o3 is optional. */ PyObject *PyNumber_Negative(PyObject *o); /* Returns the negation of o on success, or null on failure. This is the equivalent of the Python expression: -o. */ PyObject *PyNumber_Positive(PyObject *o); /* Returns the (what?) of o on success, or NULL on failure. This is the equivalent of the Python expression: +o. */ PyObject *PyNumber_Absolute(PyObject *o); /* Returns the absolute value of o, or null on failure. This is the equivalent of the Python expression: abs(o). */ PyObject *PyNumber_Invert(PyObject *o); /* Returns the bitwise negation of o on success, or NULL on failure. This is the equivalent of the Python expression: ~o. */ PyObject *PyNumber_Lshift(PyObject *o1, PyObject *o2); /* Returns the result of left shifting o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1 << o2. */ PyObject *PyNumber_Rshift(PyObject *o1, PyObject *o2); /* Returns the result of right shifting o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1 >> o2. */ PyObject *PyNumber_And(PyObject *o1, PyObject *o2); /* Returns the result of bitwise and of o1 and o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1&o2. */ PyObject *PyNumber_Xor(PyObject *o1, PyObject *o2); /* Returns the bitwise exclusive or of o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1^o2. */ PyObject *PyNumber_Or(PyObject *o1, PyObject *o2); /* Returns the result of bitwise or on o1 and o2 on success, or NULL on failure. This is the equivalent of the Python expression: o1|o2. */ #define PyIndex_Check(obj) \ ((obj)->ob_type->tp_as_number != NULL && \ (obj)->ob_type->tp_as_number->nb_index != NULL) PyObject *PyNumber_Index(PyObject *o); /* Returns the object converted to a Python int or NULL with an error raised on failure. */ Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc); /* Returns the object converted to Py_ssize_t by going through PyNumber_Index first. If an overflow error occurs while converting the int to Py_ssize_t, then the second argument is the error-type to return. If it is NULL, then the overflow error is cleared and the value is clipped. */ PyObject *PyNumber_Long(PyObject *o); /* Returns the o converted to an integer object on success, or NULL on failure. This is the equivalent of the Python expression: int(o). */ PyObject *PyNumber_Float(PyObject *o); /* Returns the o converted to a float object on success, or NULL on failure. This is the equivalent of the Python expression: float(o). */ /* In-place variants of (some of) the above number protocol functions */ PyObject *PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2); /* Returns the result of adding o2 to o1, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 += o2. */ PyObject *PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2); /* Returns the result of subtracting o2 from o1, possibly in-place or null on failure. This is the equivalent of the Python expression: o1 -= o2. */ PyObject *PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2); /* Returns the result of multiplying o1 by o2, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 *= o2. */ #if !defined(Py_LIMITED_API) || Py_LIMITED_API + 0 >= 0x03050000 PyObject *PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2); /* This is the equivalent of the Python expression: o1 @= o2. */ #endif PyObject *PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2); /* Returns the result of dividing o1 by o2 giving an integral result, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 /= o2. */ PyObject *PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2); /* Returns the result of dividing o1 by o2 giving a float result, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 /= o2. */ PyObject *PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2); /* Returns the remainder of dividing o1 by o2, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 %= o2. */ PyObject *PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3); /* Returns the result of raising o1 to the power of o2, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present. */ PyObject *PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2); /* Returns the result of left shifting o1 by o2, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 <<= o2. */ PyObject *PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2); /* Returns the result of right shifting o1 by o2, possibly in-place or null on failure. This is the equivalent of the Python expression: o1 >>= o2. */ PyObject *PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2); /* Returns the result of bitwise and of o1 and o2, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 &= o2. */ PyObject *PyNumber_InPlaceXor(PyObject *o1, PyObject *o2); /* Returns the bitwise exclusive or of o1 by o2, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 ^= o2. */ PyObject *PyNumber_InPlaceOr(PyObject *o1, PyObject *o2); /* Returns the result of bitwise or of o1 and o2, possibly in-place, or null on failure. This is the equivalent of the Python expression: o1 |= o2. */ PyObject *PyNumber_ToBase(PyObject *n, int base); /* Returns the integer n converted to a string with a base, with a base marker of 0b, 0o or 0x prefixed if applicable. If n is not an int object, it is converted with PyNumber_Index first. */ /* Sequence protocol:*/ int PySequence_Check(PyObject *o); /* Return 1 if the object provides sequence protocol, and zero otherwise. This function always succeeds. */ Py_ssize_t PySequence_Size(PyObject *o); /* Return the size of sequence object o, or -1 on failure. */ /* For DLL compatibility */ #undef PySequence_Length Py_ssize_t PySequence_Length(PyObject *o); #define PySequence_Length PySequence_Size PyObject *PySequence_Concat(PyObject *o1, PyObject *o2); /* Return the concatenation of o1 and o2 on success, and NULL on failure. This is the equivalent of the Python expression: o1+o2. */ PyObject *PySequence_Repeat(PyObject *o, Py_ssize_t count); /* Return the result of repeating sequence object o count times, or NULL on failure. This is the equivalent of the Python expression: o1*count. */ PyObject *PySequence_GetItem(PyObject *o, Py_ssize_t i); /* Return the ith element of o, or NULL on failure. This is the equivalent of the Python expression: o[i]. */ PyObject *PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* Return the slice of sequence object o between i1 and i2, or NULL on failure. This is the equivalent of the Python expression: o[i1:i2]. */ int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v); /* Assign object v to the ith element of o. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o[i]=v. */ int PySequence_DelItem(PyObject *o, Py_ssize_t i); /* Delete the ith element of object v. Returns -1 on failure. This is the equivalent of the Python statement: del o[i]. */ int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v); /* Assign the sequence object, v, to the slice in sequence object, o, from i1 to i2. Returns -1 on failure. This is the equivalent of the Python statement: o[i1:i2]=v. */ int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2); /* Delete the slice in sequence object, o, from i1 to i2. Returns -1 on failure. This is the equivalent of the Python statement: del o[i1:i2]. */ PyObject *PySequence_Tuple(PyObject *o); /* Returns the sequence, o, as a tuple on success, and NULL on failure. This is equivalent to the Python expression: tuple(o) */ PyObject *PySequence_List(PyObject *o); /* Returns the sequence, o, as a list on success, and NULL on failure. This is equivalent to the Python expression: list(o) */ PyObject *PySequence_Fast(PyObject *o, const char *m); /* Return the sequence, o, as a list, unless it's already a tuple or list. Use PySequence_Fast_GET_ITEM to access the members of this list, and PySequence_Fast_GET_SIZE to get its length. Returns NULL on failure. If the object does not support iteration, raises a TypeError exception with m as the message text. */ #define PySequence_Fast_GET_SIZE(o) \ (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o)) /* Return the size of o, assuming that o was returned by PySequence_Fast and is not NULL. */ #define PySequence_Fast_GET_ITEM(o, i) \ (PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i)) /* Return the ith element of o, assuming that o was returned by PySequence_Fast, and that i is within bounds. */ #define PySequence_ITEM(o, i) (Py_TYPE(o)->tp_as_sequence->sq_item(o, i)) /* Assume tp_as_sequence and sq_item exist and that i does not need to be corrected for a negative index */ #define PySequence_Fast_ITEMS(sf) \ (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \ : ((PyTupleObject *)(sf))->ob_item) /* Return a pointer to the underlying item array for an object retured by PySequence_Fast */ Py_ssize_t PySequence_Count(PyObject *o, PyObject *value); /* Return the number of occurrences on value on o, that is, return the number of keys for which o[key]==value. On failure, return -1. This is equivalent to the Python expression: o.count(value). */ int PySequence_Contains(PyObject *seq, PyObject *ob); /* Return -1 if error; 1 if ob in seq; 0 if ob not in seq. Use __contains__ if possible, else _PySequence_IterSearch(). */ #ifndef Py_LIMITED_API #define PY_ITERSEARCH_COUNT 1 #define PY_ITERSEARCH_INDEX 2 #define PY_ITERSEARCH_CONTAINS 3 Py_ssize_t _PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation); #endif /* Iterate over seq. Result depends on the operation: PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if error. PY_ITERSEARCH_INDEX: return 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. */ /* For DLL-level backwards compatibility */ #undef PySequence_In int PySequence_In(PyObject *o, PyObject *value); /* For source-level backwards compatibility */ #define PySequence_In PySequence_Contains /* Determine if o contains value. If an item in o is equal to X, return 1, otherwise return 0. On error, return -1. This is equivalent to the Python expression: value in o. */ Py_ssize_t PySequence_Index(PyObject *o, PyObject *value); /* Return the first index for which o[i]=value. On error, return -1. This is equivalent to the Python expression: o.index(value). */ /* In-place versions of some of the above Sequence functions. */ PyObject *PySequence_InPlaceConcat(PyObject *o1, PyObject *o2); /* Append o2 to o1, in-place when possible. Return the resulting object, which could be o1, or NULL on failure. This is the equivalent of the Python expression: o1 += o2. */ PyObject *PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count); /* Repeat o1 by count, in-place when possible. Return the resulting object, which could be o1, or NULL on failure. This is the equivalent of the Python expression: o1 *= count. */ /* Mapping protocol:*/ int PyMapping_Check(PyObject *o); /* Return 1 if the object provides mapping protocol, and zero otherwise. This function always succeeds. */ Py_ssize_t PyMapping_Size(PyObject *o); /* Returns the number of keys in object o on success, and -1 on failure. For objects that do not provide sequence protocol, this is equivalent to the Python expression: len(o). */ /* For DLL compatibility */ #undef PyMapping_Length Py_ssize_t PyMapping_Length(PyObject *o); #define PyMapping_Length PyMapping_Size /* implemented as a macro: int PyMapping_DelItemString(PyObject *o, const char *key); Remove the mapping for object, key, from the object *o. Returns -1 on failure. This is equivalent to the Python statement: del o[key]. */ #define PyMapping_DelItemString(O, K) PyObject_DelItemString((O), (K)) /* implemented as a macro: int PyMapping_DelItem(PyObject *o, PyObject *key); Remove the mapping for object, key, from the object *o. Returns -1 on failure. This is equivalent to the Python statement: del o[key]. */ #define PyMapping_DelItem(O, K) PyObject_DelItem((O), (K)) int PyMapping_HasKeyString(PyObject *o, const char *key); /* On success, return 1 if the mapping object has the key, key, and 0 otherwise. This is equivalent to the Python expression: key in o. This function always succeeds. */ int PyMapping_HasKey(PyObject *o, PyObject *key); /* Return 1 if the mapping object has the key, key, and 0 otherwise. This is equivalent to the Python expression: key in o. This function always succeeds. */ PyObject *PyMapping_Keys(PyObject *o); /* On success, return a list or tuple of the keys in object o. On failure, return NULL. */ PyObject *PyMapping_Values(PyObject *o); /* On success, return a list or tuple of the values in object o. On failure, return NULL. */ PyObject *PyMapping_Items(PyObject *o); /* On success, return a list or tuple of the items in object o, where each item is a tuple containing a key-value pair. On failure, return NULL. */ PyObject *PyMapping_GetItemString(PyObject *o, const char *key); /* Return element of o corresponding to the object, key, or NULL on failure. This is the equivalent of the Python expression: o[key]. */ int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value); /* Map the object, key, to the value, v. Returns -1 on failure. This is the equivalent of the Python statement: o[key]=v. */ int PyObject_IsInstance(PyObject *object, PyObject *typeorclass); /* isinstance(object, typeorclass) */ int PyObject_IsSubclass(PyObject *object, PyObject *typeorclass); /* issubclass(object, typeorclass) */ #ifndef Py_LIMITED_API int _PyObject_RealIsInstance(PyObject *inst, PyObject *cls); int _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls); char *const *_PySequence_BytesToCharpArray(PyObject *self); void _Py_FreeCharPArray(char *const array[]); /* For internal use by buffer API functions */ void _Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape); void _Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape); #endif /* !Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* Py_ABSTRACTOBJECT_H */
29,860
1,037
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/symtable.h
#ifndef Py_LIMITED_API #ifndef Py_SYMTABLE_H #define Py_SYMTABLE_H #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/compile.h" #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock } _Py_block_ty; struct _symtable_entry; struct symtable { PyObject *st_filename; /* name of file being compiled, decoded from the filesystem encoding */ struct _symtable_entry *st_cur; /* current symbol table entry */ struct _symtable_entry *st_top; /* symbol table entry for module */ PyObject *st_blocks; /* dict: map AST node addresses * to symbol table entries */ PyObject *st_stack; /* list: stack of namespace info */ PyObject *st_global; /* borrowed ref to st_top->ste_symbols */ int st_nblocks; /* number of blocks used. kept for consistency with the corresponding compiler structure */ PyObject *st_private; /* name of current class or NULL */ PyFutureFeatures *st_future; /* module's future features that affect the symbol table */ int recursion_depth; /* current recursion depth */ int recursion_limit; /* recursion limit */ }; typedef struct _symtable_entry { PyObject_HEAD PyObject *ste_id; /* int: key in ste_table->st_blocks */ PyObject *ste_symbols; /* dict: variable names to flags */ PyObject *ste_name; /* string: name of current block */ PyObject *ste_varnames; /* list of function parameters */ PyObject *ste_children; /* list of child blocks */ PyObject *ste_directives;/* locations of global and nonlocal statements */ _Py_block_ty ste_type; /* module, class, or function */ int ste_nested; /* true if block is nested */ unsigned ste_free : 1; /* true if block has free variables */ unsigned ste_child_free : 1; /* true if a child block has free vars, including free refs to globals */ unsigned ste_generator : 1; /* true if namespace is a generator */ unsigned ste_coroutine : 1; /* true if namespace is a coroutine */ unsigned ste_varargs : 1; /* true if block has varargs */ unsigned ste_varkeywords : 1; /* true if block has varkeywords */ unsigned ste_returns_value : 1; /* true if namespace uses return with an argument */ unsigned ste_needs_class_closure : 1; /* for class scopes, true if a closure over __class__ should be created */ int ste_lineno; /* first line of block */ int ste_col_offset; /* offset of first line of block */ int ste_opt_lineno; /* lineno of last exec or import * */ int ste_opt_col_offset; /* offset of last exec or import * */ int ste_tmpname; /* counter for listcomp temp vars */ struct symtable *ste_table; } PySTEntryObject; extern PyTypeObject PySTEntry_Type; #define PySTEntry_Check(op) (Py_TYPE(op) == &PySTEntry_Type) int PyST_GetScope(PySTEntryObject *, PyObject *); struct symtable * PySymtable_Build( mod_ty mod, const char *filename, /* decoded from the filesystem encoding */ PyFutureFeatures *future); struct symtable * PySymtable_BuildObject( mod_ty mod, PyObject *filename, PyFutureFeatures *future); PySTEntryObject * PySymtable_Lookup(struct symtable *, void *); void PySymtable_Free(struct symtable *); /* Flags for def-use information */ #define DEF_GLOBAL 1 /* global stmt */ #define DEF_LOCAL 2 /* assignment in code block */ #define DEF_PARAM 2<<1 /* formal parameter */ #define DEF_NONLOCAL 2<<2 /* nonlocal stmt */ #define USE 2<<3 /* name is used */ #define DEF_FREE 2<<4 /* name used but not defined in nested block */ #define DEF_FREE_CLASS 2<<5 /* free variable from class's method */ #define DEF_IMPORT 2<<6 /* assignment occurred via import */ #define DEF_ANNOT 2<<7 /* this name is annotated */ #define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT) /* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol table. GLOBAL is returned from PyST_GetScope() for either of them. It is stored in ste_symbols at bits 12-15. */ #define SCOPE_OFFSET 11 #define SCOPE_MASK (DEF_GLOBAL | DEF_LOCAL | DEF_PARAM | DEF_NONLOCAL) #define LOCAL 1 #define GLOBAL_EXPLICIT 2 #define GLOBAL_IMPLICIT 3 #define FREE 4 #define CELL 5 #define GENERATOR 1 #define GENERATOR_EXPRESSION 2 COSMOPOLITAN_C_END_ #endif /* !Py_SYMTABLE_H */ #endif /* Py_LIMITED_API */
4,963
115
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pgen.h
#ifndef Py_PGEN_H #define Py_PGEN_H #include "third_party/python/Include/grammar.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Parser generator interface */ extern grammar *meta_grammar(void); struct _node; extern grammar *pgen(struct _node *); COSMOPOLITAN_C_END_ #endif /* !Py_PGEN_H */
298
16
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/codecs.h
#ifndef Py_CODECREGISTRY_H #define Py_CODECREGISTRY_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* ------------------------------------------------------------------------ Python Codec Registry and support functions Written by Marc-Andre Lemburg ([email protected]). Copyright (c) Corporation for National Research Initiatives. ------------------------------------------------------------------------ */ /* Register a new codec search function. As side effect, this tries to load the encodings package, if not yet done, to make sure that it is always first in the list of search functions. The search_function's refcount is incremented by this function. */ int PyCodec_Register( PyObject *search_function ); /* Codec registry lookup API. Looks up the given encoding and returns a CodecInfo object with function attributes which implement the different aspects of processing the encoding. The encoding string is looked up converted to all lower-case characters. This makes encodings looked up through this mechanism effectively case-insensitive. If no codec is found, a KeyError is set and NULL returned. As side effect, this tries to load the encodings package, if not yet done. This is part of the lazy load strategy for the encodings package. */ #ifndef Py_LIMITED_API PyObject * _PyCodec_Lookup( const char *encoding ); int _PyCodec_Forget( const char *encoding ); #endif /* Codec registry encoding check API. Returns 1/0 depending on whether there is a registered codec for the given encoding. */ int PyCodec_KnownEncoding( const char *encoding ); /* Generic codec based encoding API. object is passed through the encoder function found for the given encoding using the error handling method defined by errors. errors may be NULL to use the default method defined for the codec. Raises a LookupError in case no encoder can be found. */ PyObject * PyCodec_Encode( PyObject *object, const char *encoding, const char *errors ); /* Generic codec based decoding API. object is passed through the decoder function found for the given encoding using the error handling method defined by errors. errors may be NULL to use the default method defined for the codec. Raises a LookupError in case no encoder can be found. */ PyObject * PyCodec_Decode( PyObject *object, const char *encoding, const char *errors ); #ifndef Py_LIMITED_API /* Text codec specific encoding and decoding API. Checks the encoding against a list of codecs which do not implement a str<->bytes encoding before attempting the operation. Please note that these APIs are internal and should not be used in Python C extensions. XXX (ncoghlan): should we make these, or something like them, public in Python 3.5+? */ PyObject * _PyCodec_LookupTextEncoding( const char *encoding, const char *alternate_command ); PyObject * _PyCodec_EncodeText( PyObject *object, const char *encoding, const char *errors ); PyObject * _PyCodec_DecodeText( PyObject *object, const char *encoding, const char *errors ); /* These two aren't actually text encoding specific, but _io.TextIOWrapper * is the only current API consumer. */ PyObject * _PyCodecInfo_GetIncrementalDecoder( PyObject *codec_info, const char *errors ); PyObject * _PyCodecInfo_GetIncrementalEncoder( PyObject *codec_info, const char *errors ); #endif /* --- Codec Lookup APIs -------------------------------------------------- All APIs return a codec object with incremented refcount and are based on _PyCodec_Lookup(). The same comments w/r to the encoding name also apply to these APIs. */ /* Get an encoder function for the given encoding. */ PyObject * PyCodec_Encoder( const char *encoding ); /* Get a decoder function for the given encoding. */ PyObject * PyCodec_Decoder( const char *encoding ); /* Get an IncrementalEncoder object for the given encoding. */ PyObject * PyCodec_IncrementalEncoder( const char *encoding, const char *errors ); /* Get an IncrementalDecoder object function for the given encoding. */ PyObject * PyCodec_IncrementalDecoder( const char *encoding, const char *errors ); /* Get a StreamReader factory function for the given encoding. */ PyObject * PyCodec_StreamReader( const char *encoding, PyObject *stream, const char *errors ); /* Get a StreamWriter factory function for the given encoding. */ PyObject * PyCodec_StreamWriter( const char *encoding, PyObject *stream, const char *errors ); /* Unicode encoding error handling callback registry API */ /* Register the error handling callback function error under the given name. This function will be called by the codec when it encounters unencodable characters/undecodable bytes and doesn't know the callback name, when name is specified as the error parameter in the call to the encode/decode function. Return 0 on success, -1 on error */ int PyCodec_RegisterError(const char *name, PyObject *error); /* Lookup the error handling callback function registered under the given name. As a special case NULL can be passed, in which case the error handling callback for "strict" will be returned. */ PyObject * PyCodec_LookupError(const char *name); /* raise exc as an exception */ PyObject * PyCodec_StrictErrors(PyObject *exc); /* ignore the unicode error, skipping the faulty input */ PyObject * PyCodec_IgnoreErrors(PyObject *exc); /* replace the unicode encode error with ? or U+FFFD */ PyObject * PyCodec_ReplaceErrors(PyObject *exc); /* replace the unicode encode error with XML character references */ PyObject * PyCodec_XMLCharRefReplaceErrors(PyObject *exc); /* replace the unicode encode error with backslash escapes (\x, \u and \U) */ PyObject * PyCodec_BackslashReplaceErrors(PyObject *exc); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* replace the unicode encode error with backslash escapes (\N, \x, \u and \U) */ PyObject * PyCodec_NameReplaceErrors(PyObject *exc); #endif #ifndef Py_LIMITED_API extern const char * Py_hexdigits; #endif COSMOPOLITAN_C_END_ #endif /* !Py_CODECREGISTRY_H */
6,533
239
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pystrtod.h
#ifndef Py_STRTOD_H #define Py_STRTOD_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ double PyOS_string_to_double(const char *str, char **endptr, PyObject *overflow_exception); /* The caller is responsible for calling PyMem_Free to free the buffer that's is returned. */ char * PyOS_double_to_string(double val, char format_code, int precision, int flags, int *type); #ifndef Py_LIMITED_API PyObject * _Py_string_to_number_with_underscores( const char *str, Py_ssize_t len, const char *what, PyObject *obj, void *arg, PyObject *(*innerfunc)(const char *, Py_ssize_t, void *)); double _Py_parse_inf_or_nan(const char *p, char **endptr); #endif /* PyOS_double_to_string's "flags" parameter can be set to 0 or more of: */ #define Py_DTSF_SIGN 0x01 /* always add the sign */ #define Py_DTSF_ADD_DOT_0 0x02 /* if the result is an integer add ".0" */ #define Py_DTSF_ALT 0x04 /* "alternate" formatting. it's format_code specific */ /* PyOS_double_to_string's "type", if non-NULL, will be set to one of: */ #define Py_DTST_FINITE 0 #define Py_DTST_INFINITE 1 #define Py_DTST_NAN 2 COSMOPOLITAN_C_END_ #endif /* !Py_STRTOD_H */
1,477
41
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/patchlevel.h
/* clang-format off */ /* Python version identification scheme. When the major or minor version changes, the VERSION variable in configure.ac must also be changed. There is also (independent) API version information in modsupport.h. */ /* Values for PY_RELEASE_LEVEL */ #define PY_RELEASE_LEVEL_ALPHA 0xA #define PY_RELEASE_LEVEL_BETA 0xB #define PY_RELEASE_LEVEL_GAMMA 0xC /* For release candidates */ #define PY_RELEASE_LEVEL_FINAL 0xF /* Serial should be 0 here */ /* Higher for patch releases */ /* Version parsed out into numeric values */ /*--start constants--*/ #define PY_MAJOR_VERSION 3 #define PY_MINOR_VERSION 6 #define PY_MICRO_VERSION 14 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL #define PY_RELEASE_SERIAL 0 /* Version as a string */ #define PY_VERSION "3.6.14+" /*--end constants--*/ /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ... */ #define PY_VERSION_HEX ((PY_MAJOR_VERSION << 24) | \ (PY_MINOR_VERSION << 16) | \ (PY_MICRO_VERSION << 8) | \ (PY_RELEASE_LEVEL << 4) | \ (PY_RELEASE_SERIAL << 0))
1,154
37
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/methodobject.h
#ifndef Py_METHODOBJECT_H #define Py_METHODOBJECT_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyport.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* This is about the type 'builtin_function_or_method', not Python methods in user-defined classes. See classobject.h for the latter. */ extern PyTypeObject PyCFunction_Type; #define PyCFunction_Check(op) (Py_TYPE(op) == &PyCFunction_Type) typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); typedef PyObject *(*_PyCFunctionFast) (PyObject *, PyObject **, Py_ssize_t); typedef PyObject *(*PyCFunctionWithKeywords)(PyObject *, PyObject *, PyObject *); typedef PyObject *(*_PyCFunctionFastWithKeywords) (PyObject *, PyObject **, Py_ssize_t, PyObject *); typedef PyObject *(*PyNoArgsFunction)(PyObject *); PyCFunction PyCFunction_GetFunction(PyObject *); PyObject * PyCFunction_GetSelf(PyObject *); int PyCFunction_GetFlags(PyObject *); /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #ifndef Py_LIMITED_API #define PyCFunction_GET_FUNCTION(func) \ (((PyCFunctionObject *)func) -> m_ml -> ml_meth) #define PyCFunction_GET_SELF(func) \ (((PyCFunctionObject *)func) -> m_ml -> ml_flags & METH_STATIC ? \ NULL : ((PyCFunctionObject *)func) -> m_self) #define PyCFunction_GET_FLAGS(func) \ (((PyCFunctionObject *)func) -> m_ml -> ml_flags) #endif PyObject * PyCFunction_Call(PyObject *, PyObject *, PyObject *); #ifndef Py_LIMITED_API PyObject * _PyCFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); PyObject * _PyCFunction_FastCallKeywords(PyObject *func, PyObject **stack, Py_ssize_t nargs, PyObject *kwnames); #endif struct PyMethodDef { const char *ml_name; /* The name of the built-in function/method */ PyCFunction ml_meth; /* The C function that implements it */ int ml_flags; /* Combination of METH_xxx flags, which mostly describe the args expected by the C func */ const char *ml_doc; /* The __doc__ attribute, or NULL */ }; typedef struct PyMethodDef PyMethodDef; #define PyCFunction_New(ML, SELF) PyCFunction_NewEx((ML), (SELF), NULL) PyObject * PyCFunction_NewEx(PyMethodDef *, PyObject *, PyObject *); /* Flag passed to newmethodobject */ /* #define METH_OLDARGS 0x0000 -- unsupported now */ #define METH_VARARGS 0x0001 #define METH_KEYWORDS 0x0002 /* METH_NOARGS and METH_O must not be combined with the flags above. */ #define METH_NOARGS 0x0004 #define METH_O 0x0008 /* METH_CLASS and METH_STATIC are a little different; these control the construction of methods for a class. These cannot be used for functions in modules. */ #define METH_CLASS 0x0010 #define METH_STATIC 0x0020 /* METH_COEXIST allows a method to be entered even though a slot has already filled the entry. When defined, the flag allows a separate method, "__contains__" for example, to coexist with a defined slot like sq_contains. */ #define METH_COEXIST 0x0040 #ifndef Py_LIMITED_API #define METH_FASTCALL 0x0080 typedef struct { PyObject_HEAD PyMethodDef *m_ml; /* Description of the C function to call */ PyObject *m_self; /* Passed as 'self' arg to the C func, can be NULL */ PyObject *m_module; /* The __module__ attribute, can be anything */ PyObject *m_weakreflist; /* List of weak references */ } PyCFunctionObject; PyObject * _PyMethodDef_RawFastCallDict( PyMethodDef *method, PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); PyObject * _PyMethodDef_RawFastCallKeywords( PyMethodDef *method, PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames); #endif int PyCFunction_ClearFreeList(void); #ifndef Py_LIMITED_API void _PyCFunction_DebugMallocStats(FILE *out); void _PyMethod_DebugMallocStats(FILE *out); #endif COSMOPOLITAN_C_END_ #endif /* !Py_METHODOBJECT_H */
4,224
123
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/errcode.h
#ifndef Py_ERRCODE_H #define Py_ERRCODE_H COSMOPOLITAN_C_START_ /* clang-format off */ /* Error codes passed around between file input, tokenizer, parser and interpreter. This is necessary so we can turn them into Python exceptions at a higher level. Note that some errors have a slightly different meaning when passed from the tokenizer to the parser than when passed from the parser to the interpreter; e.g. the parser only returns E_EOF when it hits EOF immediately, and it never returns E_OK. */ #define E_OK 10 /* No error */ #define E_EOF 11 /* End Of File */ #define E_INTR 12 /* Interrupted */ #define E_TOKEN 13 /* Bad token */ #define E_SYNTAX 14 /* Syntax error */ #define E_NOMEM 15 /* Ran out of memory */ #define E_DONE 16 /* Parsing complete */ #define E_ERROR 17 /* Execution error */ #define E_TABSPACE 18 /* Inconsistent mixing of tabs and spaces */ #define E_OVERFLOW 19 /* Node had too many children */ #define E_TOODEEP 20 /* Too many indentation levels */ #define E_DEDENT 21 /* No matching outer block for dedent */ #define E_DECODE 22 /* Error in decoding into Unicode */ #define E_EOFS 23 /* EOF in triple-quoted string */ #define E_EOLS 24 /* EOL in single-quoted string */ #define E_LINECONT 25 /* Unexpected characters after a line continuation */ #define E_IDENTIFIER 26 /* Invalid characters in identifier */ #define E_BADSINGLE 27 /* Ill-formed single statement input */ COSMOPOLITAN_C_END_ #endif /* !Py_ERRCODE_H */
1,495
36
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pystrcmp.h
#ifndef Py_STRCMP_H #define Py_STRCMP_H #include "third_party/python/Include/pyport.h" COSMOPOLITAN_C_START_ /* clang-format off */ int PyOS_mystrnicmp(const char *, const char *, Py_ssize_t); int PyOS_mystricmp(const char *, const char *); #ifdef MS_WINDOWS #define PyOS_strnicmp strnicmp #define PyOS_stricmp stricmp #else #define PyOS_strnicmp PyOS_mystrnicmp #define PyOS_stricmp PyOS_mystricmp #endif COSMOPOLITAN_C_END_ #endif /* !Py_STRCMP_H */
455
20
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pycapsule.h
#ifndef Py_CAPSULE_H #define Py_CAPSULE_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Capsule objects let you wrap a C "void *" pointer in a Python object. They're a way of passing data through the Python interpreter without creating your own custom type. Capsules are used for communication between extension modules. They provide a way for an extension module to export a C interface to other extension modules, so that extension modules can use the Python import mechanism to link to one another. For more information, please see "c-api/capsule.html" in the documentation. */ extern PyTypeObject PyCapsule_Type; typedef void (*PyCapsule_Destructor)(PyObject *); #define PyCapsule_CheckExact(op) (Py_TYPE(op) == &PyCapsule_Type) PyObject * PyCapsule_New( void *pointer, const char *name, PyCapsule_Destructor destructor); void * PyCapsule_GetPointer(PyObject *capsule, const char *name); PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule); const char * PyCapsule_GetName(PyObject *capsule); void * PyCapsule_GetContext(PyObject *capsule); int PyCapsule_IsValid(PyObject *capsule, const char *name); int PyCapsule_SetPointer(PyObject *capsule, void *pointer); int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor); int PyCapsule_SetName(PyObject *capsule, const char *name); int PyCapsule_SetContext(PyObject *capsule, void *context); void * PyCapsule_Import( const char *name, /* UTF-8 encoded string */ int no_block); COSMOPOLITAN_C_END_ #endif /* !Py_CAPSULE_H */
1,632
56
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/cellobject.h
#ifndef Py_LIMITED_API #ifndef Py_CELLOBJECT_H #define Py_CELLOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef struct { PyObject_HEAD PyObject *ob_ref; /* Content of the cell or NULL when empty */ } PyCellObject; extern PyTypeObject PyCell_Type; #define PyCell_Check(op) (Py_TYPE(op) == &PyCell_Type) PyObject * PyCell_New(PyObject *); PyObject * PyCell_Get(PyObject *); int PyCell_Set(PyObject *, PyObject *); #define PyCell_GET(op) (((PyCellObject *)(op))->ob_ref) #define PyCell_SET(op, v) (((PyCellObject *)(op))->ob_ref = v) COSMOPOLITAN_C_END_ #endif /* !Py_TUPLEOBJECT_H */ #endif /* Py_LIMITED_API */
677
27
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/op.h
#ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_OP_H_ #define COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_OP_H_ /* Rich comparison opcodes */ #define Py_LT 0 #define Py_LE 1 #define Py_EQ 2 #define Py_NE 3 #define Py_GT 4 #define Py_GE 5 #endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_OP_H_ */
295
13
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/sysmodule.h
#ifndef Py_SYSMODULE_H #define Py_SYSMODULE_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyport.h" COSMOPOLITAN_C_START_ /* clang-format off */ PyObject * PySys_GetObject(const char *); int PySys_SetObject(const char *, PyObject *); #ifndef Py_LIMITED_API PyObject * _PySys_GetObjectId(_Py_Identifier *key); int _PySys_SetObjectId(_Py_Identifier *key, PyObject *); #endif void PySys_SetArgv(int, wchar_t **); void PySys_SetArgvEx(int, wchar_t **, int); void PySys_SetPath(const wchar_t *); void PySys_FormatStdout(const char *, ...); void PySys_FormatStderr(const char *, ...); void PySys_ResetWarnOptions(void); void PySys_AddWarnOption(const wchar_t *); void PySys_AddWarnOptionUnicode(PyObject *); int PySys_HasWarnOptions(void); void PySys_AddXOption(const wchar_t *); PyObject * PySys_GetXOptions(void); #ifndef Py_LIMITED_API size_t _PySys_GetSizeOf(PyObject *); #endif COSMOPOLITAN_C_END_ #endif /* !Py_SYSMODULE_H */
970
33
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/enumobject.h
#ifndef Py_ENUMOBJECT_H #define Py_ENUMOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ extern PyTypeObject PyEnum_Type; extern PyTypeObject PyReversed_Type; COSMOPOLITAN_C_END_ #endif /* !Py_ENUMOBJECT_H */
262
12
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/fileobject.h
#ifndef Py_FILEOBJECT_H #define Py_FILEOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define PY_STDIOTEXTMODE "b" PyObject * PyFile_FromFd(int, const char *, const char *, int, const char *, const char *, const char *, int); PyObject * PyFile_GetLine(PyObject *, int); int PyFile_WriteObject(PyObject *, PyObject *, int); int PyFile_WriteString(const char *, PyObject *); int PyObject_AsFileDescriptor(PyObject *); #ifndef Py_LIMITED_API char * Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *); #endif /* The default encoding used by the platform file system APIs If non-NULL, this is different than the default encoding for strings */ extern const char * Py_FileSystemDefaultEncoding; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 extern const char * Py_FileSystemDefaultEncodeErrors; #endif extern int Py_HasFileSystemDefaultEncoding; /* Internal API The std printer acts as a preliminary sys.stderr until the new io infrastructure is in place. */ #ifndef Py_LIMITED_API PyObject * PyFile_NewStdPrinter(int); extern PyTypeObject PyStdPrinter_Type; #endif /* Py_LIMITED_API */ /* A routine to check if a file descriptor can be select()-ed. */ #ifdef HAVE_SELECT #define _PyIsSelectable_fd(FD) ((unsigned int)(FD) < (unsigned int)FD_SETSIZE) #else #define _PyIsSelectable_fd(FD) (1) #endif /* HAVE_SELECT */ COSMOPOLITAN_C_END_ #endif /* !Py_FILEOBJECT_H */
1,530
47
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/modsupport.h
#ifndef Py_MODSUPPORT_H #define Py_MODSUPPORT_H #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/object.h" #pragma GCC diagnostic ignored "-Wredundant-decls" COSMOPOLITAN_C_START_ /* clang-format off */ /* If PY_SSIZE_T_CLEAN is defined, each functions treats #-specifier to mean Py_ssize_t */ #ifdef PY_SSIZE_T_CLEAN #define PyArg_Parse _PyArg_Parse_SizeT #define PyArg_ParseTuple _PyArg_ParseTuple_SizeT #define PyArg_ParseTupleAndKeywords _PyArg_ParseTupleAndKeywords_SizeT #define PyArg_VaParse _PyArg_VaParse_SizeT #define PyArg_VaParseTupleAndKeywords _PyArg_VaParseTupleAndKeywords_SizeT #define Py_BuildValue _Py_BuildValue_SizeT #define Py_VaBuildValue _Py_VaBuildValue_SizeT #else #ifndef Py_LIMITED_API PyObject * _Py_VaBuildValue_SizeT(const char *, va_list); #endif /* !Py_LIMITED_API */ #endif #define _Py_VaBuildStack _Py_VaBuildStack_SizeT PyObject ** _Py_VaBuildStack_SizeT( PyObject **small_stack, Py_ssize_t small_stack_len, const char *format, va_list va, Py_ssize_t *p_nargs); /* Due to a glitch in 3.2, the _SizeT versions weren't exported from the DLL. */ #if !defined(PY_SSIZE_T_CLEAN) || !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 int PyArg_Parse(PyObject *, const char *, ...); int PyArg_ParseTuple(PyObject *, const char *, ...); int PyArg_ParseTupleAndKeywords(PyObject *, PyObject *, const char *, char **, ...); int PyArg_VaParse(PyObject *, const char *, va_list); int PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *, const char *, char **, va_list); #endif int PyArg_ValidateKeywordArguments(PyObject *); int PyArg_UnpackTuple(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...); PyObject * Py_BuildValue(const char *, ...); PyObject * _Py_BuildValue_SizeT(const char *, ...); #ifndef Py_LIMITED_API int _PyArg_UnpackStack( PyObject **args, Py_ssize_t nargs, const char *name, Py_ssize_t min, Py_ssize_t max, ...); int _PyArg_NoKeywords(const char *funcname, PyObject *kwargs); int _PyArg_NoStackKeywords(const char *funcname, PyObject *kwnames); int _PyArg_NoPositional(const char *funcname, PyObject *args); #define _PyArg_NoKeywords(funcname, kwargs) \ ((kwargs) == NULL || _PyArg_NoKeywords((funcname), (kwargs))) #define _PyArg_NoStackKeywords(funcname, kwnames) \ ((kwnames) == NULL || _PyArg_NoStackKeywords((funcname), (kwnames))) #define _PyArg_NoPositional(funcname, args) \ ((args) == NULL || _PyArg_NoPositional((funcname), (args))) #endif PyObject * Py_VaBuildValue(const char *, va_list); #ifndef Py_LIMITED_API typedef struct _PyArg_Parser { const char *format; const char * const *keywords; const char *fname; const char *custom_msg; int pos; /* number of positional-only arguments */ int min; /* minimal number of arguments */ int max; /* maximal number of positional arguments */ PyObject *kwtuple; /* tuple of keyword parameter names */ struct _PyArg_Parser *next; } _PyArg_Parser; #ifdef PY_SSIZE_T_CLEAN #define _PyArg_ParseTupleAndKeywordsFast _PyArg_ParseTupleAndKeywordsFast_SizeT #define _PyArg_ParseStack _PyArg_ParseStack_SizeT #define _PyArg_ParseStackAndKeywords _PyArg_ParseStackAndKeywords_SizeT #define _PyArg_VaParseTupleAndKeywordsFast _PyArg_VaParseTupleAndKeywordsFast_SizeT #endif int _PyArg_ParseTupleAndKeywordsFast(PyObject *, PyObject *, struct _PyArg_Parser *, ...); int _PyArg_ParseStack(PyObject **args, Py_ssize_t nargs, const char *format, ...); int _PyArg_ParseStackAndKeywords(PyObject **args, Py_ssize_t nargs, PyObject *kwnames, struct _PyArg_Parser *, ...); int _PyArg_VaParseTupleAndKeywordsFast(PyObject *, PyObject *, struct _PyArg_Parser *, va_list); void _PyArg_Fini(void); #endif int PyModule_AddObject(PyObject *, const char *, PyObject *); int PyModule_AddIntConstant(PyObject *, const char *, long); int PyModule_AddStringConstant(PyObject *, const char *, const char *); #define PyModule_AddIntMacro(m, c) PyModule_AddIntConstant(m, #c, c) #define PyModule_AddStringMacro(m, c) PyModule_AddStringConstant(m, #c, c) #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ int PyModule_SetDocString(PyObject *, const char *); int PyModule_AddFunctions(PyObject *, PyMethodDef *); int PyModule_ExecDef(PyObject *module, PyModuleDef *def); #endif #define Py_CLEANUP_SUPPORTED 0x20000 #define PYTHON_API_VERSION 1013 #define PYTHON_API_STRING "1013" /* The API version is maintained (independently from the Python version) so we can detect mismatches between the interpreter and dynamically loaded modules. These are diagnosed by an error message but the module is still loaded (because the mismatch can only be tested after loading the module). The error message is intended to explain the core dump a few seconds later. The symbol PYTHON_API_STRING defines the same value as a string literal. *** PLEASE MAKE SURE THE DEFINITIONS MATCH. *** Please add a line or two to the top of this log for each API version change: 22-Feb-2006 MvL 1013 PEP 353 - long indices for sequence lengths 19-Aug-2002 GvR 1012 Changes to string object struct for interning changes, saving 3 bytes. 17-Jul-2001 GvR 1011 Descr-branch, just to be on the safe side 25-Jan-2001 FLD 1010 Parameters added to PyCode_New() and PyFrame_New(); Python 2.1a2 14-Mar-2000 GvR 1009 Unicode API added 3-Jan-1999 GvR 1007 Decided to change back! (Don't reuse 1008!) 3-Dec-1998 GvR 1008 Python 1.5.2b1 18-Jan-1997 GvR 1007 string interning and other speedups 11-Oct-1996 GvR renamed Py_Ellipses to Py_Ellipsis :-( 30-Jul-1996 GvR Slice and ellipses syntax added 23-Jul-1996 GvR For 1.4 -- better safe than sorry this time :-) 7-Nov-1995 GvR Keyword arguments (should've been done at 1.3 :-( ) 10-Jan-1995 GvR Renamed globals to new naming scheme 9-Jan-1995 GvR Initial version (incompatible with older API) */ /* The PYTHON_ABI_VERSION is introduced in PEP 384. For the lifetime of Python 3, it will stay at the value of 3; changes to the limited API must be performed in a strictly backwards-compatible manner. */ #define PYTHON_ABI_VERSION 3 #define PYTHON_ABI_STRING "3" #ifdef Py_TRACE_REFS /* When we are tracing reference counts, rename module creation functions so modules compiled with incompatible settings will generate a link-time error. */ #define PyModule_Create2 PyModule_Create2TraceRefs #define PyModule_FromDefAndSpec2 PyModule_FromDefAndSpec2TraceRefs #endif PyObject * PyModule_Create2(struct PyModuleDef*, int apiver); #ifdef Py_LIMITED_API #define PyModule_Create(module) \ PyModule_Create2(module, PYTHON_ABI_VERSION) #else #define PyModule_Create(module) \ PyModule_Create2(module, PYTHON_API_VERSION) #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ PyObject * PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version); #ifdef Py_LIMITED_API #define PyModule_FromDefAndSpec(module, spec) \ PyModule_FromDefAndSpec2(module, spec, PYTHON_ABI_VERSION) #else #define PyModule_FromDefAndSpec(module, spec) \ PyModule_FromDefAndSpec2(module, spec, PYTHON_API_VERSION) #endif /* Py_LIMITED_API */ #endif /* New in 3.5 */ #ifndef Py_LIMITED_API extern char * _Py_PackageContext; #endif COSMOPOLITAN_C_END_ #endif /* !Py_MODSUPPORT_H */
8,143
205
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/weakrefobject.h
#ifndef Py_WEAKREFOBJECT_H #define Py_WEAKREFOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef struct _PyWeakReference PyWeakReference; /* PyWeakReference is the base struct for the Python ReferenceType, ProxyType, * and CallableProxyType. */ #ifndef Py_LIMITED_API struct _PyWeakReference { PyObject_HEAD /* The object to which this is a weak reference, or Py_None if none. * Note that this is a stealth reference: wr_object's refcount is * not incremented to reflect this pointer. */ PyObject *wr_object; /* A callable to invoke when wr_object dies, or NULL if none. */ PyObject *wr_callback; /* A cache for wr_object's hash code. As usual for hashes, this is -1 * if the hash code isn't known yet. */ Py_hash_t hash; /* If wr_object is weakly referenced, wr_object has a doubly-linked NULL- * terminated list of weak references to it. These are the list pointers. * If wr_object goes away, wr_object is set to Py_None, and these pointers * have no meaning then. */ PyWeakReference *wr_prev; PyWeakReference *wr_next; }; #endif extern PyTypeObject _PyWeakref_RefType; extern PyTypeObject _PyWeakref_ProxyType; extern PyTypeObject _PyWeakref_CallableProxyType; #define PyWeakref_CheckRef(op) PyObject_TypeCheck(op, &_PyWeakref_RefType) #define PyWeakref_CheckRefExact(op) \ (Py_TYPE(op) == &_PyWeakref_RefType) #define PyWeakref_CheckProxy(op) \ ((Py_TYPE(op) == &_PyWeakref_ProxyType) || \ (Py_TYPE(op) == &_PyWeakref_CallableProxyType)) #define PyWeakref_Check(op) \ (PyWeakref_CheckRef(op) || PyWeakref_CheckProxy(op)) PyObject * PyWeakref_NewRef(PyObject *ob, PyObject *callback); PyObject * PyWeakref_NewProxy(PyObject *ob, PyObject *callback); PyObject * PyWeakref_GetObject(PyObject *ref); #ifndef Py_LIMITED_API Py_ssize_t _PyWeakref_GetWeakrefCount(PyWeakReference *head); void _PyWeakref_ClearRef(PyWeakReference *self); #endif /* Explanation for the Py_REFCNT() check: when a weakref's target is part of a long chain of deallocations which triggers the trashcan mechanism, clearing the weakrefs can be delayed long after the target's refcount has dropped to zero. In the meantime, code accessing the weakref will be able to "see" the target object even though it is supposed to be unreachable. See issue #16602. */ #define PyWeakref_GET_OBJECT(ref) \ (Py_REFCNT(((PyWeakReference *)(ref))->wr_object) > 0 \ ? ((PyWeakReference *)(ref))->wr_object \ : Py_None) COSMOPOLITAN_C_END_ #endif /* !Py_WEAKREFOBJECT_H */
2,791
81
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/genobject.h
#ifndef Py_LIMITED_API #ifndef Py_GENOBJECT_H #define Py_GENOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ struct _frame; /* Avoid including frameobject.h */ /* _PyGenObject_HEAD defines the initial segment of generator and coroutine objects. */ #define _PyGenObject_HEAD(prefix) \ PyObject_HEAD \ /* Note: gi_frame can be NULL if the generator is "finished" */ \ struct _frame *prefix##_frame; \ /* True if generator is being executed. */ \ char prefix##_running; \ /* The code object backing the generator */ \ PyObject *prefix##_code; \ /* List of weak reference. */ \ PyObject *prefix##_weakreflist; \ /* Name of the generator. */ \ PyObject *prefix##_name; \ /* Qualified name of the generator. */ \ PyObject *prefix##_qualname; typedef struct { /* The gi_ prefix is intended to remind of generator-iterator. */ _PyGenObject_HEAD(gi) } PyGenObject; extern PyTypeObject PyGen_Type; #define PyGen_Check(op) PyObject_TypeCheck(op, &PyGen_Type) #define PyGen_CheckExact(op) (Py_TYPE(op) == &PyGen_Type) PyObject * PyGen_New(struct _frame *); PyObject * PyGen_NewWithQualName(struct _frame *, PyObject *name, PyObject *qualname); int PyGen_NeedsFinalizing(PyGenObject *); int _PyGen_SetStopIterationValue(PyObject *); int _PyGen_FetchStopIterationValue(PyObject **); PyObject * _PyGen_Send(PyGenObject *, PyObject *); PyObject *_PyGen_yf(PyGenObject *); void _PyGen_Finalize(PyObject *self); #ifndef Py_LIMITED_API typedef struct { _PyGenObject_HEAD(cr) } PyCoroObject; extern PyTypeObject PyCoro_Type; extern PyTypeObject _PyCoroWrapper_Type; extern PyTypeObject _PyAIterWrapper_Type; PyObject *_PyAIterWrapper_New(PyObject *aiter); #define PyCoro_CheckExact(op) (Py_TYPE(op) == &PyCoro_Type) PyObject *_PyCoro_GetAwaitableIter(PyObject *o); PyObject * PyCoro_New(struct _frame *, PyObject *name, PyObject *qualname); /* Asynchronous Generators */ typedef struct { _PyGenObject_HEAD(ag) PyObject *ag_finalizer; /* Flag is set to 1 when hooks set up by sys.set_asyncgen_hooks were called on the generator, to avoid calling them more than once. */ int ag_hooks_inited; /* Flag is set to 1 when aclose() is called for the first time, or when a StopAsyncIteration exception is raised. */ int ag_closed; } PyAsyncGenObject; extern PyTypeObject PyAsyncGen_Type; extern PyTypeObject _PyAsyncGenASend_Type; extern PyTypeObject _PyAsyncGenWrappedValue_Type; extern PyTypeObject _PyAsyncGenAThrow_Type; PyObject * PyAsyncGen_New(struct _frame *, PyObject *name, PyObject *qualname); #define PyAsyncGen_CheckExact(op) (Py_TYPE(op) == &PyAsyncGen_Type) PyObject *_PyAsyncGenValueWrapperNew(PyObject *); int PyAsyncGen_ClearFreeLists(void); #endif #undef _PyGenObject_HEAD COSMOPOLITAN_C_END_ #endif /* !Py_GENOBJECT_H */ #endif /* Py_LIMITED_API */
3,445
100
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/structmember.h
#ifndef Py_STRUCTMEMBER_H #define Py_STRUCTMEMBER_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Interface to map C struct members to Python object attributes */ /* An array of PyMemberDef structures defines the name, type and offset of selected members of a C structure. These can be read by PyMember_GetOne() and set by PyMember_SetOne() (except if their READONLY flag is set). The array must be terminated with an entry whose name pointer is NULL. */ typedef struct PyMemberDef { char *name; int type; Py_ssize_t offset; int flags; char *doc; } PyMemberDef; /* Types */ #define T_SHORT 0 #define T_INT 1 #define T_LONG 2 #define T_FLOAT 3 #define T_DOUBLE 4 #define T_STRING 5 #define T_OBJECT 6 /* XXX the ordering here is weird for binary compatibility */ #define T_CHAR 7 /* 1-character string */ #define T_BYTE 8 /* 8-bit signed int */ /* unsigned variants: */ #define T_UBYTE 9 #define T_USHORT 10 #define T_UINT 11 #define T_ULONG 12 /* Added by Jack: strings contained in the structure */ #define T_STRING_INPLACE 13 /* Added by Lillo: bools contained in the structure (assumed char) */ #define T_BOOL 14 #define T_OBJECT_EX 16 /* Like T_OBJECT, but raises AttributeError when the value is NULL, instead of converting to None. */ #define T_LONGLONG 17 #define T_ULONGLONG 18 #define T_PYSSIZET 19 /* Py_ssize_t */ #define T_NONE 20 /* Value is always None */ /* Flags */ #define READONLY 1 #define READ_RESTRICTED 2 #define PY_WRITE_RESTRICTED 4 #define RESTRICTED (READ_RESTRICTED | PY_WRITE_RESTRICTED) /* Current API, use this */ PyObject * PyMember_GetOne(const char *, struct PyMemberDef *); int PyMember_SetOne(char *, struct PyMemberDef *, PyObject *); COSMOPOLITAN_C_END_ #endif /* !Py_STRUCTMEMBER_H */
1,996
68
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/bltinmodule.h
#ifndef Py_BLTINMODULE_H #define Py_BLTINMODULE_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ extern PyTypeObject PyFilter_Type; extern PyTypeObject PyMap_Type; extern PyTypeObject PyZip_Type; COSMOPOLITAN_C_END_ #endif /* !Py_BLTINMODULE_H */
294
13
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pymath.h
#ifndef Py_PYMATH_H #define Py_PYMATH_H #include "libc/math.h" #include "third_party/python/pyconfig.h" /* clang-format off */ /************************************************************************** Symbols and macros to supply platform-independent interfaces to mathematical functions and constants **************************************************************************/ /* Python provides implementations for copysign, round and hypot in * Python/pymath.c just in case your math library doesn't provide the * functions. * *Note: PC/pyconfig.h defines copysign as _copysign */ #ifndef HAVE_COPYSIGN extern double copysign(double, double); #endif #ifndef HAVE_ROUND extern double round(double); #endif #ifndef HAVE_HYPOT extern double hypot(double, double); #endif /* extra declarations */ #ifndef _MSC_VER #ifndef __STDC__ extern double fmod(double, double); extern double frexp(double, int *); extern double ldexp(double, int); extern double modf(double, double *); extern double pow(double, double); #endif /* __STDC__ */ #endif /* _MSC_VER */ /* High precision definition of pi and e (Euler) * The values are taken from libc6's math.h. */ #ifndef Py_MATH_PIl #define Py_MATH_PIl 3.1415926535897932384626433832795029L #endif #ifndef Py_MATH_PI #define Py_MATH_PI 3.14159265358979323846 #endif #ifndef Py_MATH_El #define Py_MATH_El 2.7182818284590452353602874713526625L #endif #ifndef Py_MATH_E #define Py_MATH_E 2.7182818284590452354 #endif /* Tau (2pi) to 40 digits, taken from tauday.com/tau-digits. */ #ifndef Py_MATH_TAU #define Py_MATH_TAU 6.2831853071795864769252867665590057683943L #endif /* On x86, Py_FORCE_DOUBLE forces a floating-point number out of an x87 FPU register and into a 64-bit memory location, rounding from extended precision to double precision in the process. On other platforms it does nothing. */ /* we take double rounding as evidence of x87 usage */ #ifndef Py_LIMITED_API #ifndef Py_FORCE_DOUBLE #ifdef X87_DOUBLE_ROUNDING double _Py_force_double(double); #define Py_FORCE_DOUBLE(X) (_Py_force_double(X)) #else #define Py_FORCE_DOUBLE(X) (X) #endif #endif #endif #ifndef Py_LIMITED_API #ifdef HAVE_GCC_ASM_FOR_X87 unsigned short _Py_get_387controlword(void); void _Py_set_387controlword(unsigned short); #endif #endif /* Py_IS_NAN(X) * Return 1 if float or double arg is a NaN, else 0. * Caution: * X is evaluated more than once. * This may not work on all platforms. Each platform has *some* * way to spell this, though -- override in pyconfig.h if you have * a platform where it doesn't work. * Note: PC/pyconfig.h defines Py_IS_NAN as _isnan */ #ifndef Py_IS_NAN #if defined HAVE_DECL_ISNAN && HAVE_DECL_ISNAN == 1 #define Py_IS_NAN(X) isnan(X) #else #define Py_IS_NAN(X) ((X) != (X)) #endif #endif /* Py_IS_INFINITY(X) * Return 1 if float or double arg is an infinity, else 0. * Caution: * X is evaluated more than once. * This implementation may set the underflow flag if |X| is very small; * it really can't be implemented correctly (& easily) before C99. * Override in pyconfig.h if you have a better spelling on your platform. * Py_FORCE_DOUBLE is used to avoid getting false negatives from a * non-infinite value v sitting in an 80-bit x87 register such that * v becomes infinite when spilled from the register to 64-bit memory. * Note: PC/pyconfig.h defines Py_IS_INFINITY as _isinf */ #ifndef Py_IS_INFINITY #if defined HAVE_DECL_ISINF && HAVE_DECL_ISINF == 1 #define Py_IS_INFINITY(X) isinf(X) #else #define Py_IS_INFINITY(X) \ ((X) && (Py_FORCE_DOUBLE(X) * 0.5 == Py_FORCE_DOUBLE(X))) #endif #endif /* Py_IS_FINITE(X) * Return 1 if float or double arg is neither infinite nor NAN, else 0. * Some compilers (e.g. VisualStudio) have intrisics for this, so a special * macro for this particular test is useful * Note: PC/pyconfig.h defines Py_IS_FINITE as _finite */ #ifndef Py_IS_FINITE #if defined HAVE_DECL_ISFINITE && HAVE_DECL_ISFINITE == 1 #define Py_IS_FINITE(X) isfinite(X) #elif defined HAVE_FINITE #define Py_IS_FINITE(X) finite(X) #else #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X)) #endif #endif /* HUGE_VAL is supposed to expand to a positive double infinity. Python * uses Py_HUGE_VAL instead because some platforms are broken in this * respect. We used to embed code in pyport.h to try to worm around that, * but different platforms are broken in conflicting ways. If you're on * a platform where HUGE_VAL is defined incorrectly, fiddle your Python * config to #define Py_HUGE_VAL to something that works on your platform. */ #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif /* Py_NAN * A value that evaluates to a NaN. On IEEE 754 platforms INF*0 or * INF/INF works. Define Py_NO_NAN in pyconfig.h if your platform * doesn't support NaNs. */ #if !defined(Py_NAN) && !defined(Py_NO_NAN) #if !defined(__INTEL_COMPILER) #define Py_NAN (Py_HUGE_VAL * 0.) #else /* __INTEL_COMPILER */ #if defined(ICC_NAN_STRICT) #pragma float_control(push) #pragma float_control(precise, on) #pragma float_control(except, on) #if defined(_MSC_VER) __declspec(noinline) #else /* Linux */ __attribute__((noinline)) #endif /* _MSC_VER */ static double __icc_nan() { return sqrt(-1.0); } #pragma float_control(pop) #define Py_NAN __icc_nan() #else /* ICC_NAN_RELAXED as default for Intel Compiler */ static const union { unsigned char buf[8]; double __icc_nan; } __nan_store = {0, 0, 0, 0, 0, 0, 0xf8, 0x7f}; #define Py_NAN (__nan_store.__icc_nan) #endif /* ICC_NAN_STRICT */ #endif /* __INTEL_COMPILER */ #endif /* Py_OVERFLOWED(X) * Return 1 iff a libm function overflowed. Set errno to 0 before calling * a libm function, and invoke this macro after, passing the function * result. * Caution: * This isn't reliable. C99 no longer requires libm to set errno under * any exceptional condition, but does require +- HUGE_VAL return * values on overflow. A 754 box *probably* maps HUGE_VAL to a * double infinity, and we're cool if that's so, unless the input * was an infinity and an infinity is the expected result. A C89 * system sets errno to ERANGE, so we check for that too. We're * out of luck if a C99 754 box doesn't map HUGE_VAL to +Inf, or * if the returned result is a NaN, or if a C89 box returns HUGE_VAL * in non-overflow cases. * X is evaluated more than once. * Some platforms have better way to spell this, so expect some #ifdef'ery. * * OpenBSD uses 'isinf()' because a compiler bug on that platform causes * the longer macro version to be mis-compiled. This isn't optimal, and * should be removed once a newer compiler is available on that platform. * The system that had the failure was running OpenBSD 3.2 on Intel, with * gcc 2.95.3. * * According to Tim's checkin, the FreeBSD systems use isinf() to work * around a FPE bug on that platform. */ #if defined(__FreeBSD__) || defined(__OpenBSD__) #define Py_OVERFLOWED(X) isinf(X) #else #define Py_OVERFLOWED(X) \ ((X) != 0.0 && (errno == ERANGE || (X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL)) #endif /* Return whether integral type *type* is signed or not. */ #define _Py_IntegralTypeSigned(type) ((type)(-1) < 0) /* Return the maximum value of integral type *type*. */ #define _Py_IntegralTypeMax(type) \ ((_Py_IntegralTypeSigned(type)) \ ? (((((type)1 << (sizeof(type) * CHAR_BIT - 2)) - 1) << 1) + 1) \ : ~(type)0) /* Return the minimum value of integral type *type*. */ #define _Py_IntegralTypeMin(type) \ ((_Py_IntegralTypeSigned(type)) ? -_Py_IntegralTypeMax(type) - 1 : 0) /* Check whether *v* is in the range of integral type *type*. This is most * useful if *v* is floating-point, since demoting a floating-point *v* to an * integral type that cannot represent *v*'s integral part is undefined * behavior. */ #define _Py_InIntegralTypeRange(type, v) \ (_Py_IntegralTypeMin(type) <= v && v <= _Py_IntegralTypeMax(type)) #endif /* Py_PYMATH_H */
8,100
237
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pyerrors.h
#ifndef Py_ERRORS_H #define Py_ERRORS_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/unicodeobject.h" COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API /* PyException_HEAD defines the initial segment of every exception class. */ #define PyException_HEAD PyObject_HEAD PyObject *dict;\ PyObject *args; PyObject *traceback;\ PyObject *context; PyObject *cause;\ char suppress_context; typedef struct { PyException_HEAD } PyBaseExceptionObject; typedef struct { PyException_HEAD PyObject *msg; PyObject *filename; PyObject *lineno; PyObject *offset; PyObject *text; PyObject *print_file_and_line; } PySyntaxErrorObject; typedef struct { PyException_HEAD PyObject *msg; PyObject *name; PyObject *path; } PyImportErrorObject; typedef struct { PyException_HEAD PyObject *encoding; PyObject *object; Py_ssize_t start; Py_ssize_t end; PyObject *reason; } PyUnicodeErrorObject; typedef struct { PyException_HEAD PyObject *code; } PySystemExitObject; typedef struct { PyException_HEAD PyObject *myerrno; PyObject *strerror; PyObject *filename; PyObject *filename2; #ifdef MS_WINDOWS PyObject *winerror; #endif Py_ssize_t written; /* only for BlockingIOError, -1 otherwise */ } PyOSErrorObject; typedef struct { PyException_HEAD PyObject *value; } PyStopIterationObject; /* Compatibility typedefs */ typedef PyOSErrorObject PyEnvironmentErrorObject; #ifdef MS_WINDOWS typedef PyOSErrorObject PyWindowsErrorObject; #endif #endif /* !Py_LIMITED_API */ /* Error handling definitions */ void PyErr_SetNone(PyObject *); void PyErr_SetObject(PyObject *, PyObject *); #ifndef Py_LIMITED_API void _PyErr_SetKeyError(PyObject *); #endif void PyErr_SetString( PyObject *exception, const char *string /* decoded from utf-8 */ ); PyObject * PyErr_Occurred(void); void PyErr_Clear(void); void PyErr_Fetch(PyObject **, PyObject **, PyObject **); void PyErr_Restore(PyObject *, PyObject *, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 void PyErr_GetExcInfo(PyObject **, PyObject **, PyObject **); void PyErr_SetExcInfo(PyObject *, PyObject *, PyObject *); #endif #if defined(__clang__) || \ (defined(__GNUC__) && \ ((__GNUC__ >= 3) || \ (__GNUC__ == 2) && (__GNUC_MINOR__ >= 5))) #define _Py_NO_RETURN __attribute__((__noreturn__)) #else #define _Py_NO_RETURN #endif /* Defined in Python/pylifecycle.c */ void Py_FatalError(const char *message) relegated _Py_NO_RETURN; #if defined(Py_DEBUG) || defined(Py_LIMITED_API) #define _PyErr_OCCURRED() PyErr_Occurred() #else #define _PyErr_OCCURRED() (PyThreadState_GET()->curexc_type) #endif /* Error testing and normalization */ int PyErr_GivenExceptionMatches(PyObject *, PyObject *); int PyErr_ExceptionMatches(PyObject *); void PyErr_NormalizeException(PyObject**, PyObject**, PyObject**); /* Traceback manipulation (PEP 3134) */ int PyException_SetTraceback(PyObject *, PyObject *); PyObject * PyException_GetTraceback(PyObject *); /* Cause manipulation (PEP 3134) */ PyObject * PyException_GetCause(PyObject *); void PyException_SetCause(PyObject *, PyObject *); /* Context manipulation (PEP 3134) */ PyObject * PyException_GetContext(PyObject *); void PyException_SetContext(PyObject *, PyObject *); #ifndef Py_LIMITED_API void _PyErr_ChainExceptions(PyObject *, PyObject *, PyObject *); #endif /* */ #define PyExceptionClass_Check(x) \ (PyType_Check((x)) && \ PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS)) #define PyExceptionInstance_Check(x) \ PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS) #define PyExceptionClass_Name(x) \ ((char *)(((PyTypeObject*)(x))->tp_name)) #define PyExceptionInstance_Class(x) ((PyObject*)((x)->ob_type)) /* Predefined exceptions */ extern PyObject * PyExc_BaseException; extern PyObject * PyExc_Exception; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 extern PyObject * PyExc_StopAsyncIteration; #endif extern PyObject * PyExc_StopIteration; extern PyObject * PyExc_GeneratorExit; extern PyObject * PyExc_ArithmeticError; extern PyObject * PyExc_LookupError; extern PyObject * PyExc_AssertionError; extern PyObject * PyExc_AttributeError; extern PyObject * PyExc_BufferError; extern PyObject * PyExc_EOFError; extern PyObject * PyExc_FloatingPointError; extern PyObject * PyExc_OSError; extern PyObject * PyExc_ImportError; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 extern PyObject * PyExc_ModuleNotFoundError; #endif extern PyObject * PyExc_IndexError; extern PyObject * PyExc_KeyError; extern PyObject * PyExc_KeyboardInterrupt; extern PyObject * PyExc_MemoryError; extern PyObject * PyExc_NameError; extern PyObject * PyExc_OverflowError; extern PyObject * PyExc_RuntimeError; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 extern PyObject * PyExc_RecursionError; #endif extern PyObject * PyExc_NotImplementedError; extern PyObject * PyExc_SyntaxError; extern PyObject * PyExc_IndentationError; extern PyObject * PyExc_TabError; extern PyObject * PyExc_ReferenceError; extern PyObject * PyExc_SystemError; extern PyObject * PyExc_SystemExit; extern PyObject * PyExc_TypeError; extern PyObject * PyExc_UnboundLocalError; extern PyObject * PyExc_UnicodeError; extern PyObject * PyExc_UnicodeEncodeError; extern PyObject * PyExc_UnicodeDecodeError; extern PyObject * PyExc_UnicodeTranslateError; extern PyObject * PyExc_ValueError; extern PyObject * PyExc_ZeroDivisionError; #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 extern PyObject * PyExc_BlockingIOError; extern PyObject * PyExc_BrokenPipeError; extern PyObject * PyExc_ChildProcessError; extern PyObject * PyExc_ConnectionError; extern PyObject * PyExc_ConnectionAbortedError; extern PyObject * PyExc_ConnectionRefusedError; extern PyObject * PyExc_ConnectionResetError; extern PyObject * PyExc_FileExistsError; extern PyObject * PyExc_FileNotFoundError; extern PyObject * PyExc_InterruptedError; extern PyObject * PyExc_IsADirectoryError; extern PyObject * PyExc_NotADirectoryError; extern PyObject * PyExc_PermissionError; extern PyObject * PyExc_ProcessLookupError; extern PyObject * PyExc_TimeoutError; #endif /* Compatibility aliases */ extern PyObject * PyExc_EnvironmentError; extern PyObject * PyExc_IOError; #ifdef MS_WINDOWS extern PyObject * PyExc_WindowsError; #endif /* Predefined warning categories */ extern PyObject * PyExc_Warning; extern PyObject * PyExc_UserWarning; extern PyObject * PyExc_DeprecationWarning; extern PyObject * PyExc_PendingDeprecationWarning; extern PyObject * PyExc_SyntaxWarning; extern PyObject * PyExc_RuntimeWarning; extern PyObject * PyExc_FutureWarning; extern PyObject * PyExc_ImportWarning; extern PyObject * PyExc_UnicodeWarning; extern PyObject * PyExc_BytesWarning; extern PyObject * PyExc_ResourceWarning; /* Convenience functions */ int PyErr_BadArgument(void); PyObject * PyErr_NoMemory(void); PyObject * PyErr_SetFromErrno(PyObject *); PyObject * PyErr_SetFromErrnoWithFilenameObject( PyObject *, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000 PyObject * PyErr_SetFromErrnoWithFilenameObjects( PyObject *, PyObject *, PyObject *); #endif PyObject * PyErr_SetFromErrnoWithFilename( PyObject *exc, const char *filename /* decoded from the filesystem encoding */ ); #if !defined(Py_LIMITED_API) PyObject * PyErr_SetFromErrnoWithUnicodeFilename( PyObject *, const Py_UNICODE *); #endif /* MS_WINDOWS */ PyObject * PyErr_Format( PyObject *exception, const char *format, /* ASCII-encoded string */ ... ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 PyObject * PyErr_FormatV( PyObject *exception, const char *format, va_list vargs); #endif #ifndef Py_LIMITED_API /* Like PyErr_Format(), but saves current exception as __context__ and __cause__. */ PyObject * _PyErr_FormatFromCause( PyObject *exception, const char *format, /* ASCII-encoded string */ ... ); #endif PyObject * PyErr_SetFromWindowsErrWithFilename( int ierr, const char *filename /* decoded from the filesystem encoding */ ); #ifndef Py_LIMITED_API /* XXX redeclare to use WSTRING */ PyObject * PyErr_SetFromWindowsErrWithUnicodeFilename( int, const Py_UNICODE *); #endif PyObject * PyErr_SetFromWindowsErr(int); PyObject * PyErr_SetExcFromWindowsErrWithFilenameObject( PyObject *,int, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000 PyObject * PyErr_SetExcFromWindowsErrWithFilenameObjects( PyObject *,int, PyObject *, PyObject *); #endif PyObject * PyErr_SetExcFromWindowsErrWithFilename( PyObject *exc, int ierr, const char *filename /* decoded from the filesystem encoding */ ); #ifndef Py_LIMITED_API PyObject * PyErr_SetExcFromWindowsErrWithUnicodeFilename( PyObject *,int, const Py_UNICODE *); #endif PyObject * PyErr_SetExcFromWindowsErr(PyObject *, int); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 PyObject * PyErr_SetImportErrorSubclass(PyObject *, PyObject *, PyObject *, PyObject *); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject * PyErr_SetImportError(PyObject *, PyObject *, PyObject *); #endif /* Export the old function so that the existing API remains available: */ void PyErr_BadInternalCall(void); void _PyErr_BadInternalCall(const char *filename, int lineno); /* Mask the old API with a call to the new API for code compiled under Python 2.0: */ #if IsModeDbg() #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__) #else #define PyErr_BadInternalCall() #endif /* Function to create a new exception */ PyObject * PyErr_NewException( const char *name, PyObject *base, PyObject *dict); PyObject * PyErr_NewExceptionWithDoc( const char *name, const char *doc, PyObject *base, PyObject *dict); void PyErr_WriteUnraisable(PyObject *); /* In exceptions.c */ #ifndef Py_LIMITED_API /* Helper that attempts to replace the current exception with one of the * same type but with a prefix added to the exception text. The resulting * exception description looks like: * * prefix (exc_type: original_exc_str) * * Only some exceptions can be safely replaced. If the function determines * it isn't safe to perform the replacement, it will leave the original * unmodified exception in place. * * Returns a borrowed reference to the new exception (if any), NULL if the * existing exception was left in place. */ PyObject * _PyErr_TrySetFromCause( const char *prefix_format, /* ASCII-encoded string */ ... ); #endif /* In sigcheck.c or signalmodule.c */ int PyErr_CheckSignals(void); void PyErr_SetInterrupt(void); /* In signalmodule.c */ #ifndef Py_LIMITED_API int PySignal_SetWakeupFd(int fd); #endif /* Support for adding program text to SyntaxErrors */ void PyErr_SyntaxLocation( const char *filename, /* decoded from the filesystem encoding */ int lineno); void PyErr_SyntaxLocationEx( const char *filename, /* decoded from the filesystem encoding */ int lineno, int col_offset); #ifndef Py_LIMITED_API void PyErr_SyntaxLocationObject( PyObject *filename, int lineno, int col_offset); #endif PyObject * PyErr_ProgramText( const char *filename, /* decoded from the filesystem encoding */ int lineno); #ifndef Py_LIMITED_API PyObject * PyErr_ProgramTextObject( PyObject *filename, int lineno); #endif /* The following functions are used to create and modify unicode exceptions from C */ /* create a UnicodeDecodeError object */ PyObject * PyUnicodeDecodeError_Create( const char *encoding, /* UTF-8 encoded string */ const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason /* UTF-8 encoded string */ ); /* create a UnicodeEncodeError object */ #ifndef Py_LIMITED_API PyObject * PyUnicodeEncodeError_Create( const char *encoding, /* UTF-8 encoded string */ const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason /* UTF-8 encoded string */ ); #endif /* create a UnicodeTranslateError object */ #ifndef Py_LIMITED_API PyObject * PyUnicodeTranslateError_Create( const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason /* UTF-8 encoded string */ ); PyObject * _PyUnicodeTranslateError_Create( PyObject *object, Py_ssize_t start, Py_ssize_t end, const char *reason /* UTF-8 encoded string */ ); #endif /* get the encoding attribute */ PyObject * PyUnicodeEncodeError_GetEncoding(PyObject *); PyObject * PyUnicodeDecodeError_GetEncoding(PyObject *); /* get the object attribute */ PyObject * PyUnicodeEncodeError_GetObject(PyObject *); PyObject * PyUnicodeDecodeError_GetObject(PyObject *); PyObject * PyUnicodeTranslateError_GetObject(PyObject *); /* get the value of the start attribute (the int * may not be NULL) return 0 on success, -1 on failure */ int PyUnicodeEncodeError_GetStart(PyObject *, Py_ssize_t *); int PyUnicodeDecodeError_GetStart(PyObject *, Py_ssize_t *); int PyUnicodeTranslateError_GetStart(PyObject *, Py_ssize_t *); /* assign a new value to the start attribute return 0 on success, -1 on failure */ int PyUnicodeEncodeError_SetStart(PyObject *, Py_ssize_t); int PyUnicodeDecodeError_SetStart(PyObject *, Py_ssize_t); int PyUnicodeTranslateError_SetStart(PyObject *, Py_ssize_t); /* get the value of the end attribute (the int *may not be NULL) return 0 on success, -1 on failure */ int PyUnicodeEncodeError_GetEnd(PyObject *, Py_ssize_t *); int PyUnicodeDecodeError_GetEnd(PyObject *, Py_ssize_t *); int PyUnicodeTranslateError_GetEnd(PyObject *, Py_ssize_t *); /* assign a new value to the end attribute return 0 on success, -1 on failure */ int PyUnicodeEncodeError_SetEnd(PyObject *, Py_ssize_t); int PyUnicodeDecodeError_SetEnd(PyObject *, Py_ssize_t); int PyUnicodeTranslateError_SetEnd(PyObject *, Py_ssize_t); /* get the value of the reason attribute */ PyObject * PyUnicodeEncodeError_GetReason(PyObject *); PyObject * PyUnicodeDecodeError_GetReason(PyObject *); PyObject * PyUnicodeTranslateError_GetReason(PyObject *); /* assign a new value to the reason attribute return 0 on success, -1 on failure */ int PyUnicodeEncodeError_SetReason( PyObject *exc, const char *reason /* UTF-8 encoded string */ ); int PyUnicodeDecodeError_SetReason( PyObject *exc, const char *reason /* UTF-8 encoded string */ ); int PyUnicodeTranslateError_SetReason( PyObject *exc, const char *reason /* UTF-8 encoded string */ ); int PyOS_snprintf(char *str, size_t size, const char *format, ...) Py_GCC_ATTRIBUTE((format(printf, 3, 4))); int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va) Py_GCC_ATTRIBUTE((format(printf, 3, 0))); COSMOPOLITAN_C_END_ #endif /* !Py_ERRORS_H */
15,404
486
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/traceback.h
#ifndef Py_TRACEBACK_H #define Py_TRACEBACK_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/pystate.h" COSMOPOLITAN_C_START_ /* clang-format off */ struct _frame; /* Traceback interface */ #ifndef Py_LIMITED_API typedef struct _traceback { PyObject_HEAD struct _traceback *tb_next; struct _frame *tb_frame; int tb_lasti; int tb_lineno; } PyTracebackObject; #endif int PyTraceBack_Here(struct _frame *); int PyTraceBack_Print(PyObject *, PyObject *); #ifndef Py_LIMITED_API int _Py_DisplaySourceLine(PyObject *, PyObject *, int, int); void _PyTraceback_Add(const char *, const char *, int); #endif /* Reveal traceback type so we can typecheck traceback objects */ extern PyTypeObject PyTraceBack_Type; #define PyTraceBack_Check(v) (Py_TYPE(v) == &PyTraceBack_Type) #ifndef Py_LIMITED_API /* Write the Python traceback into the file 'fd'. For example: Traceback (most recent call first): File "xxx", line xxx in <xxx> File "xxx", line xxx in <xxx> ... File "xxx", line xxx in <xxx> This function is written for debug purpose only, to dump the traceback in the worst case: after a segmentation fault, at fatal error, etc. That's why, it is very limited. Strings are truncated to 100 characters and encoded to ASCII with backslashreplace. It doesn't write the source code, only the function name, filename and line number of each frame. Write only the first 100 frames: if the traceback is truncated, write the line " ...". This function is signal safe. */ void _Py_DumpTraceback( int fd, PyThreadState *tstate); /* Write the traceback of all threads into the file 'fd'. current_thread can be NULL. Return NULL on success, or an error message on error. This function is written for debug purpose only. It calls _Py_DumpTraceback() for each thread, and so has the same limitations. It only write the traceback of the first 100 threads: write "..." if there are more threads. If current_tstate is NULL, the function tries to get the Python thread state of the current thread. It is not an error if the function is unable to get the current Python thread state. If interp is NULL, the function tries to get the interpreter state from the current Python thread state, or from _PyGILState_GetInterpreterStateUnsafe() in last resort. It is better to pass NULL to interp and current_tstate, the function tries different options to retrieve these informations. This function is signal safe. */ const char* _Py_DumpTracebackThreads( int fd, PyInterpreterState *interp, PyThreadState *current_tstate); #endif /* !Py_LIMITED_API */ #ifndef Py_LIMITED_API /* Write a Unicode object into the file descriptor fd. Encode the string to ASCII using the backslashreplace error handler. Do nothing if text is not a Unicode object. The function accepts Unicode string which is not ready (PyUnicode_WCHAR_KIND). This function is signal safe. */ void _Py_DumpASCII(int fd, PyObject *text); /* Format an integer as decimal into the file descriptor fd. This function is signal safe. */ void _Py_DumpDecimal( int fd, unsigned long value); /* Format an integer as hexadecimal into the file descriptor fd with at least width digits. The maximum width is sizeof(unsigned long)*2 digits. This function is signal safe. */ void _Py_DumpHexadecimal( int fd, unsigned long value, Py_ssize_t width); #endif /* !Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_TRACEBACK_H */
3,600
115
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/yoink.h
#ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_YOINK_H_ #define COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_YOINK_H_ #ifdef __x86_64__ #define PYTHON_YOINK(s) \ __asm__(".section .yoink\n\t" \ "nopl\t\"pyc:" s "\"\n\t" \ ".previous") #elif defined(__aarch64__) #define PYTHON_YOINK(s) \ __asm__(".section .yoink\n\t" \ "bl\t\"pyc:" s "\"\n\t" \ ".previous") #else #error "architecture unsupported" #endif /* __x86_64__ */ #define PYTHON_PROVIDE(s) \ __asm__(".section .yoink\n" \ "\"pyc:" s "\":\n\t" \ ".globl\t\"pyc:" s "\"\n\t" \ ".previous") #endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_YOINK_H_ */
739
25
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/osmodule.h
#ifndef Py_OSMODULE_H #define Py_OSMODULE_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000 PyObject * PyOS_FSPath(PyObject *path); #endif COSMOPOLITAN_C_END_ #endif /* !Py_OSMODULE_H */
296
13
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/iterobject.h
#ifndef Py_ITEROBJECT_H #define Py_ITEROBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ extern PyTypeObject PySeqIter_Type; extern PyTypeObject PyCallIter_Type; extern PyTypeObject PyCmpWrapper_Type; #define PySeqIter_Check(op) (Py_TYPE(op) == &PySeqIter_Type) PyObject * PySeqIter_New(PyObject *); #define PyCallIter_Check(op) (Py_TYPE(op) == &PyCallIter_Type) PyObject * PyCallIter_New(PyObject *, PyObject *); COSMOPOLITAN_C_END_ #endif /* !Py_ITEROBJECT_H */
523
23
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pystrhex.h
#ifndef Py_STRHEX_H #define Py_STRHEX_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API /* Returns a str() containing the hex representation of argbuf. */ PyObject* _Py_strhex(const char* argbuf, const Py_ssize_t arglen); /* Returns a bytes() containing the ASCII hex representation of argbuf. */ PyObject* _Py_strhex_bytes(const char* argbuf, const Py_ssize_t arglen); #endif /* !Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_STRHEX_H */
514
16
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/sliceobject.h
#ifndef Py_SLICEOBJECT_H #define Py_SLICEOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* The unique ellipsis object "..." */ extern PyObject _Py_EllipsisObject; /* Don't use this directly */ #define Py_Ellipsis (&_Py_EllipsisObject) /* Slice object interface */ /* A slice object containing start, stop, and step data members (the names are from range). After much talk with Guido, it was decided to let these be any arbitrary python type. Py_None stands for omitted values. */ #ifndef Py_LIMITED_API typedef struct { PyObject_HEAD PyObject *start, *stop, *step; /* not NULL */ } PySliceObject; #endif extern PyTypeObject PySlice_Type; extern PyTypeObject PyEllipsis_Type; #define PySlice_Check(op) (Py_TYPE(op) == &PySlice_Type) PyObject * PySlice_New(PyObject* start, PyObject* stop, PyObject* step); #ifndef Py_LIMITED_API PyObject * _PySlice_FromIndices(Py_ssize_t start, Py_ssize_t stop); int _PySlice_GetLongIndices(PySliceObject *self, PyObject *length, PyObject **start_ptr, PyObject **stop_ptr, PyObject **step_ptr); #endif int PySlice_GetIndices(PyObject *r, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step); 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 !defined(Py_LIMITED_API) || (Py_LIMITED_API+0 >= 0x03050400 && Py_LIMITED_API+0 < 0x03060000) || Py_LIMITED_API+0 >= 0x03060100 #ifdef Py_LIMITED_API #define PySlice_GetIndicesEx(slice, length, start, stop, step, slicelen) ( \ PySlice_Unpack((slice), (start), (stop), (step)) < 0 ? \ ((*(slicelen) = 0), -1) : \ ((*(slicelen) = PySlice_AdjustIndices((length), (start), (stop), *(step))), \ 0)) #endif int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step); Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step); #endif COSMOPOLITAN_C_END_ #endif /* !Py_SLICEOBJECT_H */
2,431
64
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/ast.h
#ifndef Py_AST_H #define Py_AST_H #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/pythonrun.h" COSMOPOLITAN_C_START_ /* clang-format off */ extern int foo; int PyAST_Validate(mod_ty); mod_ty PyAST_FromNode( const node *n, PyCompilerFlags *flags, const char *filename, /* decoded from the filesystem encoding */ PyArena *arena); mod_ty PyAST_FromNodeObject( const node *n, PyCompilerFlags *flags, PyObject *filename, PyArena *arena); COSMOPOLITAN_C_END_ #endif /* !Py_AST_H */
601
24
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/frameobject.h
#ifndef Py_LIMITED_API #ifndef Py_FRAMEOBJECT_H #define Py_FRAMEOBJECT_H #include "third_party/python/Include/code.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pystate.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef struct { int b_type; /* what kind of block this is */ int b_handler; /* where to jump to find handler */ int b_level; /* value stack level to pop to */ } PyTryBlock; typedef struct _frame { PyObject_VAR_HEAD struct _frame *f_back; /* previous frame, or NULL */ PyCodeObject *f_code; /* code segment */ PyObject *f_builtins; /* builtin symbol table (PyDictObject) */ PyObject *f_globals; /* global symbol table (PyDictObject) */ PyObject *f_locals; /* local symbol table (any mapping) */ PyObject **f_valuestack; /* points after the last local */ /* Next free slot in f_valuestack. Frame creation sets to f_valuestack. Frame evaluation usually NULLs it, but a frame that yields sets it to the current stack top. */ PyObject **f_stacktop; PyObject *f_trace; /* Trace function */ /* In a generator, we need to be able to swap between the exception state inside the generator and the exception state of the calling frame (which shouldn't be impacted when the generator "yields" from an except handler). These three fields exist exactly for that, and are unused for non-generator frames. See the save_exc_state and swap_exc_state functions in ceval.c for details of their use. */ PyObject *f_exc_type, *f_exc_value, *f_exc_traceback; /* Borrowed reference to a generator, or NULL */ PyObject *f_gen; int f_lasti; /* Last instruction if called */ /* Call PyFrame_GetLineNumber() instead of reading this field directly. As of 2.3 f_lineno is only valid when tracing is active (i.e. when f_trace is set). At other times we use PyCode_Addr2Line to calculate the line from the current bytecode index. */ int f_lineno; /* Current line number */ int f_iblock; /* index in f_blockstack */ char f_executing; /* whether the frame is still executing */ PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */ PyObject *f_localsplus[1]; /* locals+stack, dynamically sized */ } PyFrameObject; /* Standard object interface */ extern PyTypeObject PyFrame_Type; #define PyFrame_Check(op) (Py_TYPE(op) == &PyFrame_Type) PyFrameObject * PyFrame_New(PyThreadState *, PyCodeObject *, PyObject *, PyObject *); /* only internal use */ PyFrameObject* _PyFrame_New_NoTrack(PyThreadState *, PyCodeObject *, PyObject *, PyObject *); /* The rest of the interface is specific for frame objects */ /* Block management functions */ void PyFrame_BlockSetup(PyFrameObject *, int, int, int); PyTryBlock * PyFrame_BlockPop(PyFrameObject *); /* Extend the value stack */ PyObject ** PyFrame_ExtendStack(PyFrameObject *, int, int); /* Conversions between "fast locals" and locals in dictionary */ void PyFrame_LocalsToFast(PyFrameObject *, int); int PyFrame_FastToLocalsWithError(PyFrameObject *f); void PyFrame_FastToLocals(PyFrameObject *); int PyFrame_ClearFreeList(void); void _PyFrame_DebugMallocStats(FILE *out); /* Return the line of code the frame is currently executing. */ int PyFrame_GetLineNumber(PyFrameObject *); COSMOPOLITAN_C_END_ #endif /* !Py_FRAMEOBJECT_H */ #endif /* Py_LIMITED_API */
3,655
96
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pyfpe.h
#ifndef Py_PYFPE_H #define Py_PYFPE_H COSMOPOLITAN_C_START_ /* clang-format off */ #ifdef WANT_SIGFPE_HANDLER extern jmp_buf PyFPE_jbuf; extern int PyFPE_counter; extern double PyFPE_dummy(void *); #define PyFPE_START_PROTECT(err_string, leave_stmt) \ if (!PyFPE_counter++ && setjmp(PyFPE_jbuf)) { \ PyErr_SetString(PyExc_FloatingPointError, err_string); \ PyFPE_counter = 0; \ leave_stmt; \ } #define PyFPE_END_PROTECT(v) PyFPE_counter -= (int)PyFPE_dummy(&(v)); #else #define PyFPE_START_PROTECT(err_string, leave_stmt) #define PyFPE_END_PROTECT(v) #endif COSMOPOLITAN_C_END_ #endif /* !Py_PYFPE_H */
606
22
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/odictobject.h
#ifndef Py_ODICTOBJECT_H #define Py_ODICTOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* OrderedDict */ /* This API is optional and mostly redundant. */ #ifndef Py_LIMITED_API typedef struct _odictobject PyODictObject; extern PyTypeObject PyODict_Type; extern PyTypeObject PyODictIter_Type; extern PyTypeObject PyODictKeys_Type; extern PyTypeObject PyODictItems_Type; extern PyTypeObject PyODictValues_Type; #define PyODict_Check(op) PyObject_TypeCheck(op, &PyODict_Type) #define PyODict_CheckExact(op) (Py_TYPE(op) == &PyODict_Type) #define PyODict_SIZE(op) ((PyDictObject *)op)->ma_used PyObject * PyODict_New(void); int PyODict_SetItem(PyObject *od, PyObject *key, PyObject *item); int PyODict_DelItem(PyObject *od, PyObject *key); /* wrappers around PyDict* functions */ #define PyODict_GetItem(od, key) PyDict_GetItem((PyObject *)od, key) #define PyODict_GetItemWithError(od, key) \ PyDict_GetItemWithError((PyObject *)od, key) #define PyODict_Contains(od, key) PyDict_Contains((PyObject *)od, key) #define PyODict_Size(od) PyDict_Size((PyObject *)od) #define PyODict_GetItemString(od, key) \ PyDict_GetItemString((PyObject *)od, key) #endif COSMOPOLITAN_C_END_ #endif /* !Py_ODICTOBJECT_H */
1,271
41
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pygetopt.h
#ifndef Py_PYGETOPT_H #define Py_PYGETOPT_H COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API extern int _PyOS_opterr; extern int _PyOS_optind; extern wchar_t * _PyOS_optarg; void _PyOS_ResetGetOpt(void); int _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring); #endif /* !Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_PYGETOPT_H */
368
18
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/bitset.h
#ifndef Py_BITSET_H #define Py_BITSET_H #include "third_party/python/Include/pgenheaders.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define BYTE char typedef BYTE *bitset; bitset newbitset(int nbits); void delbitset(bitset bs); #define testbit(ss, ibit) (((ss)[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0) int addbit(bitset bs, int ibit); /* Returns 0 if already set */ int samebitset(bitset bs1, bitset bs2, int nbits); void mergebitset(bitset bs1, bitset bs2, int nbits); #define BITSPERBYTE (8*sizeof(BYTE)) #define NBYTES(nbits) (((nbits) + BITSPERBYTE - 1) / BITSPERBYTE) #define BIT2BYTE(ibit) ((ibit) / BITSPERBYTE) #define BIT2SHIFT(ibit) ((ibit) % BITSPERBYTE) #define BIT2MASK(ibit) (1 << BIT2SHIFT(ibit)) #define BYTE2BIT(ibyte) ((ibyte) * BITSPERBYTE) COSMOPOLITAN_C_END_ #endif /* !Py_BITSET_H */
817
28
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pydtrace.h
#ifndef Py_DTRACE_H #define Py_DTRACE_H COSMOPOLITAN_C_START_ #define PyDTrace_LINE(arg0, arg1, arg2) #define PyDTrace_FUNCTION_ENTRY(arg0, arg1, arg2) #define PyDTrace_FUNCTION_RETURN(arg0, arg1, arg2) #define PyDTrace_GC_START(arg0) #define PyDTrace_GC_DONE(arg0) #define PyDTrace_INSTANCE_NEW_START(arg0) #define PyDTrace_INSTANCE_NEW_DONE(arg0) #define PyDTrace_INSTANCE_DELETE_START(arg0) #define PyDTrace_INSTANCE_DELETE_DONE(arg0) #define PyDTrace_LINE_ENABLED() 0 #define PyDTrace_FUNCTION_ENTRY_ENABLED() 0 #define PyDTrace_FUNCTION_RETURN_ENABLED() 0 #define PyDTrace_GC_START_ENABLED() 0 #define PyDTrace_GC_DONE_ENABLED() 0 #define PyDTrace_INSTANCE_NEW_START_ENABLED() 0 #define PyDTrace_INSTANCE_NEW_DONE_ENABLED() 0 #define PyDTrace_INSTANCE_DELETE_START_ENABLED() 0 #define PyDTrace_INSTANCE_DELETE_DONE_ENABLED() 0 COSMOPOLITAN_C_END_ #endif /* !Py_DTRACE_H */
946
27
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/datetime.h
#ifndef Py_LIMITED_API #ifndef DATETIME_H #define DATETIME_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Fields are packed into successive bytes, each viewed as unsigned and * big-endian, unless otherwise noted: * * byte offset * 0 year 2 bytes, 1-9999 * 2 month 1 byte, 1-12 * 3 day 1 byte, 1-31 * 4 hour 1 byte, 0-23 * 5 minute 1 byte, 0-59 * 6 second 1 byte, 0-59 * 7 usecond 3 bytes, 0-999999 * 10 */ /* # of bytes for year, month, and day. */ #define _PyDateTime_DATE_DATASIZE 4 /* # of bytes for hour, minute, second, and usecond. */ #define _PyDateTime_TIME_DATASIZE 6 /* # of bytes for year, month, day, hour, minute, second, and usecond. */ #define _PyDateTime_DATETIME_DATASIZE 10 typedef struct { PyObject_HEAD Py_hash_t hashcode; /* -1 when unknown */ int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ int seconds; /* 0 <= seconds < 24*3600 is invariant */ int microseconds; /* 0 <= microseconds < 1000000 is invariant */ } PyDateTime_Delta; typedef struct { PyObject_HEAD /* a pure abstract base class */ } PyDateTime_TZInfo; /* The datetime and time types have hashcodes, and an optional tzinfo member, * present if and only if hastzinfo is true. */ #define _PyTZINFO_HEAD \ PyObject_HEAD \ Py_hash_t hashcode; \ char hastzinfo; /* boolean flag */ /* No _PyDateTime_BaseTZInfo is allocated; it's just to have something * convenient to cast to, when getting at the hastzinfo member of objects * starting with _PyTZINFO_HEAD. */ typedef struct { _PyTZINFO_HEAD } _PyDateTime_BaseTZInfo; /* All time objects are of PyDateTime_TimeType, but that can be allocated * in two ways, with or without a tzinfo member. Without is the same as * tzinfo == None, but consumes less memory. _PyDateTime_BaseTime is an * internal struct used to allocate the right amount of space for the * "without" case. */ #define _PyDateTime_TIMEHEAD \ _PyTZINFO_HEAD \ unsigned char data[_PyDateTime_TIME_DATASIZE]; typedef struct { _PyDateTime_TIMEHEAD } _PyDateTime_BaseTime; /* hastzinfo false */ typedef struct { _PyDateTime_TIMEHEAD unsigned char fold; PyObject *tzinfo; } PyDateTime_Time; /* hastzinfo true */ /* All datetime objects are of PyDateTime_DateTimeType, but that can be * allocated in two ways too, just like for time objects above. In addition, * the plain date type is a base class for datetime, so it must also have * a hastzinfo member (although it's unused there). */ typedef struct { _PyTZINFO_HEAD unsigned char data[_PyDateTime_DATE_DATASIZE]; } PyDateTime_Date; #define _PyDateTime_DATETIMEHEAD \ _PyTZINFO_HEAD \ unsigned char data[_PyDateTime_DATETIME_DATASIZE]; typedef struct { _PyDateTime_DATETIMEHEAD } _PyDateTime_BaseDateTime; /* hastzinfo false */ typedef struct { _PyDateTime_DATETIMEHEAD unsigned char fold; PyObject *tzinfo; } PyDateTime_DateTime; /* hastzinfo true */ /* Apply for date and datetime instances. */ #define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \ ((PyDateTime_Date*)o)->data[1]) #define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2]) #define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3]) #define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4]) #define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5]) #define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6]) #define PyDateTime_DATE_GET_MICROSECOND(o) \ ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ (((PyDateTime_DateTime*)o)->data[8] << 8) | \ ((PyDateTime_DateTime*)o)->data[9]) #define PyDateTime_DATE_GET_FOLD(o) (((PyDateTime_DateTime*)o)->fold) /* Apply for time instances. */ #define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0]) #define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1]) #define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2]) #define PyDateTime_TIME_GET_MICROSECOND(o) \ ((((PyDateTime_Time*)o)->data[3] << 16) | \ (((PyDateTime_Time*)o)->data[4] << 8) | \ ((PyDateTime_Time*)o)->data[5]) #define PyDateTime_TIME_GET_FOLD(o) (((PyDateTime_Time*)o)->fold) /* Apply for time delta instances */ #define PyDateTime_DELTA_GET_DAYS(o) (((PyDateTime_Delta*)o)->days) #define PyDateTime_DELTA_GET_SECONDS(o) (((PyDateTime_Delta*)o)->seconds) #define PyDateTime_DELTA_GET_MICROSECONDS(o) \ (((PyDateTime_Delta*)o)->microseconds) /* Define structure for C API. */ typedef struct { /* type objects */ PyTypeObject *DateType; PyTypeObject *DateTimeType; PyTypeObject *TimeType; PyTypeObject *DeltaType; PyTypeObject *TZInfoType; /* constructors */ PyObject *(*Date_FromDate)(int, int, int, PyTypeObject*); PyObject *(*DateTime_FromDateAndTime)(int, int, int, int, int, int, int, PyObject*, PyTypeObject*); PyObject *(*Time_FromTime)(int, int, int, int, PyObject*, PyTypeObject*); PyObject *(*Delta_FromDelta)(int, int, int, int, PyTypeObject*); /* constructors for the DB API */ PyObject *(*DateTime_FromTimestamp)(PyObject*, PyObject*, PyObject*); PyObject *(*Date_FromTimestamp)(PyObject*, PyObject*); /* PEP 495 constructors */ PyObject *(*DateTime_FromDateAndTimeAndFold)(int, int, int, int, int, int, int, PyObject*, int, PyTypeObject*); PyObject *(*Time_FromTimeAndFold)(int, int, int, int, PyObject*, int, PyTypeObject*); } PyDateTime_CAPI; #define PyDateTime_CAPSULE_NAME "datetime.datetime_CAPI" #ifdef Py_BUILD_CORE /* Macros for type checking when building the Python core. */ #define PyDate_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateType) #define PyDate_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DateType) #define PyDateTime_Check(op) PyObject_TypeCheck(op, &PyDateTime_DateTimeType) #define PyDateTime_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DateTimeType) #define PyTime_Check(op) PyObject_TypeCheck(op, &PyDateTime_TimeType) #define PyTime_CheckExact(op) (Py_TYPE(op) == &PyDateTime_TimeType) #define PyDelta_Check(op) PyObject_TypeCheck(op, &PyDateTime_DeltaType) #define PyDelta_CheckExact(op) (Py_TYPE(op) == &PyDateTime_DeltaType) #define PyTZInfo_Check(op) PyObject_TypeCheck(op, &PyDateTime_TZInfoType) #define PyTZInfo_CheckExact(op) (Py_TYPE(op) == &PyDateTime_TZInfoType) #else /* Define global variable for the C API and a macro for setting it. */ static PyDateTime_CAPI *PyDateTimeAPI = NULL; #define PyDateTime_IMPORT \ PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0) /* Macros for type checking when not building the Python core. */ #define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType) #define PyDate_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DateType) #define PyDateTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateTimeType) #define PyDateTime_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DateTimeType) #define PyTime_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->TimeType) #define PyTime_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->TimeType) #define PyDelta_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DeltaType) #define PyDelta_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->DeltaType) #define PyTZInfo_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->TZInfoType) #define PyTZInfo_CheckExact(op) (Py_TYPE(op) == PyDateTimeAPI->TZInfoType) /* Macros for accessing constructors in a simplified fashion. */ #define PyDate_FromDate(year, month, day) \ PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType) #define PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, usec) \ PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \ min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType) #define PyDateTime_FromDateAndTimeAndFold(year, month, day, hour, min, sec, usec, fold) \ PyDateTimeAPI->DateTime_FromDateAndTimeAndFold(year, month, day, hour, \ min, sec, usec, Py_None, fold, PyDateTimeAPI->DateTimeType) #define PyTime_FromTime(hour, minute, second, usecond) \ PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \ Py_None, PyDateTimeAPI->TimeType) #define PyTime_FromTimeAndFold(hour, minute, second, usecond, fold) \ PyDateTimeAPI->Time_FromTimeAndFold(hour, minute, second, usecond, \ Py_None, fold, PyDateTimeAPI->TimeType) #define PyDelta_FromDSU(days, seconds, useconds) \ PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \ PyDateTimeAPI->DeltaType) /* Macros supporting the DB API. */ #define PyDateTime_FromTimestamp(args) \ PyDateTimeAPI->DateTime_FromTimestamp( \ (PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL) #define PyDate_FromTimestamp(args) \ PyDateTimeAPI->Date_FromTimestamp( \ (PyObject*) (PyDateTimeAPI->DateType), args) #endif /* Py_BUILD_CORE */ COSMOPOLITAN_C_END_ #endif #endif /* !Py_LIMITED_API */
9,440
257
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pymem.h
#ifndef Py_PYMEM_H #define Py_PYMEM_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyport.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Debug-mode build with pymalloc implies PYMALLOC_DEBUG. * PYMALLOC_DEBUG is in error if pymalloc is not in use. */ #if defined(Py_DEBUG) && defined(WITH_PYMALLOC) && !defined(PYMALLOC_DEBUG) #define PYMALLOC_DEBUG #endif #if defined(PYMALLOC_DEBUG) && !defined(WITH_PYMALLOC) #error "PYMALLOC_DEBUG requires WITH_PYMALLOC" #endif #ifndef Py_LIMITED_API void * PyMem_RawMalloc(size_t size); void * PyMem_RawCalloc(size_t nelem, size_t elsize); void * PyMem_RawRealloc(void *ptr, size_t new_size); void PyMem_RawFree(void *ptr); /* Configure the Python memory allocators. Pass NULL to use default allocators. */ int _PyMem_SetupAllocators(const char *opt); #ifdef WITH_PYMALLOC int _PyMem_PymallocEnabled(void); #endif /* Identifier of an address space (domain) in tracemalloc */ typedef unsigned int _PyTraceMalloc_domain_t; /* Track an allocated memory block in the tracemalloc module. Return 0 on success, return -1 on error (failed to allocate memory to store the trace). Return -2 if tracemalloc is disabled. If memory block is already tracked, update the existing trace. */ int _PyTraceMalloc_Track( _PyTraceMalloc_domain_t domain, uintptr_t ptr, size_t size); /* Untrack an allocated memory block in the tracemalloc module. Do nothing if the block was not tracked. Return -2 if tracemalloc is disabled, otherwise return 0. */ int _PyTraceMalloc_Untrack( _PyTraceMalloc_domain_t domain, uintptr_t ptr); /* Get the traceback where a memory block was allocated. Return a tuple of (filename: str, lineno: int) tuples. Return None if the tracemalloc module is disabled or if the memory block is not tracked by tracemalloc. Raise an exception and return NULL on error. */ PyObject* _PyTraceMalloc_GetTraceback( _PyTraceMalloc_domain_t domain, uintptr_t ptr); int _PyMem_IsFreed(void *ptr, size_t size); #if !IsModeDbg() #define _PyTraceMalloc_Track(domain, ptr, size) (-2) #define _PyTraceMalloc_Untrack(domain, ptr) (-2) #define _PyTraceMalloc_GetTraceback(domain, ptr) (&_Py_NoneStruct) #define _PyMem_IsFreed(ptr, size) (0) #endif #endif /* !defined(Py_LIMITED_API) */ /* BEWARE: Each interface exports both functions and macros. Extension modules should use the functions, to ensure binary compatibility across Python versions. Because the Python implementation is free to change internal details, and the macros may (or may not) expose details for speed, if you do use the macros you must recompile your extensions with each Python release. Never mix calls to PyMem_ with calls to the platform malloc/realloc/ calloc/free. For example, on Windows different DLLs may end up using different heaps, and if you use PyMem_Malloc you'll get the memory from the heap used by the Python DLL; it could be a disaster if you free()'ed that directly in your own extension. Using PyMem_Free instead ensures Python can return the memory to the proper heap. As another example, in PYMALLOC_DEBUG mode, Python wraps all calls to all PyMem_ and PyObject_ memory functions in special debugging wrappers that add additional debugging info to dynamic memory blocks. The system routines have no idea what to do with that stuff, and the Python wrappers have no idea what to do with raw blocks obtained directly by the system routines then. The GIL must be held when using these APIs. */ /* * Raw memory interface * ==================== */ /* Functions Functions supplying platform-independent semantics for malloc/realloc/ free. These functions make sure that allocating 0 bytes returns a distinct non-NULL pointer (whenever possible -- if we're flat out of memory, NULL may be returned), even if the platform malloc and realloc don't. Returned pointers must be checked for NULL explicitly. No action is performed on failure (no exception is set, no warning is printed, etc). */ void * PyMem_Malloc(size_t size); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 void * PyMem_Calloc(size_t nelem, size_t elsize); #endif void * PyMem_Realloc(void *ptr, size_t new_size); void PyMem_Free(void *ptr); #ifndef Py_LIMITED_API char * _PyMem_RawStrdup(const char *str); char * _PyMem_Strdup(const char *str); #endif /* Macros. */ /* PyMem_MALLOC(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. */ /* Returns NULL to indicate error if a negative size or size larger than Py_ssize_t can represent is supplied. Helps prevents security holes. */ #define PyMem_MALLOC(n) PyMem_Malloc(n) #define PyMem_REALLOC(p, n) PyMem_Realloc(p, n) #define PyMem_FREE(p) PyMem_Free(p) /* * Type-oriented memory interface * ============================== * * Allocate memory for n objects of the given type. Returns a new pointer * or NULL if the request was too large or memory allocation failed. Use * these macros rather than doing the multiplication yourself so that proper * overflow checking is always done. */ #define PyMem_New(type, n) \ ( ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ ( (type *) PyMem_Malloc((n) * sizeof(type)) ) ) #define PyMem_NEW(type, n) \ ( ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ ( (type *) PyMem_MALLOC((n) * sizeof(type)) ) ) /* * The value of (p) is always clobbered by this macro regardless of success. * The caller MUST check if (p) is NULL afterwards and deal with the memory * error if so. This means the original value of (p) MUST be saved for the * caller's memory error handler to not lose track of it. */ #define PyMem_Resize(p, type, n) \ ( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ (type *) PyMem_Realloc((p), (n) * sizeof(type)) ) #define PyMem_RESIZE(p, type, n) \ ( (p) = ((size_t)(n) > PY_SSIZE_T_MAX / sizeof(type)) ? NULL : \ (type *) PyMem_REALLOC((p), (n) * sizeof(type)) ) /* PyMem{Del,DEL} are left over from ancient days, and shouldn't be used * anymore. They're just confusing aliases for PyMem_{Free,FREE} now. */ #define PyMem_Del PyMem_Free #define PyMem_DEL PyMem_FREE #if IsModeDbg() #ifndef Py_LIMITED_API typedef enum { /* PyMem_RawMalloc(), PyMem_RawRealloc() and PyMem_RawFree() */ PYMEM_DOMAIN_RAW, /* PyMem_Malloc(), PyMem_Realloc() and PyMem_Free() */ PYMEM_DOMAIN_MEM, /* PyObject_Malloc(), PyObject_Realloc() and PyObject_Free() */ PYMEM_DOMAIN_OBJ } PyMemAllocatorDomain; typedef struct { /* user context passed as the first argument to the 4 functions */ void *ctx; /* allocate a memory block */ void* (*malloc) (void *ctx, size_t size); /* allocate a memory block initialized by zeros */ void* (*calloc) (void *ctx, size_t nelem, size_t elsize); /* allocate or resize a memory block */ void* (*realloc) (void *ctx, void *ptr, size_t new_size); /* release a memory block */ void (*free) (void *ctx, void *ptr); } PyMemAllocatorEx; /* Get the memory block allocator of the specified domain. */ void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator); /* Set the memory block allocator of the specified domain. The new allocator must return a distinct non-NULL pointer when requesting zero bytes. For the PYMEM_DOMAIN_RAW domain, the allocator must be thread-safe: the GIL is not held when the allocator is called. If the new allocator is not a hook (don't call the previous allocator), the PyMem_SetupDebugHooks() function must be called to reinstall the debug hooks on top on the new allocator. */ void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator); /* Setup hooks to detect bugs in the following Python memory allocator functions: - PyMem_RawMalloc(), PyMem_RawRealloc(), PyMem_RawFree() - PyMem_Malloc(), PyMem_Realloc(), PyMem_Free() - PyObject_Malloc(), PyObject_Realloc() and PyObject_Free() Newly allocated memory is filled with the byte 0xCB, freed memory is filled with the byte 0xDB. Additionnal checks: - detect API violations, ex: PyObject_Free() called on a buffer allocated by PyMem_Malloc() - detect write before the start of the buffer (buffer underflow) - detect write after the end of the buffer (buffer overflow) The function does nothing if Python is not compiled is debug mode. */ void PyMem_SetupDebugHooks(void); #endif #endif COSMOPOLITAN_C_END_ #endif /* !Py_PYMEM_H */
8,873
247
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pythonrun.h
#ifndef Py_PYTHONRUN_H #define Py_PYTHONRUN_H #include "third_party/python/Include/code.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyarena.h" #include "third_party/python/Include/pystate.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define PyCF_MASK (CO_FUTURE_DIVISION | CO_FUTURE_ABSOLUTE_IMPORT | \ CO_FUTURE_WITH_STATEMENT | CO_FUTURE_PRINT_FUNCTION | \ CO_FUTURE_UNICODE_LITERALS | CO_FUTURE_BARRY_AS_BDFL | \ CO_FUTURE_GENERATOR_STOP) #define PyCF_MASK_OBSOLETE (CO_NESTED) #define PyCF_SOURCE_IS_UTF8 0x0100 #define PyCF_DONT_IMPLY_DEDENT 0x0200 #define PyCF_ONLY_AST 0x0400 #define PyCF_IGNORE_COOKIE 0x0800 #ifndef Py_LIMITED_API typedef struct { int cf_flags; /* bitmask of CO_xxx flags relevant to future */ } PyCompilerFlags; #endif #ifndef Py_LIMITED_API int PyRun_SimpleStringFlags(const char *, PyCompilerFlags *); int PyRun_AnyFileFlags(FILE *, const char *, PyCompilerFlags *); int PyRun_AnyFileExFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ int closeit, PyCompilerFlags *flags); int PyRun_SimpleFileExFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ int closeit, PyCompilerFlags *flags); int PyRun_InteractiveOneFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ PyCompilerFlags *flags); int PyRun_InteractiveOneObject( FILE *fp, PyObject *filename, PyCompilerFlags *flags); int PyRun_InteractiveLoopFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ PyCompilerFlags *flags); struct _mod * PyParser_ASTFromString( const char *s, const char *filename, /* decoded from the filesystem encoding */ int start, PyCompilerFlags *flags, PyArena *arena); struct _mod * PyParser_ASTFromStringObject( const char *s, PyObject *filename, int start, PyCompilerFlags *flags, PyArena *arena); struct _mod * PyParser_ASTFromFile( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ const char* enc, int start, const char *ps1, const char *ps2, PyCompilerFlags *flags, int *errcode, PyArena *arena); struct _mod * PyParser_ASTFromFileObject( FILE *fp, PyObject *filename, const char* enc, int start, const char *ps1, const char *ps2, PyCompilerFlags *flags, int *errcode, PyArena *arena); #endif #ifndef PyParser_SimpleParseString #define PyParser_SimpleParseString(S, B) \ PyParser_SimpleParseStringFlags(S, B, 0) #define PyParser_SimpleParseFile(FP, S, B) \ PyParser_SimpleParseFileFlags(FP, S, B, 0) #endif struct _node * PyParser_SimpleParseStringFlags(const char *, int, int); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 struct _node * PyParser_SimpleParseStringFlagsFilename(const char *, const char *, int, int); #endif struct _node * PyParser_SimpleParseFileFlags(FILE *, const char *, int, int); #ifndef Py_LIMITED_API PyObject * PyRun_StringFlags(const char *, int, PyObject *, PyObject *, PyCompilerFlags *); PyObject * PyRun_FileExFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags); #endif #ifdef Py_LIMITED_API PyObject * Py_CompileString(const char *, const char *, int); #else #define Py_CompileString(str, p, s) Py_CompileStringExFlags(str, p, s, NULL, -1) #define Py_CompileStringFlags(str, p, s, f) Py_CompileStringExFlags(str, p, s, f, -1) PyObject * Py_CompileStringExFlags( const char *str, const char *filename, /* decoded from the filesystem encoding */ int start, PyCompilerFlags *flags, int optimize); PyObject * Py_CompileStringObject( const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize); #endif struct symtable * Py_SymtableString( const char *str, const char *filename, /* decoded from the filesystem encoding */ int start); #ifndef Py_LIMITED_API struct symtable * Py_SymtableStringObject( const char *str, PyObject *filename, int start); #endif void PyErr_Print(void); void PyErr_PrintEx(int); void PyErr_Display(PyObject *, PyObject *, PyObject *); #ifndef Py_LIMITED_API /* Use macros for a bunch of old variants */ #define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL) #define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL) #define PyRun_AnyFileEx(fp, name, closeit) \ PyRun_AnyFileExFlags(fp, name, closeit, NULL) #define PyRun_AnyFileFlags(fp, name, flags) \ PyRun_AnyFileExFlags(fp, name, 0, flags) #define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL) #define PyRun_SimpleFile(f, p) PyRun_SimpleFileExFlags(f, p, 0, NULL) #define PyRun_SimpleFileEx(f, p, c) PyRun_SimpleFileExFlags(f, p, c, NULL) #define PyRun_InteractiveOne(f, p) PyRun_InteractiveOneFlags(f, p, NULL) #define PyRun_InteractiveLoop(f, p) PyRun_InteractiveLoopFlags(f, p, NULL) #define PyRun_File(fp, p, s, g, l) \ PyRun_FileExFlags(fp, p, s, g, l, 0, NULL) #define PyRun_FileEx(fp, p, s, g, l, c) \ PyRun_FileExFlags(fp, p, s, g, l, c, NULL) #define PyRun_FileFlags(fp, p, s, g, l, flags) \ PyRun_FileExFlags(fp, p, s, g, l, 0, flags) #endif /* Stuff with no proper home (yet) */ #ifndef Py_LIMITED_API char * PyOS_Readline(FILE *, FILE *, const char *); #endif extern int (*PyOS_InputHook)(void); extern char *(*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, const char *); #ifndef Py_LIMITED_API extern PyThreadState* _PyOS_ReadlineTState; #endif /* Stack size, in "pointers" (so we get extra safety margins on 64-bit platforms). On a 32-bit platform, this translates to an 8k margin. */ #define PYOS_STACK_MARGIN 2048 #if defined(WIN32) && !defined(MS_WIN64) && defined(_MSC_VER) && _MSC_VER >= 1300 /* Enable stack checking under Microsoft C */ #define USE_STACKCHECK #endif #ifdef USE_STACKCHECK /* Check that we aren't overflowing our stack */ int PyOS_CheckStack(void); #endif COSMOPOLITAN_C_END_ #endif /* !Py_PYTHONRUN_H */
6,579
196
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/memoryobject.h
#ifndef Py_MEMORYOBJECT_H #define Py_MEMORYOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API extern PyTypeObject _PyManagedBuffer_Type; #endif extern PyTypeObject PyMemoryView_Type; #define PyMemoryView_Check(op) (Py_TYPE(op) == &PyMemoryView_Type) #ifndef Py_LIMITED_API /* Get a pointer to the memoryview's private copy of the exporter's buffer. */ #define PyMemoryView_GET_BUFFER(op) (&((PyMemoryViewObject *)(op))->view) /* Get a pointer to the exporting object (this may be NULL!). */ #define PyMemoryView_GET_BASE(op) (((PyMemoryViewObject *)(op))->view.obj) #endif PyObject * PyMemoryView_FromObject(PyObject *base); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject * PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags); #endif #ifndef Py_LIMITED_API PyObject * PyMemoryView_FromBuffer(Py_buffer *info); #endif PyObject * PyMemoryView_GetContiguous(PyObject *base, int buffertype, char order); /* The structs are declared here so that macros can work, but they shouldn't be considered public. Don't access their fields directly, use the macros and functions instead! */ #ifndef Py_LIMITED_API #define _Py_MANAGED_BUFFER_RELEASED 0x001 /* access to exporter blocked */ #define _Py_MANAGED_BUFFER_FREE_FORMAT 0x002 /* free format */ typedef struct { PyObject_HEAD int flags; /* state flags */ Py_ssize_t exports; /* number of direct memoryview exports */ Py_buffer master; /* snapshot buffer obtained from the original exporter */ } _PyManagedBufferObject; /* memoryview state flags */ #define _Py_MEMORYVIEW_RELEASED 0x001 /* access to master buffer blocked */ #define _Py_MEMORYVIEW_C 0x002 /* C-contiguous layout */ #define _Py_MEMORYVIEW_FORTRAN 0x004 /* Fortran contiguous layout */ #define _Py_MEMORYVIEW_SCALAR 0x008 /* scalar: ndim = 0 */ #define _Py_MEMORYVIEW_PIL 0x010 /* PIL-style layout */ typedef struct { PyObject_VAR_HEAD _PyManagedBufferObject *mbuf; /* managed buffer */ Py_hash_t hash; /* hash value for read-only views */ int flags; /* state flags */ Py_ssize_t exports; /* number of buffer re-exports */ Py_buffer view; /* private copy of the exporter's view */ PyObject *weakreflist; Py_ssize_t ob_array[1]; /* shape, strides, suboffsets */ } PyMemoryViewObject; #endif COSMOPOLITAN_C_END_ #endif /* !Py_MEMORYOBJECT_H */
2,680
69
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/parsetok.h
#ifndef Py_LIMITED_API #ifndef Py_PARSETOK_H #define Py_PARSETOK_H #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef struct { int error; #ifndef PGEN /* The filename is useless for pgen, see comment in tok_state structure */ PyObject *filename; #endif int lineno; int offset; char *text; /* UTF-8-encoded string */ int token; int expected; } perrdetail; #if 0 #define PyPARSE_YIELD_IS_KEYWORD 0x0001 #endif #define PyPARSE_DONT_IMPLY_DEDENT 0x0002 #if 0 #define PyPARSE_WITH_IS_KEYWORD 0x0003 #define PyPARSE_PRINT_IS_FUNCTION 0x0004 #define PyPARSE_UNICODE_LITERALS 0x0008 #endif #define PyPARSE_IGNORE_COOKIE 0x0010 #define PyPARSE_BARRY_AS_BDFL 0x0020 node * PyParser_ParseString(const char *, grammar *, int, perrdetail *); node * PyParser_ParseFile (FILE *, const char *, grammar *, int, const char *, const char *, perrdetail *); node * PyParser_ParseStringFlags(const char *, grammar *, int, perrdetail *, int); node * PyParser_ParseFileFlags( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int flags); node * PyParser_ParseFileFlagsEx( FILE *fp, const char *filename, /* decoded from the filesystem encoding */ const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags); node * PyParser_ParseFileObject( FILE *fp, PyObject *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags); node * PyParser_ParseStringFlagsFilename( const char *s, const char *filename, /* decoded from the filesystem encoding */ grammar *g, int start, perrdetail *err_ret, int flags); node * PyParser_ParseStringFlagsFilenameEx( const char *s, const char *filename, /* decoded from the filesystem encoding */ grammar *g, int start, perrdetail *err_ret, int *flags); node * PyParser_ParseStringObject( const char *s, PyObject *filename, grammar *g, int start, perrdetail *err_ret, int *flags); /* Note that the following functions are defined in pythonrun.c, not in parsetok.c */ void PyParser_SetError(perrdetail *); void PyParser_ClearError(perrdetail *); COSMOPOLITAN_C_END_ #endif /* !Py_PARSETOK_H */ #endif /* !Py_LIMITED_API */
2,852
107
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/bytesobject.h
#ifndef Py_BYTESOBJECT_H #define Py_BYTESOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Type PyBytesObject represents a character string. An extra zero byte is reserved at the end to ensure it is zero-terminated, but a size is present so strings with null bytes in them can be represented. This is an immutable object type. There are functions to create new string objects, to test an object for string-ness, and to get the string value. The latter function returns a null pointer if the object is not of the proper type. There is a variant that takes an explicit size as well as a variant that assumes a zero-terminated string. Note that none of the functions should be applied to nil objects. */ /* Caching the hash (ob_shash) saves recalculation of a string's hash value. This significantly speeds up dict lookups. */ #ifndef Py_LIMITED_API typedef struct { PyObject_VAR_HEAD Py_hash_t ob_shash; char ob_sval[1]; /* Invariants: * ob_sval contains space for 'ob_size+1' elements. * ob_sval[ob_size] == 0. * ob_shash is the hash of the string or -1 if not computed yet. */ } PyBytesObject; #endif extern PyTypeObject PyBytes_Type; extern PyTypeObject PyBytesIter_Type; #define PyBytes_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_BYTES_SUBCLASS) #define PyBytes_CheckExact(op) (Py_TYPE(op) == &PyBytes_Type) PyObject * PyBytes_FromStringAndSize(const char *, Py_ssize_t); PyObject * PyBytes_FromString(const char *); PyObject * PyBytes_FromObject(PyObject *); PyObject * PyBytes_FromFormatV(const char*, va_list) Py_GCC_ATTRIBUTE((format(printf, 1, 0))); PyObject * PyBytes_FromFormat(const char*, ...) Py_GCC_ATTRIBUTE((format(printf, 1, 2))); Py_ssize_t PyBytes_Size(PyObject *); char * PyBytes_AsString(PyObject *); PyObject * PyBytes_Repr(PyObject *, int); void PyBytes_Concat(PyObject **, PyObject *); void PyBytes_ConcatAndDel(PyObject **, PyObject *); #ifndef Py_LIMITED_API int _PyBytes_Resize(PyObject **, Py_ssize_t); PyObject* _PyBytes_FormatEx( const char *format, Py_ssize_t format_len, PyObject *args, int use_bytearray); PyObject* _PyBytes_FromHex( PyObject *string, int use_bytearray); #endif PyObject * PyBytes_DecodeEscape(const char *, Py_ssize_t, const char *, Py_ssize_t, const char *); #ifndef Py_LIMITED_API /* Helper for PyBytes_DecodeEscape that detects invalid escape chars. */ PyObject * _PyBytes_DecodeEscape(const char *, Py_ssize_t, const char *, Py_ssize_t, const char *, const char **); #endif /* Macro, trading safety for speed */ #ifndef Py_LIMITED_API #define PyBytes_AS_STRING(op) (assert(PyBytes_Check(op)), \ (((PyBytesObject *)(op))->ob_sval)) #define PyBytes_GET_SIZE(op) (assert(PyBytes_Check(op)),Py_SIZE(op)) #endif /* _PyBytes_Join(sep, x) is like sep.join(x). sep must be PyBytesObject*, x must be an iterable object. */ #ifndef Py_LIMITED_API PyObject * _PyBytes_Join(PyObject *sep, PyObject *x); #endif /* Provides access to the internal data buffer and size of a string object or the default encoded version of a Unicode object. Passing NULL as *len parameter will force the string buffer to be 0-terminated (passing a string with embedded NULL characters will cause an exception). */ int PyBytes_AsStringAndSize( PyObject *obj, /* string or Unicode object */ char **s, /* pointer to buffer variable */ Py_ssize_t *len /* pointer to length variable or NULL (only possible for 0-terminated strings) */ ); /* Using the current locale, insert the thousands grouping into the string pointed to by buffer. For the argument descriptions, see Objects/stringlib/localeutil.h */ #ifndef Py_LIMITED_API Py_ssize_t _PyBytes_InsertThousandsGroupingLocale(char *buffer, Py_ssize_t n_buffer, char *digits, Py_ssize_t n_digits, Py_ssize_t min_width); /* Using explicit passed-in values, insert the thousands grouping into the string pointed to by buffer. For the argument descriptions, see Objects/stringlib/localeutil.h */ Py_ssize_t _PyBytes_InsertThousandsGrouping(char *buffer, Py_ssize_t n_buffer, char *digits, Py_ssize_t n_digits, Py_ssize_t min_width, const char *grouping, const char *thousands_sep); #endif /* Flags used by string formatting */ #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) #ifndef Py_LIMITED_API /* The _PyBytesWriter structure is big: it contains an embedded "stack buffer". A _PyBytesWriter variable must be declared at the end of variables in a function to optimize the memory allocation on the stack. */ typedef struct { /* bytes, bytearray or NULL (when the small buffer is used) */ PyObject *buffer; /* Number of allocated size. */ Py_ssize_t allocated; /* Minimum number of allocated bytes, incremented by _PyBytesWriter_Prepare() */ Py_ssize_t min_size; /* If non-zero, use a bytearray instead of a bytes object for buffer. */ int use_bytearray; /* If non-zero, overallocate the buffer (default: 0). This flag must be zero if use_bytearray is non-zero. */ int overallocate; /* Stack buffer */ int use_small_buffer; char small_buffer[512]; } _PyBytesWriter; /* Initialize a bytes writer By default, the overallocation is disabled. Set the overallocate attribute to control the allocation of the buffer. */ void _PyBytesWriter_Init(_PyBytesWriter *writer); /* Get the buffer content and reset the writer. Return a bytes object, or a bytearray object if use_bytearray is non-zero. Raise an exception and return NULL on error. */ PyObject * _PyBytesWriter_Finish(_PyBytesWriter *writer, void *str); /* Deallocate memory of a writer (clear its internal buffer). */ void _PyBytesWriter_Dealloc(_PyBytesWriter *writer); /* 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 the buffer is large enough to write *size* bytes. Add size to the writer minimum size (min_size attribute). str is the current pointer inside the buffer. Return the updated current pointer inside the buffer. Raise an exception and return NULL on error. */ void* _PyBytesWriter_Prepare(_PyBytesWriter *writer, void *str, Py_ssize_t size); /* Resize the buffer to make it larger. The new buffer may be larger than size bytes because of overallocation. Return the updated current pointer inside the buffer. Raise an exception and return NULL on error. Note: size must be greater than the number of allocated bytes in the writer. This function doesn't use the writer minimum size (min_size attribute). See also _PyBytesWriter_Prepare(). */ void* _PyBytesWriter_Resize(_PyBytesWriter *writer, void *str, Py_ssize_t size); /* Write bytes. Raise an exception and return NULL on error. */ void* _PyBytesWriter_WriteBytes(_PyBytesWriter *writer, void *str, const void *bytes, Py_ssize_t size); #endif /* Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_BYTESOBJECT_H */
8,025
218
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pyatomic.h
#ifndef Py_ATOMIC_H #define Py_ATOMIC_H #include "libc/assert.h" #include "third_party/python/Include/dynamic_annotations.h" #include "third_party/python/pyconfig.h" /* clang-format off */ /* This is modeled after the atomics interface from C1x, according to * the draft at * http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1425.pdf. * Operations and types are named the same except with a _Py_ prefix * and have the same semantics. * * Beware, the implementations here are deep magic. */ #if defined(HAVE_STD_ATOMIC) typedef enum _Py_memory_order { _Py_memory_order_relaxed = memory_order_relaxed, _Py_memory_order_acquire = memory_order_acquire, _Py_memory_order_release = memory_order_release, _Py_memory_order_acq_rel = memory_order_acq_rel, _Py_memory_order_seq_cst = memory_order_seq_cst } _Py_memory_order; typedef struct _Py_atomic_address { atomic_uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { atomic_int _value; } _Py_atomic_int; #define _Py_atomic_signal_fence(/*memory_order*/ ORDER) \ atomic_signal_fence(ORDER) #define _Py_atomic_thread_fence(/*memory_order*/ ORDER) \ atomic_thread_fence(ORDER) #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ atomic_store_explicit(&(ATOMIC_VAL)->_value, NEW_VAL, ORDER) #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ atomic_load_explicit(&(ATOMIC_VAL)->_value, ORDER) /* Use builtin atomic operations in GCC >= 4.7 */ #elif defined(HAVE_BUILTIN_ATOMIC) typedef enum _Py_memory_order { _Py_memory_order_relaxed = __ATOMIC_RELAXED, _Py_memory_order_acquire = __ATOMIC_ACQUIRE, _Py_memory_order_release = __ATOMIC_RELEASE, _Py_memory_order_acq_rel = __ATOMIC_ACQ_REL, _Py_memory_order_seq_cst = __ATOMIC_SEQ_CST } _Py_memory_order; typedef struct _Py_atomic_address { uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { int _value; } _Py_atomic_int; #define _Py_atomic_signal_fence(/*memory_order*/ ORDER) \ __atomic_signal_fence(ORDER) #define _Py_atomic_thread_fence(/*memory_order*/ ORDER) \ __atomic_thread_fence(ORDER) #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ (assert((ORDER) == __ATOMIC_RELAXED \ || (ORDER) == __ATOMIC_SEQ_CST \ || (ORDER) == __ATOMIC_RELEASE), \ __atomic_store_n(&(ATOMIC_VAL)->_value, NEW_VAL, ORDER)) #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ (assert((ORDER) == __ATOMIC_RELAXED \ || (ORDER) == __ATOMIC_SEQ_CST \ || (ORDER) == __ATOMIC_ACQUIRE \ || (ORDER) == __ATOMIC_CONSUME), \ __atomic_load_n(&(ATOMIC_VAL)->_value, ORDER)) #else typedef enum _Py_memory_order { _Py_memory_order_relaxed, _Py_memory_order_acquire, _Py_memory_order_release, _Py_memory_order_acq_rel, _Py_memory_order_seq_cst } _Py_memory_order; typedef struct _Py_atomic_address { uintptr_t _value; } _Py_atomic_address; typedef struct _Py_atomic_int { int _value; } _Py_atomic_int; /* Only support GCC (for expression statements) and x86 (for simple * atomic semantics) for now */ #if defined(__GNUC__) && (defined(__i386__) || defined(__amd64)) static __inline__ void _Py_atomic_signal_fence(_Py_memory_order order) { if (order != _Py_memory_order_relaxed) __asm__ volatile("":::"memory"); } static __inline__ void _Py_atomic_thread_fence(_Py_memory_order order) { if (order != _Py_memory_order_relaxed) __asm__ volatile("mfence":::"memory"); } /* Tell the race checker about this operation's effects. */ static __inline__ void _Py_ANNOTATE_MEMORY_ORDER(const volatile void *address, _Py_memory_order order) { (void)address; /* shut up -Wunused-parameter */ switch(order) { case _Py_memory_order_release: case _Py_memory_order_acq_rel: case _Py_memory_order_seq_cst: _Py_ANNOTATE_HAPPENS_BEFORE(address); break; case _Py_memory_order_relaxed: case _Py_memory_order_acquire: break; } switch(order) { case _Py_memory_order_acquire: case _Py_memory_order_acq_rel: case _Py_memory_order_seq_cst: _Py_ANNOTATE_HAPPENS_AFTER(address); break; case _Py_memory_order_relaxed: case _Py_memory_order_release: break; } } #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ __extension__ ({ \ __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \ __typeof__(atomic_val->_value) new_val = NEW_VAL;\ volatile __typeof__(new_val) *volatile_data = &atomic_val->_value; \ _Py_memory_order order = ORDER; \ _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \ \ /* Perform the operation. */ \ _Py_ANNOTATE_IGNORE_WRITES_BEGIN(); \ switch(order) { \ case _Py_memory_order_release: \ _Py_atomic_signal_fence(_Py_memory_order_release); \ /* fallthrough */ \ case _Py_memory_order_relaxed: \ *volatile_data = new_val; \ break; \ \ case _Py_memory_order_acquire: \ case _Py_memory_order_acq_rel: \ case _Py_memory_order_seq_cst: \ __asm__ volatile("xchg %0, %1" \ : "+r"(new_val) \ : "m"(atomic_val->_value) \ : "memory"); \ break; \ } \ _Py_ANNOTATE_IGNORE_WRITES_END(); \ }) #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ __extension__ ({ \ __typeof__(ATOMIC_VAL) atomic_val = ATOMIC_VAL; \ __typeof__(atomic_val->_value) result; \ volatile __typeof__(result) *volatile_data = &atomic_val->_value; \ _Py_memory_order order = ORDER; \ _Py_ANNOTATE_MEMORY_ORDER(atomic_val, order); \ \ /* Perform the operation. */ \ _Py_ANNOTATE_IGNORE_READS_BEGIN(); \ switch(order) { \ case _Py_memory_order_release: \ case _Py_memory_order_acq_rel: \ case _Py_memory_order_seq_cst: \ /* Loads on x86 are not releases by default, so need a */ \ /* thread fence. */ \ _Py_atomic_thread_fence(_Py_memory_order_release); \ break; \ default: \ /* No fence */ \ break; \ } \ result = *volatile_data; \ switch(order) { \ case _Py_memory_order_acquire: \ case _Py_memory_order_acq_rel: \ case _Py_memory_order_seq_cst: \ /* Loads on x86 are automatically acquire operations so */ \ /* can get by with just a compiler fence. */ \ _Py_atomic_signal_fence(_Py_memory_order_acquire); \ break; \ default: \ /* No fence */ \ break; \ } \ _Py_ANNOTATE_IGNORE_READS_END(); \ result; \ }) #else /* !gcc x86 */ /* Fall back to other compilers and processors by assuming that simple volatile accesses are atomic. This is false, so people should port this. */ #define _Py_atomic_signal_fence(/*memory_order*/ ORDER) ((void)0) #define _Py_atomic_thread_fence(/*memory_order*/ ORDER) ((void)0) #define _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, ORDER) \ ((ATOMIC_VAL)->_value = NEW_VAL) #define _Py_atomic_load_explicit(ATOMIC_VAL, ORDER) \ ((ATOMIC_VAL)->_value) #endif /* !gcc x86 */ #endif /* Standardized shortcuts. */ #define _Py_atomic_store(ATOMIC_VAL, NEW_VAL) \ _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, _Py_memory_order_seq_cst) #define _Py_atomic_load(ATOMIC_VAL) \ _Py_atomic_load_explicit(ATOMIC_VAL, _Py_memory_order_seq_cst) /* Python-local extensions */ #define _Py_atomic_store_relaxed(ATOMIC_VAL, NEW_VAL) \ _Py_atomic_store_explicit(ATOMIC_VAL, NEW_VAL, _Py_memory_order_relaxed) #define _Py_atomic_load_relaxed(ATOMIC_VAL) \ _Py_atomic_load_explicit(ATOMIC_VAL, _Py_memory_order_relaxed) #endif /* Py_ATOMIC_H */
8,111
245
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/tupleobject.h
#ifndef Py_TUPLEOBJECT_H #define Py_TUPLEOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Another generally useful object type is a tuple of object pointers. For Python, this is an immutable type. C code can change the tuple items (but not their number), and even use tuples are general-purpose arrays of object references, but in general only brand new tuples should be mutated, not ones that might already have been exposed to Python code. *** WARNING *** PyTuple_SetItem does not increment the new item's reference count, but does decrement the reference count of the item it replaces, if not nil. It does *decrement* the reference count if it is *not* inserted in the tuple. Similarly, PyTuple_GetItem does not increment the returned item's reference count. */ #ifndef Py_LIMITED_API typedef struct { PyObject_VAR_HEAD PyObject *ob_item[1]; /* ob_item contains space for 'ob_size' elements. * Items must normally not be NULL, except during construction when * the tuple is not yet visible outside the function that builds it. */ } PyTupleObject; #endif extern PyTypeObject PyTuple_Type; extern PyTypeObject PyTupleIter_Type; #define PyTuple_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TUPLE_SUBCLASS) #define PyTuple_CheckExact(op) (Py_TYPE(op) == &PyTuple_Type) PyObject * PyTuple_New(Py_ssize_t); Py_ssize_t PyTuple_Size(PyObject *); PyObject * PyTuple_GetItem(PyObject *, Py_ssize_t); int PyTuple_SetItem(PyObject *, Py_ssize_t, PyObject *); PyObject * PyTuple_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t); #ifndef Py_LIMITED_API int _PyTuple_Resize(PyObject **, Py_ssize_t); #endif PyObject *PyTuple_Pack(Py_ssize_t, ...); #ifndef Py_LIMITED_API void _PyTuple_MaybeUntrack(PyObject *); #endif /* Macro, trading safety for speed */ #ifndef Py_LIMITED_API #define PyTuple_GET_ITEM(op, i) (((PyTupleObject *)(op))->ob_item[i]) #define PyTuple_GET_SIZE(op) Py_SIZE(op) /* Macro, *only* to be used to fill in brand new tuples */ #define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = v) #endif int PyTuple_ClearFreeList(void); #ifndef Py_LIMITED_API void _PyTuple_DebugMallocStats(FILE *out); #endif /* Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_TUPLEOBJECT_H */
2,322
69
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/funcobject.h
#ifndef Py_LIMITED_API #ifndef Py_FUNCOBJECT_H #define Py_FUNCOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Function objects and code objects should not be confused with each other: * * Function objects are created by the execution of the 'def' statement. * They reference a code object in their __code__ attribute, which is a * purely syntactic object, i.e. nothing more than a compiled version of some * source code lines. There is one code object per source code "fragment", * but each code object can be referenced by zero or many function objects * depending only on how many times the 'def' statement in the source was * executed so far. */ typedef struct { PyObject_HEAD PyObject *func_code; /* A code object, the __code__ attribute */ PyObject *func_globals; /* A dictionary (other mappings won't do) */ PyObject *func_defaults; /* NULL or a tuple */ PyObject *func_kwdefaults; /* NULL or a dict */ PyObject *func_closure; /* NULL or a tuple of cell objects */ PyObject *func_doc; /* The __doc__ attribute, can be anything */ PyObject *func_name; /* The __name__ attribute, a string object */ PyObject *func_dict; /* The __dict__ attribute, a dict or NULL */ PyObject *func_weakreflist; /* List of weak references */ PyObject *func_module; /* The __module__ attribute, can be anything */ PyObject *func_annotations; /* Annotations, a dict or NULL */ PyObject *func_qualname; /* The qualified name */ /* Invariant: * func_closure contains the bindings for func_code->co_freevars, so * PyTuple_Size(func_closure) == PyCode_GetNumFree(func_code) * (func_closure may be NULL if PyCode_GetNumFree(func_code) == 0). */ } PyFunctionObject; extern PyTypeObject PyFunction_Type; #define PyFunction_Check(op) (Py_TYPE(op) == &PyFunction_Type) PyObject * PyFunction_New(PyObject *, PyObject *); PyObject * PyFunction_NewWithQualName(PyObject *, PyObject *, PyObject *); PyObject * PyFunction_GetCode(PyObject *); PyObject * PyFunction_GetGlobals(PyObject *); PyObject * PyFunction_GetModule(PyObject *); PyObject * PyFunction_GetDefaults(PyObject *); int PyFunction_SetDefaults(PyObject *, PyObject *); PyObject * PyFunction_GetKwDefaults(PyObject *); int PyFunction_SetKwDefaults(PyObject *, PyObject *); PyObject * PyFunction_GetClosure(PyObject *); int PyFunction_SetClosure(PyObject *, PyObject *); PyObject * PyFunction_GetAnnotations(PyObject *); int PyFunction_SetAnnotations(PyObject *, PyObject *); #ifndef Py_LIMITED_API PyObject * _PyFunction_FastCallDict( PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); PyObject * _PyFunction_FastCallKeywords( PyObject *func, PyObject **stack, Py_ssize_t nargs, PyObject *kwnames); #endif /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #define PyFunction_GET_CODE(func) \ (((PyFunctionObject *)func) -> func_code) #define PyFunction_GET_GLOBALS(func) \ (((PyFunctionObject *)func) -> func_globals) #define PyFunction_GET_MODULE(func) \ (((PyFunctionObject *)func) -> func_module) #define PyFunction_GET_DEFAULTS(func) \ (((PyFunctionObject *)func) -> func_defaults) #define PyFunction_GET_KW_DEFAULTS(func) \ (((PyFunctionObject *)func) -> func_kwdefaults) #define PyFunction_GET_CLOSURE(func) \ (((PyFunctionObject *)func) -> func_closure) #define PyFunction_GET_ANNOTATIONS(func) \ (((PyFunctionObject *)func) -> func_annotations) /* The classmethod and staticmethod types lives here, too */ extern PyTypeObject PyClassMethod_Type; extern PyTypeObject PyStaticMethod_Type; PyObject * PyClassMethod_New(PyObject *); PyObject * PyStaticMethod_New(PyObject *); COSMOPOLITAN_C_END_ #endif /* !Py_FUNCOBJECT_H */ #endif /* Py_LIMITED_API */
3,872
100
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/marshal.h
#ifndef Py_MARSHAL_H #define Py_MARSHAL_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define Py_MARSHAL_VERSION 4 void PyMarshal_WriteLongToFile(long, FILE *, int); void PyMarshal_WriteObjectToFile(PyObject *, FILE *, int); PyObject * PyMarshal_WriteObjectToString(PyObject *, int); #ifndef Py_LIMITED_API long PyMarshal_ReadLongFromFile(FILE *); int PyMarshal_ReadShortFromFile(FILE *); PyObject * PyMarshal_ReadObjectFromFile(FILE *); PyObject * PyMarshal_ReadLastObjectFromFile(FILE *); #endif PyObject * PyMarshal_ReadObjectFromString(const char *, Py_ssize_t); COSMOPOLITAN_C_END_ #endif /* !Py_MARSHAL_H */
666
23
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pystate.h
#ifndef Py_PYSTATE_H #define Py_PYSTATE_H #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyatomic.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* This limitation is for performance and simplicity. If needed it can be removed (with effort). */ #define MAX_CO_EXTRA_USERS 255 /* State shared between threads */ struct _ts; /* Forward */ struct _is; /* Forward */ struct _frame; /* Forward declaration for PyFrameObject. */ #ifdef Py_LIMITED_API typedef struct _is PyInterpreterState; #else typedef PyObject* (*_PyFrameEvalFunction)(struct _frame *, int); typedef struct _is { struct _is *next; struct _ts *tstate_head; PyObject *modules; PyObject *modules_by_index; PyObject *sysdict; PyObject *builtins; PyObject *importlib; PyObject *codec_search_path; PyObject *codec_search_cache; PyObject *codec_error_registry; int codecs_initialized; int fscodec_initialized; #ifdef HAVE_DLOPEN int dlopenflags; #endif PyObject *builtins_copy; PyObject *import_func; /* Initialized to PyEval_EvalFrameDefault(). */ _PyFrameEvalFunction eval_frame; } PyInterpreterState; #endif typedef struct _co_extra_state { struct _co_extra_state *next; PyInterpreterState* interp; Py_ssize_t co_extra_user_count; freefunc co_extra_freefuncs[MAX_CO_EXTRA_USERS]; } __PyCodeExtraState; /* This is temporary for backwards compat in 3.6 and will be removed in 3.7 */ __PyCodeExtraState* __PyCodeExtraState_Get(void); /* State unique per thread */ #ifndef Py_LIMITED_API /* Py_tracefunc return -1 when raising an exception, or 0 for success. */ typedef int (*Py_tracefunc)(PyObject *, struct _frame *, int, PyObject *); /* The following values are used for 'what' for tracefunc functions: */ #define PyTrace_CALL 0 #define PyTrace_EXCEPTION 1 #define PyTrace_LINE 2 #define PyTrace_RETURN 3 #define PyTrace_C_CALL 4 #define PyTrace_C_EXCEPTION 5 #define PyTrace_C_RETURN 6 #endif #ifdef Py_LIMITED_API typedef struct _ts PyThreadState; #else typedef struct _ts { /* See Python/ceval.c for comments explaining most fields */ struct _ts *prev; struct _ts *next; PyInterpreterState *interp; struct _frame *frame; int recursion_depth; char overflowed; /* The stack has overflowed. Allow 50 more calls to handle the runtime error. */ char recursion_critical; /* The current calls must not cause a stack overflow. */ /* 'tracing' keeps track of the execution depth when tracing/profiling. This is to prevent the actual trace/profile code from being recorded in the trace/profile. */ int tracing; int use_tracing; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; PyObject *exc_type; PyObject *exc_value; PyObject *exc_traceback; PyObject *dict; /* Stores per-thread state */ int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ long thread_id; /* Thread id where this tstate was created */ int trash_delete_nesting; PyObject *trash_delete_later; /* Called when a thread state is deleted normally, but not when it * is destroyed after fork(). * Pain: to prevent rare but fatal shutdown errors (issue 18808), * Thread.join() must wait for the join'ed thread's tstate to be unlinked * from the tstate chain. That happens at the end of a thread's life, * in pystate.c. * The obvious way doesn't quite work: create a lock which the tstate * unlinking code releases, and have Thread.join() wait to acquire that * lock. The problem is that we _are_ at the end of the thread's life: * if the thread holds the last reference to the lock, decref'ing the * lock will delete the lock, and that may trigger arbitrary Python code * if there's a weakref, with a callback, to the lock. But by this time * _PyThreadState_Current is already NULL, so only the simplest of C code * can be allowed to run (in particular it must not be possible to * release the GIL). * So instead of holding the lock directly, the tstate holds a weakref to * the lock: that's the value of on_delete_data below. Decref'ing a * weakref is harmless. * on_delete points to _threadmodule.c's static release_sentinel() function. * After the tstate is unlinked, release_sentinel is called with the * weakref-to-lock (on_delete_data) argument, and release_sentinel releases * the indirectly held lock. */ void (*on_delete)(void *); void *on_delete_data; PyObject *coroutine_wrapper; int in_coroutine_wrapper; /* Now used from PyInterpreterState, kept here for ABI compatibility with PyThreadState */ Py_ssize_t _preserve_36_ABI_1; freefunc _preserve_36_ABI_2[MAX_CO_EXTRA_USERS]; PyObject *async_gen_firstiter; PyObject *async_gen_finalizer; /* XXX signal handlers should also be here */ } PyThreadState; #endif PyInterpreterState * PyInterpreterState_New(void); void PyInterpreterState_Clear(PyInterpreterState *); void PyInterpreterState_Delete(PyInterpreterState *); #ifndef Py_LIMITED_API int _PyState_AddModule(PyObject*, struct PyModuleDef*); #endif /* !Py_LIMITED_API */ #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* New in 3.3 */ int PyState_AddModule(PyObject*, struct PyModuleDef*); int PyState_RemoveModule(struct PyModuleDef*); #endif PyObject* PyState_FindModule(struct PyModuleDef*); #ifndef Py_LIMITED_API void _PyState_ClearModules(void); #endif PyThreadState * PyThreadState_New(PyInterpreterState *); #ifndef Py_LIMITED_API PyThreadState * _PyThreadState_Prealloc(PyInterpreterState *); void _PyThreadState_Init(PyThreadState *); #endif /* !Py_LIMITED_API */ void PyThreadState_Clear(PyThreadState *); void PyThreadState_Delete(PyThreadState *); #ifndef Py_LIMITED_API void _PyThreadState_DeleteExcept(PyThreadState *tstate); #endif /* !Py_LIMITED_API */ #ifdef WITH_THREAD void PyThreadState_DeleteCurrent(void); #ifndef Py_LIMITED_API void _PyGILState_Reinit(void); #endif /* !Py_LIMITED_API */ #endif /* Return the current thread state. The global interpreter lock must be held. * When the current thread state is NULL, this issues a fatal error (so that * the caller needn't check for NULL). */ PyThreadState * PyThreadState_Get(void); #ifndef Py_LIMITED_API /* Similar to PyThreadState_Get(), but don't issue a fatal error * if it is NULL. */ PyThreadState * _PyThreadState_UncheckedGet(void); #define _PyThreadState_UncheckedGet() \ ((PyThreadState *)_Py_atomic_load_relaxed(&_PyThreadState_Current)) #endif /* !Py_LIMITED_API */ PyThreadState * PyThreadState_Swap(PyThreadState *); PyObject * PyThreadState_GetDict(void); int PyThreadState_SetAsyncExc(long, PyObject *); /* Variable and macro for in-line access to current thread state */ /* Assuming the current thread holds the GIL, this is the PyThreadState for the current thread. */ #ifdef Py_BUILD_CORE extern _Py_atomic_address _PyThreadState_Current; # define PyThreadState_GET() \ ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current)) #else # define PyThreadState_GET() PyThreadState_Get() #endif typedef enum {PyGILState_LOCKED, PyGILState_UNLOCKED} PyGILState_STATE; #ifdef WITH_THREAD /* Ensure that the current thread is ready to call the Python C API, regardless of the current state of Python, or of its thread lock. This may be called as many times as desired by a thread so long as each call is matched with a call to PyGILState_Release(). In general, other thread-state APIs may be used between _Ensure() and _Release() calls, so long as the thread-state is restored to its previous state before the Release(). For example, normal use of the Py_BEGIN_ALLOW_THREADS/ Py_END_ALLOW_THREADS macros are acceptable. The return value is an opaque "handle" to the thread state when PyGILState_Ensure() was called, and must be passed to PyGILState_Release() to ensure Python is left in the same state. Even though recursive calls are allowed, these handles can *not* be shared - each unique call to PyGILState_Ensure must save the handle for its call to PyGILState_Release. When the function returns, the current thread will hold the GIL. Failure is a fatal error. */ PyGILState_STATE PyGILState_Ensure(void); /* Release any resources previously acquired. After this call, Python's state will be the same as it was prior to the corresponding PyGILState_Ensure() call (but generally this state will be unknown to the caller, hence the use of the GILState API.) Every call to PyGILState_Ensure must be matched by a call to PyGILState_Release on the same thread. */ void PyGILState_Release(PyGILState_STATE); /* Helper/diagnostic function - get the current thread state for this thread. May return NULL if no GILState API has been used on the current thread. Note that the main thread always has such a thread-state, even if no auto-thread-state call has been made on the main thread. */ PyThreadState * PyGILState_GetThisThreadState(void); #ifndef Py_LIMITED_API /* Issue #26558: Flag to disable PyGILState_Check(). If set to non-zero, PyGILState_Check() always return 1. */ extern int _PyGILState_check_enabled; /* Helper/diagnostic function - return 1 if the current thread currently holds the GIL, 0 otherwise. The function returns 1 if _PyGILState_check_enabled is non-zero. */ int PyGILState_Check(void); /* Unsafe function to get the single PyInterpreterState used by this process' GILState implementation. Return NULL before _PyGILState_Init() is called and after _PyGILState_Fini() is called. */ PyInterpreterState * _PyGILState_GetInterpreterStateUnsafe(void); #endif #endif /* #ifdef WITH_THREAD */ /* The implementation of sys._current_frames() Returns a dict mapping thread id to that thread's current frame. */ #ifndef Py_LIMITED_API PyObject * _PyThread_CurrentFrames(void); #endif /* Routines for advanced debuggers, requested by David Beazley. Don't use unless you know what you are doing! */ #ifndef Py_LIMITED_API PyInterpreterState * PyInterpreterState_Head(void); PyInterpreterState * PyInterpreterState_Next(PyInterpreterState *); PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *); PyThreadState * PyThreadState_Next(PyThreadState *); typedef struct _frame *(*PyThreadFrameGetter)(PyThreadState *self_); #endif /* hook for PyEval_GetFrame(), requested for Psyco */ #ifndef Py_LIMITED_API extern PyThreadFrameGetter _PyThreadState_GetFrame; #endif COSMOPOLITAN_C_END_ #endif /* !Py_PYSTATE_H */
10,947
324
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/dictobject.h
#ifndef Py_DICTOBJECT_H #define Py_DICTOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Dictionary object type -- mapping from hashable object to object */ /* 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. */ #ifndef Py_LIMITED_API typedef struct _dictkeysobject PyDictKeysObject; /* The ma_values pointer is NULL for a combined table * or points to an array of PyObject* for a split table */ typedef struct { PyObject_HEAD /* Number of items in the dictionary */ Py_ssize_t ma_used; /* Dictionary version: globally unique, value change each time the dictionary is modified */ uint64_t ma_version_tag; PyDictKeysObject *ma_keys; /* If ma_values is NULL, the table is "combined": keys and values are stored in ma_keys. If ma_values is not NULL, the table is splitted: keys are stored in ma_keys and values are stored in ma_values */ PyObject **ma_values; } PyDictObject; typedef struct { PyObject_HEAD PyDictObject *dv_dict; } _PyDictViewObject; #endif /* Py_LIMITED_API */ extern PyTypeObject PyDict_Type; extern PyTypeObject PyDictIterKey_Type; extern PyTypeObject PyDictIterValue_Type; extern PyTypeObject PyDictIterItem_Type; extern PyTypeObject PyDictKeys_Type; extern PyTypeObject PyDictItems_Type; extern PyTypeObject PyDictValues_Type; #define PyDict_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_DICT_SUBCLASS) #define PyDict_CheckExact(op) (Py_TYPE(op) == &PyDict_Type) #define PyDictKeys_Check(op) PyObject_TypeCheck(op, &PyDictKeys_Type) #define PyDictItems_Check(op) PyObject_TypeCheck(op, &PyDictItems_Type) #define PyDictValues_Check(op) PyObject_TypeCheck(op, &PyDictValues_Type) /* This excludes Values, since they are not sets. */ # define PyDictViewSet_Check(op) \ (PyDictKeys_Check(op) || PyDictItems_Check(op)) PyObject * PyDict_New(void); PyObject * PyDict_GetItem(PyObject *mp, PyObject *key); #ifndef Py_LIMITED_API PyObject * _PyDict_GetItem_KnownHash(PyObject *mp, PyObject *key, Py_hash_t hash); #endif PyObject * PyDict_GetItemWithError(PyObject *mp, PyObject *key); #ifndef Py_LIMITED_API PyObject * _PyDict_GetItemIdWithError(PyObject *dp, struct _Py_Identifier *key); PyObject * PyDict_SetDefault( PyObject *mp, PyObject *key, PyObject *defaultobj); #endif int PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item); #ifndef Py_LIMITED_API int _PyDict_SetItem_KnownHash(PyObject *mp, PyObject *key, PyObject *item, Py_hash_t hash); #endif int PyDict_DelItem(PyObject *mp, PyObject *key); #ifndef Py_LIMITED_API int _PyDict_DelItem_KnownHash(PyObject *mp, PyObject *key, Py_hash_t hash); int _PyDict_DelItemIf(PyObject *mp, PyObject *key, int (*predicate)(PyObject *value)); #endif void PyDict_Clear(PyObject *mp); int PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value); #ifndef Py_LIMITED_API PyDictKeysObject *_PyDict_NewKeysForClass(void); PyObject * PyObject_GenericGetDict(PyObject *, void *); int _PyDict_Next( PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, Py_hash_t *hash); PyObject *_PyDictView_New(PyObject *, PyTypeObject *); #endif PyObject * PyDict_Keys(PyObject *mp); PyObject * PyDict_Values(PyObject *mp); PyObject * PyDict_Items(PyObject *mp); Py_ssize_t PyDict_Size(PyObject *mp); PyObject * PyDict_Copy(PyObject *mp); int PyDict_Contains(PyObject *mp, PyObject *key); #ifndef Py_LIMITED_API int _PyDict_Contains(PyObject *mp, PyObject *key, Py_hash_t hash); #define PyDict_GET_SIZE(mp) (assert(PyDict_Check(mp)),((PyDictObject *)mp)->ma_used) PyObject * _PyDict_NewPresized(Py_ssize_t minused); void _PyDict_MaybeUntrack(PyObject *mp); int _PyDict_HasOnlyStringKeys(PyObject *mp); Py_ssize_t _PyDict_KeysSize(PyDictKeysObject *keys); Py_ssize_t _PyDict_SizeOf(PyDictObject *); PyObject * _PyDict_Pop(PyObject *, PyObject *, PyObject *); PyObject *_PyDict_Pop_KnownHash(PyObject *, PyObject *, Py_hash_t, PyObject *); PyObject *_PyDict_FromKeys(PyObject *, PyObject *, PyObject *); #define _PyDict_HasSplitTable(d) ((d)->ma_values != NULL) int PyDict_ClearFreeList(void); #endif /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */ int PyDict_Update(PyObject *mp, PyObject *other); /* PyDict_Merge updates/merges from a mapping object (an object that supports PyMapping_Keys() and PyObject_GetItem()). If override is true, the last occurrence of a key wins, else the first. The Python dict.update(other) is equivalent to PyDict_Merge(dict, other, 1). */ int PyDict_Merge(PyObject *mp, PyObject *other, int override); #ifndef Py_LIMITED_API /* Like PyDict_Merge, but override can be 0, 1 or 2. If override is 0, the first occurrence of a key wins, if override is 1, the last occurrence of a key wins, if override is 2, a KeyError with conflicting key as argument is raised. */ int _PyDict_MergeEx(PyObject *mp, PyObject *other, int override); PyObject * _PyDictView_Intersect(PyObject* self, PyObject *other); #endif /* PyDict_MergeFromSeq2 updates/merges from an iterable object producing iterable objects of length 2. If override is true, the last occurrence of a key wins, else the first. The Python dict constructor dict(seq2) is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1). */ int PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override); PyObject * PyDict_GetItemString(PyObject *dp, const char *key); #ifndef Py_LIMITED_API PyObject * _PyDict_GetItemId(PyObject *dp, struct _Py_Identifier *key); #endif /* !Py_LIMITED_API */ int PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item); #ifndef Py_LIMITED_API int _PyDict_SetItemId(PyObject *dp, struct _Py_Identifier *key, PyObject *item); #endif /* !Py_LIMITED_API */ int PyDict_DelItemString(PyObject *dp, const char *key); #ifndef Py_LIMITED_API int _PyDict_DelItemId(PyObject *mp, struct _Py_Identifier *key); void _PyDict_DebugMallocStats(FILE *out); int _PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr, PyObject *name, PyObject *value); PyObject *_PyDict_LoadGlobal(PyDictObject *, PyDictObject *, PyObject *); #endif COSMOPOLITAN_C_END_ #endif /* !Py_DICTOBJECT_H */
6,805
176
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/grammar.h
#ifndef Py_GRAMMAR_H #define Py_GRAMMAR_H #include "libc/stdio/stdio.h" #include "third_party/python/Include/bitset.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* A label of an arc */ typedef struct { int lb_type; char *lb_str; } label; #define EMPTY 0 /* Label number 0 is by definition the empty label */ /* A list of labels */ typedef struct { int ll_nlabels; label *ll_label; } labellist; /* An arc from one state to another */ typedef struct { short a_lbl; /* Label of this arc */ short a_arrow; /* State where this arc goes to */ } arc; /* A state in a DFA */ typedef struct { int s_narcs; /* [jart/abi] moving s_accept here saves 4k */ int s_accept; /* [optional] Nonzero for accepting state */ arc *s_arc; /* Array of arcs */ int s_lower; /* [optional] Lowest label index */ int s_upper; /* [optional] Highest label index */ int *s_accel; /* [optional] Accelerator */ } state; /* A DFA */ typedef struct { int d_type; /* Non-terminal this represents */ char *d_name; /* For printing */ int d_initial; /* Initial state */ int d_nstates; state *d_state; /* Array of states */ bitset d_first; } dfa; /* A grammar */ typedef struct { int g_ndfas; dfa *g_dfa; /* Array of DFAs */ labellist g_ll; int g_start; /* Start symbol of the grammar */ int g_accel; /* Set if accelerators present */ } grammar; grammar *newgrammar(int); void freegrammar(grammar *); dfa *adddfa(grammar *, int, const char *); int addstate(dfa *); void addarc(dfa *, int, int, int); dfa *PyGrammar_FindDFA(grammar *, int); int addlabel(labellist *, int, const char *); int findlabel(labellist *, int, const char *); const char *PyGrammar_LabelRepr(label *); void translatelabels(grammar *); void addfirstsets(grammar *); void PyGrammar_AddAccelerators(grammar *); void PyGrammar_RemoveAccelerators(grammar *); void printgrammar(grammar *, FILE *); void printnonterminals(grammar *, FILE *); #ifndef Py_LIMITED_API extern grammar _PyParser_Grammar; #endif COSMOPOLITAN_C_END_ #endif /* !Py_GRAMMAR_H */
2,122
79
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/py_curses.h
#ifndef Py_CURSES_H #define Py_CURSES_H #include "third_party/python/Include/object.h" /* clang-format off */ #if !defined(HAVE_CURSES_IS_PAD) && defined(WINDOW_HAS_FLAGS) /* The following definition is necessary for ncurses 5.7; without it, some of [n]curses.h set NCURSES_OPAQUE to 1, and then Python can't get at the WINDOW flags field. */ #define NCURSES_OPAQUE 0 #endif #ifdef HAVE_NCURSES_H /* configure was checking <curses.h>, but we will use <ncurses.h>, which has some or all these features. */ #if !defined(WINDOW_HAS_FLAGS) && !(NCURSES_OPAQUE+0) #define WINDOW_HAS_FLAGS 1 #endif #if !defined(HAVE_CURSES_IS_PAD) && NCURSES_VERSION_PATCH+0 >= 20090906 #define HAVE_CURSES_IS_PAD 1 #endif #ifndef MVWDELCH_IS_EXPRESSION #define MVWDELCH_IS_EXPRESSION 1 #endif #endif COSMOPOLITAN_C_START_ #define PyCurses_API_pointers 4 /* Type declarations */ typedef struct { PyObject_HEAD WINDOW *win; char *encoding; } PyCursesWindowObject; #define PyCursesWindow_Check(v) (Py_TYPE(v) == &PyCursesWindow_Type) #define PyCurses_CAPSULE_NAME "_curses._C_API" #ifdef CURSES_MODULE /* This section is used when compiling _cursesmodule.c */ #else /* This section is used in modules that use the _cursesmodule API */ static void **PyCurses_API; #define PyCursesWindow_Type (*(PyTypeObject *) PyCurses_API[0]) #define PyCursesSetupTermCalled {if (! ((int (*)(void))PyCurses_API[1]) () ) return NULL;} #define PyCursesInitialised {if (! ((int (*)(void))PyCurses_API[2]) () ) return NULL;} #define PyCursesInitialisedColor {if (! ((int (*)(void))PyCurses_API[3]) () ) return NULL;} #define import_curses() \ PyCurses_API = (void **)PyCapsule_Import(PyCurses_CAPSULE_NAME, 1); #endif /* general error messages */ static const char catchall_ERR[] = "curses function returned ERR"; static const char catchall_NULL[] = "curses function returned NULL"; /* Function Prototype Macros - They are ugly but very, very useful. ;-) X - function name TYPE - parameter Type ERGSTR - format string for construction of the return value PARSESTR - format string for argument parsing */ #define NoArgNoReturnFunction(X) \ static PyObject *PyCurses_ ## X (PyObject *self) \ { \ PyCursesInitialised \ return PyCursesCheckERR(X(), # X); } #define NoArgOrFlagNoReturnFunction(X) \ static PyObject *PyCurses_ ## X (PyObject *self, PyObject *args) \ { \ int flag = 0; \ PyCursesInitialised \ switch(PyTuple_Size(args)) { \ case 0: \ return PyCursesCheckERR(X(), # X); \ case 1: \ if (!PyArg_ParseTuple(args, "i;True(1) or False(0)", &flag)) return NULL; \ if (flag) return PyCursesCheckERR(X(), # X); \ else return PyCursesCheckERR(no ## X (), # X); \ default: \ PyErr_SetString(PyExc_TypeError, # X " requires 0 or 1 arguments"); \ return NULL; } } #define NoArgReturnIntFunction(X) \ static PyObject *PyCurses_ ## X (PyObject *self) \ { \ PyCursesInitialised \ return PyLong_FromLong((long) X()); } #define NoArgReturnStringFunction(X) \ static PyObject *PyCurses_ ## X (PyObject *self) \ { \ PyCursesInitialised \ return PyBytes_FromString(X()); } #define NoArgTrueFalseFunction(X) \ static PyObject *PyCurses_ ## X (PyObject *self) \ { \ PyCursesInitialised \ if (X () == FALSE) { \ Py_INCREF(Py_False); \ return Py_False; \ } \ Py_INCREF(Py_True); \ return Py_True; } #define NoArgNoReturnVoidFunction(X) \ static PyObject *PyCurses_ ## X (PyObject *self) \ { \ PyCursesInitialised \ X(); \ Py_INCREF(Py_None); \ return Py_None; } COSMOPOLITAN_C_END_ #endif /* !defined(Py_CURSES_H) */
3,604
130
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/eval.h
#ifndef Py_EVAL_H #define Py_EVAL_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ PyObject * PyEval_EvalCode(PyObject *, PyObject *, PyObject *); PyObject * PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argc, PyObject **kwds, int kwdc, PyObject **defs, int defc, PyObject *kwdefs, PyObject *closure); #ifndef Py_LIMITED_API PyObject * _PyEval_EvalCodeWithName( PyObject *co, PyObject *globals, PyObject *locals, PyObject **args, Py_ssize_t argcount, PyObject **kwnames, PyObject **kwargs, Py_ssize_t kwcount, int kwstep, PyObject **defs, Py_ssize_t defcount, PyObject *kwdefs, PyObject *closure, PyObject *name, PyObject *qualname); PyObject * _PyEval_CallTracing(PyObject *func, PyObject *args); #endif COSMOPOLITAN_C_END_ #endif /* !Py_EVAL_H */
905
33
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/setobject.h
#ifndef Py_SETOBJECT_H #define Py_SETOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API /* There are three kinds of entries in the table: 1. Unused: key == NULL and hash == 0 2. Dummy: key == dummy and hash == -1 3. Active: key != NULL and key != dummy and hash != -1 The hash field of Unused slots is always zero. The hash field of Dummy slots are set to -1 meaning that dummy entries can be detected by either entry->key==dummy or by entry->hash==-1. */ #define PySet_MINSIZE 8 typedef struct { PyObject *key; Py_hash_t hash; /* Cached hash code of the key */ } setentry; /* The SetObject data structure is shared by set and frozenset objects. Invariant for sets: - hash is -1 Invariants for frozensets: - data is immutable. - hash is the hash of the frozenset or -1 if not computed yet. */ typedef struct { PyObject_HEAD Py_ssize_t fill; /* Number active and dummy entries*/ Py_ssize_t used; /* Number active entries */ /* The table contains mask + 1 slots, and that's a power of 2. * We store the mask instead of the size because the mask is more * frequently needed. */ Py_ssize_t mask; /* The table points to a fixed-size smalltable for small tables * or to additional malloc'ed memory for bigger tables. * The table pointer is never NULL which saves us from repeated * runtime null-tests. */ setentry *table; Py_hash_t hash; /* Only used by frozenset objects */ Py_ssize_t finger; /* Search finger for pop() */ setentry smalltable[PySet_MINSIZE]; PyObject *weakreflist; /* List of weak references */ } PySetObject; #define PySet_GET_SIZE(so) (((PySetObject *)(so))->used) extern PyObject * _PySet_Dummy; int _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash); int _PySet_Update(PyObject *set, PyObject *iterable); int PySet_ClearFreeList(void); #endif /* Section excluded by Py_LIMITED_API */ extern PyTypeObject PySet_Type; extern PyTypeObject PyFrozenSet_Type; extern PyTypeObject PySetIter_Type; PyObject * PySet_New(PyObject *); PyObject * PyFrozenSet_New(PyObject *); int PySet_Add(PyObject *set, PyObject *key); int PySet_Clear(PyObject *set); int PySet_Contains(PyObject *anyset, PyObject *key); int PySet_Discard(PyObject *set, PyObject *key); PyObject * PySet_Pop(PyObject *set); Py_ssize_t PySet_Size(PyObject *anyset); #define PyFrozenSet_CheckExact(ob) (Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_CheckExact(ob) \ (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type) #define PyAnySet_Check(ob) \ (Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) #define PySet_Check(ob) \ (Py_TYPE(ob) == &PySet_Type || \ PyType_IsSubtype(Py_TYPE(ob), &PySet_Type)) #define PyFrozenSet_Check(ob) \ (Py_TYPE(ob) == &PyFrozenSet_Type || \ PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type)) COSMOPOLITAN_C_END_ #endif /* !Py_SETOBJECT_H */
3,198
105
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/node.h
#ifndef Py_NODE_H #define Py_NODE_H #include "third_party/python/Include/pyport.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef struct _node { short n_type; char *n_str; int n_lineno; int n_col_offset; int n_nchildren; struct _node *n_child; } node; node * PyNode_New(int type); int PyNode_AddChild(node *n, int type, char *str, int lineno, int col_offset); void PyNode_Free(node *n); #ifndef Py_LIMITED_API Py_ssize_t _PyNode_SizeOf(node *n); #endif /* Node access functions */ #define NCH(n) ((n)->n_nchildren) #define CHILD(n, i) (&(n)->n_child[i]) #define RCHILD(n, i) (CHILD(n, NCH(n) + i)) #define TYPE(n) ((n)->n_type) #define STR(n) ((n)->n_str) #define LINENO(n) ((n)->n_lineno) /* Assert that the type of a node is what we expect */ #define REQ(n, type) assert(TYPE(n) == (type)) void PyNode_ListTree(node *); COSMOPOLITAN_C_END_ #endif /* !Py_NODE_H */
958
40
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/typeslots.h
/* clang-format off */ /* Do not renumber the file; these numbers are part of the stable ABI. */ /* Disabled, see #10181 */ #undef Py_bf_getbuffer #undef Py_bf_releasebuffer #define Py_mp_ass_subscript 3 #define Py_mp_length 4 #define Py_mp_subscript 5 #define Py_nb_absolute 6 #define Py_nb_add 7 #define Py_nb_and 8 #define Py_nb_bool 9 #define Py_nb_divmod 10 #define Py_nb_float 11 #define Py_nb_floor_divide 12 #define Py_nb_index 13 #define Py_nb_inplace_add 14 #define Py_nb_inplace_and 15 #define Py_nb_inplace_floor_divide 16 #define Py_nb_inplace_lshift 17 #define Py_nb_inplace_multiply 18 #define Py_nb_inplace_or 19 #define Py_nb_inplace_power 20 #define Py_nb_inplace_remainder 21 #define Py_nb_inplace_rshift 22 #define Py_nb_inplace_subtract 23 #define Py_nb_inplace_true_divide 24 #define Py_nb_inplace_xor 25 #define Py_nb_int 26 #define Py_nb_invert 27 #define Py_nb_lshift 28 #define Py_nb_multiply 29 #define Py_nb_negative 30 #define Py_nb_or 31 #define Py_nb_positive 32 #define Py_nb_power 33 #define Py_nb_remainder 34 #define Py_nb_rshift 35 #define Py_nb_subtract 36 #define Py_nb_true_divide 37 #define Py_nb_xor 38 #define Py_sq_ass_item 39 #define Py_sq_concat 40 #define Py_sq_contains 41 #define Py_sq_inplace_concat 42 #define Py_sq_inplace_repeat 43 #define Py_sq_item 44 #define Py_sq_length 45 #define Py_sq_repeat 46 #define Py_tp_alloc 47 #define Py_tp_base 48 #define Py_tp_bases 49 #define Py_tp_call 50 #define Py_tp_clear 51 #define Py_tp_dealloc 52 #define Py_tp_del 53 #define Py_tp_descr_get 54 #define Py_tp_descr_set 55 #define Py_tp_doc 56 #define Py_tp_getattr 57 #define Py_tp_getattro 58 #define Py_tp_hash 59 #define Py_tp_init 60 #define Py_tp_is_gc 61 #define Py_tp_iter 62 #define Py_tp_iternext 63 #define Py_tp_methods 64 #define Py_tp_new 65 #define Py_tp_repr 66 #define Py_tp_richcompare 67 #define Py_tp_setattr 68 #define Py_tp_setattro 69 #define Py_tp_str 70 #define Py_tp_traverse 71 #define Py_tp_members 72 #define Py_tp_getset 73 #define Py_tp_free 74 #define Py_nb_matrix_multiply 75 #define Py_nb_inplace_matrix_multiply 76 #define Py_am_await 77 #define Py_am_aiter 78 #define Py_am_anext 79 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000 /* New in 3.5 */ #define Py_tp_finalize 80 #endif
2,276
87
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/ezprint.h
#ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_EZPRINT_H_ #define COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_EZPRINT_H_ #include "libc/calls/calls.h" #include "libc/intrin/kprintf.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/unicodeobject.h" #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ static void EzPrint(PyObject *x, const char *s) { PyObject *u, *r, *t; kprintf("%s = ", s); if (!s) { kprintf("NULL"); } else { t = PyObject_Type(x); r = PyObject_Repr(t); u = PyUnicode_AsUTF8String(r); kprintf("%.*s ", PyBytes_GET_SIZE(u), PyBytes_AS_STRING(u)); Py_DECREF(u); Py_DECREF(r); Py_DECREF(t); r = PyObject_Repr(x); u = PyUnicode_AsUTF8String(r); kprintf("%.*s", PyBytes_GET_SIZE(u), PyBytes_AS_STRING(u)); Py_DECREF(u); Py_DECREF(r); } kprintf("\n"); } #define EZPRINT(x) EzPrint(x, #x) COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_EZPRINT_H_ */
1,143
39
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/cosmo.h
#ifndef Py_COSMO_H #define Py_COSMO_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ PyMODINIT_FUNC PyInit_cosmo(void); COSMOPOLITAN_C_END_ #endif /* !Py_IMPORT_H */
190
10
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pyctype.h
#ifndef Py_LIMITED_API #ifndef PYCTYPE_H #define PYCTYPE_H #include "libc/str/tab.internal.h" #define Py_TOLOWER(c) kToLower[255 & (c)] #define Py_TOUPPER(c) kToUpper[255 & (c)] #define Py_ISDIGIT(C) \ ({ \ unsigned char c_ = (C); \ '0' <= c_&& c_ <= '9'; \ }) #define Py_ISLOWER(C) \ ({ \ unsigned char c_ = (C); \ 'a' <= c_&& c_ <= 'z'; \ }) #define Py_ISUPPER(C) \ ({ \ unsigned char c_ = (C); \ 'A' <= c_&& c_ <= 'Z'; \ }) #define Py_ISALPHA(C) \ ({ \ unsigned char c_ = (C); \ ('A' <= c_ && c_ <= 'Z') || ('a' <= c_ && c_ <= 'z'); \ }) #define Py_ISALNUM(C) \ ({ \ unsigned char c_ = (C); \ (('0' <= c_ && c_ <= '9') || ('A' <= c_ && c_ <= 'Z') || \ ('a' <= c_ && c_ <= 'z')); \ }) #define Py_ISSPACE(C) \ ({ \ unsigned char c_ = (C); \ (c_ == ' ' || c_ == '\t' || c_ == '\r' || c_ == '\n' || c_ == '\f' || \ c_ == '\v'); \ }) #define Py_ISXDIGIT(C) \ ({ \ unsigned char c_ = (C); \ (('0' <= c_ && c_ <= '9') || ('A' <= c_ && c_ <= 'F') || \ ('a' <= c_ && c_ <= 'f')); \ }) #endif /* !PYCTYPE_H */ #endif /* !Py_LIMITED_API */
1,885
56
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pyhash.h
#ifndef Py_HASH_H #define Py_HASH_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Helpers for hash functions */ #ifndef Py_LIMITED_API Py_hash_t _Py_HashDouble(double); Py_hash_t _Py_HashPointer(void*); Py_hash_t _Py_HashBytes(const void*, Py_ssize_t); #endif /* Prime multiplier used in string and various other hashes. */ #define _PyHASH_MULTIPLIER 1000003UL /* 0xf4243 */ /* Parameters used for the numeric hash implementation. See notes for _Py_HashDouble in Python/pyhash.c. Numeric hashes are based on reduction modulo the prime 2**_PyHASH_BITS - 1. */ #if SIZEOF_VOID_P >= 8 # define _PyHASH_BITS 61 #else # define _PyHASH_BITS 31 #endif #define _PyHASH_MODULUS (((size_t)1 << _PyHASH_BITS) - 1) #define _PyHASH_INF 314159 #define _PyHASH_NAN 0 #define _PyHASH_IMAG _PyHASH_MULTIPLIER /* hash secret * * memory layout on 64 bit systems * cccccccc cccccccc cccccccc uc -- unsigned char[24] * pppppppp ssssssss ........ fnv -- two Py_hash_t * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t * ........ ........ ssssssss djbx33a -- 16 bytes padding + one Py_hash_t * ........ ........ eeeeeeee pyexpat XML hash salt * * memory layout on 32 bit systems * cccccccc cccccccc cccccccc uc * ppppssss ........ ........ fnv -- two Py_hash_t * k0k0k0k0 k1k1k1k1 ........ siphash -- two uint64_t (*) * ........ ........ ssss.... djbx33a -- 16 bytes padding + one Py_hash_t * ........ ........ eeee.... pyexpat XML hash salt * * (*) The siphash member may not be available on 32 bit platforms without * an unsigned int64 data type. */ #ifndef Py_LIMITED_API typedef union { /* ensure 24 bytes */ unsigned char uc[24]; /* two Py_hash_t for FNV */ struct { Py_hash_t prefix; Py_hash_t suffix; } fnv; /* two uint64 for SipHash24 */ struct { uint64_t k0; uint64_t k1; } siphash; /* a different (!) Py_hash_t for small string optimization */ struct { unsigned char padding[16]; Py_hash_t suffix; } djbx33a; struct { unsigned char padding[16]; Py_hash_t hashsalt; } expat; } _Py_HashSecret_t; extern _Py_HashSecret_t _Py_HashSecret; #endif #ifdef Py_DEBUG extern int _Py_HashSecret_Initialized; #endif /* hash function definition */ #ifndef Py_LIMITED_API typedef struct { Py_hash_t (*const hash)(const void *, Py_ssize_t); const char *name; const int hash_bits; const int seed_bits; } PyHash_FuncDef; PyHash_FuncDef* PyHash_GetFuncDef(void); #endif /* cutoff for small string DJBX33A optimization in range [1, cutoff). * * About 50% of the strings in a typical Python application are smaller than * 6 to 7 chars. However DJBX33A is vulnerable to hash collision attacks. * NEVER use DJBX33A for long strings! * * A Py_HASH_CUTOFF of 0 disables small string optimization. 32 bit platforms * should use a smaller cutoff because it is easier to create colliding * strings. A cutoff of 7 on 64bit platforms and 5 on 32bit platforms should * provide a decent safety margin. */ #ifndef Py_HASH_CUTOFF # define Py_HASH_CUTOFF 0 #elif (Py_HASH_CUTOFF > 7 || Py_HASH_CUTOFF < 0) # error Py_HASH_CUTOFF must in range 0...7. #endif /* Py_HASH_CUTOFF */ /* hash algorithm selection * * The values for Py_HASH_SIPHASH24 and Py_HASH_FNV are hard-coded in the * configure script. * * - FNV is available on all platforms and architectures. * - SIPHASH24 only works on plaforms that don't require aligned memory for integers. * - With EXTERNAL embedders can provide an alternative implementation with:: * * PyHash_FuncDef PyHash_Func = {...}; * * XXX: Figure out __declspec() for extern PyHash_FuncDef. */ #define Py_HASH_EXTERNAL 0 #define Py_HASH_SIPHASH24 1 #define Py_HASH_FNV 2 #ifndef Py_HASH_ALGORITHM # ifndef HAVE_ALIGNED_REQUIRED # define Py_HASH_ALGORITHM Py_HASH_SIPHASH24 # else # define Py_HASH_ALGORITHM Py_HASH_FNV # endif /* uint64_t && uint32_t && aligned */ #endif /* Py_HASH_ALGORITHM */ COSMOPOLITAN_C_END_ #endif /* !Py_HASH_H */
4,125
143
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/accu.h
#ifndef Py_LIMITED_API #ifndef Py_ACCU_H #define Py_ACCU_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ #undef small /* defined by some Windows headers */ typedef struct { PyObject *large; /* A list of previously accumulated large strings */ PyObject *small; /* Pending small strings */ } _PyAccu; int _PyAccu_Init(_PyAccu *acc); int _PyAccu_Accumulate(_PyAccu *acc, PyObject *unicode); PyObject * _PyAccu_FinishAsList(_PyAccu *acc); PyObject * _PyAccu_Finish(_PyAccu *acc); void _PyAccu_Destroy(_PyAccu *acc); COSMOPOLITAN_C_END_ #endif /* Py_ACCU_H */ #endif /* Py_LIMITED_API */
643
24
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/longobject.h
#ifndef Py_LONGOBJECT_H #define Py_LONGOBJECT_H #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/unicodeobject.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Long (arbitrary precision) integer object interface */ typedef struct _longobject PyLongObject; /* Revealed in longintrepr.h */ extern PyTypeObject PyLong_Type; #define PyLong_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_LONG_SUBCLASS) #define PyLong_CheckExact(op) (Py_TYPE(op) == &PyLong_Type) PyObject * PyLong_FromLong(long); PyObject * PyLong_FromUnsignedLong(unsigned long); PyObject * PyLong_FromSize_t(size_t); PyObject * PyLong_FromSsize_t(Py_ssize_t); PyObject * PyLong_FromDouble(double); long PyLong_AsLong(PyObject *); long PyLong_AsLongAndOverflow(PyObject *, int *); Py_ssize_t PyLong_AsSsize_t(PyObject *); size_t PyLong_AsSize_t(PyObject *); unsigned long PyLong_AsUnsignedLong(PyObject *); unsigned long PyLong_AsUnsignedLongMask(PyObject *); #ifndef Py_LIMITED_API int _PyLong_AsInt(PyObject *); #endif PyObject * PyLong_GetInfo(void); /* It may be useful in the future. I've added it in the PyInt -> PyLong cleanup to keep the extra information. [CH] */ #define PyLong_AS_LONG(op) PyLong_AsLong(op) /* Issue #1983: pid_t can be longer than a C long on some systems */ #if !defined(SIZEOF_PID_T) || SIZEOF_PID_T == SIZEOF_INT #define _Py_PARSE_PID "i" #define PyLong_FromPid PyLong_FromLong #define PyLong_AsPid PyLong_AsLong #elif SIZEOF_PID_T == SIZEOF_LONG #define _Py_PARSE_PID "l" #define PyLong_FromPid PyLong_FromLong #define PyLong_AsPid PyLong_AsLong #elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG #define _Py_PARSE_PID "L" #define PyLong_FromPid PyLong_FromLongLong #define PyLong_AsPid PyLong_AsLongLong #else #error "sizeof(pid_t) is neither sizeof(int), sizeof(long) or sizeof(long long)" #endif /* SIZEOF_PID_T */ #if SIZEOF_VOID_P == SIZEOF_INT # define _Py_PARSE_INTPTR "i" # define _Py_PARSE_UINTPTR "I" #elif SIZEOF_VOID_P == SIZEOF_LONG # define _Py_PARSE_INTPTR "l" # define _Py_PARSE_UINTPTR "k" #elif defined(SIZEOF_LONG_LONG) && SIZEOF_VOID_P == SIZEOF_LONG_LONG # define _Py_PARSE_INTPTR "L" # define _Py_PARSE_UINTPTR "K" #else # error "void* different in size from int, long and long long" #endif /* SIZEOF_VOID_P */ /* Used by Python/mystrtoul.c, _PyBytes_FromHex(), _PyBytes_DecodeEscapeRecode(), etc. */ #ifndef Py_LIMITED_API extern const unsigned char _PyLong_DigitValue[256]; #endif /* _PyLong_Frexp returns a double x and an exponent e such that the true value is approximately equal to x * 2**e. e is >= 0. x is 0.0 if and only if the input is 0 (in which case, e and x are both zeroes); otherwise, 0.5 <= abs(x) < 1.0. On overflow, which is possible if the number of bits doesn't fit into a Py_ssize_t, sets OverflowError and returns -1.0 for x, 0 for e. */ #ifndef Py_LIMITED_API double _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e); #endif double PyLong_AsDouble(PyObject *); PyObject * PyLong_FromVoidPtr(void *); void * PyLong_AsVoidPtr(PyObject *); PyObject * PyLong_FromLongLong(long long); PyObject * PyLong_FromUnsignedLongLong(unsigned long long); long long PyLong_AsLongLong(PyObject *); unsigned long long PyLong_AsUnsignedLongLong(PyObject *); unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *); long long PyLong_AsLongLongAndOverflow(PyObject *, int *); PyObject * PyLong_FromString(const char *, char **, int); #ifndef Py_LIMITED_API PyObject * PyLong_FromUnicode(Py_UNICODE*, Py_ssize_t, int); PyObject * PyLong_FromUnicodeObject(PyObject *u, int base); PyObject * _PyLong_FromBytes(const char *, Py_ssize_t, int); #endif #ifndef Py_LIMITED_API /* _PyLong_Sign. Return 0 if v is 0, -1 if v < 0, +1 if v > 0. v must not be NULL, and must be a normalized long. There are no error cases. */ int _PyLong_Sign(PyObject *v); /* _PyLong_NumBits. Return the number of bits needed to represent the absolute value of a long. For example, this returns 1 for 1 and -1, 2 for 2 and -2, and 2 for 3 and -3. It returns 0 for 0. v must not be NULL, and must be a normalized long. (size_t)-1 is returned and OverflowError set if the true result doesn't fit in a size_t. */ size_t _PyLong_NumBits(PyObject *v); /* _PyLong_DivmodNear. Given integers a and b, compute the nearest integer q to the exact quotient a / b, rounding to the nearest even integer in the case of a tie. Return (q, r), where r = a - q*b. The remainder r will satisfy abs(r) <= abs(b)/2, with equality possible only if q is even. */ PyObject * _PyLong_DivmodNear(PyObject *, PyObject *); /* _PyLong_FromByteArray: View the n unsigned bytes as a binary integer in base 256, and return a Python int with the same numeric value. If n is 0, the integer is 0. Else: If little_endian is 1/true, bytes[n-1] is the MSB and bytes[0] the LSB; else (little_endian is 0/false) bytes[0] is the MSB and bytes[n-1] the LSB. If is_signed is 0/false, view the bytes as a non-negative integer. If is_signed is 1/true, view the bytes as a 2's-complement integer, non-negative if bit 0x80 of the MSB is clear, negative if set. Error returns: + Return NULL with the appropriate exception set if there's not enough memory to create the Python int. */ PyObject * _PyLong_FromByteArray( const unsigned char* bytes, size_t n, int little_endian, int is_signed); /* _PyLong_AsByteArray: Convert the least-significant 8*n bits of long v to a base-256 integer, stored in array bytes. Normally return 0, return -1 on error. If little_endian is 1/true, store the MSB at bytes[n-1] and the LSB at bytes[0]; else (little_endian is 0/false) store the MSB at bytes[0] and the LSB at bytes[n-1]. If is_signed is 0/false, it's an error if v < 0; else (v >= 0) n bytes are filled and there's nothing special about bit 0x80 of the MSB. If is_signed is 1/true, bytes is filled with the 2's-complement representation of v's value. Bit 0x80 of the MSB is the sign bit. Error returns (-1): + is_signed is 0 and v < 0. TypeError is set in this case, and bytes isn't altered. + n isn't big enough to hold the full mathematical value of v. For example, if is_signed is 0 and there are more digits in the v than fit in n; or if is_signed is 1, v < 0, and n is just 1 bit shy of being large enough to hold a sign bit. OverflowError is set in this case, but bytes holds the least-significant n bytes of the true value. */ int _PyLong_AsByteArray(PyLongObject* v, unsigned char* bytes, size_t n, int little_endian, int is_signed); /* _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 *); /* _PyLong_Format: Convert the long to a string object with given base, appending a base prefix of 0[box] if base is 2, 8 or 16. */ PyObject * _PyLong_Format(PyObject *obj, int base); int _PyLong_FormatWriter( _PyUnicodeWriter *writer, PyObject *obj, int base, int alternate); char* _PyLong_FormatBytesWriter( _PyBytesWriter *writer, char *str, PyObject *obj, int base, int alternate); /* Format the object based on the format_spec, as defined in PEP 3101 (Advanced String Formatting). */ int _PyLong_FormatAdvancedWriter( _PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end); #endif /* Py_LIMITED_API */ /* These aren't really part of the int object, but they're handy. The functions are in Python/mystrtoul.c. */ unsigned long PyOS_strtoul(const char *, char **, int); long PyOS_strtol(const char *, char **, int); #ifndef Py_LIMITED_API /* For use by the gcd function in mathmodule.c */ PyObject * _PyLong_GCD(PyObject *, PyObject *); #endif /* !Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_LONGOBJECT_H */
8,137
215
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/graminit.h
/* clang-format off */ /* Generated by Parser/pgen */ #define single_input 256 #define file_input 257 #define eval_input 258 #define decorator 259 #define decorators 260 #define decorated 261 #define async_funcdef 262 #define funcdef 263 #define parameters 264 #define typedargslist 265 #define tfpdef 266 #define varargslist 267 #define vfpdef 268 #define stmt 269 #define simple_stmt 270 #define small_stmt 271 #define expr_stmt 272 #define annassign 273 #define testlist_star_expr 274 #define augassign 275 #define del_stmt 276 #define pass_stmt 277 #define flow_stmt 278 #define break_stmt 279 #define continue_stmt 280 #define return_stmt 281 #define yield_stmt 282 #define raise_stmt 283 #define import_stmt 284 #define import_name 285 #define import_from 286 #define import_as_name 287 #define dotted_as_name 288 #define import_as_names 289 #define dotted_as_names 290 #define dotted_name 291 #define global_stmt 292 #define nonlocal_stmt 293 #define assert_stmt 294 #define compound_stmt 295 #define async_stmt 296 #define if_stmt 297 #define while_stmt 298 #define for_stmt 299 #define try_stmt 300 #define with_stmt 301 #define with_item 302 #define except_clause 303 #define suite 304 #define test 305 #define test_nocond 306 #define lambdef 307 #define lambdef_nocond 308 #define or_test 309 #define and_test 310 #define not_test 311 #define comparison 312 #define comp_op 313 #define star_expr 314 #define expr 315 #define xor_expr 316 #define and_expr 317 #define shift_expr 318 #define arith_expr 319 #define term 320 #define factor 321 #define power 322 #define atom_expr 323 #define atom 324 #define testlist_comp 325 #define trailer 326 #define subscriptlist 327 #define subscript 328 #define sliceop 329 #define exprlist 330 #define testlist 331 #define dictorsetmaker 332 #define classdef 333 #define arglist 334 #define argument 335 #define comp_iter 336 #define comp_for 337 #define comp_if 338 #define encoding_decl 339 #define yield_expr 340 #define yield_arg 341
1,989
90
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/bytearrayobject.h
#ifndef Py_BYTEARRAYOBJECT_H #define Py_BYTEARRAYOBJECT_H #include "libc/assert.h" #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Type PyByteArrayObject represents a mutable array of bytes. * The Python API is that of a sequence; * the bytes are mapped to ints in [0, 256). * Bytes are not characters; they may be used to encode characters. * The only way to go between bytes and str/unicode is via encoding * and decoding. * For the convenience of C programmers, the bytes type is considered * to contain a char pointer, not an unsigned char pointer. */ /* Object layout */ #ifndef Py_LIMITED_API typedef struct { PyObject_VAR_HEAD Py_ssize_t ob_alloc; /* How many bytes allocated in ob_bytes */ char *ob_bytes; /* Physical backing buffer */ char *ob_start; /* Logical start inside ob_bytes */ /* XXX(nnorwitz): should ob_exports be Py_ssize_t? */ int ob_exports; /* How many buffer exports */ } PyByteArrayObject; #endif /* Type object */ extern PyTypeObject PyByteArray_Type; extern PyTypeObject PyByteArrayIter_Type; /* Type check macros */ #define PyByteArray_Check(self) PyObject_TypeCheck(self, &PyByteArray_Type) #define PyByteArray_CheckExact(self) (Py_TYPE(self) == &PyByteArray_Type) /* Direct API functions */ PyObject * PyByteArray_FromObject(PyObject *); PyObject * PyByteArray_Concat(PyObject *, PyObject *); PyObject * PyByteArray_FromStringAndSize(const char *, Py_ssize_t); Py_ssize_t PyByteArray_Size(PyObject *); char * PyByteArray_AsString(PyObject *); int PyByteArray_Resize(PyObject *, Py_ssize_t); /* Macros, trading safety for speed */ #ifndef Py_LIMITED_API #define PyByteArray_AS_STRING(self) \ (assert(PyByteArray_Check(self)), \ Py_SIZE(self) ? ((PyByteArrayObject *)(self))->ob_start : _PyByteArray_empty_string) #define PyByteArray_GET_SIZE(self) (assert(PyByteArray_Check(self)), Py_SIZE(self)) extern char _PyByteArray_empty_string[]; #endif COSMOPOLITAN_C_END_ #endif /* !Py_BYTEARRAYOBJECT_H */
2,042
58
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/complexobject.h
#ifndef Py_COMPLEXOBJECT_H #define Py_COMPLEXOBJECT_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/unicodeobject.h" COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API typedef struct { double real; double imag; } Py_complex; /* Operations on complex numbers from complexmodule.c */ Py_complex _Py_c_sum(Py_complex, Py_complex); Py_complex _Py_c_diff(Py_complex, Py_complex); Py_complex _Py_c_neg(Py_complex); Py_complex _Py_c_prod(Py_complex, Py_complex); Py_complex _Py_c_quot(Py_complex, Py_complex); Py_complex _Py_c_pow(Py_complex, Py_complex); double _Py_c_abs(Py_complex); #endif /* Complex object interface */ /* PyComplexObject represents a complex number with double-precision real and imaginary parts. */ #ifndef Py_LIMITED_API typedef struct { PyObject_HEAD Py_complex cval; } PyComplexObject; #endif extern PyTypeObject PyComplex_Type; #define PyComplex_Check(op) PyObject_TypeCheck(op, &PyComplex_Type) #define PyComplex_CheckExact(op) (Py_TYPE(op) == &PyComplex_Type) #ifndef Py_LIMITED_API PyObject * PyComplex_FromCComplex(Py_complex); #endif PyObject * PyComplex_FromDoubles(double real, double imag); double PyComplex_RealAsDouble(PyObject *op); double PyComplex_ImagAsDouble(PyObject *op); #ifndef Py_LIMITED_API Py_complex PyComplex_AsCComplex(PyObject *op); #endif /* Format the object based on the format_spec, as defined in PEP 3101 (Advanced String Formatting). */ #ifndef Py_LIMITED_API int _PyComplex_FormatAdvancedWriter( _PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end); #endif COSMOPOLITAN_C_END_ #endif /* !Py_COMPLEXOBJECT_H */
1,713
67
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/dynamic_annotations.h
#ifndef __DYNAMIC_ANNOTATIONS_H__ #define __DYNAMIC_ANNOTATIONS_H__ #ifndef DYNAMIC_ANNOTATIONS_ENABLED #define DYNAMIC_ANNOTATIONS_ENABLED 0 #endif #if DYNAMIC_ANNOTATIONS_ENABLED != 0 /* clang-format off */ /* Copyright (c) 2008-2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * --- * Author: Kostya Serebryany * Copied to CPython by Jeffrey Yasskin, with all macros renamed to * start with _Py_ to avoid colliding with users embedding Python, and * with deprecated macros removed. */ /* This file defines dynamic annotations for use with dynamic analysis tool such as valgrind, PIN, etc. Dynamic annotation is a source code annotation that affects the generated code (that is, the annotation is not a comment). Each such annotation is attached to a particular instruction and/or to a particular object (address) in the program. The annotations that should be used by users are macros in all upper-case (e.g., _Py_ANNOTATE_NEW_MEMORY). Actual implementation of these macros may differ depending on the dynamic analysis tool being used. See http://code.google.com/p/data-race-test/ for more information. This file supports the following dynamic analysis tools: - None (DYNAMIC_ANNOTATIONS_ENABLED is not defined or zero). Macros are defined empty. - ThreadSanitizer, Helgrind, DRD (DYNAMIC_ANNOTATIONS_ENABLED is 1). Macros are defined as calls to non-inlinable empty functions that are intercepted by Valgrind. */ /* ------------------------------------------------------------- Annotations useful when implementing condition variables such as CondVar, using conditional critical sections (Await/LockWhen) and when constructing user-defined synchronization mechanisms. The annotations _Py_ANNOTATE_HAPPENS_BEFORE() and _Py_ANNOTATE_HAPPENS_AFTER() can be used to define happens-before arcs in user-defined synchronization mechanisms: the race detector will infer an arc from the former to the latter when they share the same argument pointer. Example 1 (reference counting): void Unref() { _Py_ANNOTATE_HAPPENS_BEFORE(&refcount_); if (AtomicDecrementByOne(&refcount_) == 0) { _Py_ANNOTATE_HAPPENS_AFTER(&refcount_); delete this; } } Example 2 (message queue): void MyQueue::Put(Type *e) { MutexLock lock(&mu_); _Py_ANNOTATE_HAPPENS_BEFORE(e); PutElementIntoMyQueue(e); } Type *MyQueue::Get() { MutexLock lock(&mu_); Type *e = GetElementFromMyQueue(); _Py_ANNOTATE_HAPPENS_AFTER(e); return e; } Note: when possible, please use the existing reference counting and message queue implementations instead of inventing new ones. */ /* Report that wait on the condition variable at address "cv" has succeeded and the lock at address "lock" is held. */ #define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \ AnnotateCondVarWait(__FILE__, __LINE__, cv, lock) /* Report that wait on the condition variable at "cv" has succeeded. Variant w/o lock. */ #define _Py_ANNOTATE_CONDVAR_WAIT(cv) \ AnnotateCondVarWait(__FILE__, __LINE__, cv, NULL) /* Report that we are about to signal on the condition variable at address "cv". */ #define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) \ AnnotateCondVarSignal(__FILE__, __LINE__, cv) /* Report that we are about to signal_all on the condition variable at "cv". */ #define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \ AnnotateCondVarSignalAll(__FILE__, __LINE__, cv) /* Annotations for user-defined synchronization mechanisms. */ #define _Py_ANNOTATE_HAPPENS_BEFORE(obj) _Py_ANNOTATE_CONDVAR_SIGNAL(obj) #define _Py_ANNOTATE_HAPPENS_AFTER(obj) _Py_ANNOTATE_CONDVAR_WAIT(obj) /* Report that the bytes in the range [pointer, pointer+size) are about to be published safely. The race checker will create a happens-before arc from the call _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) to subsequent accesses to this memory. Note: this annotation may not work properly if the race detector uses sampling, i.e. does not observe all memory accesses. */ #define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \ AnnotatePublishMemoryRange(__FILE__, __LINE__, pointer, size) /* Instruct the tool to create a happens-before arc between mu->Unlock() and mu->Lock(). This annotation may slow down the race detector and hide real races. Normally it is used only when it would be difficult to annotate each of the mutex's critical sections individually using the annotations above. This annotation makes sense only for hybrid race detectors. For pure happens-before detectors this is a no-op. For more details see http://code.google.com/p/data-race-test/wiki/PureHappensBeforeVsHybrid . */ #define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) \ AnnotateMutexIsUsedAsCondVar(__FILE__, __LINE__, mu) /* ------------------------------------------------------------- Annotations useful when defining memory allocators, or when memory that was protected in one way starts to be protected in another. */ /* Report that a new memory at "address" of size "size" has been allocated. This might be used when the memory has been retrieved from a free list and is about to be reused, or when the locking discipline for a variable changes. */ #define _Py_ANNOTATE_NEW_MEMORY(address, size) \ AnnotateNewMemory(__FILE__, __LINE__, address, size) /* ------------------------------------------------------------- Annotations useful when defining FIFO queues that transfer data between threads. */ /* Report that the producer-consumer queue (such as ProducerConsumerQueue) at address "pcq" has been created. The _Py_ANNOTATE_PCQ_* annotations should be used only for FIFO queues. For non-FIFO queues use _Py_ANNOTATE_HAPPENS_BEFORE (for put) and _Py_ANNOTATE_HAPPENS_AFTER (for get). */ #define _Py_ANNOTATE_PCQ_CREATE(pcq) \ AnnotatePCQCreate(__FILE__, __LINE__, pcq) /* Report that the queue at address "pcq" is about to be destroyed. */ #define _Py_ANNOTATE_PCQ_DESTROY(pcq) \ AnnotatePCQDestroy(__FILE__, __LINE__, pcq) /* Report that we are about to put an element into a FIFO queue at address "pcq". */ #define _Py_ANNOTATE_PCQ_PUT(pcq) \ AnnotatePCQPut(__FILE__, __LINE__, pcq) /* Report that we've just got an element from a FIFO queue at address "pcq". */ #define _Py_ANNOTATE_PCQ_GET(pcq) \ AnnotatePCQGet(__FILE__, __LINE__, pcq) /* ------------------------------------------------------------- Annotations that suppress errors. It is usually better to express the program's synchronization using the other annotations, but these can be used when all else fails. */ /* Report that we may have a benign race at "pointer", with size "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the point where "pointer" has been allocated, preferably close to the point where the race happens. See also _Py_ANNOTATE_BENIGN_RACE_STATIC. */ #define _Py_ANNOTATE_BENIGN_RACE(pointer, description) \ AnnotateBenignRaceSized(__FILE__, __LINE__, pointer, \ sizeof(*(pointer)), description) /* Same as _Py_ANNOTATE_BENIGN_RACE(address, description), but applies to the memory range [address, address+size). */ #define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \ AnnotateBenignRaceSized(__FILE__, __LINE__, address, size, description) /* Request the analysis tool to ignore all reads in the current thread until _Py_ANNOTATE_IGNORE_READS_END is called. Useful to ignore intentional racey reads, while still checking other reads and all writes. See also _Py_ANNOTATE_UNPROTECTED_READ. */ #define _Py_ANNOTATE_IGNORE_READS_BEGIN() \ AnnotateIgnoreReadsBegin(__FILE__, __LINE__) /* Stop ignoring reads. */ #define _Py_ANNOTATE_IGNORE_READS_END() \ AnnotateIgnoreReadsEnd(__FILE__, __LINE__) /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore writes. */ #define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() \ AnnotateIgnoreWritesBegin(__FILE__, __LINE__) /* Stop ignoring writes. */ #define _Py_ANNOTATE_IGNORE_WRITES_END() \ AnnotateIgnoreWritesEnd(__FILE__, __LINE__) /* Start ignoring all memory accesses (reads and writes). */ #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \ do {\ _Py_ANNOTATE_IGNORE_READS_BEGIN();\ _Py_ANNOTATE_IGNORE_WRITES_BEGIN();\ }while(0)\ /* Stop ignoring all memory accesses. */ #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() \ do {\ _Py_ANNOTATE_IGNORE_WRITES_END();\ _Py_ANNOTATE_IGNORE_READS_END();\ }while(0)\ /* Similar to _Py_ANNOTATE_IGNORE_READS_BEGIN, but ignore synchronization events: RWLOCK* and CONDVAR*. */ #define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() \ AnnotateIgnoreSyncBegin(__FILE__, __LINE__) /* Stop ignoring sync events. */ #define _Py_ANNOTATE_IGNORE_SYNC_END() \ AnnotateIgnoreSyncEnd(__FILE__, __LINE__) /* Enable (enable!=0) or disable (enable==0) race detection for all threads. This annotation could be useful if you want to skip expensive race analysis during some period of program execution, e.g. during initialization. */ #define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) \ AnnotateEnableRaceDetection(__FILE__, __LINE__, enable) /* ------------------------------------------------------------- Annotations useful for debugging. */ /* Request to trace every access to "address". */ #define _Py_ANNOTATE_TRACE_MEMORY(address) \ AnnotateTraceMemory(__FILE__, __LINE__, address) /* Report the current thread name to a race detector. */ #define _Py_ANNOTATE_THREAD_NAME(name) \ AnnotateThreadName(__FILE__, __LINE__, name) /* ------------------------------------------------------------- Annotations useful when implementing locks. They are not normally needed by modules that merely use locks. The "lock" argument is a pointer to the lock object. */ /* Report that a lock has been created at address "lock". */ #define _Py_ANNOTATE_RWLOCK_CREATE(lock) \ AnnotateRWLockCreate(__FILE__, __LINE__, lock) /* Report that the lock at address "lock" is about to be destroyed. */ #define _Py_ANNOTATE_RWLOCK_DESTROY(lock) \ AnnotateRWLockDestroy(__FILE__, __LINE__, lock) /* Report that the lock at address "lock" has been acquired. is_w=1 for writer lock, is_w=0 for reader lock. */ #define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \ AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w) /* Report that the lock at address "lock" is about to be released. */ #define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) \ AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w) /* ------------------------------------------------------------- Annotations useful when implementing barriers. They are not normally needed by modules that merely use barriers. The "barrier" argument is a pointer to the barrier object. */ /* Report that the "barrier" has been initialized with initial "count". If 'reinitialization_allowed' is true, initialization is allowed to happen multiple times w/o calling barrier_destroy() */ #define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) \ AnnotateBarrierInit(__FILE__, __LINE__, barrier, count, \ reinitialization_allowed) /* Report that we are about to enter barrier_wait("barrier"). */ #define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) \ AnnotateBarrierWaitBefore(__FILE__, __LINE__, barrier) /* Report that we just exited barrier_wait("barrier"). */ #define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) \ AnnotateBarrierWaitAfter(__FILE__, __LINE__, barrier) /* Report that the "barrier" has been destroyed. */ #define _Py_ANNOTATE_BARRIER_DESTROY(barrier) \ AnnotateBarrierDestroy(__FILE__, __LINE__, barrier) /* ------------------------------------------------------------- Annotations useful for testing race detectors. */ /* Report that we expect a race on the variable at "address". Use only in unit tests for a race detector. */ #define _Py_ANNOTATE_EXPECT_RACE(address, description) \ AnnotateExpectRace(__FILE__, __LINE__, address, description) /* A no-op. Insert where you like to test the interceptors. */ #define _Py_ANNOTATE_NO_OP(arg) \ AnnotateNoOp(__FILE__, __LINE__, arg) /* Force the race detector to flush its state. The actual effect depends on * the implementation of the detector. */ #define _Py_ANNOTATE_FLUSH_STATE() \ AnnotateFlushState(__FILE__, __LINE__) COSMOPOLITAN_C_START_ void AnnotateRWLockCreate(const char *file, int line, const volatile void *lock); void AnnotateRWLockDestroy(const char *file, int line, const volatile void *lock); void AnnotateRWLockAcquired(const char *file, int line, const volatile void *lock, long is_w); void AnnotateRWLockReleased(const char *file, int line, const volatile void *lock, long is_w); void AnnotateBarrierInit(const char *file, int line, const volatile void *barrier, long count, long reinitialization_allowed); void AnnotateBarrierWaitBefore(const char *file, int line, const volatile void *barrier); void AnnotateBarrierWaitAfter(const char *file, int line, const volatile void *barrier); void AnnotateBarrierDestroy(const char *file, int line, const volatile void *barrier); void AnnotateCondVarWait(const char *file, int line, const volatile void *cv, const volatile void *lock); void AnnotateCondVarSignal(const char *file, int line, const volatile void *cv); void AnnotateCondVarSignalAll(const char *file, int line, const volatile void *cv); void AnnotatePublishMemoryRange(const char *file, int line, const volatile void *address, long size); void AnnotateUnpublishMemoryRange(const char *file, int line, const volatile void *address, long size); void AnnotatePCQCreate(const char *file, int line, const volatile void *pcq); void AnnotatePCQDestroy(const char *file, int line, const volatile void *pcq); void AnnotatePCQPut(const char *file, int line, const volatile void *pcq); void AnnotatePCQGet(const char *file, int line, const volatile void *pcq); void AnnotateNewMemory(const char *file, int line, const volatile void *address, long size); void AnnotateExpectRace(const char *file, int line, const volatile void *address, const char *description); void AnnotateBenignRace(const char *file, int line, const volatile void *address, const char *description); void AnnotateBenignRaceSized(const char *file, int line, const volatile void *address, long size, const char *description); void AnnotateMutexIsUsedAsCondVar(const char *file, int line, const volatile void *mu); void AnnotateTraceMemory(const char *file, int line, const volatile void *arg); void AnnotateThreadName(const char *file, int line, const char *name); void AnnotateIgnoreReadsBegin(const char *file, int line); void AnnotateIgnoreReadsEnd(const char *file, int line); void AnnotateIgnoreWritesBegin(const char *file, int line); void AnnotateIgnoreWritesEnd(const char *file, int line); void AnnotateEnableRaceDetection(const char *file, int line, int enable); void AnnotateNoOp(const char *file, int line, const volatile void *arg); void AnnotateFlushState(const char *file, int line); /* Return non-zero value if running under valgrind. If "valgrind.h" is included into dynamic_annotations.c, the regular valgrind mechanism will be used. See http://valgrind.org/docs/manual/manual-core-adv.html about RUNNING_ON_VALGRIND and other valgrind "client requests". The file "valgrind.h" may be obtained by doing svn co svn://svn.valgrind.org/valgrind/trunk/include If for some reason you can't use "valgrind.h" or want to fake valgrind, there are two ways to make this function return non-zero: - Use environment variable: export RUNNING_ON_VALGRIND=1 - Make your tool intercept the function RunningOnValgrind() and change its return value. */ int RunningOnValgrind(void); COSMOPOLITAN_C_END_ #ifdef __cplusplus /* _Py_ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads. Instead of doing _Py_ANNOTATE_IGNORE_READS_BEGIN(); ... = x; _Py_ANNOTATE_IGNORE_READS_END(); one can use ... = _Py_ANNOTATE_UNPROTECTED_READ(x); */ template <class T> inline T _Py_ANNOTATE_UNPROTECTED_READ(const volatile T &x) { _Py_ANNOTATE_IGNORE_READS_BEGIN(); T res = x; _Py_ANNOTATE_IGNORE_READS_END(); return res; } /* Apply _Py_ANNOTATE_BENIGN_RACE_SIZED to a static variable. */ #define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \ namespace { \ class static_var ## _annotator { \ public: \ static_var ## _annotator() { \ _Py_ANNOTATE_BENIGN_RACE_SIZED(&static_var, \ sizeof(static_var), \ # static_var ": " description); \ } \ }; \ static static_var ## _annotator the ## static_var ## _annotator;\ } #endif /* __cplusplus */ #else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */ #define _Py_ANNOTATE_RWLOCK_CREATE(lock) #define _Py_ANNOTATE_RWLOCK_DESTROY(lock) #define _Py_ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) #define _Py_ANNOTATE_RWLOCK_RELEASED(lock, is_w) #define _Py_ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) /* */ #define _Py_ANNOTATE_BARRIER_WAIT_BEFORE(barrier) #define _Py_ANNOTATE_BARRIER_WAIT_AFTER(barrier) #define _Py_ANNOTATE_BARRIER_DESTROY(barrier) #define _Py_ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) #define _Py_ANNOTATE_CONDVAR_WAIT(cv) #define _Py_ANNOTATE_CONDVAR_SIGNAL(cv) #define _Py_ANNOTATE_CONDVAR_SIGNAL_ALL(cv) #define _Py_ANNOTATE_HAPPENS_BEFORE(obj) #define _Py_ANNOTATE_HAPPENS_AFTER(obj) #define _Py_ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) #define _Py_ANNOTATE_UNPUBLISH_MEMORY_RANGE(address, size) #define _Py_ANNOTATE_SWAP_MEMORY_RANGE(address, size) #define _Py_ANNOTATE_PCQ_CREATE(pcq) #define _Py_ANNOTATE_PCQ_DESTROY(pcq) #define _Py_ANNOTATE_PCQ_PUT(pcq) #define _Py_ANNOTATE_PCQ_GET(pcq) #define _Py_ANNOTATE_NEW_MEMORY(address, size) #define _Py_ANNOTATE_EXPECT_RACE(address, description) #define _Py_ANNOTATE_BENIGN_RACE(address, description) #define _Py_ANNOTATE_BENIGN_RACE_SIZED(address, size, description) #define _Py_ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) #define _Py_ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) #define _Py_ANNOTATE_TRACE_MEMORY(arg) #define _Py_ANNOTATE_THREAD_NAME(name) #define _Py_ANNOTATE_IGNORE_READS_BEGIN() #define _Py_ANNOTATE_IGNORE_READS_END() #define _Py_ANNOTATE_IGNORE_WRITES_BEGIN() #define _Py_ANNOTATE_IGNORE_WRITES_END() #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() #define _Py_ANNOTATE_IGNORE_READS_AND_WRITES_END() #define _Py_ANNOTATE_IGNORE_SYNC_BEGIN() #define _Py_ANNOTATE_IGNORE_SYNC_END() #define _Py_ANNOTATE_ENABLE_RACE_DETECTION(enable) #define _Py_ANNOTATE_NO_OP(arg) #define _Py_ANNOTATE_FLUSH_STATE() #define _Py_ANNOTATE_UNPROTECTED_READ(x) (x) #define _Py_ANNOTATE_BENIGN_RACE_STATIC(static_var, description) #endif /* DYNAMIC_ANNOTATIONS_ENABLED */ #endif /* __DYNAMIC_ANNOTATIONS_H__ */
21,772
486
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/warnings.h
#ifndef Py_WARNINGS_H #define Py_WARNINGS_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ #ifndef Py_LIMITED_API PyObject *_PyWarnings_Init(void); #endif int PyErr_WarnEx(PyObject *, const char *, Py_ssize_t); int PyErr_WarnFormat(PyObject *, Py_ssize_t, const char *, ...); #if !defined(Py_LIMITED_API) || Py_LIMITED_API + 0 >= 0x03060000 int PyErr_ResourceWarning(PyObject *, Py_ssize_t, const char *, ...); #endif #ifndef Py_LIMITED_API int PyErr_WarnExplicitObject(PyObject *, PyObject *, PyObject *, int, PyObject *, PyObject *); #endif int PyErr_WarnExplicit(PyObject *, const char *, const char *, int, const char *, PyObject *); #ifndef Py_LIMITED_API int PyErr_WarnExplicitFormat(PyObject *, const char *, int, const char *, PyObject *, const char *, ...); #endif #ifndef Py_LIMITED_API #define PyErr_Warn(category, msg) PyErr_WarnEx(category, msg, 1) #endif COSMOPOLITAN_C_END_ #endif /* !Py_WARNINGS_H */
1,028
36
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/intrcheck.h
#ifndef Py_INTRCHECK_H #define Py_INTRCHECK_H COSMOPOLITAN_C_START_ /* clang-format off */ int PyOS_InterruptOccurred(void); void PyOS_InitInterrupts(void); void PyOS_AfterFork(void); #ifndef Py_LIMITED_API int _PyOS_IsMainThread(void); #ifdef MS_WINDOWS /* windows.h is not included by Python.h so use void* instead of HANDLE */ void* _PyOS_SigintEvent(void); #endif #endif /* !Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_INTRCHECK_H */
450
21
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/floatobject.h
#ifndef Py_FLOATOBJECT_H #define Py_FLOATOBJECT_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/unicodeobject.h" COSMOPOLITAN_C_START_ /* clang-format off */ #ifndef Py_LIMITED_API typedef struct { PyObject_HEAD double ob_fval; } PyFloatObject; #endif extern PyTypeObject PyFloat_Type; #define PyFloat_Check(op) PyObject_TypeCheck(op, &PyFloat_Type) #define PyFloat_CheckExact(op) (Py_TYPE(op) == &PyFloat_Type) #ifdef Py_NAN #define Py_RETURN_NAN return PyFloat_FromDouble(Py_NAN) #endif #define Py_RETURN_INF(sign) do \ if (copysign(1., sign) == 1.) { \ return PyFloat_FromDouble(Py_HUGE_VAL); \ } else { \ return PyFloat_FromDouble(-Py_HUGE_VAL); \ } while(0) double PyFloat_GetMax(void); double PyFloat_GetMin(void); PyObject * PyFloat_GetInfo(void); /* Return Python float from string PyObject. */ PyObject * PyFloat_FromString(PyObject*); /* Return Python float from C double. */ PyObject * PyFloat_FromDouble(double); /* Extract C double from Python float. The macro version trades safety for speed. */ double PyFloat_AsDouble(PyObject *); #ifndef Py_LIMITED_API #define PyFloat_AS_DOUBLE(op) (((PyFloatObject *)(op))->ob_fval) #endif #ifndef Py_LIMITED_API /* _PyFloat_{Pack,Unpack}{4,8} * * The struct and pickle (at least) modules need an efficient platform- * independent way to store floating-point values as byte strings. * The Pack routines produce a string from a C double, and the Unpack * routines produce a C double from such a string. The suffix (4 or 8) * specifies the number of bytes in the string. * * On platforms that appear to use (see _PyFloat_Init()) IEEE-754 formats * these functions work by copying bits. On other platforms, the formats the * 4- byte format is identical to the IEEE-754 single precision format, and * the 8-byte format to the IEEE-754 double precision format, although the * packing of INFs and NaNs (if such things exist on the platform) isn't * handled correctly, and attempting to unpack a string containing an IEEE * INF or NaN will raise an exception. * * On non-IEEE platforms with more precision, or larger dynamic range, than * 754 supports, not all values can be packed; on non-IEEE platforms with less * precision, or smaller dynamic range, not all values can be unpacked. What * happens in such cases is partly accidental (alas). */ /* The pack routines write 2, 4 or 8 bytes, starting at p. le is a bool * argument, true if you want the string in little-endian format (exponent * last, at p+1, p+3 or p+7), false if you want big-endian format (exponent * first, at p). * Return value: 0 if all is OK, -1 if error (and an exception is * set, most likely OverflowError). * There are two problems on non-IEEE platforms: * 1): What this does is undefined if x is a NaN or infinity. * 2): -0.0 and +0.0 produce the same string. */ int _PyFloat_Pack2(double x, unsigned char *p, int le); int _PyFloat_Pack4(double x, unsigned char *p, int le); int _PyFloat_Pack8(double x, unsigned char *p, int le); /* Needed for the old way for marshal to store a floating point number. Returns the string length copied into p, -1 on error. */ int _PyFloat_Repr(double x, char *p, size_t len); /* Used to get the important decimal digits of a double */ int _PyFloat_Digits(char *buf, double v, int *signum); void _PyFloat_DigitsInit(void); /* The unpack routines read 2, 4 or 8 bytes, starting at p. le is a bool * argument, true if the string is in little-endian format (exponent * last, at p+1, p+3 or p+7), false if big-endian (exponent first, at p). * Return value: The unpacked double. On error, this is -1.0 and * PyErr_Occurred() is true (and an exception is set, most likely * OverflowError). Note that on a non-IEEE platform this will refuse * to unpack a string that represents a NaN or infinity. */ double _PyFloat_Unpack2(const unsigned char *p, int le); double _PyFloat_Unpack4(const unsigned char *p, int le); double _PyFloat_Unpack8(const unsigned char *p, int le); /* free list api */ int PyFloat_ClearFreeList(void); void _PyFloat_DebugMallocStats(FILE* out); /* Format the object based on the format_spec, as defined in PEP 3101 (Advanced String Formatting). */ int _PyFloat_FormatAdvancedWriter( _PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end); #endif /* Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_FLOATOBJECT_H */
4,565
123
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/unicodeobject.h
#ifndef Py_UNICODEOBJECT_H #define Py_UNICODEOBJECT_H #include "libc/assert.h" #include "third_party/python/Include/object.h" #include "third_party/python/pyconfig.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define Py_USING_UNICODE #ifndef SIZEOF_WCHAR_T #error Must define SIZEOF_WCHAR_T #endif #define Py_UNICODE_SIZE SIZEOF_WCHAR_T /* If wchar_t can be used for UCS-4 storage, set Py_UNICODE_WIDE. Otherwise, Unicode strings are stored as UCS-2 (with limited support for UTF-16) */ #if Py_UNICODE_SIZE >= 4 #define Py_UNICODE_WIDE #endif /* Set these flags if the platform has "wchar.h" and the wchar_t type is a 16-bit unsigned type */ /* #define HAVE_WCHAR_H */ /* #define HAVE_USABLE_WCHAR_T */ /* Py_UNICODE was the native Unicode storage format (code unit) used by Python and represents a single Unicode element in the Unicode type. With PEP 393, Py_UNICODE is deprecated and replaced with a typedef to wchar_t. */ #ifndef Py_LIMITED_API #define PY_UNICODE_TYPE wchar_t typedef wchar_t Py_UNICODE; #endif /* If the compiler provides a wchar_t type we try to support it through the interface functions PyUnicode_FromWideChar(), PyUnicode_AsWideChar() and PyUnicode_AsWideCharString(). */ #ifdef HAVE_USABLE_WCHAR_T # ifndef HAVE_WCHAR_H # define HAVE_WCHAR_H # endif #endif /* Py_UCS4 and Py_UCS2 are typedefs for the respective unicode representations. */ typedef uint32_t Py_UCS4; typedef uint16_t Py_UCS2; typedef uint8_t Py_UCS1; /* --- Internal Unicode Operations ---------------------------------------- */ /* Since splitting on whitespace is an important use case, and whitespace in most situations is solely ASCII whitespace, we optimize for the common case by using a quick look-up table _Py_ascii_whitespace (see below) with an inlined check. */ #ifndef Py_LIMITED_API #define Py_UNICODE_ISSPACE(ch) \ ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch)) #define Py_UNICODE_ISLOWER(ch) _PyUnicode_IsLowercase(ch) #define Py_UNICODE_ISUPPER(ch) _PyUnicode_IsUppercase(ch) #define Py_UNICODE_ISTITLE(ch) _PyUnicode_IsTitlecase(ch) #define Py_UNICODE_ISLINEBREAK(ch) _PyUnicode_IsLinebreak(ch) #define Py_UNICODE_TOLOWER(ch) _PyUnicode_ToLowercase(ch) #define Py_UNICODE_TOUPPER(ch) _PyUnicode_ToUppercase(ch) #define Py_UNICODE_TOTITLE(ch) _PyUnicode_ToTitlecase(ch) #define Py_UNICODE_ISDECIMAL(ch) _PyUnicode_IsDecimalDigit(ch) #define Py_UNICODE_ISDIGIT(ch) _PyUnicode_IsDigit(ch) #define Py_UNICODE_ISNUMERIC(ch) _PyUnicode_IsNumeric(ch) #define Py_UNICODE_ISPRINTABLE(ch) _PyUnicode_IsPrintable(ch) #define Py_UNICODE_TODECIMAL(ch) _PyUnicode_ToDecimalDigit(ch) #define Py_UNICODE_TODIGIT(ch) _PyUnicode_ToDigit(ch) #define Py_UNICODE_TONUMERIC(ch) _PyUnicode_ToNumeric(ch) #define Py_UNICODE_ISALPHA(ch) _PyUnicode_IsAlpha(ch) #define Py_UNICODE_ISALNUM(ch) \ (Py_UNICODE_ISALPHA(ch) || \ Py_UNICODE_ISDECIMAL(ch) || \ Py_UNICODE_ISDIGIT(ch) || \ Py_UNICODE_ISNUMERIC(ch)) #define Py_UNICODE_COPY(target, source, length) \ memcpy((target), (source), (length)*sizeof(Py_UNICODE)) #define Py_UNICODE_FILL(target, value, length) \ do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\ for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\ } while (0) /* macros to work with surrogates */ #define Py_UNICODE_IS_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDFFF) #define Py_UNICODE_IS_HIGH_SURROGATE(ch) (0xD800 <= (ch) && (ch) <= 0xDBFF) #define Py_UNICODE_IS_LOW_SURROGATE(ch) (0xDC00 <= (ch) && (ch) <= 0xDFFF) /* Join two surrogate characters and return a single Py_UCS4 value. */ #define Py_UNICODE_JOIN_SURROGATES(high, low) \ (((((Py_UCS4)(high) & 0x03FF) << 10) | \ ((Py_UCS4)(low) & 0x03FF)) + 0x10000) /* high surrogate = top 10 bits added to D800 */ #define Py_UNICODE_HIGH_SURROGATE(ch) (0xD800 - (0x10000 >> 10) + ((ch) >> 10)) /* low surrogate = bottom 10 bits added to DC00 */ #define Py_UNICODE_LOW_SURROGATE(ch) (0xDC00 + ((ch) & 0x3FF)) /* Check if substring matches at given offset. The offset must be valid, and the substring must not be empty. */ #define Py_UNICODE_MATCH(string, offset, substring) \ ((*((string)->wstr + (offset)) == *((substring)->wstr)) && \ ((*((string)->wstr + (offset) + (substring)->wstr_length-1) == *((substring)->wstr + (substring)->wstr_length-1))) && \ !bcmp((string)->wstr + (offset), (substring)->wstr, (substring)->wstr_length*sizeof(Py_UNICODE))) #endif /* Py_LIMITED_API */ /* --- Unicode Type ------------------------------------------------------- */ #ifndef Py_LIMITED_API /* ASCII-only strings created through PyUnicode_New use the PyASCIIObject structure. state.ascii and state.compact are set, and the data immediately follow the structure. utf8_length and wstr_length can be found in the length field; the utf8 pointer is equal to the data pointer. */ typedef struct { PyObject_HEAD Py_ssize_t length; /* Number of code points in the string */ Py_hash_t hash; /* Hash value; -1 if not set */ struct { /* SSTATE_NOT_INTERNED (0) SSTATE_INTERNED_MORTAL (1) SSTATE_INTERNED_IMMORTAL (2) If interned != SSTATE_NOT_INTERNED, the two references from the dictionary to this object are *not* counted in ob_refcnt. */ unsigned int interned:2; /* Character size: - PyUnicode_WCHAR_KIND (0): * character type = wchar_t (16 or 32 bits, depending on the platform) - PyUnicode_1BYTE_KIND (1): * character type = Py_UCS1 (8 bits, unsigned) * all characters are in the range U+0000-U+00FF (latin1) * if ascii is set, all characters are in the range U+0000-U+007F (ASCII), otherwise at least one character is in the range U+0080-U+00FF - PyUnicode_2BYTE_KIND (2): * character type = Py_UCS2 (16 bits, unsigned) * all characters are in the range U+0000-U+FFFF (BMP) * at least one character is in the range U+0100-U+FFFF - PyUnicode_4BYTE_KIND (4): * character type = Py_UCS4 (32 bits, unsigned) * all characters are in the range U+0000-U+10FFFF * at least one character is in the range U+10000-U+10FFFF */ unsigned int kind:3; /* Compact is with respect to the allocation scheme. Compact unicode objects only require one memory block while non-compact objects use one block for the PyUnicodeObject struct and another for its data buffer. */ unsigned int compact:1; /* The string only contains characters in the range U+0000-U+007F (ASCII) and the kind is PyUnicode_1BYTE_KIND. If ascii is set and compact is set, use the PyASCIIObject structure. */ unsigned int ascii:1; /* The ready flag indicates whether the object layout is initialized completely. This means that this is either a compact object, or the data pointer is filled out. The bit is redundant, and helps to minimize the test in PyUnicode_IS_READY(). */ unsigned int ready:1; /* Padding to ensure that PyUnicode_DATA() is always aligned to 4 bytes (see issue #19537 on m68k). */ unsigned int :24; } state; wchar_t *wstr; /* wchar_t representation (null-terminated) */ } PyASCIIObject; /* Non-ASCII strings allocated through PyUnicode_New use the PyCompactUnicodeObject structure. state.compact is set, and the data immediately follow the structure. */ typedef struct { PyASCIIObject _base; Py_ssize_t utf8_length; /* Number of bytes in utf8, excluding the * terminating \0. */ char *utf8; /* UTF-8 representation (null-terminated) */ Py_ssize_t wstr_length; /* Number of code points in wstr, possible * surrogates count as two code points. */ } PyCompactUnicodeObject; /* Strings allocated through PyUnicode_FromUnicode(NULL, len) use the PyUnicodeObject structure. The actual string data is initially in the wstr block, and copied into the data block using _PyUnicode_Ready. */ typedef struct { PyCompactUnicodeObject _base; union { void *any; Py_UCS1 *latin1; Py_UCS2 *ucs2; Py_UCS4 *ucs4; } data; /* Canonical, smallest-form Unicode buffer */ } PyUnicodeObject; #endif extern PyTypeObject PyUnicode_Type; extern PyTypeObject PyUnicodeIter_Type; #define PyUnicode_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_UNICODE_SUBCLASS) #define PyUnicode_CheckExact(op) (Py_TYPE(op) == &PyUnicode_Type) /* Fast access macros */ #ifndef Py_LIMITED_API #define PyUnicode_WSTR_LENGTH(op) \ (PyUnicode_IS_COMPACT_ASCII(op) ? \ ((PyASCIIObject*)op)->length : \ ((PyCompactUnicodeObject*)op)->wstr_length) /* Returns the deprecated Py_UNICODE representation's size in code units (this includes surrogate pairs as 2 units). If the Py_UNICODE representation is not available, it will be computed on request. Use PyUnicode_GET_LENGTH() for the length in code points. */ #define PyUnicode_GET_SIZE(op) \ (assert(PyUnicode_Check(op)), \ (((PyASCIIObject *)(op))->wstr) ? \ PyUnicode_WSTR_LENGTH(op) : \ ((void)PyUnicode_AsUnicode((PyObject *)(op)), \ assert(((PyASCIIObject *)(op))->wstr), \ PyUnicode_WSTR_LENGTH(op))) #define PyUnicode_GET_DATA_SIZE(op) \ (PyUnicode_GET_SIZE(op) * Py_UNICODE_SIZE) /* Alias for PyUnicode_AsUnicode(). This will create a wchar_t/Py_UNICODE representation on demand. Using this macro is very inefficient now, try to port your code to use the new PyUnicode_*BYTE_DATA() macros or use PyUnicode_WRITE() and PyUnicode_READ(). */ #define PyUnicode_AS_UNICODE(op) \ (assert(PyUnicode_Check(op)), \ (((PyASCIIObject *)(op))->wstr) ? (((PyASCIIObject *)(op))->wstr) : \ PyUnicode_AsUnicode((PyObject *)(op))) #define PyUnicode_AS_DATA(op) \ ((const char *)(PyUnicode_AS_UNICODE(op))) /* --- Flexible String Representation Helper Macros (PEP 393) -------------- */ /* Values for PyASCIIObject.state: */ /* Interning state. */ #define SSTATE_NOT_INTERNED 0 #define SSTATE_INTERNED_MORTAL 1 #define SSTATE_INTERNED_IMMORTAL 2 /* Return true if the string contains only ASCII characters, or 0 if not. The string may be compact (PyUnicode_IS_COMPACT_ASCII) or not, but must be ready. */ #define PyUnicode_IS_ASCII(op) \ (assert(PyUnicode_Check(op)), \ assert(PyUnicode_IS_READY(op)), \ ((PyASCIIObject*)op)->state.ascii) /* Return true if the string is compact or 0 if not. No type checks or Ready calls are performed. */ #define PyUnicode_IS_COMPACT(op) \ (((PyASCIIObject*)(op))->state.compact) /* Return true if the string is a compact ASCII string (use PyASCIIObject structure), or 0 if not. No type checks or Ready calls are performed. */ #define PyUnicode_IS_COMPACT_ASCII(op) \ (((PyASCIIObject*)op)->state.ascii && PyUnicode_IS_COMPACT(op)) enum PyUnicode_Kind { /* String contains only wstr byte characters. This is only possible when the string was created with a legacy API and _PyUnicode_Ready() has not been called yet. */ PyUnicode_WCHAR_KIND = 0, /* Return values of the PyUnicode_KIND() macro: */ PyUnicode_1BYTE_KIND = 1, PyUnicode_2BYTE_KIND = 2, PyUnicode_4BYTE_KIND = 4 }; /* Return pointers to the canonical representation cast to unsigned char, Py_UCS2, or Py_UCS4 for direct character access. No checks are performed, use PyUnicode_KIND() before to ensure these will work correctly. */ #define PyUnicode_1BYTE_DATA(op) ((Py_UCS1*)PyUnicode_DATA(op)) #define PyUnicode_2BYTE_DATA(op) ((Py_UCS2*)PyUnicode_DATA(op)) #define PyUnicode_4BYTE_DATA(op) ((Py_UCS4*)PyUnicode_DATA(op)) /* Return one of the PyUnicode_*_KIND values defined above. */ #define PyUnicode_KIND(op) \ (assert(PyUnicode_Check(op)), \ assert(PyUnicode_IS_READY(op)), \ ((PyASCIIObject *)(op))->state.kind) /* Return a void pointer to the raw unicode buffer. */ #define _PyUnicode_COMPACT_DATA(op) \ (PyUnicode_IS_ASCII(op) ? \ ((void*)((PyASCIIObject*)(op) + 1)) : \ ((void*)((PyCompactUnicodeObject*)(op) + 1))) #define _PyUnicode_NONCOMPACT_DATA(op) \ (assert(((PyUnicodeObject*)(op))->data.any), \ ((((PyUnicodeObject *)(op))->data.any))) #define PyUnicode_DATA(op) \ (assert(PyUnicode_Check(op)), \ PyUnicode_IS_COMPACT(op) ? _PyUnicode_COMPACT_DATA(op) : \ _PyUnicode_NONCOMPACT_DATA(op)) /* In the access macros below, "kind" may be evaluated more than once. All other macro parameters are evaluated exactly once, so it is safe to put side effects into them (such as increasing the index). */ /* Write into the canonical representation, this macro does not do any sanity checks and is intended for usage in loops. The caller should cache the kind and data pointers obtained from other macro calls. index is the index in the string (starts at 0) and value is the new code point value which should be written to that location. */ #define PyUnicode_WRITE(kind, data, index, value) \ do { \ switch ((kind)) { \ case PyUnicode_1BYTE_KIND: { \ ((Py_UCS1 *)(data))[(index)] = (Py_UCS1)(value); \ break; \ } \ case PyUnicode_2BYTE_KIND: { \ ((Py_UCS2 *)(data))[(index)] = (Py_UCS2)(value); \ break; \ } \ default: { \ assert((kind) == PyUnicode_4BYTE_KIND); \ ((Py_UCS4 *)(data))[(index)] = (Py_UCS4)(value); \ } \ } \ } while (0) /* Read a code point from the string's canonical representation. No checks or ready calls are performed. */ #define PyUnicode_READ(kind, data, index) \ ((Py_UCS4) \ ((kind) == PyUnicode_1BYTE_KIND ? \ ((const Py_UCS1 *)(data))[(index)] : \ ((kind) == PyUnicode_2BYTE_KIND ? \ ((const Py_UCS2 *)(data))[(index)] : \ ((const Py_UCS4 *)(data))[(index)] \ ) \ )) /* PyUnicode_READ_CHAR() is less efficient than PyUnicode_READ() because it calls PyUnicode_KIND() and might call it twice. For single reads, use PyUnicode_READ_CHAR, for multiple consecutive reads callers should cache kind and use PyUnicode_READ instead. */ #define PyUnicode_READ_CHAR(unicode, index) \ (assert(PyUnicode_Check(unicode)), \ assert(PyUnicode_IS_READY(unicode)), \ (Py_UCS4) \ (PyUnicode_KIND((unicode)) == PyUnicode_1BYTE_KIND ? \ ((const Py_UCS1 *)(PyUnicode_DATA((unicode))))[(index)] : \ (PyUnicode_KIND((unicode)) == PyUnicode_2BYTE_KIND ? \ ((const Py_UCS2 *)(PyUnicode_DATA((unicode))))[(index)] : \ ((const Py_UCS4 *)(PyUnicode_DATA((unicode))))[(index)] \ ) \ )) /* Returns the length of the unicode string. The caller has to make sure that the string has it's canonical representation set before calling this macro. Call PyUnicode_(FAST_)Ready to ensure that. */ #define PyUnicode_GET_LENGTH(op) \ (assert(PyUnicode_Check(op)), \ assert(PyUnicode_IS_READY(op)), \ ((PyASCIIObject *)(op))->length) /* Fast check to determine whether an object is ready. Equivalent to PyUnicode_IS_COMPACT(op) || ((PyUnicodeObject*)(op))->data.any) */ #define PyUnicode_IS_READY(op) (((PyASCIIObject*)op)->state.ready) /* PyUnicode_READY() does less work than _PyUnicode_Ready() in the best case. If the canonical representation is not yet set, it will still call _PyUnicode_Ready(). Returns 0 on success and -1 on errors. */ #define PyUnicode_READY(op) \ (assert(PyUnicode_Check(op)), \ (PyUnicode_IS_READY(op) ? \ 0 : _PyUnicode_Ready((PyObject *)(op)))) /* Return a maximum character value which is suitable for creating another string based on op. This is always an approximation but more efficient than iterating over the string. */ #define PyUnicode_MAX_CHAR_VALUE(op) \ (assert(PyUnicode_IS_READY(op)), \ (PyUnicode_IS_ASCII(op) ? \ (0x7f) : \ (PyUnicode_KIND(op) == PyUnicode_1BYTE_KIND ? \ (0xffU) : \ (PyUnicode_KIND(op) == PyUnicode_2BYTE_KIND ? \ (0xffffU) : \ (0x10ffffU))))) #endif /* --- Constants ---------------------------------------------------------- */ /* This Unicode character will be used as replacement character during decoding if the errors argument is set to "replace". Note: the Unicode character U+FFFD is the official REPLACEMENT CHARACTER in Unicode 3.0. */ #define Py_UNICODE_REPLACEMENT_CHARACTER ((Py_UCS4) 0xFFFD) /* === Public API ========================================================= */ /* --- Plain Py_UNICODE --------------------------------------------------- */ /* With PEP 393, this is the recommended way to allocate a new unicode object. This function will allocate the object and its buffer in a single memory block. Objects created using this function are not resizable. */ #ifndef Py_LIMITED_API PyObject* PyUnicode_New( Py_ssize_t size, /* Number of code points in the new string */ Py_UCS4 maxchar /* maximum code point value in the string */ ); #endif /* Initializes the canonical string representation from the deprecated wstr/Py_UNICODE representation. This function is used to convert Unicode objects which were created using the old API to the new flexible format introduced with PEP 393. Don't call this function directly, use the public PyUnicode_READY() macro instead. */ #ifndef Py_LIMITED_API int _PyUnicode_Ready( PyObject *unicode /* Unicode object */ ); #endif /* Get a copy of a Unicode string. */ #ifndef Py_LIMITED_API PyObject* _PyUnicode_Copy( PyObject *unicode ); #endif /* Copy character from one unicode object into another, this function performs character conversion when necessary and falls back to memcpy() if possible. Fail if to is too small (smaller than *how_many* or smaller than len(from)-from_start), or if kind(from[from_start:from_start+how_many]) > kind(to), or if *to* has more than 1 reference. Return the number of written character, or return -1 and raise an exception on error. Pseudo-code: how_many = min(how_many, len(from) - from_start) to[to_start:to_start+how_many] = from[from_start:from_start+how_many] return how_many Note: The function doesn't write a terminating null character. */ #ifndef Py_LIMITED_API Py_ssize_t PyUnicode_CopyCharacters( PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many ); /* Unsafe version of PyUnicode_CopyCharacters(): don't check arguments and so may crash if parameters are invalid (e.g. if the output string is too short). */ void _PyUnicode_FastCopyCharacters( PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many ); #endif #ifndef Py_LIMITED_API /* Fill a string with a character: write fill_char into unicode[start:start+length]. Fail if fill_char is bigger than the string maximum character, or if the string has more than 1 reference. Return the number of written character, or return -1 and raise an exception on error. */ Py_ssize_t PyUnicode_Fill( PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char ); /* Unsafe version of PyUnicode_Fill(): don't check arguments and so may crash if parameters are invalid (e.g. if length is longer than the string). */ void _PyUnicode_FastFill( PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char ); #endif /* Create a Unicode Object from the Py_UNICODE buffer u of the given size. u may be NULL which causes the contents to be undefined. It is the user's responsibility to fill in the needed data afterwards. Note that modifying the Unicode object contents after construction is only allowed if u was set to NULL. The buffer is copied into the new object. */ #ifndef Py_LIMITED_API PyObject* PyUnicode_FromUnicode( const Py_UNICODE *u, /* Unicode buffer */ Py_ssize_t size /* size of buffer */ ); #endif /* Similar to PyUnicode_FromUnicode(), but u points to UTF-8 encoded bytes */ PyObject* PyUnicode_FromStringAndSize( const char *u, /* UTF-8 encoded string */ Py_ssize_t size /* size of buffer */ ); /* Similar to PyUnicode_FromUnicode(), but u points to null-terminated UTF-8 encoded bytes. The size is determined with strlen(). */ PyObject* PyUnicode_FromString( const char *u /* UTF-8 encoded string */ ); #ifndef Py_LIMITED_API /* Create a new string from a buffer of Py_UCS1, Py_UCS2 or Py_UCS4 characters. Scan the string to find the maximum character. */ PyObject* PyUnicode_FromKindAndData( int kind, const void *buffer, Py_ssize_t size); /* Create a new string from a buffer of ASCII characters. WARNING: Don't check if the string contains any non-ASCII character. */ PyObject* _PyUnicode_FromASCII( const char *buffer, Py_ssize_t size); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject* PyUnicode_Substring( PyObject *str, Py_ssize_t start, Py_ssize_t end); #endif #ifndef Py_LIMITED_API /* Compute the maximum character of the substring unicode[start:end]. Return 127 for an empty string. */ Py_UCS4 _PyUnicode_FindMaxChar ( PyObject *unicode, Py_ssize_t start, Py_ssize_t end); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Copy the string into a UCS4 buffer including the null character if copy_null is set. Return NULL and raise an exception on error. Raise a SystemError if the buffer is smaller than the string. Return buffer on success. buflen is the length of the buffer in (Py_UCS4) characters. */ Py_UCS4* PyUnicode_AsUCS4( PyObject *unicode, Py_UCS4* buffer, Py_ssize_t buflen, int copy_null); /* Copy the string into a UCS4 buffer. A new buffer is allocated using * PyMem_Malloc; if this fails, NULL is returned with a memory error exception set. */ Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *unicode); #endif #ifndef Py_LIMITED_API /* Return a read-only pointer to the Unicode object's internal Py_UNICODE buffer. If the wchar_t/Py_UNICODE representation is not yet available, this function will calculate it. */ Py_UNICODE * PyUnicode_AsUnicode( PyObject *unicode /* Unicode object */ ); /* Similar to PyUnicode_AsUnicode(), but raises a ValueError if the string contains null characters. */ const Py_UNICODE * _PyUnicode_AsUnicode( PyObject *unicode /* Unicode object */ ); /* Return a read-only pointer to the Unicode object's internal Py_UNICODE buffer and save the length at size. If the wchar_t/Py_UNICODE representation is not yet available, this function will calculate it. */ Py_UNICODE * PyUnicode_AsUnicodeAndSize( PyObject *unicode, /* Unicode object */ Py_ssize_t *size /* location where to save the length */ ); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Get the length of the Unicode object. */ Py_ssize_t PyUnicode_GetLength( PyObject *unicode ); #endif /* Get the number of Py_UNICODE units in the string representation. */ Py_ssize_t PyUnicode_GetSize( PyObject *unicode /* Unicode object */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Read a character from the string. */ Py_UCS4 PyUnicode_ReadChar( PyObject *unicode, Py_ssize_t index ); /* Write a character to the string. The string must have been created through PyUnicode_New, must not be shared, and must not have been hashed yet. Return 0 on success, -1 on error. */ int PyUnicode_WriteChar( PyObject *unicode, Py_ssize_t index, Py_UCS4 character ); #endif #ifndef Py_LIMITED_API /* Get the maximum ordinal for a Unicode character. */ Py_UNICODE PyUnicode_GetMax(void); #endif /* Resize a Unicode object. The length is the number of characters, except if the kind of the string is PyUnicode_WCHAR_KIND: in this case, the length is the number of Py_UNICODE characters. *unicode is modified to point to the new (resized) object and 0 returned on success. Try to resize the string in place (which is usually faster than allocating a new string and copy characters), or create a new string. Error handling is implemented as follows: an exception is set, -1 is returned and *unicode left untouched. WARNING: The function doesn't check string content, the result may not be a string in canonical representation. */ int PyUnicode_Resize( PyObject **unicode, /* Pointer to the Unicode object */ Py_ssize_t length /* New length */ ); /* Decode obj to a Unicode object. bytes, bytearray and other bytes-like objects are decoded according to the given encoding and error handler. The encoding and error handler can be NULL to have the interface use UTF-8 and "strict". All other objects (including Unicode objects) raise an exception. The API returns NULL in case of an error. The caller is responsible for decref'ing the returned objects. */ PyObject* PyUnicode_FromEncodedObject( PyObject *obj, /* Object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Copy an instance of a Unicode subtype to a new true Unicode object if necessary. If obj is already a true Unicode object (not a subtype), return the reference with *incremented* refcount. The API returns NULL in case of an error. The caller is responsible for decref'ing the returned objects. */ PyObject* PyUnicode_FromObject( PyObject *obj /* Object */ ); PyObject * PyUnicode_FromFormatV( const char *format, /* ASCII-encoded string */ va_list vargs ); PyObject * PyUnicode_FromFormat( const char *format, /* ASCII-encoded string */ ... ); #ifndef Py_LIMITED_API typedef struct { PyObject *buffer; void *data; enum PyUnicode_Kind kind; Py_UCS4 maxchar; Py_ssize_t size; Py_ssize_t pos; /* minimum number of allocated characters (default: 0) */ Py_ssize_t min_length; /* minimum character (default: 127, ASCII) */ Py_UCS4 min_char; /* If non-zero, overallocate the buffer (default: 0). */ unsigned char overallocate; /* If readonly is 1, buffer is a shared string (cannot be modified) and size is set to 0. */ unsigned char readonly; } _PyUnicodeWriter ; /* Initialize a Unicode writer. * * By default, the minimum buffer size is 0 character and overallocation is * disabled. Set min_length, min_char and overallocate attributes to control * the allocation of the buffer. */ void _PyUnicodeWriter_Init(_PyUnicodeWriter *writer); /* Prepare the buffer to write 'length' characters with the specified maximum character. Return 0 on success, raise an exception and return -1 on error. */ #define _PyUnicodeWriter_Prepare(WRITER, LENGTH, MAXCHAR) \ (((MAXCHAR) <= (WRITER)->maxchar \ && (LENGTH) <= (WRITER)->size - (WRITER)->pos) \ ? 0 \ : (((LENGTH) == 0) \ ? 0 \ : _PyUnicodeWriter_PrepareInternal((WRITER), (LENGTH), (MAXCHAR)))) /* Don't call this function directly, use the _PyUnicodeWriter_Prepare() macro instead. */ int _PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer, Py_ssize_t length, Py_UCS4 maxchar); /* Prepare the buffer to have at least the kind KIND. For example, kind=PyUnicode_2BYTE_KIND ensures that the writer will support characters in range U+000-U+FFFF. Return 0 on success, raise an exception and return -1 on error. */ #define _PyUnicodeWriter_PrepareKind(WRITER, KIND) \ (assert((KIND) != PyUnicode_WCHAR_KIND), \ (KIND) <= (WRITER)->kind \ ? 0 \ : _PyUnicodeWriter_PrepareKindInternal((WRITER), (KIND))) /* Don't call this function directly, use the _PyUnicodeWriter_PrepareKind() macro instead. */ int _PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer, enum PyUnicode_Kind kind); /* Append a Unicode character. Return 0 on success, raise an exception and return -1 on error. */ int _PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch ); /* Append a Unicode string. Return 0 on success, raise an exception and return -1 on error. */ int _PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str /* Unicode string */ ); /* Append a substring of a Unicode string. Return 0 on success, raise an exception and return -1 on error. */ int _PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str, /* Unicode string */ Py_ssize_t start, Py_ssize_t end ); /* Append an ASCII-encoded byte string. Return 0 on success, raise an exception and return -1 on error. */ int _PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer, const char *str, /* ASCII-encoded byte string */ Py_ssize_t len /* number of bytes, or -1 if unknown */ ); /* Append a latin1-encoded byte string. Return 0 on success, raise an exception and return -1 on error. */ int _PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer, const char *str, /* latin1-encoded byte string */ Py_ssize_t len /* length in bytes */ ); /* Get the value of the writer as a Unicode string. Clear the buffer of the writer. Raise an exception and return NULL on error. */ PyObject * _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer); /* Deallocate memory of a writer (clear its internal buffer). */ void _PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer); #endif #ifndef Py_LIMITED_API /* Format the object based on the format_spec, as defined in PEP 3101 (Advanced String Formatting). */ int _PyUnicode_FormatAdvancedWriter( _PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end); #endif void PyUnicode_InternInPlace(PyObject **); void PyUnicode_InternImmortal(PyObject **); PyObject * PyUnicode_InternFromString( const char *u /* UTF-8 encoded string */ ); #ifndef Py_LIMITED_API void _Py_ReleaseInternedUnicodeStrings(void); #endif /* Use only if you know it's a string */ #define PyUnicode_CHECK_INTERNED(op) \ (((PyASCIIObject *)(op))->state.interned) /* --- wchar_t support for platforms which support it --------------------- */ #ifdef HAVE_WCHAR_H /* Create a Unicode Object from the wchar_t buffer w of the given size. The buffer is copied into the new object. */ PyObject* PyUnicode_FromWideChar( const wchar_t *w, /* wchar_t buffer */ Py_ssize_t size /* size of buffer */ ); /* Copies the Unicode Object contents into the wchar_t buffer w. At most size wchar_t characters are copied. Note that the resulting wchar_t string may or may not be 0-terminated. It is the responsibility of the caller to make sure that the wchar_t string is 0-terminated in case this is required by the application. Returns the number of wchar_t characters copied (excluding a possibly trailing 0-termination character) or -1 in case of an error. */ Py_ssize_t PyUnicode_AsWideChar( PyObject *unicode, /* Unicode object */ wchar_t *w, /* wchar_t buffer */ Py_ssize_t size /* size of buffer */ ); /* Convert the Unicode object to a wide character string. The output string always ends with a nul character. If size is not NULL, write the number of wide characters (excluding the null character) into *size. Returns a buffer allocated by PyMem_Malloc() (use PyMem_Free() to free it) on success. On error, returns NULL, *size is undefined and raises a MemoryError. */ wchar_t* PyUnicode_AsWideCharString( PyObject *unicode, /* Unicode object */ Py_ssize_t *size /* number of characters of the result */ ); #ifndef Py_LIMITED_API /* Similar to PyUnicode_AsWideCharString(unicode, NULL), but check if the string contains null characters. */ wchar_t* _PyUnicode_AsWideCharString( PyObject *unicode /* Unicode object */ ); void* _PyUnicode_AsKind(PyObject *s, unsigned int kind); #endif #endif /* --- Unicode ordinals --------------------------------------------------- */ /* Create a Unicode Object from the given Unicode code point ordinal. The ordinal must be in range(0x110000). A ValueError is raised in case it is not. */ PyObject* PyUnicode_FromOrdinal(int ordinal); /* --- Free-list management ----------------------------------------------- */ /* Clear the free list used by the Unicode implementation. This can be used to release memory used for objects on the free list back to the Python memory allocator. */ int PyUnicode_ClearFreeList(void); /* === Builtin Codecs ===================================================== Many of these APIs take two arguments encoding and errors. These parameters encoding and errors have the same semantics as the ones of the builtin str() API. Setting encoding to NULL causes the default encoding (UTF-8) to be used. Error handling is set by errors which may also be set to NULL meaning to use the default handling defined for the codec. Default error handling for all builtin codecs is "strict" (ValueErrors are raised). The codecs all use a similar interface. Only deviation from the generic ones are documented. */ /* --- Manage the default encoding ---------------------------------------- */ /* Returns a pointer to the default encoding (UTF-8) of the Unicode object unicode and the size of the encoded representation in bytes stored in *size. In case of an error, no *size is set. This function caches the UTF-8 encoded string in the unicodeobject and subsequent calls will return the same string. The memory is released when the unicodeobject is deallocated. _PyUnicode_AsStringAndSize is a #define for PyUnicode_AsUTF8AndSize to support the previous internal function with the same behaviour. *** This API is for interpreter INTERNAL USE ONLY and will likely *** be removed or changed in the future. *** If you need to access the Unicode object as UTF-8 bytes string, *** please use PyUnicode_AsUTF8String() instead. */ #ifndef Py_LIMITED_API char * PyUnicode_AsUTF8AndSize( PyObject *unicode, Py_ssize_t *size); #define _PyUnicode_AsStringAndSize PyUnicode_AsUTF8AndSize #endif /* Returns a pointer to the default encoding (UTF-8) of the Unicode object unicode. Like PyUnicode_AsUTF8AndSize(), this also caches the UTF-8 representation in the unicodeobject. _PyUnicode_AsString is a #define for PyUnicode_AsUTF8 to support the previous internal function with the same behaviour. Use of this API is DEPRECATED since no size information can be extracted from the returned data. *** This API is for interpreter INTERNAL USE ONLY and will likely *** be removed or changed for Python 3.1. *** If you need to access the Unicode object as UTF-8 bytes string, *** please use PyUnicode_AsUTF8String() instead. */ #ifndef Py_LIMITED_API char * PyUnicode_AsUTF8(PyObject *unicode); #define _PyUnicode_AsString PyUnicode_AsUTF8 #endif /* Returns "utf-8". */ const char* PyUnicode_GetDefaultEncoding(void); /* --- Generic Codecs ----------------------------------------------------- */ /* Create a Unicode object by decoding the encoded string s of the given size. */ PyObject* PyUnicode_Decode( const char *s, /* encoded string */ Py_ssize_t size, /* size of buffer */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Decode a Unicode object unicode and return the result as Python object. This API is DEPRECATED. The only supported standard encoding is rot13. Use PyCodec_Decode() to decode with rot13 and non-standard codecs that decode from str. */ PyObject* PyUnicode_AsDecodedObject( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ) Py_DEPRECATED(3.6); /* Decode a Unicode object unicode and return the result as Unicode object. This API is DEPRECATED. The only supported standard encoding is rot13. Use PyCodec_Decode() to decode with rot13 and non-standard codecs that decode from str to str. */ PyObject* PyUnicode_AsDecodedUnicode( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ) Py_DEPRECATED(3.6); /* Encodes a Py_UNICODE buffer of the given size and returns a Python string object. */ #ifndef Py_LIMITED_API PyObject* PyUnicode_Encode( const Py_UNICODE *s, /* Unicode char buffer */ Py_ssize_t size, /* number of Py_UNICODE chars to encode */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); #endif /* Encodes a Unicode object and returns the result as Python object. This API is DEPRECATED. It is superceeded by PyUnicode_AsEncodedString() since all standard encodings (except rot13) encode str to bytes. Use PyCodec_Encode() for encoding with rot13 and non-standard codecs that encode form str to non-bytes. */ PyObject* PyUnicode_AsEncodedObject( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ) Py_DEPRECATED(3.6); /* Encodes a Unicode object and returns the result as Python string object. */ PyObject* PyUnicode_AsEncodedString( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ); /* Encodes a Unicode object and returns the result as Unicode object. This API is DEPRECATED. The only supported standard encodings is rot13. Use PyCodec_Encode() to encode with rot13 and non-standard codecs that encode from str to str. */ PyObject* PyUnicode_AsEncodedUnicode( PyObject *unicode, /* Unicode object */ const char *encoding, /* encoding */ const char *errors /* error handling */ ) Py_DEPRECATED(3.6); /* Build an encoding map. */ PyObject* PyUnicode_BuildEncodingMap( PyObject* string /* 256 character map */ ); /* --- UTF-7 Codecs ------------------------------------------------------- */ PyObject* PyUnicode_DecodeUTF7( const char *string, /* UTF-7 encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyObject* PyUnicode_DecodeUTF7Stateful( const char *string, /* UTF-7 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ Py_ssize_t *consumed /* bytes consumed */ ); #ifndef Py_LIMITED_API PyObject* PyUnicode_EncodeUTF7( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ int base64SetO, /* Encode RFC2152 Set O characters in base64 */ int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ const char *errors /* error handling */ ); PyObject* _PyUnicode_EncodeUTF7( PyObject *unicode, /* Unicode object */ int base64SetO, /* Encode RFC2152 Set O characters in base64 */ int base64WhiteSpace, /* Encode whitespace (sp, ht, nl, cr) in base64 */ const char *errors /* error handling */ ); #endif /* --- UTF-8 Codecs ------------------------------------------------------- */ PyObject* PyUnicode_DecodeUTF8( const char *string, /* UTF-8 encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyObject* PyUnicode_DecodeUTF8Stateful( const char *string, /* UTF-8 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ Py_ssize_t *consumed /* bytes consumed */ ); PyObject* PyUnicode_AsUTF8String( PyObject *unicode /* Unicode object */ ); #ifndef Py_LIMITED_API PyObject* _PyUnicode_AsUTF8String( PyObject *unicode, const char *errors); PyObject* PyUnicode_EncodeUTF8( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ const char *errors /* error handling */ ); #endif /* --- UTF-32 Codecs ------------------------------------------------------ */ /* Decodes length bytes from a UTF-32 encoded buffer string and returns the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: *byteorder == -1: little endian *byteorder == 0: native order *byteorder == 1: big endian In native mode, the first four bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order adjusted and the BOM skipped. In the other modes, no BOM mark interpretation is done. After completion, *byteorder is set to the current byte order at the end of input data. If byteorder is NULL, the codec starts in native order mode. */ PyObject* PyUnicode_DecodeUTF32( const char *string, /* UTF-32 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ int *byteorder /* pointer to byteorder to use 0=native;-1=LE,1=BE; updated on exit */ ); PyObject* PyUnicode_DecodeUTF32Stateful( const char *string, /* UTF-32 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ int *byteorder, /* pointer to byteorder to use 0=native;-1=LE,1=BE; updated on exit */ Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-32 encoding in native byte order. The string always starts with a BOM mark. */ PyObject* PyUnicode_AsUTF32String( PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-32 encoded value of the Unicode data. If byteorder is not 0, output is written according to the following byte order: byteorder == -1: little endian byteorder == 0: native byte order (writes a BOM mark) byteorder == 1: big endian If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended. */ #ifndef Py_LIMITED_API PyObject* PyUnicode_EncodeUTF32( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ const char *errors, /* error handling */ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); PyObject* _PyUnicode_EncodeUTF32( PyObject *object, /* Unicode object */ const char *errors, /* error handling */ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); #endif /* --- UTF-16 Codecs ------------------------------------------------------ */ /* Decodes length bytes from a UTF-16 encoded buffer string and returns the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to "strict". If byteorder is non-NULL, the decoder starts decoding using the given byte order: *byteorder == -1: little endian *byteorder == 0: native order *byteorder == 1: big endian In native mode, the first two bytes of the stream are checked for a BOM mark. If found, the BOM mark is analysed, the byte order adjusted and the BOM skipped. In the other modes, no BOM mark interpretation is done. After completion, *byteorder is set to the current byte order at the end of input data. If byteorder is NULL, the codec starts in native order mode. */ PyObject* PyUnicode_DecodeUTF16( const char *string, /* UTF-16 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ int *byteorder /* pointer to byteorder to use 0=native;-1=LE,1=BE; updated on exit */ ); PyObject* PyUnicode_DecodeUTF16Stateful( const char *string, /* UTF-16 encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ int *byteorder, /* pointer to byteorder to use 0=native;-1=LE,1=BE; updated on exit */ Py_ssize_t *consumed /* bytes consumed */ ); /* Returns a Python string using the UTF-16 encoding in native byte order. The string always starts with a BOM mark. */ PyObject* PyUnicode_AsUTF16String( PyObject *unicode /* Unicode object */ ); /* Returns a Python string object holding the UTF-16 encoded value of the Unicode data. If byteorder is not 0, output is written according to the following byte order: byteorder == -1: little endian byteorder == 0: native byte order (writes a BOM mark) byteorder == 1: big endian If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended. Note that Py_UNICODE data is being interpreted as UTF-16 reduced to UCS-2. This trick makes it possible to add full UTF-16 capabilities at a later point without compromising the APIs. */ #ifndef Py_LIMITED_API PyObject* PyUnicode_EncodeUTF16( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ const char *errors, /* error handling */ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); PyObject* _PyUnicode_EncodeUTF16( PyObject* unicode, /* Unicode object */ const char *errors, /* error handling */ int byteorder /* byteorder to use 0=BOM+native;-1=LE,1=BE */ ); #endif /* --- Unicode-Escape Codecs ---------------------------------------------- */ PyObject* PyUnicode_DecodeUnicodeEscape( const char *string, /* Unicode-Escape encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); #ifndef Py_LIMITED_API /* Helper for PyUnicode_DecodeUnicodeEscape that detects invalid escape chars. */ PyObject* _PyUnicode_DecodeUnicodeEscape( const char *string, /* Unicode-Escape encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ const char **first_invalid_escape /* on return, points to first invalid escaped char in string. */ ); #endif PyObject* PyUnicode_AsUnicodeEscapeString( PyObject *unicode /* Unicode object */ ); #ifndef Py_LIMITED_API PyObject* PyUnicode_EncodeUnicodeEscape( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); #endif /* --- Raw-Unicode-Escape Codecs ------------------------------------------ */ PyObject* PyUnicode_DecodeRawUnicodeEscape( const char *string, /* Raw-Unicode-Escape encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyObject* PyUnicode_AsRawUnicodeEscapeString( PyObject *unicode /* Unicode object */ ); #ifndef Py_LIMITED_API PyObject* PyUnicode_EncodeRawUnicodeEscape( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length /* Number of Py_UNICODE chars to encode */ ); #endif /* --- Unicode Internal Codec --------------------------------------------- Only for internal use in _codecsmodule.c */ #ifndef Py_LIMITED_API PyObject *_PyUnicode_DecodeUnicodeInternal( const char *string, Py_ssize_t length, const char *errors ); #endif /* --- Latin-1 Codecs ----------------------------------------------------- Note: Latin-1 corresponds to the first 256 Unicode ordinals. */ PyObject* PyUnicode_DecodeLatin1( const char *string, /* Latin-1 encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyObject* PyUnicode_AsLatin1String( PyObject *unicode /* Unicode object */ ); #ifndef Py_LIMITED_API PyObject* _PyUnicode_AsLatin1String( PyObject* unicode, const char* errors); PyObject* PyUnicode_EncodeLatin1( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ const char *errors /* error handling */ ); #endif /* --- ASCII Codecs ------------------------------------------------------- Only 7-bit ASCII data is excepted. All other codes generate errors. */ PyObject* PyUnicode_DecodeASCII( const char *string, /* ASCII encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyObject* PyUnicode_AsASCIIString( PyObject *unicode /* Unicode object */ ); #ifndef Py_LIMITED_API PyObject* _PyUnicode_AsASCIIString( PyObject* unicode, const char* errors); PyObject* PyUnicode_EncodeASCII( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ const char *errors /* error handling */ ); #endif /* --- Character Map Codecs ----------------------------------------------- This codec uses mappings to encode and decode characters. Decoding mappings must map byte ordinals (integers in the range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode ordinals) or None. Unmapped data bytes (ones which cause a LookupError) as well as mapped to None, 0xFFFE or '\ufffe' are treated as "undefined mapping" and cause an error. Encoding mappings must map Unicode ordinal integers to bytes objects, integers in the range from 0 to 255 or None. Unmapped character ordinals (ones which cause a LookupError) as well as mapped to None are treated as "undefined mapping" and cause an error. */ PyObject* PyUnicode_DecodeCharmap( const char *string, /* Encoded string */ Py_ssize_t length, /* size of string */ PyObject *mapping, /* decoding mapping */ const char *errors /* error handling */ ); PyObject* PyUnicode_AsCharmapString( PyObject *unicode, /* Unicode object */ PyObject *mapping /* encoding mapping */ ); #ifndef Py_LIMITED_API PyObject* PyUnicode_EncodeCharmap( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ PyObject *mapping, /* encoding mapping */ const char *errors /* error handling */ ); PyObject* _PyUnicode_EncodeCharmap( PyObject *unicode, /* Unicode object */ PyObject *mapping, /* encoding mapping */ const char *errors /* error handling */ ); #endif /* Translate a Py_UNICODE buffer of the given length by applying a character mapping table to it and return the resulting Unicode object. The mapping table must map Unicode ordinal integers to Unicode strings, Unicode ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is. */ #ifndef Py_LIMITED_API PyObject * PyUnicode_TranslateCharmap( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ PyObject *table, /* Translate table */ const char *errors /* error handling */ ); #endif #ifdef MS_WINDOWS /* --- MBCS codecs for Windows -------------------------------------------- */ PyObject* PyUnicode_DecodeMBCS( const char *string, /* MBCS encoded string */ Py_ssize_t length, /* size of string */ const char *errors /* error handling */ ); PyObject* PyUnicode_DecodeMBCSStateful( const char *string, /* MBCS encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ Py_ssize_t *consumed /* bytes consumed */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject* PyUnicode_DecodeCodePageStateful( int code_page, /* code page number */ const char *string, /* encoded string */ Py_ssize_t length, /* size of string */ const char *errors, /* error handling */ Py_ssize_t *consumed /* bytes consumed */ ); #endif PyObject* PyUnicode_AsMBCSString( PyObject *unicode /* Unicode object */ ); #ifndef Py_LIMITED_API PyObject* PyUnicode_EncodeMBCS( const Py_UNICODE *data, /* Unicode char buffer */ Py_ssize_t length, /* number of Py_UNICODE chars to encode */ const char *errors /* error handling */ ); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject* PyUnicode_EncodeCodePage( int code_page, /* code page number */ PyObject *unicode, /* Unicode object */ const char *errors /* error handling */ ); #endif #endif /* MS_WINDOWS */ /* --- Decimal Encoder ---------------------------------------------------- */ /* Takes a Unicode string holding a decimal value and writes it into an output buffer using standard ASCII digit codes. The output buffer has to provide at least length+1 bytes of storage area. The output string is 0-terminated. The encoder converts whitespace to ' ', decimal characters to their corresponding ASCII digit and all other Latin-1 characters except \0 as-is. Characters outside this range (Unicode ordinals 1-256) are treated as errors. This includes embedded NULL bytes. Error handling is defined by the errors argument: NULL or "strict": raise a ValueError "ignore": ignore the wrong characters (these are not copied to the output buffer) "replace": replaces illegal characters with '?' Returns 0 on success, -1 on failure. */ #ifndef Py_LIMITED_API int PyUnicode_EncodeDecimal( Py_UNICODE *s, /* Unicode buffer */ Py_ssize_t length, /* Number of Py_UNICODE chars to encode */ char *output, /* Output buffer; must have size >= length */ const char *errors /* error handling */ ); #endif /* Transforms code points that have decimal digit property to the corresponding ASCII digit code points. Returns a new Unicode string on success, NULL on failure. */ #ifndef Py_LIMITED_API PyObject* PyUnicode_TransformDecimalToASCII( Py_UNICODE *s, /* Unicode buffer */ Py_ssize_t length /* Number of Py_UNICODE chars to transform */ ); #endif /* Similar to PyUnicode_TransformDecimalToASCII(), but takes a PyObject as argument instead of a raw buffer and length. This function additionally transforms spaces to ASCII because this is what the callers in longobject, floatobject, and complexobject did anyways. */ #ifndef Py_LIMITED_API PyObject* _PyUnicode_TransformDecimalAndSpaceToASCII( PyObject *unicode /* Unicode object */ ); #endif /* --- Locale encoding --------------------------------------------------- */ #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Decode a string from the current locale encoding. The decoder is strict if *surrogateescape* is equal to zero, otherwise it uses the 'surrogateescape' error handler (PEP 383) to escape undecodable bytes. If a byte sequence can be decoded as a surrogate character and *surrogateescape* is not equal to zero, the byte sequence is escaped using the 'surrogateescape' error handler instead of being decoded. *str* must end with a null character but cannot contain embedded null characters. */ PyObject* PyUnicode_DecodeLocaleAndSize( const char *str, Py_ssize_t len, const char *errors); /* Similar to PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen(). */ PyObject* PyUnicode_DecodeLocale( const char *str, const char *errors); /* Encode a Unicode object to the current locale encoding. The encoder is strict is *surrogateescape* is equal to zero, otherwise the "surrogateescape" error handler is used. Return a bytes object. The string cannot contain embedded null characters. */ PyObject* PyUnicode_EncodeLocale( PyObject *unicode, const char *errors ); #endif /* --- File system encoding ---------------------------------------------- */ /* ParseTuple converter: encode str objects to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output as-is. */ int PyUnicode_FSConverter(PyObject*, void*); /* ParseTuple converter: decode bytes objects to unicode using PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is. */ int PyUnicode_FSDecoder(PyObject*, void*); /* Decode a null-terminated string using Py_FileSystemDefaultEncoding and the "surrogateescape" error handler. If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding. Use PyUnicode_DecodeFSDefaultAndSize() if the string length is known. */ PyObject* PyUnicode_DecodeFSDefault( const char *s /* encoded string */ ); /* Decode a string using Py_FileSystemDefaultEncoding and the "surrogateescape" error handler. If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding. */ PyObject* PyUnicode_DecodeFSDefaultAndSize( const char *s, /* encoded string */ Py_ssize_t size /* size */ ); /* Encode a Unicode object to Py_FileSystemDefaultEncoding with the "surrogateescape" error handler, and return bytes. If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding. */ PyObject* PyUnicode_EncodeFSDefault( PyObject *unicode ); /* --- Methods & Slots ---------------------------------------------------- These are capable of handling Unicode objects and strings on input (we refer to them as strings in the descriptions) and return Unicode objects or integers as appropriate. */ /* Concat two strings giving a new Unicode string. */ PyObject* PyUnicode_Concat( PyObject *left, /* Left string */ PyObject *right /* Right string */ ); /* Concat two strings and put the result in *pleft (sets *pleft to NULL on error) */ void PyUnicode_Append( PyObject **pleft, /* Pointer to left string */ PyObject *right /* Right string */ ); /* Concat two strings, put the result in *pleft and drop the right object (sets *pleft to NULL on error) */ void PyUnicode_AppendAndDel( PyObject **pleft, /* Pointer to left string */ PyObject *right /* Right string */ ); /* Split a string giving a list of Unicode strings. If sep is NULL, splitting will be done at all whitespace substrings. Otherwise, splits occur at the given separator. At most maxsplit splits will be done. If negative, no limit is set. Separators are not included in the resulting list. */ PyObject* PyUnicode_Split( PyObject *s, /* String to split */ PyObject *sep, /* String separator */ Py_ssize_t maxsplit /* Maxsplit count */ ); /* Dito, but split at line breaks. CRLF is considered to be one line break. Line breaks are not included in the resulting list. */ PyObject* PyUnicode_Splitlines( PyObject *s, /* String to split */ int keepends /* If true, line end markers are included */ ); /* Partition a string using a given separator. */ PyObject* PyUnicode_Partition( PyObject *s, /* String to partition */ PyObject *sep /* String separator */ ); /* Partition a string using a given separator, searching from the end of the string. */ PyObject* PyUnicode_RPartition( PyObject *s, /* String to partition */ PyObject *sep /* String separator */ ); /* Split a string giving a list of Unicode strings. If sep is NULL, splitting will be done at all whitespace substrings. Otherwise, splits occur at the given separator. At most maxsplit splits will be done. But unlike PyUnicode_Split PyUnicode_RSplit splits from the end of the string. If negative, no limit is set. Separators are not included in the resulting list. */ PyObject* PyUnicode_RSplit( PyObject *s, /* String to split */ PyObject *sep, /* String separator */ Py_ssize_t maxsplit /* Maxsplit count */ ); /* Translate a string by applying a character mapping table to it and return the resulting Unicode object. The mapping table must map Unicode ordinal integers to Unicode strings, Unicode ordinal integers or None (causing deletion of the character). Mapping tables may be dictionaries or sequences. Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is. */ PyObject * PyUnicode_Translate( PyObject *str, /* String */ PyObject *table, /* Translate table */ const char *errors /* error handling */ ); /* Join a sequence of strings using the given separator and return the resulting Unicode string. */ PyObject* PyUnicode_Join( PyObject *separator, /* Separator string */ PyObject *seq /* Sequence object */ ); #ifndef Py_LIMITED_API PyObject * _PyUnicode_JoinArray( PyObject *separator, PyObject **items, Py_ssize_t seqlen ); #endif /* Py_LIMITED_API */ /* Return 1 if substr matches str[start:end] at the given tail end, 0 otherwise. */ Py_ssize_t PyUnicode_Tailmatch( PyObject *str, /* String */ PyObject *substr, /* Prefix or Suffix string */ Py_ssize_t start, /* Start index */ Py_ssize_t end, /* Stop index */ int direction /* Tail end: -1 prefix, +1 suffix */ ); /* Return the first position of substr in str[start:end] using the given search direction or -1 if not found. -2 is returned in case an error occurred and an exception is set. */ Py_ssize_t PyUnicode_Find( PyObject *str, /* String */ PyObject *substr, /* Substring to find */ Py_ssize_t start, /* Start index */ Py_ssize_t end, /* Stop index */ int direction /* Find direction: +1 forward, -1 backward */ ); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 /* Like PyUnicode_Find, but search for single character only. */ Py_ssize_t PyUnicode_FindChar( PyObject *str, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction ); #endif /* Count the number of occurrences of substr in str[start:end]. */ Py_ssize_t PyUnicode_Count( PyObject *str, /* String */ PyObject *substr, /* Substring to count */ Py_ssize_t start, /* Start index */ Py_ssize_t end /* Stop index */ ); /* Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. */ PyObject * PyUnicode_Replace( PyObject *str, /* String */ PyObject *substr, /* Substring to find */ PyObject *replstr, /* Substring to replace */ Py_ssize_t maxcount /* Max. number of replacements to apply; -1 = all */ ); /* Compare two strings and return -1, 0, 1 for less than, equal, greater than resp. Raise an exception and return -1 on error. */ int PyUnicode_Compare( PyObject *left, /* Left string */ PyObject *right /* Right string */ ); #ifndef Py_LIMITED_API /* Test whether a unicode is equal to ASCII identifier. Return 1 if true, 0 otherwise. The right argument must be ASCII identifier. Any error occurs inside will be cleared before return. */ int _PyUnicode_EqualToASCIIId( PyObject *left, /* Left string */ _Py_Identifier *right /* Right identifier */ ); #endif /* Compare a Unicode object with C string and return -1, 0, 1 for less than, equal, and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input string as ISO-8859-1 if it contains non-ASCII characters. This function does not raise exceptions. */ int PyUnicode_CompareWithASCIIString( PyObject *left, const char *right /* ASCII-encoded string */ ); #ifndef Py_LIMITED_API /* Test whether a unicode is equal to ASCII string. Return 1 if true, 0 otherwise. The right argument must be ASCII-encoded string. Any error occurs inside will be cleared before return. */ int _PyUnicode_EqualToASCIIString( PyObject *left, const char *right /* ASCII-encoded string */ ); #endif /* Rich compare two strings and return one of the following: - NULL in case an exception was raised - Py_True or Py_False for successful comparisons - Py_NotImplemented in case the type combination is unknown Possible values for op: Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE */ PyObject * PyUnicode_RichCompare( PyObject *left, /* Left string */ PyObject *right, /* Right string */ int op /* Operation: Py_EQ, Py_NE, Py_GT, etc. */ ); /* Apply an argument tuple or dictionary to a format string and return the resulting Unicode string. */ PyObject * PyUnicode_Format( PyObject *format, /* Format string */ PyObject *args /* Argument tuple or dictionary */ ); /* Checks whether element is contained in container and return 1/0 accordingly. element has to coerce to a one element Unicode string. -1 is returned in case of an error. */ int PyUnicode_Contains( PyObject *container, /* Container string */ PyObject *element /* Element string */ ); /* Checks whether argument is a valid identifier. */ int PyUnicode_IsIdentifier(PyObject *s); #ifndef Py_LIMITED_API /* Externally visible for str.strip(unicode) */ PyObject * _PyUnicode_XStrip( PyObject *self, int striptype, PyObject *sepobj ); #endif /* Using explicit passed-in values, insert the thousands grouping into the string pointed to by buffer. For the argument descriptions, see Objects/stringlib/localeutil.h */ #ifndef Py_LIMITED_API 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); #endif /* === Characters Type APIs =============================================== */ /* Helper array used by Py_UNICODE_ISSPACE(). */ #ifndef Py_LIMITED_API extern const unsigned char _Py_ascii_whitespace[]; /* These should not be used directly. Use the Py_UNICODE_IS* and Py_UNICODE_TO* macros instead. These APIs are implemented in Objects/unicodectype.c. */ int _PyUnicode_IsLowercase( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsUppercase( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsTitlecase( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsXidStart( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsXidContinue( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsWhitespace( const Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsLinebreak( const Py_UCS4 ch /* Unicode character */ ); Py_UCS4 _PyUnicode_ToLowercase( Py_UCS4 ch /* Unicode character */ ); Py_UCS4 _PyUnicode_ToUppercase( Py_UCS4 ch /* Unicode character */ ); Py_UCS4 _PyUnicode_ToTitlecase( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_ToLowerFull( Py_UCS4 ch, /* Unicode character */ Py_UCS4 *res ); int _PyUnicode_ToTitleFull( Py_UCS4 ch, /* Unicode character */ Py_UCS4 *res ); int _PyUnicode_ToUpperFull( Py_UCS4 ch, /* Unicode character */ Py_UCS4 *res ); int _PyUnicode_ToFoldedFull( Py_UCS4 ch, /* Unicode character */ Py_UCS4 *res ); int _PyUnicode_IsCaseIgnorable( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsCased( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_ToDecimalDigit( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_ToDigit( Py_UCS4 ch /* Unicode character */ ); double _PyUnicode_ToNumeric( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsDecimalDigit( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsDigit( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsNumeric( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsPrintable( Py_UCS4 ch /* Unicode character */ ); int _PyUnicode_IsAlpha( Py_UCS4 ch /* Unicode character */ ); size_t Py_UNICODE_strlen( const Py_UNICODE *u ); Py_UNICODE* Py_UNICODE_strcpy( Py_UNICODE *s1, const Py_UNICODE *s2); Py_UNICODE* Py_UNICODE_strcat( Py_UNICODE *s1, const Py_UNICODE *s2); Py_UNICODE* Py_UNICODE_strncpy( Py_UNICODE *s1, const Py_UNICODE *s2, size_t n); int Py_UNICODE_strcmp( const Py_UNICODE *s1, const Py_UNICODE *s2 ); int Py_UNICODE_strncmp( const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n ); Py_UNICODE* Py_UNICODE_strchr( const Py_UNICODE *s, Py_UNICODE c ); Py_UNICODE* Py_UNICODE_strrchr( const Py_UNICODE *s, Py_UNICODE c ); PyObject* _PyUnicode_FormatLong(PyObject *, int, int, int); /* Create a copy of a unicode string ending with a nul character. Return NULL and raise a MemoryError exception on memory allocation failure, otherwise return a new allocated buffer (use PyMem_Free() to free the buffer). */ Py_UNICODE* PyUnicode_AsUnicodeCopy( PyObject *unicode ); #endif /* Py_LIMITED_API */ #if defined(Py_DEBUG) && !defined(Py_LIMITED_API) int _PyUnicode_CheckConsistency( PyObject *op, int check_content); #elif !defined(NDEBUG) /* For asserts that call _PyUnicode_CheckConsistency(), which would * otherwise be a problem when building with asserts but without Py_DEBUG. */ #define _PyUnicode_CheckConsistency(op, check_content) PyUnicode_Check(op) #endif #ifndef Py_LIMITED_API /* Return an interned Unicode object for an Identifier; may fail if there is no memory.*/ PyObject* _PyUnicode_FromId(_Py_Identifier*); /* Clear all static strings. */ void _PyUnicode_ClearStaticStrings(void); /* Fast equality check when the inputs are known to be exact unicode types and where the hash values are equal (i.e. a very probable match) */ int _PyUnicode_EQ(PyObject *, PyObject *); #endif /* !Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_UNICODEOBJECT_H */
74,472
2,200
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/classobject.h
#ifndef Py_LIMITED_API #ifndef Py_CLASSOBJECT_H #define Py_CLASSOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef struct { PyObject_HEAD PyObject *im_func; /* The callable object implementing the method */ PyObject *im_self; /* The instance it is bound to */ PyObject *im_weakreflist; /* List of weak references */ } PyMethodObject; extern PyTypeObject PyMethod_Type; #define PyMethod_Check(op) ((op)->ob_type == &PyMethod_Type) PyObject * PyMethod_New(PyObject *, PyObject *); PyObject * PyMethod_Function(PyObject *); PyObject * PyMethod_Self(PyObject *); /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #define PyMethod_GET_FUNCTION(meth) \ (((PyMethodObject *)meth) -> im_func) #define PyMethod_GET_SELF(meth) \ (((PyMethodObject *)meth) -> im_self) int PyMethod_ClearFreeList(void); typedef struct { PyObject_HEAD PyObject *func; } PyInstanceMethodObject; extern PyTypeObject PyInstanceMethod_Type; #define PyInstanceMethod_Check(op) ((op)->ob_type == &PyInstanceMethod_Type) PyObject * PyInstanceMethod_New(PyObject *); PyObject * PyInstanceMethod_Function(PyObject *); /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #define PyInstanceMethod_GET_FUNCTION(meth) \ (((PyInstanceMethodObject *)meth) -> func) COSMOPOLITAN_C_END_ #endif /* !Py_CLASSOBJECT_H */ #endif /* Py_LIMITED_API */
1,501
53
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pythread.h
#ifndef Py_PYTHREAD_H #define Py_PYTHREAD_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef void *PyThread_type_lock; typedef void *PyThread_type_sema; /* Return status codes for Python lock acquisition. Chosen for maximum * backwards compatibility, ie failure -> 0, success -> 1. */ typedef enum PyLockStatus { PY_LOCK_FAILURE = 0, PY_LOCK_ACQUIRED = 1, PY_LOCK_INTR } PyLockStatus; void PyThread_init_thread(void); long PyThread_start_new_thread(void (*)(void *), void *); void PyThread_exit_thread(void); long PyThread_get_thread_ident(void); PyThread_type_lock PyThread_allocate_lock(void); void PyThread_free_lock(PyThread_type_lock); int PyThread_acquire_lock(PyThread_type_lock, int); #define WAIT_LOCK 1 #define NOWAIT_LOCK 0 /* PY_TIMEOUT_T is the integral type used to specify timeouts when waiting on a lock (see PyThread_acquire_lock_timed() below). PY_TIMEOUT_MAX is the highest usable value (in microseconds) of that type, and depends on the system threading API. NOTE: this isn't the same value as `_thread.TIMEOUT_MAX`. The _thread module exposes a higher-level API, with timeouts expressed in seconds and floating-point numbers allowed. */ #define PY_TIMEOUT_T long long #define PY_TIMEOUT_MAX PY_LLONG_MAX /* In the NT API, the timeout is a DWORD and is expressed in milliseconds */ #if defined (NT_THREADS) #if 0xFFFFFFFFLL * 1000 < PY_TIMEOUT_MAX #undef PY_TIMEOUT_MAX #define PY_TIMEOUT_MAX (0xFFFFFFFFLL * 1000) #endif #endif /* If microseconds == 0, the call is non-blocking: it returns immediately even when the lock can't be acquired. If microseconds > 0, the call waits up to the specified duration. If microseconds < 0, the call waits until success (or abnormal failure) microseconds must be less than PY_TIMEOUT_MAX. Behaviour otherwise is undefined. If intr_flag is true and the acquire is interrupted by a signal, then the call will return PY_LOCK_INTR. The caller may reattempt to acquire the lock. */ PyLockStatus PyThread_acquire_lock_timed(PyThread_type_lock, PY_TIMEOUT_T microseconds, int intr_flag); void PyThread_release_lock(PyThread_type_lock); size_t PyThread_get_stacksize(void); int PyThread_set_stacksize(size_t); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject* PyThread_GetInfo(void); #endif /* Thread Local Storage (TLS) API */ int PyThread_create_key(void); void PyThread_delete_key(int); int PyThread_set_key_value(int, void *); void * PyThread_get_key_value(int); void PyThread_delete_key_value(int key); /* Cleanup after a fork */ void PyThread_ReInitTLS(void); COSMOPOLITAN_C_END_ #endif /* !Py_PYTHREAD_H */
2,818
86
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/descrobject.h
#ifndef Py_DESCROBJECT_H #define Py_DESCROBJECT_H #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyport.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef PyObject *(*getter)(PyObject *, void *); typedef int (*setter)(PyObject *, PyObject *, void *); typedef struct PyGetSetDef { char *name; getter get; setter set; char *doc; void *closure; } PyGetSetDef; #ifndef Py_LIMITED_API typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args, void *wrapped); typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds); struct wrapperbase { char *name; int offset; void *function; wrapperfunc wrapper; char *doc; int flags; PyObject *name_strobj; }; /* Flags for above struct */ #define PyWrapperFlag_KEYWORDS 1 /* wrapper function takes keyword args */ /* Various kinds of descriptor objects */ typedef struct { PyObject_HEAD PyTypeObject *d_type; PyObject *d_name; PyObject *d_qualname; } PyDescrObject; #define PyDescr_COMMON PyDescrObject d_common #define PyDescr_TYPE(x) (((PyDescrObject *)(x))->d_type) #define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name) typedef struct { PyDescr_COMMON; PyMethodDef *d_method; } PyMethodDescrObject; typedef struct { PyDescr_COMMON; struct PyMemberDef *d_member; } PyMemberDescrObject; typedef struct { PyDescr_COMMON; PyGetSetDef *d_getset; } PyGetSetDescrObject; typedef struct { PyDescr_COMMON; struct wrapperbase *d_base; void *d_wrapped; /* This can be any function pointer */ } PyWrapperDescrObject; #endif /* Py_LIMITED_API */ extern PyTypeObject PyClassMethodDescr_Type; extern PyTypeObject PyGetSetDescr_Type; extern PyTypeObject PyMemberDescr_Type; extern PyTypeObject PyMethodDescr_Type; extern PyTypeObject PyWrapperDescr_Type; extern PyTypeObject PyDictProxy_Type; #ifndef Py_LIMITED_API extern PyTypeObject _PyMethodWrapper_Type; #endif /* Py_LIMITED_API */ PyObject * PyDescr_NewMethod(PyTypeObject *, PyMethodDef *); PyObject * PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *); struct PyMemberDef; /* forward declaration for following prototype */ PyObject * PyDescr_NewMember(PyTypeObject *, struct PyMemberDef *); PyObject * PyDescr_NewGetSet(PyTypeObject *, struct PyGetSetDef *); #ifndef Py_LIMITED_API PyObject * _PyMethodDescr_FastCallKeywords( PyObject *descrobj, PyObject *const *stack, Py_ssize_t nargs, PyObject *kwnames); PyObject * PyDescr_NewWrapper(PyTypeObject *, struct wrapperbase *, void *); #define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL) #endif PyObject * PyDictProxy_New(PyObject *); PyObject * PyWrapper_New(PyObject *, PyObject *); extern PyTypeObject PyProperty_Type; COSMOPOLITAN_C_END_ #endif /* !Py_DESCROBJECT_H */
3,101
109
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/structseq.h
#ifndef Py_STRUCTSEQ_H #define Py_STRUCTSEQ_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/tupleobject.h" COSMOPOLITAN_C_START_ /* clang-format off */ typedef struct PyStructSequence_Field { char *name; char *doc; } PyStructSequence_Field; typedef struct PyStructSequence_Desc { char *name; char *doc; struct PyStructSequence_Field *fields; int n_in_sequence; } PyStructSequence_Desc; extern char* PyStructSequence_UnnamedField; #ifndef Py_LIMITED_API void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc); int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc); #endif PyTypeObject* PyStructSequence_NewType(PyStructSequence_Desc *desc); PyObject * PyStructSequence_New(PyTypeObject* type); #ifndef Py_LIMITED_API typedef PyTupleObject PyStructSequence; /* Macro, *only* to be used to fill in brand new objects */ #define PyStructSequence_SET_ITEM(op, i, v) PyTuple_SET_ITEM(op, i, v) #define PyStructSequence_GET_ITEM(op, i) PyTuple_GET_ITEM(op, i) #endif void PyStructSequence_SetItem(PyObject*, Py_ssize_t, PyObject*); PyObject* PyStructSequence_GetItem(PyObject*, Py_ssize_t); COSMOPOLITAN_C_END_ #endif /* !Py_STRUCTSEQ_H */
1,341
46
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/object.h
#ifndef Py_OBJECT_H #define Py_OBJECT_H /* DO NOT INCLUDE pystate.h */ #include "libc/stdio/stdio.h" #include "third_party/python/Include/op.h" #include "third_party/python/Include/pyport.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Object and type object interface */ /* Objects are structures allocated on the heap. Special rules apply to the use of objects to ensure they are properly garbage-collected. Objects are never allocated statically or on the stack; they must be accessed through special macros and functions only. (Type objects are exceptions to the first rule; the standard types are represented by statically initialized type objects, although work on type/class unification for Python 2.2 made it possible to have heap-allocated type objects too). An object has a 'reference count' that is increased or decreased when a pointer to the object is copied or deleted; when the reference count reaches zero there are no references to the object left and it can be removed from the heap. An object has a 'type' that determines what it represents and what kind of data it contains. An object's type is fixed when it is created. Types themselves are represented as objects; an object contains a pointer to the corresponding type object. The type itself has a type pointer pointing to the object representing the type 'type', which contains a pointer to itself!). Objects do not float around in memory; once allocated an object keeps the same size and address. Objects that must hold variable-size data can contain pointers to variable-size parts of the object. Not all objects of the same type have the same size; but the size cannot change after allocation. (These restrictions are made so a reference to an object can be simply a pointer -- moving an object would require updating all the pointers, and changing an object's size would require moving it if there was another object right next to it.) Objects are always accessed through pointers of the type 'PyObject *'. The type 'PyObject' is a structure that only contains the reference count and the type pointer. The actual memory allocated for an object contains other data that can only be accessed after casting the pointer to a pointer to a longer structure type. This longer type must start with the reference count and type fields; the macro PyObject_HEAD should be used for this (to accommodate for future changes). The implementation of a particular object type can cast the object pointer to the proper type and back. A standard interface exists for objects that contain an array of items whose size is determined when the object is allocated. */ /* Py_DEBUG implies Py_TRACE_REFS. */ #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS) #define Py_TRACE_REFS #endif /* Py_TRACE_REFS implies Py_REF_DEBUG. */ #if defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG) #define Py_REF_DEBUG #endif #if defined(Py_LIMITED_API) && defined(Py_REF_DEBUG) #error Py_LIMITED_API is incompatible with Py_DEBUG, Py_TRACE_REFS, and Py_REF_DEBUG #endif #ifdef Py_TRACE_REFS /* Define pointers to support a doubly-linked list of all live heap objects. */ #define _PyObject_HEAD_EXTRA \ struct _object *_ob_next; \ struct _object *_ob_prev; #define _PyObject_EXTRA_INIT 0, 0, #else #define _PyObject_HEAD_EXTRA #define _PyObject_EXTRA_INIT #endif /* PyObject_HEAD defines the initial segment of every PyObject. */ #define PyObject_HEAD PyObject ob_base; #define PyObject_HEAD_INIT(type) \ { _PyObject_EXTRA_INIT \ 1, type }, #define PyVarObject_HEAD_INIT(type, size) \ { PyObject_HEAD_INIT(type) size }, /* PyObject_VAR_HEAD defines the initial segment of all variable-size * container objects. These end with a declaration of an array with 1 * element, but enough space is malloc'ed so that the array actually * has room for ob_size elements. Note that ob_size is an element count, * not necessarily a byte count. */ #define PyObject_VAR_HEAD PyVarObject ob_base; #define Py_INVALID_SIZE (Py_ssize_t)-1 /* Nothing is actually declared to be a PyObject, but every pointer to * a Python object can be cast to a PyObject*. This is inheritance built * by hand. Similarly every pointer to a variable-size Python object can, * in addition, be cast to PyVarObject*. */ typedef struct _object { _PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt; struct _typeobject *ob_type; } PyObject; typedef struct { PyObject ob_base; Py_ssize_t ob_size; /* Number of items in variable part */ } PyVarObject; #define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt) #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size) #ifndef Py_LIMITED_API /********************* String Literals ****************************************/ /* This structure helps managing static strings. The basic usage goes like this: Instead of doing r = PyObject_CallMethod(o, "foo", "args", ...); do _Py_IDENTIFIER(foo); ... r = _PyObject_CallMethodId(o, &PyId_foo, "args", ...); PyId_foo is a static variable, either on block level or file level. On first usage, the string "foo" is interned, and the structures are linked. On interpreter shutdown, all strings are released (through _PyUnicode_ClearStaticStrings). Alternatively, _Py_static_string allows choosing the variable name. _PyUnicode_FromId returns a borrowed reference to the interned string. _PyObject_{Get,Set,Has}AttrId are __getattr__ versions using _Py_Identifier*. */ typedef struct _Py_Identifier { struct _Py_Identifier *next; const char* string; PyObject *object; } _Py_Identifier; #define _Py_static_string_init(value) { .next = NULL, .string = value, .object = NULL } #define _Py_static_string(varname, value) static _Py_Identifier varname = _Py_static_string_init(value) #define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname) #endif /* !Py_LIMITED_API */ /* Type objects contain a string containing the type name (to help somewhat in debugging), the allocation parameters (see PyObject_New() and PyObject_NewVar()), and methods for accessing objects of the type. Methods are optional, a nil pointer meaning that particular kind of access is not available for this type. The Py_DECREF() macro uses the tp_dealloc method without checking for a nil pointer; it should always be implemented except if the implementation can guarantee that the reference count will never reach zero (e.g., for statically allocated type objects). NB: the methods for certain type groups are now contained in separate method blocks. */ typedef PyObject * (*unaryfunc)(PyObject *); typedef PyObject * (*binaryfunc)(PyObject *, PyObject *); typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *); typedef int (*inquiry)(PyObject *); typedef Py_ssize_t (*lenfunc)(PyObject *); typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t); typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t); typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *); typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *); typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *); #ifndef Py_LIMITED_API /* buffer interface */ typedef struct bufferinfo { void *buf; PyObject *obj; /* owned reference */ Py_ssize_t len; Py_ssize_t itemsize; /* This is Py_ssize_t so it can be pointed to by strides in simple case.*/ int readonly; int ndim; char *format; Py_ssize_t *shape; Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; } Py_buffer; typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); typedef void (*releasebufferproc)(PyObject *, Py_buffer *); /* Maximum number of dimensions */ #define PyBUF_MAX_NDIM 64 /* Flags for getting buffers */ #define PyBUF_SIMPLE 0 #define PyBUF_WRITABLE 0x0001 /* we used to include an E, backwards compatible alias */ #define PyBUF_WRITEABLE PyBUF_WRITABLE #define PyBUF_FORMAT 0x0004 #define PyBUF_ND 0x0008 #define PyBUF_STRIDES (0x0010 | PyBUF_ND) #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES) #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES) #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES) #define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE) #define PyBUF_CONTIG_RO (PyBUF_ND) #define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE) #define PyBUF_STRIDED_RO (PyBUF_STRIDES) #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT) #define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT) #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT) #define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT) #define PyBUF_READ 0x100 #define PyBUF_WRITE 0x200 /* End buffer interface */ #endif /* Py_LIMITED_API */ typedef int (*objobjproc)(PyObject *, PyObject *); typedef int (*visitproc)(PyObject *, void *); typedef int (*traverseproc)(PyObject *, visitproc, void *); #ifndef Py_LIMITED_API typedef struct { /* Number implementations must check *both* arguments for proper type and implement the necessary conversions in the slot functions themselves. */ binaryfunc nb_add; binaryfunc nb_subtract; binaryfunc nb_multiply; binaryfunc nb_remainder; binaryfunc nb_divmod; ternaryfunc nb_power; unaryfunc nb_negative; unaryfunc nb_positive; unaryfunc nb_absolute; inquiry nb_bool; unaryfunc nb_invert; binaryfunc nb_lshift; binaryfunc nb_rshift; binaryfunc nb_and; binaryfunc nb_xor; binaryfunc nb_or; unaryfunc nb_int; void *nb_reserved; /* the slot formerly known as nb_long */ unaryfunc nb_float; binaryfunc nb_inplace_add; binaryfunc nb_inplace_subtract; binaryfunc nb_inplace_multiply; binaryfunc nb_inplace_remainder; ternaryfunc nb_inplace_power; binaryfunc nb_inplace_lshift; binaryfunc nb_inplace_rshift; binaryfunc nb_inplace_and; binaryfunc nb_inplace_xor; binaryfunc nb_inplace_or; binaryfunc nb_floor_divide; binaryfunc nb_true_divide; binaryfunc nb_inplace_floor_divide; binaryfunc nb_inplace_true_divide; unaryfunc nb_index; binaryfunc nb_matrix_multiply; binaryfunc nb_inplace_matrix_multiply; } PyNumberMethods; typedef struct { lenfunc sq_length; binaryfunc sq_concat; ssizeargfunc sq_repeat; ssizeargfunc sq_item; void *was_sq_slice; ssizeobjargproc sq_ass_item; void *was_sq_ass_slice; objobjproc sq_contains; binaryfunc sq_inplace_concat; ssizeargfunc sq_inplace_repeat; } PySequenceMethods; typedef struct { lenfunc mp_length; binaryfunc mp_subscript; objobjargproc mp_ass_subscript; } PyMappingMethods; typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } PyAsyncMethods; typedef struct { getbufferproc bf_getbuffer; releasebufferproc bf_releasebuffer; } PyBufferProcs; #endif /* Py_LIMITED_API */ typedef void (*freefunc)(void *); typedef void (*destructor)(PyObject *); #ifndef Py_LIMITED_API /* We can't provide a full compile-time check that limited-API users won't implement tp_print. However, not defining printfunc and making tp_print of a different function pointer type should at least cause a warning in most cases. */ typedef int (*printfunc)(PyObject *, FILE *, int); #endif typedef PyObject *(*getattrfunc)(PyObject *, char *); typedef PyObject *(*getattrofunc)(PyObject *, PyObject *); typedef int (*setattrfunc)(PyObject *, char *, PyObject *); typedef int (*setattrofunc)(PyObject *, PyObject *, PyObject *); typedef PyObject *(*reprfunc)(PyObject *); typedef Py_hash_t (*hashfunc)(PyObject *); typedef PyObject *(*richcmpfunc) (PyObject *, PyObject *, int); typedef PyObject *(*getiterfunc) (PyObject *); typedef PyObject *(*iternextfunc) (PyObject *); typedef PyObject *(*descrgetfunc) (PyObject *, PyObject *, PyObject *); typedef int (*descrsetfunc) (PyObject *, PyObject *, PyObject *); typedef int (*initproc)(PyObject *, PyObject *, PyObject *); typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *); typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t); #ifdef Py_LIMITED_API typedef struct _typeobject PyTypeObject; /* opaque */ #else typedef struct _typeobject { PyObject_VAR_HEAD const char *tp_name; /* For printing, in format "<module>.<name>" */ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */ /* Methods to implement standard operations */ destructor tp_dealloc; printfunc tp_print; getattrfunc tp_getattr; setattrfunc tp_setattr; PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2) or tp_reserved (Python 3) */ reprfunc tp_repr; /* Method suites for standard classes */ PyNumberMethods *tp_as_number; PySequenceMethods *tp_as_sequence; PyMappingMethods *tp_as_mapping; /* More standard operations (here for binary compatibility) */ hashfunc tp_hash; ternaryfunc tp_call; reprfunc tp_str; getattrofunc tp_getattro; setattrofunc tp_setattro; /* Functions to access object as input/output buffer */ PyBufferProcs *tp_as_buffer; /* Flags to define presence of optional/expanded features */ unsigned long tp_flags; const char *tp_doc; /* Documentation string */ /* Assigned meaning in release 2.0 */ /* call function for all accessible objects */ traverseproc tp_traverse; /* delete references to contained objects */ inquiry tp_clear; /* Assigned meaning in release 2.1 */ /* rich comparisons */ richcmpfunc tp_richcompare; /* weak reference enabler */ Py_ssize_t tp_weaklistoffset; /* Iterators */ getiterfunc tp_iter; iternextfunc tp_iternext; /* Attribute descriptor and subclassing stuff */ struct PyMethodDef *tp_methods; struct PyMemberDef *tp_members; struct PyGetSetDef *tp_getset; struct _typeobject *tp_base; PyObject *tp_dict; descrgetfunc tp_descr_get; descrsetfunc tp_descr_set; Py_ssize_t tp_dictoffset; initproc tp_init; allocfunc tp_alloc; newfunc tp_new; freefunc tp_free; /* Low-level free-memory routine */ inquiry tp_is_gc; /* For PyObject_IS_GC */ PyObject *tp_bases; PyObject *tp_mro; /* method resolution order */ PyObject *tp_cache; PyObject *tp_subclasses; PyObject *tp_weaklist; destructor tp_del; /* Type attribute cache version tag. Added in version 2.6 */ unsigned int tp_version_tag; destructor tp_finalize; #ifdef COUNT_ALLOCS /* these must be last and never explicitly initialized */ Py_ssize_t tp_allocs; Py_ssize_t tp_frees; Py_ssize_t tp_maxalloc; struct _typeobject *tp_prev; struct _typeobject *tp_next; #endif } PyTypeObject; #endif typedef struct{ int slot; /* slot id, see below */ void *pfunc; /* function pointer */ } PyType_Slot; typedef struct{ const char* name; int basicsize; int itemsize; unsigned int flags; PyType_Slot *slots; /* terminated by slot==0. */ } PyType_Spec; PyObject* PyType_FromSpec(PyType_Spec*); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 PyObject* PyType_FromSpecWithBases(PyType_Spec*, PyObject*); #endif #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03040000 void* PyType_GetSlot(PyTypeObject*, int); #endif #ifndef Py_LIMITED_API /* The *real* layout of a type object when allocated on the heap */ typedef struct _heaptypeobject { /* Note: there's a dependency on the order of these members in slotptr() in typeobject.c . */ PyTypeObject ht_type; PyAsyncMethods as_async; PyNumberMethods as_number; PyMappingMethods as_mapping; PySequenceMethods as_sequence; /* as_sequence comes after as_mapping, so that the mapping wins when both the mapping and the sequence define a given operator (e.g. __getitem__). see add_operators() in typeobject.c . */ PyBufferProcs as_buffer; PyObject *ht_name, *ht_slots, *ht_qualname; struct _dictkeysobject *ht_cached_keys; /* here are optional user slots, followed by the members. */ } PyHeapTypeObject; /* access macro to the members which are floating "behind" the object */ #define PyHeapType_GET_MEMBERS(etype) \ ((PyMemberDef *)(((char *)etype) + Py_TYPE(etype)->tp_basicsize)) #endif /* Generic type check */ int PyType_IsSubtype(PyTypeObject *, PyTypeObject *); #define PyObject_TypeCheck(ob, tp) \ (Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp))) extern PyTypeObject PyType_Type; /* built-in 'type' */ extern PyTypeObject PyBaseObject_Type; /* built-in 'object' */ extern PyTypeObject PySuper_Type; /* built-in 'super' */ unsigned long PyType_GetFlags(PyTypeObject*); #define PyType_Check(op) \ PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS) #define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type) int PyType_Ready(PyTypeObject *); PyObject * PyType_GenericAlloc(PyTypeObject *, Py_ssize_t); PyObject * PyType_GenericNew(PyTypeObject *, PyObject *, PyObject *); #ifndef Py_LIMITED_API PyObject * _PyType_Lookup(PyTypeObject *, PyObject *); PyObject * _PyType_LookupId(PyTypeObject *, _Py_Identifier *); PyObject * _PyObject_LookupSpecial(PyObject *, _Py_Identifier *); PyTypeObject * _PyType_CalculateMetaclass(PyTypeObject *, PyObject *); #endif unsigned int PyType_ClearCache(void); void PyType_Modified(PyTypeObject *); #ifndef Py_LIMITED_API PyObject * _PyType_GetDocFromInternalDoc(const char *, const char *); PyObject * _PyType_GetTextSignatureFromInternalDoc(const char *, const char *); #endif /* Generic operations on objects */ #ifndef Py_LIMITED_API struct _Py_Identifier; int PyObject_Print(PyObject *, FILE *, int); void _Py_BreakPoint(void); void _PyObject_Dump(PyObject *); int _PyObject_IsFreed(PyObject *); #endif PyObject * PyObject_Repr(PyObject *); PyObject * PyObject_Str(PyObject *); PyObject * PyObject_ASCII(PyObject *); PyObject * PyObject_Bytes(PyObject *); PyObject * PyObject_RichCompare(PyObject *, PyObject *, int); int PyObject_RichCompareBool(PyObject *, PyObject *, int); PyObject * PyObject_GetAttrString(PyObject *, const char *); int PyObject_SetAttrString(PyObject *, const char *, PyObject *); int PyObject_HasAttrString(PyObject *, const char *); PyObject * PyObject_GetAttr(PyObject *, PyObject *); int PyObject_SetAttr(PyObject *, PyObject *, PyObject *); int PyObject_HasAttr(PyObject *, PyObject *); #ifndef Py_LIMITED_API int _PyObject_IsAbstract(PyObject *); PyObject * _PyObject_GetAttrId(PyObject *, struct _Py_Identifier *); int _PyObject_SetAttrId(PyObject *, struct _Py_Identifier *, PyObject *); int _PyObject_HasAttrId(PyObject *, struct _Py_Identifier *); PyObject ** _PyObject_GetDictPtr(PyObject *); #endif PyObject * PyObject_SelfIter(PyObject *); #ifndef Py_LIMITED_API PyObject * _PyObject_NextNotImplemented(PyObject *); #endif PyObject * PyObject_GenericGetAttr(PyObject *, PyObject *); int PyObject_GenericSetAttr(PyObject *, PyObject *, PyObject *); #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03030000 int PyObject_GenericSetDict(PyObject *, PyObject *, void *); #endif Py_hash_t PyObject_Hash(PyObject *); Py_hash_t PyObject_HashNotImplemented(PyObject *); int PyObject_IsTrue(PyObject *); int PyObject_Not(PyObject *); int PyCallable_Check(PyObject *); void PyObject_ClearWeakRefs(PyObject *); #ifndef Py_LIMITED_API void PyObject_CallFinalizer(PyObject *); int PyObject_CallFinalizerFromDealloc(PyObject *); #endif #ifndef Py_LIMITED_API /* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes dict as the last parameter. */ PyObject * _PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *); int _PyObject_GenericSetAttrWithDict(PyObject *, PyObject *, PyObject *, PyObject *); #endif /* !Py_LIMITED_API */ /* Helper to look up a builtin object */ #ifndef Py_LIMITED_API PyObject * _PyObject_GetBuiltin(const char *name); #endif /* PyObject_Dir(obj) acts like Python builtins.dir(obj), returning a list of strings. PyObject_Dir(NULL) is like builtins.dir(), returning the names of the current locals. In this case, if there are no current locals, NULL is returned, and PyErr_Occurred() is false. */ PyObject * PyObject_Dir(PyObject *); /* Helpers for printing recursive container types */ int Py_ReprEnter(PyObject *); void Py_ReprLeave(PyObject *); /* Flag bits for printing: */ #define Py_PRINT_RAW 1 /* No string quotes etc. */ /* `Type flags (tp_flags) These flags are used to extend the type structure in a backwards-compatible fashion. Extensions can use the flags to indicate (and test) when a given type structure contains a new feature. The Python core will use these when introducing new functionality between major revisions (to avoid mid-version changes in the PYTHON_API_VERSION). Arbitration of the flag bit positions will need to be coordinated among all extension writers who publically release their extensions (this will be fewer than you might expect!).. Most flags were removed as of Python 3.0 to make room for new flags. (Some flags are not for backwards compatibility but to indicate the presence of an optional feature; these flags remain of course.) Type definitions should use Py_TPFLAGS_DEFAULT for their tp_flags value. Code can use PyType_HasFeature(type_ob, flag_value) to test whether the given type object has a specified feature. */ /* Set if the type object is dynamically allocated */ #define Py_TPFLAGS_HEAPTYPE (1UL << 9) /* Set if the type allows subclassing */ #define Py_TPFLAGS_BASETYPE (1UL << 10) /* Set if the type is 'ready' -- fully initialized */ #define Py_TPFLAGS_READY (1UL << 12) /* Set while the type is being 'readied', to prevent recursive ready calls */ #define Py_TPFLAGS_READYING (1UL << 13) /* Objects support garbage collection (see objimp.h) */ #define Py_TPFLAGS_HAVE_GC (1UL << 14) /* These two bits are preserved for Stackless Python, next after this is 17 */ #ifdef STACKLESS #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3UL << 15) #else #define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0 #endif /* Objects support type attribute cache */ #define Py_TPFLAGS_HAVE_VERSION_TAG (1UL << 18) #define Py_TPFLAGS_VALID_VERSION_TAG (1UL << 19) /* Type is abstract and cannot be instantiated */ #define Py_TPFLAGS_IS_ABSTRACT (1UL << 20) /* These flags are used to determine if a type is a subclass. */ #define Py_TPFLAGS_LONG_SUBCLASS (1UL << 24) #define Py_TPFLAGS_LIST_SUBCLASS (1UL << 25) #define Py_TPFLAGS_TUPLE_SUBCLASS (1UL << 26) #define Py_TPFLAGS_BYTES_SUBCLASS (1UL << 27) #define Py_TPFLAGS_UNICODE_SUBCLASS (1UL << 28) #define Py_TPFLAGS_DICT_SUBCLASS (1UL << 29) #define Py_TPFLAGS_BASE_EXC_SUBCLASS (1UL << 30) #define Py_TPFLAGS_TYPE_SUBCLASS (1UL << 31) #define Py_TPFLAGS_DEFAULT ( \ Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \ Py_TPFLAGS_HAVE_VERSION_TAG | \ 0) /* NOTE: The following flags reuse lower bits (removed as part of the * Python 3.0 transition). */ /* Type structure has tp_finalize member (3.4) */ #define Py_TPFLAGS_HAVE_FINALIZE (1UL << 0) #ifdef Py_LIMITED_API #define PyType_HasFeature(t,f) ((PyType_GetFlags(t) & (f)) != 0) #else #define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0) #endif #define PyType_FastSubclass(t,f) PyType_HasFeature(t,f) /* The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement reference counts. Py_DECREF calls the object's deallocator function when the refcount falls to 0; for objects that don't contain references to other objects or heap memory this can be the standard function free(). Both macros can be used wherever a void expression is allowed. The argument must not be a NULL pointer. If it may be NULL, use Py_XINCREF/Py_XDECREF instead. The macro _Py_NewReference(op) initialize reference counts to 1, and in special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additional bookkeeping appropriate to the special build. We assume that the reference count field can never overflow; this can be proven when the size of the field is the same as the pointer size, so we ignore the possibility. Provided a C int is at least 32 bits (which is implicitly assumed in many parts of this code), that's enough for about 2**31 references to an object. XXX The following became out of date in Python 2.2, but I'm not sure XXX what the full truth is now. Certainly, heap-allocated type objects XXX can and should be deallocated. Type objects should never be deallocated; the type pointer in an object is not considered to be a reference to the type object, to save complications in the deallocation function. (This is actually a decision that's up to the implementer of each new type so if you want, you can count such references to the type object.) */ /* First define a pile of simple helper macros, one set per special * build symbol. These either expand to the obvious things, or to * nothing at all when the special mode isn't in effect. The main * macros can later be defined just once then, yet expand to different * things depending on which special build options are and aren't in effect. * Trust me <wink>: while painful, this is 20x easier to understand than, * e.g, defining _Py_NewReference five different times in a maze of nested * #ifdefs (we used to do that -- it was impenetrable). */ #ifdef Py_REF_DEBUG extern Py_ssize_t _Py_RefTotal; void _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op); Py_ssize_t _Py_GetRefTotal(void); #define _Py_INC_REFTOTAL _Py_RefTotal++ #define _Py_DEC_REFTOTAL _Py_RefTotal-- #define _Py_REF_DEBUG_COMMA , #define _Py_CHECK_REFCNT(OP) \ { if (((PyObject*)OP)->ob_refcnt < 0) \ _Py_NegativeRefcount(__FILE__, __LINE__, \ (PyObject *)(OP)); \ } /* Py_REF_DEBUG also controls the display of refcounts and memory block * allocations at the interactive prompt and at interpreter shutdown */ void _PyDebug_PrintTotalRefs(void); #define _PY_DEBUG_PRINT_TOTAL_REFS() _PyDebug_PrintTotalRefs() #else #define _Py_INC_REFTOTAL #define _Py_DEC_REFTOTAL #define _Py_REF_DEBUG_COMMA #define _Py_CHECK_REFCNT(OP) /* a semicolon */; #define _PY_DEBUG_PRINT_TOTAL_REFS() #endif /* Py_REF_DEBUG */ #ifdef COUNT_ALLOCS void inc_count(PyTypeObject *); void dec_count(PyTypeObject *); #define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP)) #define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP)) #define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees-- #define _Py_COUNT_ALLOCS_COMMA , #else #define _Py_INC_TPALLOCS(OP) #define _Py_INC_TPFREES(OP) #define _Py_DEC_TPFREES(OP) #define _Py_COUNT_ALLOCS_COMMA #endif /* COUNT_ALLOCS */ #ifdef Py_TRACE_REFS /* Py_TRACE_REFS is such major surgery that we call external routines. */ void _Py_NewReference(PyObject *); void _Py_ForgetReference(PyObject *); void _Py_Dealloc(PyObject *); void _Py_PrintReferences(FILE *); void _Py_PrintReferenceAddresses(FILE *); void _Py_AddToAllObjects(PyObject *, int force); #else /* Without Py_TRACE_REFS, there's little enough to do that we expand code * inline. */ #define _Py_NewReference(op) ( \ _Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \ _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ Py_REFCNT(op) = 1) #define _Py_ForgetReference(op) _Py_INC_TPFREES(op) #ifdef Py_LIMITED_API void _Py_Dealloc(PyObject *); #else #define _Py_Dealloc(op) ( \ _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \ (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) #endif #endif /* !Py_TRACE_REFS */ #define Py_INCREF(op) ( \ _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ ((PyObject *)(op))->ob_refcnt++) #define Py_DECREF(op) \ do { \ PyObject *_py_decref_tmp = (PyObject *)(op); \ if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ --(_py_decref_tmp)->ob_refcnt != 0) \ _Py_CHECK_REFCNT(_py_decref_tmp) \ else \ _Py_Dealloc(_py_decref_tmp); \ } while (0) /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear * and tp_dealloc implementations. * * Note that "the obvious" code can be deadly: * * Py_XDECREF(op); * op = NULL; * * Typically, `op` is something like self->containee, and `self` is done * using its `containee` member. In the code sequence above, suppose * `containee` is non-NULL with a refcount of 1. Its refcount falls to * 0 on the first line, which can trigger an arbitrary amount of code, * possibly including finalizers (like __del__ methods or weakref callbacks) * coded in Python, which in turn can release the GIL and allow other threads * to run, etc. Such code may even invoke methods of `self` again, or cause * cyclic gc to trigger, but-- oops! --self->containee still points to the * object being torn down, and it may be in an insane state while being torn * down. This has in fact been a rich historic source of miserable (rare & * hard-to-diagnose) segfaulting (and other) bugs. * * The safe way is: * * Py_CLEAR(op); * * That arranges to set `op` to NULL _before_ decref'ing, so that any code * triggered as a side-effect of `op` getting torn down no longer believes * `op` points to a valid object. * * There are cases where it's safe to use the naive code, but they're brittle. * For example, if `op` points to a Python integer, you know that destroying * one of those can't cause problems -- but in part that relies on that * Python integers aren't currently weakly referencable. Best practice is * to use Py_CLEAR() even if you can't think of a reason for why you need to. */ #define Py_CLEAR(op) \ do { \ PyObject *_py_tmp = (PyObject *)(op); \ if (_py_tmp != NULL) { \ (op) = NULL; \ Py_DECREF(_py_tmp); \ } \ } while (0) /* Macros to use in case the object pointer may be NULL: */ #define Py_XINCREF(op) \ do { \ PyObject *_py_xincref_tmp = (PyObject *)(op); \ if (_py_xincref_tmp != NULL) \ Py_INCREF(_py_xincref_tmp); \ } while (0) #define Py_XDECREF(op) \ do { \ PyObject *_py_xdecref_tmp = (PyObject *)(op); \ if (_py_xdecref_tmp != NULL) \ Py_DECREF(_py_xdecref_tmp); \ } while (0) #ifndef Py_LIMITED_API /* Safely decref `op` and set `op` to `op2`. * * As in case of Py_CLEAR "the obvious" code can be deadly: * * Py_DECREF(op); * op = op2; * * The safe way is: * * Py_SETREF(op, op2); * * That arranges to set `op` to `op2` _before_ decref'ing, so that any code * triggered as a side-effect of `op` getting torn down no longer believes * `op` points to a valid object. * * Py_XSETREF is a variant of Py_SETREF that uses Py_XDECREF instead of * Py_DECREF. */ #define Py_SETREF(op, op2) \ do { \ PyObject *_py_tmp = (PyObject *)(op); \ (op) = (op2); \ Py_DECREF(_py_tmp); \ } while (0) #define Py_XSETREF(op, op2) \ do { \ PyObject *_py_tmp = (PyObject *)(op); \ (op) = (op2); \ Py_XDECREF(_py_tmp); \ } while (0) #endif /* ifndef Py_LIMITED_API */ /* These are provided as conveniences to Python runtime embedders, so that they can have object code that is not dependent on Python compilation flags. */ void Py_IncRef(PyObject *); void Py_DecRef(PyObject *); #ifndef Py_LIMITED_API extern PyTypeObject _PyNone_Type; extern PyTypeObject _PyNotImplemented_Type; #endif /* !Py_LIMITED_API */ /* _Py_NoneStruct is an object of undefined type which can be used in contexts where NULL (nil) is not suitable (since NULL often means 'error'). Don't forget to apply Py_INCREF() when returning this value!!! */ extern PyObject _Py_NoneStruct; /* Don't use this directly */ #define Py_None (&_Py_NoneStruct) /* Macro for returning Py_None from a function */ #define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None /* Py_NotImplemented is a singleton used to signal that an operation is not implemented for a given type combination. */ extern PyObject _Py_NotImplementedStruct; /* Don't use this directly */ #define Py_NotImplemented (&_Py_NotImplementedStruct) /* Macro for returning Py_NotImplemented from a function */ #define Py_RETURN_NOTIMPLEMENTED \ return Py_INCREF(Py_NotImplemented), Py_NotImplemented #ifndef Py_LIMITED_API /* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE. * Defined in object.c. */ extern int _Py_SwappedOp[]; #endif /* !Py_LIMITED_API */ /* More conventions ================ Argument Checking ----------------- Functions that take objects as arguments normally don't check for nil arguments, but they do check the type of the argument, and return an error if the function doesn't apply to the type. Failure Modes ------------- Functions may fail for a variety of reasons, including running out of memory. This is communicated to the caller in two ways: an error string is set (see errors.h), and the function result differs: functions that normally return a pointer return NULL for failure, functions returning an integer return -1 (which could be a legal return value too!), and other functions return 0 for success and -1 for failure. Callers should always check for errors before using the result. If an error was set, the caller must either explicitly clear it, or pass the error on to its caller. Reference Counts ---------------- It takes a while to get used to the proper usage of reference counts. Functions that create an object set the reference count to 1; such new objects must be stored somewhere or destroyed again with Py_DECREF(). Some functions that 'store' objects, such as PyTuple_SetItem() and PyList_SetItem(), don't increment the reference count of the object, since the most frequent use is to store a fresh object. Functions that 'retrieve' objects, such as PyTuple_GetItem() and PyDict_GetItemString(), also don't increment the reference count, since most frequently the object is only looked at quickly. Thus, to retrieve an object and store it again, the caller must call Py_INCREF() explicitly. NOTE: functions that 'consume' a reference count, like PyList_SetItem(), consume the reference even if the object wasn't successfully stored, to simplify error handling. It seems attractive to make other functions that take an object as argument consume a reference count; however, this may quickly get confusing (even the current practice is already confusing). Consider it carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() at times. */ /* Trashcan mechanism, thanks to Christian Tismer. When deallocating a container object, it's possible to trigger an unbounded chain of deallocations, as each Py_DECREF in turn drops the refcount on "the next" object in the chain to 0. This can easily lead to stack faults, and especially in threads (which typically have less stack space to work with). A container object that participates in cyclic gc can avoid this by bracketing the body of its tp_dealloc function with a pair of macros: static void mytype_dealloc(mytype *p) { ... declarations go here ... PyObject_GC_UnTrack(p); // must untrack first Py_TRASHCAN_SAFE_BEGIN(p) ... The body of the deallocator goes here, including all calls ... ... to Py_DECREF on contained objects. ... Py_TRASHCAN_SAFE_END(p) } CAUTION: Never return from the middle of the body! If the body needs to "get out early", put a label immediately before the Py_TRASHCAN_SAFE_END call, and goto it. Else the call-depth counter (see below) will stay above 0 forever, and the trashcan will never get emptied. How it works: The BEGIN macro increments a call-depth counter. So long as this counter is small, the body of the deallocator is run directly without further ado. But if the counter gets large, it instead adds p to a list of objects to be deallocated later, skips the body of the deallocator, and resumes execution after the END macro. The tp_dealloc routine then returns without deallocating anything (and so unbounded call-stack depth is avoided). When the call stack finishes unwinding again, code generated by the END macro notices this, and calls another routine to deallocate all the objects that may have been added to the list of deferred deallocations. In effect, a chain of N deallocations is broken into N / PyTrash_UNWIND_LEVEL pieces, with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL. */ #ifndef Py_LIMITED_API /* This is the old private API, invoked by the macros before 3.2.4. Kept for binary compatibility of extensions using the stable ABI. */ void _PyTrash_deposit_object(PyObject*); void _PyTrash_destroy_chain(void); extern int _PyTrash_delete_nesting; extern PyObject * _PyTrash_delete_later; #endif /* !Py_LIMITED_API */ /* The new thread-safe private API, invoked by the macros below. */ void _PyTrash_thread_deposit_object(PyObject*); void _PyTrash_thread_destroy_chain(void); #define PyTrash_UNWIND_LEVEL 50 #define Py_TRASHCAN_SAFE_BEGIN(op) \ do { \ PyThreadState *_tstate = PyThreadState_GET(); \ if (_tstate->trash_delete_nesting < PyTrash_UNWIND_LEVEL) { \ ++_tstate->trash_delete_nesting; /* The body of the deallocator is here. */ #define Py_TRASHCAN_SAFE_END(op) \ --_tstate->trash_delete_nesting; \ if (_tstate->trash_delete_later && _tstate->trash_delete_nesting <= 0) \ _PyTrash_thread_destroy_chain(); \ } \ else \ _PyTrash_thread_deposit_object((PyObject*)op); \ } while (0); #ifndef Py_LIMITED_API void _PyDebugAllocatorStats(FILE *out, const char *block_name, int num_blocks, size_t sizeof_block); void _PyObject_DebugTypeStats(FILE *out); #endif /* ifndef Py_LIMITED_API */ COSMOPOLITAN_C_END_ #endif /* !Py_OBJECT_H */
39,427
1,070
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/rangeobject.h
#ifndef Py_RANGEOBJECT_H #define Py_RANGEOBJECT_H #include "third_party/python/Include/object.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* A range object represents an integer range. This is an immutable object; a range cannot change its value after creation. Range objects behave like the corresponding tuple objects except that they are represented by a start, stop, and step datamembers. */ extern PyTypeObject PyRange_Type; extern PyTypeObject PyRangeIter_Type; extern PyTypeObject PyLongRangeIter_Type; #define PyRange_Check(op) (Py_TYPE(op) == &PyRange_Type) COSMOPOLITAN_C_END_ #endif /* !Py_RANGEOBJECT_H */
628
23
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/osdefs.h
#ifndef Py_OSDEFS_H #define Py_OSDEFS_H COSMOPOLITAN_C_START_ #ifdef MS_WINDOWS #define SEP L'\\' #define ALTSEP L'/' #define MAXPATHLEN 256 #define DELIM L';' #endif /* Filename separator */ #ifndef SEP #define SEP L'/' #endif #ifndef MAXPATHLEN #if defined(PATH_MAX) && PATH_MAX > 1024 #define MAXPATHLEN PATH_MAX #else #define MAXPATHLEN 1024 #endif #endif /* Search path entry delimiter */ #ifndef DELIM #define DELIM L':' #endif COSMOPOLITAN_C_END_ #endif /* !Py_OSDEFS_H */
501
32
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/pymacro.h
#ifndef Py_PYMACRO_H #define Py_PYMACRO_H /* clang-format off */ /* Minimum value between x and y */ #define Py_MIN(x, y) (((x) > (y)) ? (y) : (x)) /* Maximum value between x and y */ #define Py_MAX(x, y) (((x) > (y)) ? (x) : (y)) /* Absolute value of the number x */ #define Py_ABS(x) ((x) < 0 ? -(x) : (x)) #define _Py_XSTRINGIFY(x) #x /* Convert the argument to a string. For example, Py_STRINGIFY(123) is replaced with "123" by the preprocessor. Defines are also replaced by their value. For example Py_STRINGIFY(__LINE__) is replaced by the line number, not by "__LINE__". */ #define Py_STRINGIFY(x) _Py_XSTRINGIFY(x) /* Get the size of a structure member in bytes */ #define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) /* Argument must be a char or an int in [-128, 127] or [0, 255]. */ #define Py_CHARMASK(c) ((unsigned char)((c) & 0xff)) /* Assert a build-time dependency, as an expression. Your compile will fail if the condition isn't true, or can't be evaluated by the compiler. This can be used in an expression: its value is 0. Example: #define foo_to_char(foo) \ ((char *)(foo) \ + Py_BUILD_ASSERT_EXPR(offsetof(struct foo, string) == 0)) Written by Rusty Russell, public domain, http://ccodearchive.net/ */ #define Py_BUILD_ASSERT_EXPR(cond) \ (sizeof(char [1 - 2*!(cond)]) - 1) #define Py_BUILD_ASSERT(cond) do { \ (void)Py_BUILD_ASSERT_EXPR(cond); \ } while(0) /* Get the number of elements in a visible array This does not work on pointers, or arrays declared as [], or function parameters. With correct compiler support, such usage will cause a build error (see Py_BUILD_ASSERT_EXPR). Written by Rusty Russell, public domain, http://ccodearchive.net/ Requires at GCC 3.1+ */ #if (defined(__GNUC__) && !defined(__STRICT_ANSI__) && \ (((__GNUC__ == 3) && (__GNU_MINOR__ >= 1)) || (__GNUC__ >= 4))) /* Two gcc extensions. &a[0] degrades to a pointer: a different type from an array */ #define Py_ARRAY_LENGTH(array) \ (sizeof(array) / sizeof((array)[0]) \ + Py_BUILD_ASSERT_EXPR(!__builtin_types_compatible_p(typeof(array), \ typeof(&(array)[0])))) #else #define Py_ARRAY_LENGTH(array) \ (sizeof(array) / sizeof((array)[0])) #endif /* Define macros for inline documentation. */ #define PyDoc_VAR(name) static char name[] #define PyDoc_STRVAR(name,str) PyDoc_VAR(name) = PyDoc_STR(str) #ifdef WITH_DOC_STRINGS #define PyDoc_STR(str) str #else #define PyDoc_STR(str) "" #endif /* Below "a" is a power of 2. */ /* Round down size "n" to be a multiple of "a". */ #define _Py_SIZE_ROUND_DOWN(n, a) ((size_t)(n) & ~(size_t)((a) - 1)) /* Round up size "n" to be a multiple of "a". */ #define _Py_SIZE_ROUND_UP(n, a) (((size_t)(n) + \ (size_t)((a) - 1)) & ~(size_t)((a) - 1)) /* Round pointer "p" down to the closest "a"-aligned address <= "p". */ #define _Py_ALIGN_DOWN(p, a) ((void *)((uintptr_t)(p) & ~(uintptr_t)((a) - 1))) /* Round pointer "p" up to the closest "a"-aligned address >= "p". */ #define _Py_ALIGN_UP(p, a) ((void *)(((uintptr_t)(p) + \ (uintptr_t)((a) - 1)) & ~(uintptr_t)((a) - 1))) /* Check if pointer "p" is aligned to "a"-bytes boundary. */ #define _Py_IS_ALIGNED(p, a) (!((uintptr_t)(p) & (uintptr_t)((a) - 1))) #ifdef __GNUC__ #define Py_UNUSED(name) _unused_ ## name __attribute__((unused)) #else #define Py_UNUSED(name) _unused_ ## name #endif #endif /* Py_PYMACRO_H */
3,523
100
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/bytes_methods.h
#ifndef Py_LIMITED_API #ifndef Py_BYTES_CTYPE_H #define Py_BYTES_CTYPE_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/pymacro.h" /* clang-format off */ /* * The internal implementation behind PyBytes (bytes) and PyByteArray (bytearray) * methods of the given names, they operate on ASCII byte strings. */ extern PyObject* _Py_bytes_isspace(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isalpha(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isalnum(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isdigit(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_islower(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_isupper(const char *cptr, Py_ssize_t len); extern PyObject* _Py_bytes_istitle(const char *cptr, Py_ssize_t len); /* These store their len sized answer in the given preallocated *result arg. */ extern void _Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len); extern void _Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len); extern void _Py_bytes_title(char *result, const char *s, Py_ssize_t len); extern void _Py_bytes_capitalize(char *result, const char *s, Py_ssize_t len); extern void _Py_bytes_swapcase(char *result, const char *s, Py_ssize_t len); extern PyObject *_Py_bytes_find(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_index(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_rfind(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_rindex(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_count(const char *str, Py_ssize_t len, PyObject *args); extern int _Py_bytes_contains(const char *str, Py_ssize_t len, PyObject *arg); extern PyObject *_Py_bytes_startswith(const char *str, Py_ssize_t len, PyObject *args); extern PyObject *_Py_bytes_endswith(const char *str, Py_ssize_t len, PyObject *args); /* The maketrans() static method. */ extern PyObject* _Py_bytes_maketrans(Py_buffer *frm, Py_buffer *to); /* Shared __doc__ strings. */ extern const char _Py_isspace__doc__[]; extern const char _Py_isalpha__doc__[]; extern const char _Py_isalnum__doc__[]; extern const char _Py_isdigit__doc__[]; extern const char _Py_islower__doc__[]; extern const char _Py_isupper__doc__[]; extern const char _Py_istitle__doc__[]; extern const char _Py_lower__doc__[]; extern const char _Py_upper__doc__[]; extern const char _Py_title__doc__[]; extern const char _Py_capitalize__doc__[]; extern const char _Py_swapcase__doc__[]; extern const char _Py_count__doc__[]; extern const char _Py_find__doc__[]; extern const char _Py_index__doc__[]; extern const char _Py_rfind__doc__[]; extern const char _Py_rindex__doc__[]; extern const char _Py_startswith__doc__[]; extern const char _Py_endswith__doc__[]; extern const char _Py_maketrans__doc__[]; extern const char _Py_expandtabs__doc__[]; extern const char _Py_ljust__doc__[]; extern const char _Py_rjust__doc__[]; extern const char _Py_center__doc__[]; extern const char _Py_zfill__doc__[]; /* this is needed because some docs are shared from the .o, not static */ #define PyDoc_STRVAR_shared(name,str) const char name[] = PyDoc_STR(str) #endif /* !Py_BYTES_CTYPE_H */ #endif /* !Py_LIMITED_API */
3,309
71
jart/cosmopolitan
false
cosmopolitan/third_party/python/Include/ceval.h
#ifndef Py_CEVAL_H #define Py_CEVAL_H #include "libc/dce.h" #include "libc/intrin/likely.h" #include "libc/runtime/stack.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/pythonrun.h" COSMOPOLITAN_C_START_ /* clang-format off */ /* Interface to random parts in ceval.c */ PyObject *PyEval_CallObjectWithKeywords(PyObject *, PyObject *, PyObject *); /* Inline this */ #define PyEval_CallObject(func,arg) \ PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL) PyObject *PyEval_CallFunction(PyObject *, const char *, ...); PyObject *PyEval_CallMethod(PyObject *, const char *, const char *, ...); #ifndef Py_LIMITED_API void PyEval_SetProfile(Py_tracefunc, PyObject *); void PyEval_SetTrace(Py_tracefunc, PyObject *); void _PyEval_SetCoroutineWrapper(PyObject *); PyObject *_PyEval_GetCoroutineWrapper(void); void _PyEval_SetAsyncGenFirstiter(PyObject *); PyObject *_PyEval_GetAsyncGenFirstiter(void); void _PyEval_SetAsyncGenFinalizer(PyObject *); PyObject *_PyEval_GetAsyncGenFinalizer(void); #endif struct _frame; /* Avoid including frameobject.h */ PyObject *PyEval_GetBuiltins(void); PyObject *PyEval_GetGlobals(void); PyObject *PyEval_GetLocals(void); struct _frame *PyEval_GetFrame(void); #ifndef Py_LIMITED_API /* Helper to look up a builtin object */ PyObject *_PyEval_GetBuiltinId(_Py_Identifier *); /* Look at the current frame's (if any) code's co_flags, and turn on the corresponding compiler flags in cf->cf_flags. Return 1 if any flag was set, else return 0. */ int PyEval_MergeCompilerFlags(PyCompilerFlags *); #endif int Py_AddPendingCall(int (*)(void *), void *); void _PyEval_SignalReceived(void); int Py_MakePendingCalls(void); /* Protection against deeply nested recursive calls In Python 3.0, this protection has two levels: * normal anti-recursion protection is triggered when the recursion level exceeds the current recursion limit. It raises a RecursionError, and sets the "overflowed" flag in the thread state structure. This flag temporarily *disables* the normal protection; this allows cleanup code to potentially outgrow the recursion limit while processing the RecursionError. * "last chance" anti-recursion protection is triggered when the recursion level exceeds "current recursion limit + 50". By construction, this protection can only be triggered when the "overflowed" flag is set. It means the cleanup code has itself gone into an infinite loop, or the RecursionError has been mistakingly ignored. When this protection is triggered, the interpreter aborts with a Fatal Error. In addition, the "overflowed" flag is automatically reset when the recursion level drops below "current recursion limit - 50". This heuristic is meant to ensure that the normal anti-recursion protection doesn't get disabled too long. Please note: this scheme has its own limitations. See: http://mail.python.org/pipermail/python-dev/2008-August/082106.html for some observations. */ void Py_SetRecursionLimit(int); int Py_GetRecursionLimit(void); #ifdef USE_STACKCHECK /* With USE_STACKCHECK, we artificially decrement the recursion limit in order to trigger regular stack checks in _Py_CheckRecursiveCall(), except if the "overflowed" flag is set, in which case we need the true value of _Py_CheckRecursionLimit for _Py_MakeEndRecCheck() to function properly. */ # define _Py_MakeRecCheck(x) \ (++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1)) #else # define _Py_MakeRecCheck(x) (++(x) > _Py_CheckRecursionLimit) #endif /* Compute the "lower-water mark" for a recursion limit. When * Py_LeaveRecursiveCall() is called with a recursion depth below this mark, * the overflowed flag is reset to 0. ([jart] what) */ #define _Py_RecursionLimitLowerWaterMark(limit) \ (((limit) > 200) \ ? ((limit) - 50) \ : (3 * ((limit) >> 2))) #define _Py_MakeEndRecCheck(x) \ (--(x) < _Py_RecursionLimitLowerWaterMark(_Py_CheckRecursionLimit)) int Py_EnterRecursiveCall(const char *); void Py_LeaveRecursiveCall(void); #ifndef Py_LIMITED_API extern int _Py_CheckRecursionLimit; int _Py_CheckRecursiveCall(const char *); #define Py_LeaveRecursiveCall() PyThreadState_GET()->recursion_depth-- #define Py_EnterRecursiveCall(where) \ ({ \ int rc = 0; \ intptr_t rsp, bot; \ if (IsModeDbg()) { \ PyThreadState_GET()->recursion_depth++; \ rc = _Py_CheckRecursiveCall(where); \ } else { \ rsp = (intptr_t)__builtin_frame_address(0); \ bot = GetStackAddr() + 32768; \ if (UNLIKELY(rsp < bot)) { \ PyErr_Format(PyExc_MemoryError, "Stack overflow%s", where); \ rc = -1; \ } \ } \ rc; \ }) #endif #define Py_ALLOW_RECURSION \ do { \ unsigned char _old; \ _old = PyThreadState_GET()->recursion_critical; \ PyThreadState_GET()->recursion_critical = 1; #define Py_END_ALLOW_RECURSION \ PyThreadState_GET()->recursion_critical = _old; \ } while(0); const char * PyEval_GetFuncName(PyObject *); const char * PyEval_GetFuncDesc(PyObject *); PyObject * PyEval_GetCallStats(PyObject *); PyObject * PyEval_EvalFrame(struct _frame *); PyObject * PyEval_EvalFrameEx(struct _frame *, int); #define PyEval_EvalFrameEx(fr,st) PyThreadState_GET()->interp->eval_frame(fr,st) #ifndef Py_LIMITED_API PyObject * _PyEval_EvalFrameDefault(struct _frame *, int); #endif /* Interface for threads. A module that plans to do a blocking system call (or something else that lasts a long time and doesn't touch Python data) can allow other threads to run as follows: ...preparations here... Py_BEGIN_ALLOW_THREADS ...blocking system call here... Py_END_ALLOW_THREADS ...interpret result here... The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a {}-surrounded block. To leave the block in the middle (e.g., with return), you must insert a line containing Py_BLOCK_THREADS before the return, e.g. if (...premature_exit...) { Py_BLOCK_THREADS PyErr_SetFromErrno(PyExc_IOError); return NULL; } An alternative is: Py_BLOCK_THREADS if (...premature_exit...) { PyErr_SetFromErrno(PyExc_IOError); return NULL; } Py_UNBLOCK_THREADS For convenience, that the value of 'errno' is restored across Py_END_ALLOW_THREADS and Py_BLOCK_THREADS. WARNING: NEVER NEST CALLS TO Py_BEGIN_ALLOW_THREADS AND Py_END_ALLOW_THREADS!!! The function PyEval_InitThreads() should be called only from init_thread() in "_threadmodule.c". Note that not yet all candidates have been converted to use this mechanism! */ PyThreadState * PyEval_SaveThread(void); void PyEval_RestoreThread(PyThreadState *); #ifdef WITH_THREAD int PyEval_ThreadsInitialized(void); void PyEval_InitThreads(void); #ifndef Py_LIMITED_API void _PyEval_FiniThreads(void); #endif /* !Py_LIMITED_API */ void PyEval_AcquireLock(void); void PyEval_ReleaseLock(void); void PyEval_AcquireThread(PyThreadState *tstate); void PyEval_ReleaseThread(PyThreadState *tstate); void PyEval_ReInitThreads(void); #ifndef Py_LIMITED_API void _PyEval_SetSwitchInterval(unsigned long microseconds); unsigned long _PyEval_GetSwitchInterval(void); #endif #ifndef Py_LIMITED_API Py_ssize_t _PyEval_RequestCodeExtraIndex(freefunc); #endif #define Py_BEGIN_ALLOW_THREADS { \ PyThreadState *_save; \ _save = PyEval_SaveThread(); #define Py_BLOCK_THREADS PyEval_RestoreThread(_save); #define Py_UNBLOCK_THREADS _save = PyEval_SaveThread(); #define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \ } #else /* !WITH_THREAD */ #define Py_BEGIN_ALLOW_THREADS { #define Py_BLOCK_THREADS #define Py_UNBLOCK_THREADS #define Py_END_ALLOW_THREADS } #endif /* !WITH_THREAD */ #ifndef Py_LIMITED_API int _PyEval_SliceIndex(PyObject *, Py_ssize_t *); int _PyEval_SliceIndexNotNone(PyObject *, Py_ssize_t *); void _PyEval_SignalAsyncExc(void); #endif /* Masks and values used by FORMAT_VALUE opcode. */ #define FVC_MASK 0x3 #define FVC_NONE 0x0 #define FVC_STR 0x1 #define FVC_REPR 0x2 #define FVC_ASCII 0x3 #define FVS_MASK 0x4 #define FVS_HAVE_SPEC 0x4 COSMOPOLITAN_C_END_ #endif /* !Py_CEVAL_H */
9,297
256
jart/cosmopolitan
false